code stringlengths 2 1.05M |
|---|
/**
* @module helpers/lut
*/
export default class HelpersLut {
constructor(containerID,
lut = 'default',
lutO = 'linear',
color = [[0, 0, 0, 0], [1, 1, 1, 1]],
opacity = [[0, 0], [1, 1]],
discrete = false) {
// min/max (0-1 or real intensities)
// show/hide
// horizontal/vertical
this._containerID = containerID;
this._discrete = discrete;
this._color = color;
this._lut = lut;
this._luts = {[lut]: color};
this._opacity = opacity;
this._lutO = lutO;
this._lutsO = {[lutO]: opacity};
this.initCanvas();
this.paintCanvas();
}
initCanvas() {
// container
this._canvasContainer = this.initCanvasContainer(this._containerID);
// background
this._canvasBg = this.createCanvas();
this._canvasContainer.appendChild(this._canvasBg);
// foreground
this._canvas = this.createCanvas();
this._canvasContainer.appendChild(this._canvas);
}
initCanvasContainer(canvasContainerId) {
let canvasContainer = document.getElementById(canvasContainerId);
canvasContainer.style.width = '256 px';
canvasContainer.style.height = '128 px';
canvasContainer.style.border = '1px solid #F9F9F9';
return canvasContainer;
}
createCanvas() {
let canvas = document.createElement('canvas');
canvas.height = 16;
canvas.width = 256;
return canvas;
}
paintCanvas() {
// setup context
let ctx = this._canvas.getContext('2d');
ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
ctx.globalCompositeOperation = 'source-over';
// apply color
if (!this._discrete) {
let color = ctx.createLinearGradient(0, 0, this._canvas.width, this._canvas.height);
for (let i = 0; i < this._color.length; i++) {
color.addColorStop(this._color[i][0], `rgba( ${Math.round(this._color[i][1] * 255)}, ${Math.round(this._color[i][2] * 255)}, ${Math.round(this._color[i][3] * 255)}, 1)`);
}
ctx.fillStyle = color;
ctx.fillRect(0, 0, this._canvas.width, this._canvas.height);
} else {
ctx.lineWidth=2*this._canvas.height;
for (let i=0; i<this._color.length; i++) {
let currentPos = this._color[i][0];
let nextPos = 1;
if (i < this._color.length - 1) {
nextPos = this._color[i+1][0];
}
let previousPos = 0;
if (i > 0) {
previousPos = this._color[i-1][0];
}
let from = previousPos + (currentPos - previousPos)/2;
let to = currentPos + (nextPos - currentPos)/2;
let color = this._color[i];
let opacity = this._opacity[i] ? this._opacity[i][1] : 1;
ctx.beginPath();
ctx.strokeStyle = `rgba( ${Math.round(color[1] * 255)}, ${Math.round(color[2] * 255)}, ${Math.round(color[3] * 255)}, ${opacity})`;
ctx.moveTo(from*this._canvas.width, 0);
ctx.lineTo(to*this._canvas.width, 0);
ctx.stroke();
ctx.closePath();
}
}
if (!this._discrete) {
// if discrete, we already took care of the opacity.
// setup context
ctx.globalCompositeOperation = 'destination-in';
// apply opacity
let opacity = ctx.createLinearGradient(0, 0, this._canvas.width, this._canvas.height);
for (let i = 0; i < this._opacity.length; i++) {
opacity.addColorStop(this._opacity[i][0], 'rgba(255, 255, 255, ' + this._opacity[i][1] + ')');
}
ctx.fillStyle = opacity;
ctx.fillRect(0, 0, this._canvas.width, this._canvas.height);
}
}
get texture() {
let texture = new THREE.Texture(this._canvas);
texture.mapping = THREE.UVMapping;
texture.wrapS = texture.wrapT = THREE.ClampToEdgeWrapping;
texture.magFilter = texture.minFilter = THREE.NearestFilter;
texture.premultiplyAlpha = true;
texture.needsUpdate = true;
return texture;
}
set lut(targetLUT) {
this._color = this._luts[targetLUT];
this._lut = targetLUT;
this.paintCanvas();
}
get lut() {
return this._lut;
}
set luts(newLuts) {
this._luts = newLuts;
}
get luts() {
return this._luts;
}
set lutO(targetLUTO) {
this._opacity = this._lutsO[targetLUTO];
this._lutO = targetLUTO;
this.paintCanvas();
}
get lutO() {
return this._lutO;
}
set lutsO(newLutsO) {
this._lutsO = newLutsO;
}
get lutsO() {
return this._lutsO;
}
set discrete(discrete) {
this._discrete = discrete;
this.paintCanvas();
}
get discrete() {
return this._discrete;
}
lutsAvailable(type = 'color') {
let available = [];
let luts = this._luts;
if (type !== 'color') {
luts = this._lutsO;
}
for (let i in luts) {
available.push(i);
}
return available;
}
// add luts to class' lut (so a user can add its own as well)
static presetLuts() {
return {
'default': [[0, 0, 0, 0], [1, 1, 1, 1]],
'spectrum': [[0, 0, 0, 0], [0.1, 0, 0, 1], [0.33, 0, 1, 1], [0.5, 0, 1, 0], [0.66, 1, 1, 0], [0.9, 1, 0, 0], [1, 1, 1, 1]],
'hot_and_cold': [[0, 0, 0, 1], [0.15, 0, 1, 1], [0.3, 0, 1, 0], [0.45, 0, 0, 0], [0.5, 0, 0, 0], [0.55, 0, 0, 0], [0.7, 1, 1, 0], [0.85, 1, 0, 0], [1, 1, 1, 1]],
'gold': [[0, 0, 0, 0], [0.13, 0.19, 0.03, 0], [0.25, 0.39, 0.12, 0], [0.38, 0.59, 0.26, 0], [0.50, 0.80, 0.46, 0.08], [0.63, 0.99, 0.71, 0.21], [0.75, 0.99, 0.88, 0.34], [0.88, 0.99, 0.99, 0.48], [1, 0.90, 0.95, 0.61]],
'red': [[0, 0.75, 0, 0], [0.5, 1, 0.5, 0], [0.95, 1, 1, 0], [1, 1, 1, 1]],
'green': [[0, 0, 0.75, 0], [0.5, 0.5, 1, 0], [0.95, 1, 1, 0], [1, 1, 1, 1]],
'blue': [[0, 0, 0, 1], [0.5, 0, 0.5, 1], [0.95, 0, 1, 1], [1, 1, 1, 1]],
'walking_dead': [[0, 0.1, 1, 1], [1, 1, 1, 1]],
'random': [[0, 0, 0, 0], [0.27, 0.18, 0.18, 0.18], [0.41, 1, 1, 1], [0.7, 1, 0, 0], [1, 1, 1, 1]],
};
}
static presetLutsO() {
return {
'linear': [[0, 0], [1, 1]],
'lowpass': [[0, 0.8], [0.2, 0.6], [0.3, 0.1], [1, 0]],
'bandpass': [[0, 0], [0.4, 0.8], [0.6, 0.8], [1, 0]],
'highpass': [[0, 0], [0.7, 0.1], [0.8, 0.6], [1, 0.8]],
'flat': [[0, .7], [1, 1]],
'random': [[0, 0.], [0.38, 0.], [0.55, 1.], [0.72, 1.], [1, 0.05]],
};
}
}
|
var express = require('express'),
fs = require('fs'),
app = express(),
lessMiddleware = require('less-middleware'),
_ = require('underscore')
assert = require('assert'),
path = require('path'),
regexp = require('node-regexp'),
morgan = require('morgan');
//Require config.js, check config.js for minimal configuration.
var config = require('./config.js');
var checkDrives = /([A-Za-z]):.*/;
// Development Only
// Log format : 'tiny' , 'short', 'dev' (colored), 'common', 'combined' (Apache)
if ( 'development' == app.get('env') ) {
app.use( morgan('dev') );
}
//Middle ware are called in order , so lessMiddleWare is called before express.static.
//For adding more security write your own middleware before static.
//User static file serving middleware.
app.use(lessMiddleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
//Set template engine to jade.
app.set('views', path.join(__dirname, '/public/templates'));
app.set('view engine', 'jade');
var port = process.env.PORT || config.port || 1080;
app.listen(port,function(err) {
if(err) console.log(err);
console.log('Listening on ' + port);
});
//Handle request on '/'
app.get('/',function(req,res){
if(req.query.dir != null) {
//badwords check, edit config.js to edit the list of badwords.
for(word in config.badWords) {
var badWordRegex = regexp();
badWordRegex.must(config.badWords[word]);
badWordRegex = badWordRegex.toRegExp();
}
}
//general checks on dir and badwords and if the user is trying to access drives like "/?dir=C:\" etc.
if(req.query.dir == null || req.query.dir == "" || req.query.dir.match(badWordRegex) || req.query.dir.match(checkDrives)) {
fs.readdir('./',function(err,files){
if(err) res.end(err.toString());
var filesInfoObj = [];
if(files.length != 0) {
for (var fileIndex in files) {
var stats = fs.statSync('./' + files[fileIndex]);
if(stats != undefined) {
var fileObj = {};
fileObj.path = files[fileIndex];
fileObj.isFile = stats.isFile();
fileObj.isDirectory = stats.isDirectory();
filesInfoObj.push(fileObj);
}
}
}
//Replace last called thingy.
var uppath = "./";
//Render jade page.
res.render('index', {pageTitle : config.pageTitle,
filesObj : filesInfoObj,
path : req.path + '?dir=.',
currentPath : req.query.dir != undefined ? req.query.dir : './',
upPath : uppath
});
});
}
else {
var requestFile;
if(req.query.isFile != undefined )
requestFile = JSON.parse(req.query.isFile);
if(requestFile) {
var fileName = req.query.dir.split("/")[req.query.dir.split("/").length - 1];
fileName = fileName.split("\\")[fileName.split("\\").length - 1];
var extension = fileName.split(".")[fileName.split(".").length - 1];
var deepFileExtensionCheck = false;
//Deep File Extension check.
if(extension.length == 0 || fileName == extension) {
deepFileExtensionCheck = true;
}
else {
for(ext in config.fileMatch) {
if(extension.match(regexp().end(config.fileMatch[ext]).toRegExp())) {
deepFileExtensionCheck = true;
}
}
}
if(deepFileExtensionCheck) {
fs.readFile(req.query.dir,'utf-8',function(err,file) {
if(err) res.end(JSON.stringify(err));
//change \r\n to <br> (linebreaks) maybe later we can switch to http://hilite.me/
//TODO : port http://hilite.me/api to node.js
file = file.replace(/\n?\r\n/g, '<br />' );
var uupath = req.originalUrl.replace(req.query.dir.split("/")[req.query.dir.split("/").length - 1],"");
var upath = uupath.substring(0,uupath.lastIndexOf('/'));
res.render('index', {pageTitle : config.pageTitle,
file : file,
path : req.path,
currentPath : req.query.dir != undefined ? req.query.dir : './',
upPath : upath
});
});
}
else {
res.end('Error, File extension mismatch');
}
}
else {
fs.readdir(req.query.dir,function(err,files){
if(err) res.end(err.toString());
var filesInfoObj = [];
if(files.length != 0) {
for (var fileIndex in files) {
var stats = fs.statSync(req.query.dir + '\\' + files[fileIndex]);
if(stats != undefined) {
var fileObj = {};
fileObj.path = files[fileIndex];
fileObj.isFile = stats.isFile();
fileObj.isDirectory = stats.isDirectory();
filesInfoObj.push(fileObj);
}
}
}
var uupath = req.originalUrl.replace(req.query.dir.split("/")[req.query.dir.split("/").length - 1],"");
var upath = uupath.substring(0,uupath.lastIndexOf('/'));
res.render('index', {pageTitle : config.pageTitle,
path : req.path,
currentPath : req.query.dir != undefined ? req.query.dir : './',
filesObj : filesInfoObj,
upPath : upath
});
});
}
}
});
|
(function() {
var jisp, compile;
jisp = require("./jisp");
jisp.require = require;
compile = jisp.compile;
jisp.eval = (function(code, options) {
if ((typeof options === 'undefined')) options = {};
options.wrap = false;
return eval(compile(code, options));
});
jisp.run = (function(code, options) {
var compiled;
if ((typeof options === 'undefined')) options = {};
options.wrap = false;
compiled = compile(code, options);
return Function(compile(code, options))();
});
if ((typeof window === 'undefined')) return;
jisp.load = (function(url, callback, options, hold) {
var xhr;
if ((typeof options === 'undefined')) options = {};
if ((typeof hold === 'undefined')) hold = false;
options.sourceFiles = [url];
xhr = (window.ActiveXObject ? new window.ActiveXObject("Microsoft.XMLHTTP") : new window.XMLHttpRequest());
xhr.open("GET", url, true);
if (("overrideMimeType" in xhr)) xhr.overrideMimeType("text/plain");
xhr.onreadystatechange = (function() {
var param;
if ((xhr.readyState === 4)) {
if ((xhr.status === 0 || xhr.status === 200)) {
param = [xhr.responseText, options];
if (!hold) jisp.run.apply(jisp, [].concat(param));
} else {
throw new Error(("Could not load " + url));
}
}
return (callback ? callback(param) : undefined);
});
return xhr.send(null);
});
function runScripts() {
var scripts, jisps, index, s, i, script, _i, _ref, _len, _ref0, _len0;
scripts = window.document.getElementsByTagName("script");
jisps = [];
index = 0;
_ref = scripts;
for (_i = 0, _len = _ref.length; _i < _len; ++_i) {
s = _ref[_i];
if ((s.type === "text/jisp")) jisps.push(s);
}
function execute() {
var param, _ref0;
param = jisps[index];
if ((param instanceof Array)) {
jisp.run.apply(jisp, [].concat(param));
++index;
_ref0 = execute();
} else {
_ref0 = undefined;
}
return _ref0;
}
execute;
_ref0 = jisps;
for (i = 0, _len0 = _ref0.length; i < _len0; ++i) {
script = _ref0[i];
(function(script, i) {
var options, _ref1;
options = {};
if (script.src) {
_ref1 = jisp.load(script.src, (function(param) {
jisps[i] = param;
return execute();
}), options, true);
} else {
options.sourceFiles = ["embedded"];
_ref1 = (jisps[i] = [script.innerHTML, options]);
}
return _ref1;
})(script, i);
}
return execute();
}
runScripts;
return window.addEventListener ? window.addEventListener("DOMContentLoaded", runScripts, false) : window.attachEvent("onload", runScripts);
})['call'](this); |
steal(function( steal ) {
var comments = /\/\*.*?\*\//g,
newLines = /\n*/g,
space = /[ ]+/g,
spaceChars = /\s?([;:{},+>])\s?/g,
lastSemi = /;}/g;
steal.cssMin = function( css ) {
//remove comments
return css.replace(comments, "").replace(newLines, "").replace(space, " ").replace(spaceChars, '$1').replace(lastSemi, '}')
}
}) |
/**
* Fix most common html formatting misbehaviors of browsers implementation when inserting
* content via copy & paste contentEditable
*
* @author Christopher Blum
*/
import dom from "../dom";
var cleanPastedHTML = (function() {
// TODO: We probably need more rules here
var defaultRules = {
// When pasting underlined links <a> into a contentEditable, IE thinks, it has to insert <u> to keep the styling
"a u": dom.replaceWithChildNodes
};
function cleanPastedHTML(elementOrHtml, rules, context) {
rules = rules || defaultRules;
context = context || elementOrHtml.ownerDocument || document;
var element,
isString = typeof(elementOrHtml) === "string",
method,
matches,
matchesLength,
i,
j = 0;
if (isString) {
element = dom.getAsDom(elementOrHtml, context);
} else {
element = elementOrHtml;
}
for (i in rules) {
matches = element.querySelectorAll(i);
method = rules[i];
matchesLength = matches.length;
for (; j<matchesLength; j++) {
method(matches[j]);
}
}
matches = elementOrHtml = rules = null;
return isString ? element.innerHTML : element;
}
return cleanPastedHTML;
})();
export { cleanPastedHTML }; |
import { mount } from '@vue/test-utils';
import Index from '../../views/DeviceIndex';
import { makeAvailableChannelsPageStore } from '../../../test/utils/makeStore';
import router from '../../../test/views/testRouter';
function makeWrapper() {
const wrapper = mount(Index, {
store: makeAvailableChannelsPageStore(),
...router,
});
const els = {
CoreBase: () => wrapper.findComponent({ name: 'CoreBase' }),
};
return { wrapper, els };
}
describe('DeviceIndex component', () => {
it('CoreBase is immersive when at the SELECT_CONTENT page', async () => {
const { wrapper, els } = makeWrapper();
await wrapper.vm.$router.push({ name: 'SELECT_CONTENT' });
expect(els.CoreBase().props().immersivePage).toEqual(true);
});
it('CoreBase is immersive when at the AVAILABLE_CHANNELS page', async () => {
const { wrapper, els } = makeWrapper();
await wrapper.vm.$router.push({ name: 'AVAILABLE_CHANNELS' });
expect(els.CoreBase().props().immersivePage).toEqual(true);
});
});
|
/*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
(function() {
var scope = window.PolymerLoader = {};
var flags = {};
// convert url arguments to flags
if (!flags.noOpts) {
location.search.slice(1).split('&').forEach(function(o) {
o = o.split('=');
o[0] && (flags[o[0]] = o[1] || true);
});
}
// process global logFlags
parseLogFlags(flags);
function load(scopeName) {
// imports
var scope = window[scopeName];
var entryPointName = scope.entryPointName;
var processFlags = scope.processFlags;
// acquire attributes and base path from entry point
var entryPoint = findScript(entryPointName);
var base = entryPoint.basePath;
// acquire common flags
var flags = scope.flags;
// convert attributes to flags
var flags = PolymerLoader.flags;
for (var i=0, a; (a=entryPoint.attributes[i]); i++) {
if (a.name !== 'src') {
flags[a.name] = a.value || true;
}
}
// parse log flags into global
parseLogFlags(flags);
// exports
scope.basePath = base;
scope.flags = flags;
// process flags for dynamic dependencies
if (processFlags) {
processFlags.call(scope, flags);
}
// post-process imports
var modules = scope.modules || [];
var sheets = scope.sheets || [];
// write script tags for dependencies
modules.forEach(function(src) {
document.write('<script src="' + base + src + '"></script>');
});
// write link tags for styles
sheets.forEach(function(src) {
document.write('<link rel="stylesheet" href="' + base + src + '">');
});
}
// utility method
function findScript(fileName) {
var script = document.querySelector('script[src*="' + fileName + '"]');
var src = script.attributes.src.value;
script.basePath = src.slice(0, src.indexOf(fileName));
return script;
}
function parseLogFlags(flags) {
var logFlags = window.logFlags = window.logFlags || {};
if (flags.log) {
flags.log.split(',').forEach(function(f) {
logFlags[f] = true;
});
}
}
scope.flags = flags;
scope.load = load;
})();
|
/**
* @license
* Copyright 2017 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var tsutils_1 = require("tsutils");
var ts = require("typescript");
var Lint = require("../index");
var OPTION_SINGLE_CONCAT = "allow-single-concat";
var Rule = (function (_super) {
__extends(Rule, _super);
function Rule() {
return _super !== null && _super.apply(this, arguments) || this;
}
Rule.prototype.apply = function (sourceFile) {
if (sourceFile.isDeclarationFile) {
return []; // Not possible in a declaration file
}
var allowSingleConcat = this.getOptions().ruleArguments.indexOf(OPTION_SINGLE_CONCAT) !== -1;
return this.applyWithFunction(sourceFile, function (ctx) { return walk(ctx, allowSingleConcat); });
};
return Rule;
}(Lint.Rules.AbstractRule));
/* tslint:disable:object-literal-sort-keys */
Rule.metadata = {
ruleName: "prefer-template",
description: "Prefer a template expression over string literal concatenation.",
optionsDescription: (_a = ["\n If `", "` is specified, then a single concatenation (`x + y`) is allowed, but not more (`x + y + z`)."], _a.raw = ["\n If \\`", "\\` is specified, then a single concatenation (\\`x + y\\`) is allowed, but not more (\\`x + y + z\\`)."], Lint.Utils.dedent(_a, OPTION_SINGLE_CONCAT)),
options: {
type: "string",
enum: [OPTION_SINGLE_CONCAT],
},
optionExamples: ["true", "[true, \"" + OPTION_SINGLE_CONCAT + "\"]"],
type: "style",
typescriptOnly: false,
};
/* tslint:enable:object-literal-sort-keys */
Rule.FAILURE_STRING = "Use a template literal instead of concatenating with a string literal.";
Rule.FAILURE_STRING_MULTILINE = "Use a multiline template literal instead of concatenating string literals with newlines.";
exports.Rule = Rule;
function walk(ctx, allowSingleConcat) {
return ts.forEachChild(ctx.sourceFile, function cb(node) {
var failure = getError(node, allowSingleConcat);
if (failure) {
ctx.addFailureAtNode(node, failure);
}
else {
return ts.forEachChild(node, cb);
}
});
}
function getError(node, allowSingleConcat) {
if (!isPlusExpression(node)) {
return undefined;
}
var left = node.left, right = node.right;
var l = isStringLike(left);
var r = isStringLike(right);
if (l && r) {
// They're both strings.
// If they're joined by a newline, recommend a template expression instead.
// Otherwise ignore. ("a" + "b", probably writing a long newline-less string on many lines.)
return containsNewline(left) || containsNewline(right) ? Rule.FAILURE_STRING_MULTILINE : undefined;
}
else if (!l && !r) {
// Watch out for `"a" + b + c`.
return containsAnyStringLiterals(left) ? Rule.FAILURE_STRING : undefined;
}
else if (l) {
// `"x" + y`
return !allowSingleConcat ? Rule.FAILURE_STRING : undefined;
}
else {
// `? + "b"`
return !allowSingleConcat || isPlusExpression(left) ? Rule.FAILURE_STRING : undefined;
}
}
function containsNewline(node) {
if (node.kind === ts.SyntaxKind.TemplateExpression) {
return node.templateSpans.some(function (_a) {
var text = _a.literal.text;
return text.includes("\n");
});
}
else {
return node.text.includes("\n");
}
}
function containsAnyStringLiterals(node) {
if (!isPlusExpression(node)) {
return false;
}
var left = node.left, right = node.right;
return isStringLike(right) || isStringLike(left) || containsAnyStringLiterals(left);
}
function isPlusExpression(node) {
return tsutils_1.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken;
}
function isStringLike(node) {
switch (node.kind) {
case ts.SyntaxKind.StringLiteral:
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
case ts.SyntaxKind.TemplateExpression:
return true;
default:
return false;
}
}
var _a;
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let InsertInvitation = props =>
<SvgIcon {...props}>
<path d="M17 12h-5v5h5v-5zM16 1v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-1V1h-2zm3 18H5V8h14v11z" />
</SvgIcon>;
InsertInvitation = pure(InsertInvitation);
InsertInvitation.muiName = 'SvgIcon';
export default InsertInvitation;
|
//Here's an example of a customize LESS task -- this compiles the files using the private_connect.less / private_config.less setup, rather than the default.
module.exports = {
development: {
options: {
paths: "<%= _lessPaths %>",
cleancss: false,
dumpLineNumbers: "comments"
},
files: {
"<%= _css %>main.css": "<%= _privateless %>private_connect.less",
}
},
production: {
options: {
paths: "<%= _lessPaths %>",
cleancss: true
},
files: {
"<%= _css %>main.min.css": "<%= _privateless %>private_connect.less",
}
}
};
|
/* eslint max-nested-callbacks: 0, no-console: 0 */
'use strict';
var assert = require('assert'),
fs = require('fs'),
Imbo = require('../../'),
path = require('path'),
request = require('request');
var fixtures = path.join(__dirname, '..', 'fixtures'),
imageId = /^[A-Za-z0-9_-]{1,255}$/,
catMd5 = '61da9892205a0d5077a353eb3487e8c8';
var stcUrl = 'http://127.0.0.1:6775',
runIntegrationTests = parseInt(process.env.IMBOCLIENT_RUN_INTEGRATION_TESTS, 10),
describeIntegration = (runIntegrationTests ? describe : describe.skip),
imboHost = process.env.IMBOCLIENT_INTEGRATION_HOST || 'http://127.0.0.1:9012',
imboUser = process.env.IMBOCLIENT_INTEGRATION_USER || 'test',
imboPubKey = process.env.IMBOCLIENT_INTEGRATION_PUBKEY || 'test',
imboPrivKey = process.env.IMBOCLIENT_INTEGRATION_PRIVKEY || 'test',
imageIdentifiers,
stcServer,
errServer,
client,
errClient;
describeIntegration('ImboClient (integration)', function() {
this.timeout(5000);
before(function(done) {
errClient = new Imbo.Client('http://127.0.0.1:6776', 'pub', 'priv');
errServer = require('../servers').createResetServer();
stcServer = require('../servers').createStaticServer();
var options = {
hosts: [imboHost],
user: imboUser,
publicKey: imboPubKey,
privateKey: imboPrivKey
};
client = new Imbo.Client(options);
client.getUserInfo(function(err) {
if (err) {
console.error('\nDouble check host, user and public/private keys:');
console.error(options);
throw err;
}
done();
});
});
beforeEach(function() {
imageIdentifiers = [];
});
afterEach(function(done) {
var remaining = imageIdentifiers.length;
if (remaining === 0) {
return setImmediate(done);
}
imageIdentifiers.forEach(function(identifier) {
client.deleteImage(identifier, function() {
if (--remaining === 0) {
done();
}
});
});
});
after(function(done) {
stcServer.close(function() {
errServer.close(done);
});
});
describe('#addImage', function() {
it('should return error if the local image does not exist', function(done) {
var filename = fixtures + '/does-not-exist.jpg';
client.addImage(filename, function(err) {
assert.ok(err, 'addImage should give error if file does not exist');
assert.equal(err.code, 'ENOENT');
done();
});
});
it('should return an error if the image could not be added', function(done) {
client.addImage(fixtures + '/invalid.png', function(err) {
assert(err);
assert(err.message.match(/\b415\b/));
done();
});
});
it('should return an error if the server could not be reached', function(done) {
errClient.addImage(fixtures + '/cat.jpg', function(err) {
assert.ok(err, 'addImage should give error if host is unreachable');
done();
});
});
it('should return an image identifier and an http-response on success', function(done) {
client.addImage(fixtures + '/cat.jpg', function(err, imageIdentifier, body, response) {
assert.ifError(err);
assert(imageId.test(imageIdentifier));
assert.equal(body.imageIdentifier, imageIdentifier);
assert.equal(body.extension, 'jpg');
assert.equal(response.statusCode, 201);
imageIdentifiers.push(imageIdentifier);
done();
});
});
});
describe('#addImageFromUrl', function() {
it('should return an error if the server could not be reached', function(done) {
errClient.addImageFromUrl(stcUrl + '/cat.jpg', function(err) {
assert.ok(err, 'addImageFromUrl should give error if host is unreachable');
done();
});
});
it('should return an image identifier and an http-response on success', function(done) {
client.addImageFromUrl(stcUrl + '/cat.jpg', function(err, imageIdentifier, body, response) {
assert.ifError(err);
assert(imageId.test(imageIdentifier));
assert.equal('jpg', body.extension);
assert.equal(201, response.statusCode);
imageIdentifiers.push(imageIdentifier);
done();
});
});
});
describe('#addImageFromBuffer', function() {
it('should return an error if the server could not be reached', function(done) {
var buffer = fs.readFileSync(fixtures + '/cat.jpg');
errClient.addImageFromBuffer(buffer, function(err) {
assert.ok(err, 'addImageFromBuffer should give error if host is unreachable');
done();
});
});
it('should return an image identifier and an http-response on success', function(done) {
var buffer = fs.readFileSync(fixtures + '/cat.jpg');
client.addImageFromBuffer(buffer, function(err, imageIdentifier, body, response) {
assert.ifError(err);
assert(imageId.test(imageIdentifier));
assert.equal('jpg', body.extension);
assert.equal(201, response.statusCode);
imageIdentifiers.push(imageIdentifier);
done();
});
});
});
describe('#getServerStatus()', function() {
it('should not return an error on a 200-response', function(done) {
client.getServerStatus(function(err) {
assert.ifError(err, 'getServerStatus should not give an error on success');
done();
});
});
it('should convert "date" key to a Date instance', function(done) {
client.getServerStatus(function(err, info, res) {
assert.ifError(err, 'getServerStatus should not give an error on success');
assert.ok(info.date instanceof Date);
assert.equal(200, res.statusCode);
done();
});
});
it('should add status code to info object', function(done) {
client.getServerStatus(function(err, info) {
assert.ifError(err, 'getServerStatus should not give an error on success');
assert.equal(200, info.status);
done();
});
});
});
describe('#getNumImages', function() {
it('should return a number on success', function(done) {
client.getNumImages(function(err, numImages) {
assert.ifError(err, 'getNumImages() should not give an error on success');
assert.ok(!isNaN(numImages));
done();
});
});
});
describe('#parseImageUrl()', function() {
it('should be able to parse and modify existing url', function(done) {
client.addImage(fixtures + '/cat.jpg', function(err, imageIdentifier) {
assert.ifError(err);
var url = client.getImageUrl(imageIdentifier).flipHorizontally();
var modUrl = client.parseImageUrl(url.toString()).sepia().png();
request.head(modUrl.toString(), function(headErr, res) {
assert.ifError(headErr);
assert.equal(200, res.statusCode);
assert.equal('image/png', res.headers['content-type']);
done();
});
imageIdentifiers.push(imageIdentifier);
});
});
});
describe('#getShortUrl()', function() {
it('should be able to get a short url for a transformed image', function(done) {
client.addImage(fixtures + '/cat.jpg', function(err, imageIdentifier) {
assert.ifError(err);
var url = client.getImageUrl(imageIdentifier).flipHorizontally();
client.getShortUrl(url, function(shortUrlErr, shortUrl) {
assert.ifError(shortUrlErr);
assert.ifError(err, 'getShortUrl should not give an error when getting short url');
assert.ok(shortUrl.toString().indexOf(imboHost) === 0, 'short url should contain imbo host');
assert.ok(shortUrl.toString().match(/\/s\/[a-zA-Z0-9]{7}$/));
done();
});
imageIdentifiers.push(imageIdentifier);
});
});
it('should be able to get a short url that works', function(done) {
client.addImage(fixtures + '/cat.jpg', function(err, imageIdentifier) {
assert.ifError(err);
var url = client.getImageUrl(imageIdentifier).sepia().png();
client.getShortUrl(url, function(shortUrlErr, shortUrl) {
assert.ifError(shortUrlErr);
request.head(shortUrl.toString(), function(headErr, res) {
assert.ifError(headErr);
assert.equal(200, res.statusCode);
assert.equal('image/png', res.headers['content-type']);
done();
});
});
imageIdentifiers.push(imageIdentifier);
});
});
});
describe('#deleteAllShortUrlsForImage()', function() {
it('should return error on backend failure', function(done) {
errClient.deleteAllShortUrlsForImage(catMd5, function(err) {
assert.ok(err, 'deleteAllShortUrlsForImage should give error if host is unreachable');
done();
});
});
it('should delete all short URLs currently present', function(done) {
client.addImage(fixtures + '/cat.jpg', function(err, imageIdentifier) {
assert.ifError(err);
imageIdentifiers.push(imageIdentifier);
var url = client.getImageUrl(imageIdentifier).sepia().png();
client.getShortUrl(url, function(shortUrlErr, shortUrl) {
assert.ifError(shortUrlErr);
request.head(shortUrl.toString(), function(headErr, res) {
assert.ifError(headErr, 'HEAD-request against shortUrl should not give an error');
assert.equal(200, res.statusCode, 'After generating the ShortUrl, it should exist');
assert.equal('image/png', res.headers['content-type']);
client.deleteAllShortUrlsForImage(imageIdentifier, function(deleteErr) {
assert.ifError(deleteErr, 'deleteAllShortUrlsForImage() should not give an error on success');
request.head(shortUrl.toString(), function(headErr2, secondRes) {
var msg = 'After deleting all ShortUrls, it should no longer exist';
msg += '(expected 404, got ' + secondRes.statusCode + ') - ';
msg += 'HEAD ' + shortUrl.toString();
assert.equal(404, secondRes.statusCode, msg);
done();
});
});
});
});
});
});
});
describe('#deleteShortUrlForImage', function() {
it('should delete the provided ShortUrl', function(done) {
// Add the image
client.addImage(fixtures + '/cat.jpg', function(err, imageIdentifier) {
assert.ifError(err);
imageIdentifiers.push(imageIdentifier);
var url = client.getImageUrl(imageIdentifier).desaturate().jpg();
// Generate a short-url
client.getShortUrl(url, function(shortUrlErr, shortUrl) {
assert.ifError(shortUrlErr);
// Verify that the short-url works
request.head(shortUrl.toString(), function(headErr, res) {
assert.ifError(headErr);
assert.equal(200, res.statusCode, 'After generating the ShortUrl, it should exist');
assert.equal('image/jpeg', res.headers['content-type']);
// Delete the short-url
client.deleteShortUrlForImage(imageIdentifier, shortUrl.getId(), function(deleteErr) {
assert.ifError(deleteErr, 'deleteShortUrlForImage() should not give an error on success');
// Verify that the short-url has been deleted
request.head(shortUrl.toString(), function(headErr2, secondRes) {
var msg = 'After deleting the ShortUrl, it should no longer exist';
msg += '(expected 404, got ' + secondRes.statusCode + ') - ';
msg += 'HEAD ' + shortUrl.toString();
assert.equal(404, secondRes.statusCode, msg);
done();
});
});
});
});
});
});
});
describe('#getImageData', function() {
it('should return a buffer on success', function(done) {
var expectedBuffer = fs.readFileSync(fixtures + '/cat.jpg');
client.addImageFromBuffer(expectedBuffer, function(err, imageIdentifier) {
assert.ifError(err);
imageIdentifiers.push(imageIdentifier);
client.getImageData(imageIdentifier, function(imgDataErr, data) {
assert.ifError(imgDataErr, 'getImageData() should not give an error on success');
assert.equal(expectedBuffer.length, data.length);
done();
});
});
});
it('should return an error if the image does not exist', function(done) {
client.getImageData('f00baa', function(err) {
assert(err);
assert(err.message.match(/\b404\b/));
done();
});
});
});
describe('#getImageChecksumFromBuffer()', function() {
it('should get the right md5-sum for a buffer', function(done) {
var buffer = fs.readFileSync(fixtures + '/cat.jpg');
client.getImageChecksumFromBuffer(buffer, function(err, checksum) {
assert.ifError(err, 'getImageChecksumFromBuffer() should not give an error on success');
assert.equal(catMd5, checksum);
done();
});
});
});
describe('#headImage()', function() {
it('should return error on a 404-response', function(done) {
client.headImage('foobar', function(err) {
assert(err);
assert(err.message.match(/\b404\b/));
done();
});
});
it('should not return an error on a 200-response', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
client.headImage(imageIdentifier, function(err) {
assert.ifError(err, 'headImage should not give an error on success');
done();
});
});
});
it('should return an http-response on success', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
client.headImage(imageIdentifier, function(err, res) {
assert.ifError(err);
assert.equal(res.headers['x-imbo-imageidentifier'], imageIdentifier);
done();
});
});
});
it('should return error when host could not be reached', function(done) {
this.timeout(10000);
errClient.headImage(catMd5, function(err) {
assert.ok(err, 'headImage should give error if host is unreachable');
done();
});
});
});
describe('#getImageProperties', function() {
it('should return an object on success', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
client.getImageProperties(imageIdentifier, function(err, props) {
assert.ifError(err, 'getImageProperties() should not give an error on success');
assert.equal(450, props.width);
assert.equal(320, props.height);
assert.equal(23861, props.filesize);
assert.equal('jpg', props.extension);
assert.equal('image/jpeg', props.mimetype);
done();
});
});
});
it('should return an error if the image does not exist', function(done) {
client.getImageProperties('non-existant', function(err) {
assert(err);
assert(err.message.match(/\b404\b/));
done();
});
});
});
describe('#deleteImage', function() {
it('should return an http-response on success', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
client.deleteImage(imageIdentifier, function(err, res) {
assert.ifError(err);
assert.equal(res.headers['x-imbo-imageidentifier'], imageIdentifier);
done();
});
});
});
});
describe('#imageIdentifierExists', function() {
it('should return false if the identifier does not exist', function(done) {
client.imageIdentifierExists('foobar', function(err, exists) {
assert.ifError(err, 'imageIdentifierExists should not fail when image does not exist on server');
assert.equal(false, exists);
done();
});
});
it('should return true if the identifier exists', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
client.imageIdentifierExists(imageIdentifier, function(err, exists) {
assert.ifError(err, 'Image that exists should not give an error');
assert.equal(true, exists);
done();
});
});
});
it('should return an error if the server could not be reached', function(done) {
errClient.imageIdentifierExists(catMd5, function(err) {
assert.ok(err, 'imageIdentifierExists should give error if host is unreachable');
done();
});
});
});
describe('#imageExists', function() {
it('should return error if the local image does not exist', function(done) {
var filename = fixtures + '/non-existant.jpg';
client.imageExists(filename, function(err) {
assert.equal('File does not exist (' + filename + ')', err);
done();
});
});
it('should return true if the image exists on disk and on server', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
client.imageExists(fixtures + '/cat.jpg', function(err, exists) {
assert.ifError(err, 'imageExists should not give error if image exists on disk and server');
assert.equal(true, exists);
done();
});
});
});
it('should return false if the image exists on disk but not on server', function(done) {
client.imageExists(fixtures + '/cat.jpg', function(err, exists) {
assert.ifError(err, 'imageExists should not give error if the image does not exist on server');
assert.equal(false, exists);
done();
});
});
});
describe('#getUserInfo', function() {
it('should return an object of key => value data', function(done) {
client.getUserInfo(function(err, info, res) {
assert.ifError(err, 'getUserInfo should not give an error on success');
assert.equal(imboUser, info.user);
assert.equal(200, res.statusCode);
done();
});
});
it('should return an error if the user does not exist', function(done) {
var someClient = new Imbo.Client([imboHost], 'AngLAmgALNFAGLKdmgdAGmkl', 'test');
someClient.getUserInfo(function(err, body, res) {
assert(err);
assert(err.message.match(/\b404\b/));
assert.equal(404, res.statusCode);
done();
});
});
});
describe('#getImages', function() {
it('should return an array of image objects', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
client.getImages(function(err, images, search, res) {
assert.ifError(err, 'getImages should not give an error on success');
assert.equal(true, Array.isArray(images));
assert.equal(200, res.statusCode);
done();
});
});
});
it('should return correct search params', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
var query = new Imbo.Query();
query.limit(5).checksums([catMd5]);
client.getImages(query, function(err, images, search, res) {
assert.ifError(err, 'getImages should not give an error on success');
assert.equal(true, Array.isArray(images));
assert.equal(images[0].checksum, catMd5);
assert.equal(5, search.limit);
assert.equal(1, search.hits);
assert.equal(200, res.statusCode);
done();
});
});
});
it('should return no results if unknown id is passed as filter', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
var query = new Imbo.Query();
query.limit(5).originalChecksums(['something']);
client.getImages(query, function(err, images, search, res) {
assert.ifError(err, 'getImages should not give an error on success');
assert.equal(true, Array.isArray(images));
assert.equal(5, search.limit);
assert.equal(0, search.hits);
assert.equal(200, res.statusCode);
done();
});
});
});
it('should only include filtered fields', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
var query = new Imbo.Query();
query
.limit(5)
.ids([imageIdentifier])
.addFields(['imageIdentifier', 'mime'])
.addSort('added', 'desc')
.page(1)
.from(yesterday)
.to(new Date(Date.now() + 10000));
client.getImages(query, function(err, images, search) {
assert.ifError(err, 'getImages should not give an error on success');
assert.equal('undefined', typeof images[0].size);
assert.equal('undefined', typeof images[0].metadata);
assert.equal('undefined', typeof images[0].updated);
assert.equal('image/jpeg', images[0].mime);
assert.equal(imageIdentifier, images[0].imageIdentifier);
assert.equal(1, search.hits);
done();
});
});
});
});
describe('#getMetadata', function() {
it('should return a blank object if no data is present', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
client.deleteMetadata(imageIdentifier, function() {
client.getMetadata(imageIdentifier, function(err, meta, res) {
assert.ifError(err, 'getMetadata should not give error on success');
assert.equal('{}', JSON.stringify(meta));
assert.equal(200, res.statusCode);
done();
});
});
});
});
it('should return a key => value object if data is present', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
client.editMetadata(imageIdentifier, { foo: 'bar' }, function() {
client.getMetadata(imageIdentifier, function(err, meta, res) {
assert.ifError(err, 'getMetadata should not give error on success');
assert.equal('bar', meta.foo);
assert.equal(200, res.statusCode);
done();
});
});
});
});
it('should return an error if the identifier does not exist', function(done) {
client.getMetadata('non-existant', function(err, body, res) {
assert(err);
assert(err.message.match(/\b404\b/));
assert.equal(404, res.statusCode);
done();
});
});
});
describe('#deleteMetadata', function() {
it('should return an error if the identifier does not exist', function(done) {
client.deleteMetadata('non-existant', function(err) {
assert(err);
assert(err.message.match(/\b404\b/));
done();
});
});
it('should not return any error on success', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
client.deleteMetadata(imageIdentifier, function(err) {
assert.ifError(err, 'deleteMetadata should not give error on success');
done();
});
});
});
});
describe('#editMetadata', function() {
it('should return an error if the identifier does not exist', function(done) {
client.editMetadata('non-existant', { foo: 'bar' }, function(err) {
assert(err);
assert(err.message.match(/\b404\b/));
done();
});
});
it('should not return any error on success', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
var metadata = { foo: 'bar', some: 'key' };
client.editMetadata(imageIdentifier, metadata, function(err, body, res) {
assert.ifError(err, 'editMetadata should not give error on success');
assert.equal(200, res.statusCode);
assert.equal('bar', body.foo);
assert.equal('key', body.some);
done();
});
});
});
});
describe('#replaceMetadata', function() {
it('should return an error if the identifier does not exist', function(done) {
client.replaceMetadata('non-existant', { foo: 'bar' }, function(err) {
assert(err);
assert(err.message.match(/\b404\b/));
done();
});
});
it('should not return any error on success', function(done) {
client.addImage(fixtures + '/cat.jpg', function(addErr, imageIdentifier) {
imageIdentifiers.push(imageIdentifier);
var metadata = { foo: 'bar', random: Math.floor(Math.random() * 100000) };
client.replaceMetadata(imageIdentifier, metadata, function(err, body, res) {
assert.ifError(err, 'replaceMetadata should not give error on success');
assert.equal(metadata.foo, body.foo);
assert.equal(metadata.random, body.random);
assert.equal(Object.keys(metadata).length, Object.keys(body).length);
assert.equal(200, res.statusCode);
done();
});
});
});
});
});
|
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var HighlightRules = require("./pml_highlight_rules").HighlightRules;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var FoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.HighlightRules = HighlightRules;
this.foldingRules = new FoldMode();
this.$behaviour = new CstyleBehaviour();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "//";
this.blockComment = {start: "/*", end: "*/", nestable: true};
this.$id = "ace/mode/pml"
}).call(Mode.prototype);
exports.Mode = Mode;
});
|
import baseAssignValue from './baseAssignValue.js'
import eq from '../eq.js'
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq(object[key], value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value)
}
}
export default assignMergeValue
|
"use strict";
const $ = require("jquery");
const socket = require("../socket");
const render = require("../render");
const templates = require("../../views");
const sidebar = $("#sidebar");
const utils = require("../utils");
socket.on("network", function(data) {
render.renderNetworks(data, true);
sidebar.find(".chan")
.last()
.trigger("click");
$("#connect")
.find(".btn")
.prop("disabled", false);
});
socket.on("network_changed", function(data) {
sidebar.find(`.network[data-uuid="${data.network}"]`).data("options", data.serverOptions);
});
socket.on("network:status", function(data) {
sidebar
.find(`.network[data-uuid="${data.network}"]`)
.toggleClass("not-connected", !data.connected)
.toggleClass("not-secure", !data.secure);
});
socket.on("network:info", function(data) {
$("#connect")
.html(templates.windows.connect(data))
.find("form").on("submit", function() {
const uuid = $(this).find("input[name=uuid]").val();
const newName = $(this).find("#connect\\:name").val();
sidebar.find(`.network[data-uuid="${uuid}"] .chan.lobby .name`)
.attr("title", newName)
.text(newName)
.click();
});
utils.togglePasswordField("#connect .reveal-password");
});
|
var chai = require('chai');
var expect = chai.expect;
var http = require('http');
var app = require('../../../server/app');
var Promise = require('bluebird');
var dbUtils = Promise.promisifyAll(require('../../../server/db/dbUtils'));
var config = process.env.DATABASE_TEST_URL || require('../../../server/config/config').testdb.config;
// Promise-returning request with session
var reqAsync = Promise.promisify(require('request').defaults({jar: true}));
describe('apiRouter', function() {
this.timeout(10000);
var instance;
var url = 'http://localhost:'+process.env.PORT+'/';
// Methods that have no params
var getOrgDashboard = {
method: 'GET',
uri: url+'api/orgs/dashboard'
};
var getOrgClient = {
method: 'GET',
uri: url+'api/orgs/client'
};
var clientLogin = {
method: 'POST',
uri: url+'api/client-login'
};
var logOut = {
method: 'POST',
uri: url+'api/logout'
};
before(function(done) {
instance = http.createServer(app).listen(process.env.PORT);
instance.on('listening', function() {
console.log('Listening');
done();
});
});
after(function() {
instance.close();
console.log('Stopped');
});
beforeEach(function() {
var signup = {
method: 'POST',
uri: url+'api/signup',
json: {
first_name: 'Bryan',
last_name: 'Bryan',
email: 'bryan@bry.an',
password: 'bryan'
}
};
var addOrg = {
method: 'POST',
uri: url+'api/orgs/',
json: {
name: 'Bryan\'s',
logo: 'halo.jpg',
welcome_message: 'Bryan\'s Bryan Bryan Bryans Bryanly'
}
};
var addUser = {
method: 'POST',
uri: url+'api/users/',
json: {
first_name: 'Bryan\'s',
last_name: 'Evil Twin',
email: 'bryan@br.yan',
title: 'Or Is This The Good One?'
}
};
return dbUtils.clearDbAsync(config)
.then(function() { return reqAsync(signup); })
.then(function() { return reqAsync(addOrg); })
.then(function() { return reqAsync(addUser); });
});
describe('adds and updates users and organizations', function() {
it('creates an organization', function() {
return reqAsync(getOrgDashboard).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^2\d\d$/); // Success
var orgInfo = JSON.parse(body);
expect(orgInfo.name).to.equal('Bryan\'s');
expect(orgInfo.logo).to.equal('halo.jpg');
expect(orgInfo.admin_id).to.equal(1);
expect(orgInfo.default_id).to.equal(1);
expect(orgInfo.members[1].first_name).to.equal('Bryan\'s');
expect(orgInfo.members[1].last_name).to.equal('Evil Twin');
expect(orgInfo.members[1].password_hash).to.equal(undefined);
});
});
it('adds a user', function() {
var addUser = {
method: 'POST',
uri: url+'api/users/',
json: {
first_name: 'Bryan\'s',
last_name: 'Underling',
email: 'under@ling',
title: 'My Life for Bryan'
}
};
return reqAsync(addUser).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^2\d\d$/); // Success
return reqAsync(getOrgDashboard);
}).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^2\d\d$/); // Success
var orgInfo = JSON.parse(body);
expect(orgInfo.members[2].first_name).to.equal('Bryan\'s');
expect(orgInfo.members[2].last_name).to.equal('Underling');
});
});
it('updates a user', function() {
var updateUser = {
method: 'PUT',
uri: url+'api/users/2',
json: {
last_name: 'Good Twin'
}
};
return reqAsync(updateUser).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^2\d\d$/); // Success
return reqAsync(getOrgDashboard);
}).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^2\d\d$/); // Success
var orgInfo = JSON.parse(body);
expect(orgInfo.members[1].first_name).to.equal('Bryan\'s');
expect(orgInfo.members[1].last_name).to.equal('Good Twin');
});
});
it('updates an organization', function() {
var updateOrg = {
method: 'PUT',
uri: url+'api/orgs/',
json: {
logo: 'pitchfork.jpg',
default_id: '2'
}
};
return reqAsync(updateOrg).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^2\d\d$/); // Success
return reqAsync(getOrgDashboard);
}).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^2\d\d$/); // Success
var orgInfo = JSON.parse(body);
expect(orgInfo.logo).to.equal('pitchfork.jpg');
expect(orgInfo.default_id).to.equal(2);
});
});
it('deletes users', function() {
var deleteUser = {
method: 'DELETE',
uri: url+'api/users/2'
};
return reqAsync(deleteUser).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^2\d\d$/); // Success
return reqAsync(getOrgDashboard);
}).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^2\d\d$/); // Success
var orgInfo = JSON.parse(body);
expect(orgInfo.members.length).to.equal(1);
});
});
});
describe('throws an error if permissions are insufficient', function() {
beforeEach(function() {
return reqAsync(clientLogin);
});
it('errors getting dashboard', function() {
return reqAsync(getOrgDashboard).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^4\d\d$/); // User Error
});
});
it('fails to retrieve sensitive fields', function() {
return reqAsync(getOrgClient).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^2\d\d$/); // Success
var orgInfo = JSON.parse(body);
expect(orgInfo.members[0].last_name).to.equal('Bryan');
expect(orgInfo.members[0].password_hash).to.equal(undefined);
expect(orgInfo.members[0].email).to.equal(undefined);
});
});
});
describe('throws an error if user is logged out', function() {
beforeEach(function() {
return reqAsync(logOut);
});
it('errors getting client', function() {
return reqAsync(getOrgClient).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^4\d\d$/); // User error
});
});
});
describe('throws an error if user is signed into another account', function() {
beforeEach(function() {
var signUp = {
method: 'POST',
uri: url+'api/signup',
json: {
first_name: 'notbryan',
last_name: 'notbryan',
email: 'not@bry.an',
password: 'bryan'
}
};
return reqAsync(signUp);
});
it('errors updating from another account', function() {
var updateUser = {
method: 'PUT',
uri: url+'api/users/1',
json: {
title: 'Not-At-All Evil'
}
};
return reqAsync(updateUser).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^4\d\d$/); // User error
});
});
it('errors if deleting from another account', function() {
var deleteUser = {
method: 'DELETE',
uri: url+'api/users/1'
};
return reqAsync(deleteUser).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^4\d\d$/); // User error
});
});
});
describe('throws an error if requestion illegal operations as admin', function() {
beforeEach(function() {
var signUp = {
method: 'POST',
uri: url+'api/signup',
json: {
first_name: 'notbryan',
last_name: 'notbryan',
email: 'not@bry.an',
password: 'bryan'
}
};
var addOrg = {
method: 'POST',
uri: url+'api/orgs/',
json: {
name: 'Cult of Bryan',
logo: 'rosary.png',
welcome_message: 'All hail Bryan'
}
};
return reqAsync(signUp)
.then(function() { return reqAsync(addOrg); });
});
it('throws an error if updating an unaffiliated user as an org\'s default', function() {
var updateOrg = {
method: 'PUT',
uri: url+'api/orgs/',
json: {
default_id: '1'
}
};
return reqAsync(updateOrg).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^4\d\d$/); // User Error
});
});
it('throws an error if deleting self as admin', function() {
var deleteUser = {
method: 'DELETE',
uri: url+'api/users/3'
};
return reqAsync(deleteUser).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^4\d\d$/); // User error
});
});
it('deletes an organization', function() {
var deleteOrg = {
method: 'DELETE',
uri: url+'api/orgs/'
};
return reqAsync(deleteOrg).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^2\d\d$/); // Success
return reqAsync(getOrgDashboard);
}).spread(function(res, body) {
expect(res.statusCode.toString()).to.match(/^2\d\d$/); // Success
expect(body).to.equal('{}');
});
});
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:73acc7dcebd016c365d096c5bcde9d198e6a7be2fd8842a79a13162a99c59c26
size 5453
|
'use strict';
module.exports = exports = function send(req, res) {
res.send = function(message, type) {
let detectedType;
if (typeof message === 'object') {
detectedType = 'application/json';
message = JSON.stringify(message);
} else if (message.startsWith('<!DOCTYPE html>')) {
detectedType = 'text/html';
} else {
detectedType = 'text/plain';
}
type = type || detectedType;
this.writeHead(200, { 'Content-Type': type });
this.write(message);
this.end();
};
};
|
/**
* Created by chenqiu on 15/12/26.
*/
var math = require("./math");
var parser = math.parser();
module.exports = function(pCur, r, p) {
var M = p.length;
parser.set('pCur', pCur);
parser.set('r', r);
parser.set('S', p);
parser.set('M', M);
parser.eval('rCur = zeros(M)');
parser.eval('h1 = zeros(M - 1)');
parser.eval('pDelta = zeros(M, 3)');
parser.eval('G1 = zeros(M - 1, 3)');
for(var j = 1; j <= M; j++) {
parser.set('j', j);
parser.eval('rCur[j] = norm(pCur - squeeze(S[j, :]))');
}
parser.eval('err = 0');
for(j = 1; j <= M - 1 ; j++) {
parser.set('j', j);
parser.eval('err = err + (r[j] - (rCur[j+1] - rCur[1]))^2 / (M - 1)');
}
parser.eval('err = sqrt(err)');
parser.eval('A = zeros(3, M)');
for(j = 1; j <= M ; j++) {
for(var k = 1; k <= 3 ; k++) {
parser.set('j', j);
parser.set('k', k);
parser.eval('A[k, j] = (pCur[k] - S[j, k]) / rCur[j]');
}
}
parser.eval('GDOP = sqrt(trace(inv(A * transpose(A))))');
parser.eval('errGDOP = err * GDOP');
var err = parser.get('err');
var GDOP = parser.get('GDOP');
var errGDOP = parser.get('errGDOP');
parser.clear();
return { err: err, GDOP: GDOP, errGDOP: errGDOP };
}; |
import { makeOptions, rawSend } from './apiBase/APIRequestUtils';
// import captcha from './apis/captcha';
// import modListing from './apis/modListing';
// import multis from './apis/multis';
// import multiSubscriptions from './apis/multiSubscriptions';
// import reports from './apis/reports';
// import stylesheets from './apis/stylesheets';
// import subredditRelationships from './apis/subredditRelationships';
// import trophies from './apis/trophies';
// import votes from './apis/votes';
// import wiki from './apis/wiki';
// CommentsEndpoint must be imported first followed by PostsEndpoint.
// This is because the PostsEndpoint requires the PostModel which uses the replyable
// mixin which requires the CommentsEndpoint. If they're imported out of order
// endpoints that rely on both Comments and Posts will break in suspicous ways :(
import CommentsEndpoint from './apis/CommentsEndpoint';
import PostsEndpoint from './apis/PostsEndpoint';
import AccountsEndpoint from './apis/accounts';
import ActivitiesEndpoint from './apis/activities';
import EditUserTextEndpoint from './apis/EditUserTextEndpoint';
import HiddenEndpoint from './apis/HiddenEndpoint';
import Modtools from './apis/modTools';
import PreferencesEndpoint from './apis/PreferencesEndpoint';
import RecommendedSubreddits from './apis/RecommendedSubreddits';
import SavedEndpoint from './apis/SavedEndpoint';
import SearchEndpoint from './apis/SearchEndpoint';
import SimilarPosts from './apis/SimilarPosts';
import SubredditAutocomplete from './apis/SubredditAutocomplete';
import subscriptions from './apis/subscriptions';
import SubredditEndpoint from './apis/SubredditEndpoint';
import SubredditsByPost from './apis/SubredditsByPost';
import SubredditRulesEndpoint from './apis/SubredditRulesEndpoint';
import SubredditsToPostsByPost from './apis/SubredditsToPostsByPost';
import WikisEndpoint from './apis/wikis';
import MessagesEndpoint from './apis/MessagesEndpoint';
import { APIResponse, MergedApiReponse } from './apiBase/APIResponse';
import Model from './apiBase/Model';
import Record from './apiBase/Record';
import * as ModelTypes from './models2/thingTypes';
import apiRequest from './apiBase/apiRequest';
import {
withQueryAndResult,
afterResponse,
beforeResponse,
fetchAll,
} from './apiBase/APIResponsePaging';
export const APIResponses = {
APIResponse,
MergedApiReponse,
};
export const APIResponsePaging = {
withQueryAndResult,
afterResponse,
beforeResponse,
fetchAll,
};
export const endpoints = {
// captcha,
// modListing,
// multis,
// multiSubscriptions,
// reports,
// stylesheets,
// subredditRelationships,
// subscriptions,
// trophies,
// votes,
// wiki,
AccountsEndpoint,
ActivitiesEndpoint,
EditUserTextEndpoint,
CommentsEndpoint,
HiddenEndpoint,
Modtools,
PostsEndpoint,
PreferencesEndpoint,
RecommendedSubreddits,
SavedEndpoint,
SearchEndpoint,
SimilarPosts,
subscriptions,
SubredditAutocomplete,
SubredditsByPost,
SubredditRulesEndpoint,
SubredditsToPostsByPost,
SubredditEndpoint,
WikisEndpoint,
MessagesEndpoint,
};
import NoModelError from './apiBase/errors/NoModelError';
import ResponseError from './apiBase/errors/ResponseError';
import { DisconnectedError } from './apiBase/errors/ResponseError';
import ValidationError from './apiBase/errors/ValidationError';
import BadCaptchaError from './apiBase/errors/BadCaptchaError';
import NotImplementedError from './apiBase/errors/NotImplementedError';
export const errors = {
NoModelError,
ValidationError,
ResponseError,
DisconnectedError,
NotImplementedError,
BadCaptchaError,
};
// import Award from './models/award';
// import Base from './models/base';
// import Block from './models/block';
// import BlockedUser from './models/BlockedUser';
// import Message from './models/message';
// import PromoCampaign from './models/promocampaign';
// import Subscription from './models/subscription';
// import Vote from './models/vote';
// import Report from './models/report';
// import WikiPage from './models/wikiPage';
// import WikiRevision from './models/wikiRevision';
// import WikiPageListing from './models/wikiPageListing';
// import WikiPageSettings from './models/wikiPageSettings';
// new models
import Account from './models2/Account';
import CommentModel from './models2/CommentModel';
import PostModel from './models2/PostModel';
import Preferences from './models2/Preferences';
import Subreddit from './models2/Subreddit';
import SubredditRule from './models2/SubredditRule';
import Wiki from './models2/Wiki';
import {
SubscribedSubreddits,
ModeratingSubreddits,
ContributingSubreddits,
} from './collections/SubredditLists';
import CommentsPage from './collections/CommentsPage';
import HiddenPostsAndComments from './collections/HiddenPostsAndComments';
import PostsFromSubreddit from './collections/PostsFromSubreddit';
import SavedPostsAndComments from './collections/SavedPostsAndComments';
import SearchQuery from './collections/SearchQuery';
export const models = {
// Award,
// Base,
// Block,
// BlockedUser,
// Message,
// PromoCampaign,
// Subreddit,
// Subscription,
// Vote,
// Report,
// WikiPage,
// WikiRevision,
// WikiPageListing,
// WikiPageSettings,
Model,
ModelTypes,
Record,
Account,
CommentModel,
PostModel,
Preferences,
Subreddit,
SubredditRule,
Wiki,
};
export const collections = {
CommentsPage,
ContributingSubreddits,
HiddenPostsAndComments,
ModeratingSubreddits,
PostsFromSubreddit,
SavedPostsAndComments,
SearchQuery,
SubscribedSubreddits,
};
const DEFAULT_API_ORIGIN = 'https://www.reddit.com';
const AUTHED_API_ORIGIN = 'https://oauth.reddit.com';
// Webpack 2 has an export bug where a library's export object does not state
// that it is an es6 module. Without this tag defined on the exports object,
// Webpack does not import the library correctly.
export const __esModule = true;
const DefaultOptions = {
origin: DEFAULT_API_ORIGIN,
userAgent: 'snoodev3',
appName: 'snoodev3',
env: process.env.NODE_ENV || 'dev',
};
export default makeOptions(DefaultOptions);
export const requestUtils = {
rawSend,
apiRequest,
};
export const optionsWithAuth = token => {
return {
...DefaultOptions,
token,
origin: token ? AUTHED_API_ORIGIN : DEFAULT_API_ORIGIN,
};
};
|
'use strict';
/**
@module ember-cli
*/
var Promise = require('../ext/promise');
var path = require('path');
var findup = Promise.denodeify(require('findup'));
var resolve = Promise.denodeify(require('resolve'));
var fs = require('fs');
var find = require('lodash/collection/find');
var assign = require('lodash/object/assign');
var forOwn = require('lodash/object/forOwn');
var merge = require('lodash/object/merge');
var debug = require('debug')('ember-cli:project');
var AddonDiscovery = require('../models/addon-discovery');
var AddonsFactory = require('../models/addons-factory');
var Command = require('../models/command');
var UI = require('../ui');
var versionUtils = require('../utilities/version-utils');
var emberCLIVersion = versionUtils.emberCLIVersion;
/**
The Project model is tied to your package.json. It is instiantiated
by giving Project.closest the path to your project.
@class Project
@constructor
@param {String} root Root directory for the project
@param {Object} pkg Contents of package.json
*/
function Project(root, pkg, ui) {
debug('init root: %s', root);
this.root = root;
this.pkg = pkg;
this.ui = ui;
this.addonPackages = {};
this.addons = [];
this.liveReloadFilterPatterns = [];
this.setupBowerDirectory();
this.addonDiscovery = new AddonDiscovery(this.ui);
this.addonsFactory = new AddonsFactory(this, this);
}
/**
Sets the name of the bower directory for this project
@private
@method setupBowerDirectory
*/
Project.prototype.setupBowerDirectory = function() {
var bowerrcPath = path.join(this.root, '.bowerrc');
debug('bowerrc path: %s', bowerrcPath);
if (fs.existsSync(bowerrcPath)) {
var bowerrcContent = fs.readFileSync(bowerrcPath);
try {
this.bowerDirectory = JSON.parse(bowerrcContent).directory;
} catch (exception) {
debug('failed to parse bowerc: %s', exception);
this.bowerDirectory = null;
}
}
this.bowerDirectory = this.bowerDirectory || 'bower_components';
debug('bowerDirectory: %s', this.bowerDirectory);
};
var NULL_PROJECT = new Project(process.cwd(), {});
NULL_PROJECT.isEmberCLIProject = function() {
return false;
};
NULL_PROJECT.isEmberCLIAddon = function() {
return false;
};
NULL_PROJECT.name = function() {
return path.basename(process.cwd());
};
Project.NULL_PROJECT = NULL_PROJECT;
/**
Returns the name from package.json.
@private
@method name
@return {String} Package name
*/
Project.prototype.name = function() {
return this.pkg.name;
};
/**
Returns whether or not this is an Ember CLI project.
This checks whether ember-cli is listed in devDependencies.
@private
@method isEmberCLIProject
@return {Boolean} Whether this is an Ember CLI project
*/
Project.prototype.isEmberCLIProject = function() {
return this.pkg.devDependencies && 'ember-cli' in this.pkg.devDependencies;
};
/**
Returns whether or not this is an Ember CLI addon.
@method isEmberCLIAddon
@return {Boolean} Whether or not this is an Ember CLI Addon.
*/
Project.prototype.isEmberCLIAddon = function() {
return !!this.pkg.keywords && this.pkg.keywords.indexOf('ember-addon') > -1;
};
/**
Returns the path to the configuration.
@private
@method configPath
@return {String} Configuration path
*/
Project.prototype.configPath = function() {
var configPath = 'config';
if (this.pkg['ember-addon'] && this.pkg['ember-addon']['configPath']) {
configPath = this.pkg['ember-addon']['configPath'];
}
return path.join(configPath, 'environment');
};
/**
Loads the configuration for this project and its addons.
@private
@method config
@param {String} env Environment name
@return {Object} Merged confiration object
*/
Project.prototype.config = function(env) {
var configPath = this.configPath();
if (fs.existsSync(path.join(this.root, configPath + '.js'))) {
var appConfig = this.require('./' + configPath)(env);
var addonsConfig = this.getAddonsConfig(env, appConfig);
return merge(addonsConfig, appConfig);
} else {
return this.getAddonsConfig(env, {});
}
};
/**
Returns the addons configuration.
@private
@method getAddonsConfig
@param {String} env Environment name
@param {Object} appConfig Application configuration
@return {Object} Merged configuration of all addons
*/
Project.prototype.getAddonsConfig = function(env, appConfig) {
this.initializeAddons();
var initialConfig = merge({}, appConfig);
return this.addons.reduce(function(config, addon) {
if (addon.config) {
merge(config, addon.config(env, config));
}
return config;
}, initialConfig);
};
/**
Returns whether or not the given file name is present in this project.
@private
@method has
@param {String} file File name
@return {Boolean} Whether or not the file is present
*/
Project.prototype.has = function(file) {
return fs.existsSync(path.join(this.root, file)) || fs.existsSync(path.join(this.root, file + '.js'));
};
/**
Resolves the absolute path to a file.
@private
@method resolve
@param {String} file File to resolve
@return {String} Absolute path to file
*/
Project.prototype.resolve = function(file) {
return resolve(file, {
basedir: this.root
});
};
/**
Calls `require` on a given module.
@private
@method require
@param {String} file File path or module name
@return {Object} Imported module
*/
Project.prototype.require = function(file) {
if (/^\.\//.test(file)) { // Starts with ./
return require(path.join(this.root, file));
} else {
return require(path.join(this.root, 'node_modules', file));
}
};
Project.prototype.emberCLIVersion = emberCLIVersion;
/**
Returns the dependencies from a package.json
@private
@method dependencies
@param {Object} pkg Package object. If false, the current package is used.
@param {Boolean} excludeDevDeps Whether or not development dependencies should be excluded, defaults to false.
@return {Object} Dependencies
*/
Project.prototype.dependencies = function(pkg, excludeDevDeps) {
pkg = pkg || this.pkg || {};
var devDependencies = pkg['devDependencies'];
if (excludeDevDeps) {
devDependencies = {};
}
return assign({}, devDependencies, pkg['dependencies']);
};
/**
Returns the bower dependencies for this project.
@private
@method bowerDependencies
@param {String} bower Path to bower.json
@return {Object} Bower dependencies
*/
Project.prototype.bowerDependencies = function(bower) {
if (!bower) {
var bowerPath = path.join(this.root, 'bower.json');
bower = (fs.existsSync(bowerPath)) ? require(bowerPath) : {};
}
return assign({}, bower['devDependencies'], bower['dependencies']);
};
/**
Provides the list of paths to consult for addons that may be provided
internally to this project. Used for middleware addons with built-in support.
@private
@method supportedInternalAddonPaths
*/
Project.prototype.supportedInternalAddonPaths = function(){
if (!this.root) { return []; }
var internalMiddlewarePath = path.join(this.root, path.relative(this.root, path.join(__dirname, '../tasks/server/middleware')));
return [
path.join(internalMiddlewarePath, 'tests-server'),
path.join(internalMiddlewarePath, 'history-support'),
path.join(internalMiddlewarePath, 'serve-files'),
path.join(internalMiddlewarePath, 'proxy-server')
];
};
/**
Discovers all addons for this project and stores their names and
package.json contents in this.addonPackages as key-value pairs
@private
@method discoverAddons
*/
Project.prototype.discoverAddons = function() {
var addonsList = this.addonDiscovery.discoverProjectAddons(this);
var addonPackages = {};
addonsList.forEach(function(addonPkg) {
addonPackages[addonPkg.name] = addonPkg;
});
this.addonPackages = addonPackages;
};
/**
Loads and initializes all addons for this project.
@private
@method initializeAddons
*/
Project.prototype.initializeAddons = function() {
if (this._addonsInitialized) {
return;
}
this._addonsInitialized = true;
debug('initializeAddons for: %s', this.name());
this.discoverAddons();
this.addons = this.addonsFactory.initializeAddons(this.addonPackages);
this.addons.forEach(function(addon) {
debug('addon: %s', addon.name);
});
};
/**
Returns what commands are made available by addons by inspecting
`includedCommands` for every addon.
@private
@method addonCommands
@return {Object} Addon names and command maps as key-value pairs
*/
Project.prototype.addonCommands = function() {
var commands = {};
this.addons.forEach(function(addon){
var includedCommands = (addon.includedCommands && addon.includedCommands()) || {};
var addonCommands = {};
for (var key in includedCommands) {
if (typeof includedCommands[key] === 'function') {
addonCommands[key] = includedCommands[key];
} else {
addonCommands[key] = Command.extend(includedCommands[key]);
}
}
if(Object.keys(addonCommands).length) {
commands[addon.name] = addonCommands;
}
});
return commands;
};
/**
Execute a given callback for every addon command.
Example:
```
project.eachAddonCommand(function(addonName, commands) {
console.log('Addon ' + addonName + ' exported the following commands:' + commands.keys().join(', '));
});
```
@private
@method eachAddonCommand
@param {Function} callback [description]
*/
Project.prototype.eachAddonCommand = function(callback) {
if (this.initializeAddons && this.addonCommands) {
this.initializeAddons();
var addonCommands = this.addonCommands();
forOwn(addonCommands, function(commands, addonName) {
return callback(addonName, commands);
});
}
};
/**
Path to the blueprints for this project.
@private
@method localBlueprintLookupPath
@return {String} Path to blueprints
*/
Project.prototype.localBlueprintLookupPath = function() {
return path.join(this.root, 'blueprints');
};
/**
Returns a list of paths (including addon paths) where blueprints will be looked up.
@private
@method blueprintLookupPaths
@return {Array} List of paths
*/
Project.prototype.blueprintLookupPaths = function() {
if (this.isEmberCLIProject()) {
var lookupPaths = [this.localBlueprintLookupPath()];
var addonLookupPaths = this.addonBlueprintLookupPaths();
return lookupPaths.concat(addonLookupPaths);
} else {
return [];
}
};
/**
Returns a list of addon paths where blueprints will be looked up.
@private
@method addonBlueprintLookupPaths
@return {Array} List of paths
*/
Project.prototype.addonBlueprintLookupPaths = function() {
var addonPaths = this.addons.map(function(addon) {
if (addon.blueprintsPath) {
return addon.blueprintsPath();
}
}, this);
return addonPaths.filter(Boolean).reverse();
};
/**
Reloads package.json
@private
@method reloadPkg
@return {Object} Package content
*/
Project.prototype.reloadPkg = function() {
var pkgPath = path.join(this.root, 'package.json');
// We use readFileSync instead of require to avoid the require cache.
this.pkg = JSON.parse(fs.readFileSync(pkgPath, { encoding: 'utf-8' }));
return this.pkg;
};
/**
Re-initializes addons.
@private
@method reloadAddons
*/
Project.prototype.reloadAddons = function() {
this.reloadPkg();
this._addonsInitialized = false;
return this.initializeAddons();
};
/**
Find an addon by its name
@private
@method findAddonByName
@param {String} name Addon name as specified in package.json
@return {Addon} Addon instance
*/
Project.prototype.findAddonByName = function(name) {
this.initializeAddons();
var exactMatch = find(this.addons, function(addon) {
return name === addon.name || name === addon.pkg.name;
});
if (exactMatch) {
return exactMatch;
}
return find(this.addons, function(addon) {
return name.indexOf(addon.name) > -1 || name.indexOf(addon.pkg.name) > -1;
});
};
/**
Returns a new project based on the first package.json that is found
in `pathName`.
@private
@static
@method closest
@param {String} pathName Path to your project
@return {Promise} Promise which resolves to a {Project}
*/
Project.closest = function(pathName, _ui) {
var ui = ensureUI(_ui);
return closestPackageJSON(pathName)
.then(function(result) {
debug('closest %s -> %s', pathName, result);
if (result.pkg && result.pkg.name === 'ember-cli') {
return NULL_PROJECT;
}
return new Project(result.directory, result.pkg, ui);
})
.catch(function(reason) {
handleFindupError(pathName, reason);
});
};
/**
Returns a new project based on the first package.json that is found
in `pathName`.
@private
@static
@method closestSync
@param {String} pathName Path to your project
@param {UI} ui The UI instance to provide to the created Project.
@return {Project} Project instance
*/
Project.closestSync = function(pathName, _ui) {
var ui = ensureUI(_ui);
try {
var directory = findup.sync(pathName, 'package.json');
var pkg = require(path.join(directory, 'package.json'));
if (pkg && pkg.name === 'ember-cli') {
return NULL_PROJECT;
}
debug('closestSync %s -> %s', pathName, directory);
return new Project(directory, pkg, ui);
} catch(reason) {
handleFindupError(pathName, reason);
}
};
function NotFoundError(message) {
this.name = 'NotFoundError';
this.message = message;
this.stack = (new Error()).stack;
}
NotFoundError.prototype = Object.create(Error.prototype);
NotFoundError.prototype.constructor = NotFoundError;
Project.NotFoundError = NotFoundError;
function ensureUI(_ui) {
var ui = _ui;
if (!ui) {
// TODO: one UI (lib/cli/index.js also has one for now...)
ui = new UI({
inputStream: process.stdin,
outputStream: process.stdout,
ci: process.env.CI || /^(dumb|emacs)$/.test(process.env.TERM),
writeLevel: ~process.argv.indexOf('--silent') ? 'ERROR' : undefined
});
}
return ui;
}
function closestPackageJSON(pathName) {
return findup(pathName, 'package.json')
.then(function(directory) {
return Promise.hash({
directory: directory,
pkg: require(path.join(directory, 'package.json'))
});
});
}
function handleFindupError(pathName, reason) {
// Would be nice if findup threw error subclasses
if (reason && /not found/i.test(reason.message)) {
throw new NotFoundError('No project found at or up from: `' + pathName + '`');
} else {
throw reason;
}
}
// Export
module.exports = Project;
|
'use strict';
/**
* @ngdoc overview
* @name loopbackExampleFullStackApp
* @description
* # loopbackExampleFullStackApp
*
* Main module of the application.
*/
angular
.module('loopbackExampleFullStackApp', [
'ngRoute'
])
.config(function ($routeProvider, $locationProvider) {
Object.keys(window.CONFIG.routes)
.forEach(function(route) {
var routeDef = window.CONFIG.routes[route];
$routeProvider.when(route, routeDef);
});
$routeProvider
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
});
|
// Generated by CoffeeScript 1.4.0
(function() {
var escape;
escape = function(str) {
return String(str).replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
};
window.plugins.code = (function() {
var load;
function code() {}
load = function(callback) {
wiki.getScript('/plugins/code/prettify.js', callback);
return $('<style type="text/css"></style>').html('@import url("/plugins/code/prettify.css")').appendTo("head");
};
code.emit = function(div, item) {
return load(function() {
return div.append("<pre class='prettyprint'>" + (prettyPrintOne(escape(item.text))) + "</pre>");
});
};
code.bind = function(div, item) {
return load(function() {
return div.dblclick(function() {
return wiki.textEditor(div, item);
});
});
};
return code;
})();
}).call(this);
|
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, forin: true, maxerr: 50, regexp: true */
/*global define, $, XMLHttpRequest, window */
/**
* RemoteAgent defines and provides an interface for custom remote functions
* loaded from RemoteFunctions. Remote commands are executed via
* `call(name, varargs)`.
*
* Remote events are dispatched as events on this object.
*/
define(function RemoteAgent(require, exports, module) {
"use strict";
var $exports = $(exports);
var LiveDevelopment = require("LiveDevelopment/LiveDevelopment"),
Inspector = require("LiveDevelopment/Inspector/Inspector"),
RemoteFunctions = require("text!LiveDevelopment/Agents/RemoteFunctions.js");
var _load; // deferred load
var _objectId; // the object id of the remote object
var _intervalId; // interval used to send keepAlive events
// WebInspector Event: DOM.attributeModified
function _onAttributeModified(event, res) {
// res = {nodeId, name, value}
var matches = /^data-ld-(.*)/.exec(res.name);
if (matches) {
$exports.triggerHandler(matches[1], res);
}
}
function _call(objectId, method, varargs) {
console.assert(objectId, "Attempted to call remote method without objectId set.");
var args = Array.prototype.slice.call(arguments, 2),
callback,
deferred = new $.Deferred();
// if the last argument is a function it is the callback function
if (typeof args[args.length - 1] === "function") {
callback = args.pop();
}
// Resolve node parameters
args = args.map(function (arg) {
if (arg && arg.nodeId) {
return arg.resolve();
}
return arg;
});
$.when.apply(undefined, args).done(function onResolvedAllNodes() {
var params = [];
args.forEach(function (arg) {
if (arg.objectId) {
params.push({objectId: arg.objectId});
} else {
params.push({value: arg});
}
});
Inspector.Runtime.callFunctionOn(objectId, method, params, undefined, callback)
.then(deferred.resolve, deferred.reject);
});
return deferred.promise();
}
/** Call a remote function
* The parameters are passed on to the remote functions. Nodes are resolved
* and sent as objectIds.
* @param {string} function name
*/
function call(method, varargs) {
var argsArray = [_objectId, "_LD." + method];
if (arguments.length > 1) {
argsArray = argsArray.concat(Array.prototype.slice.call(arguments, 1));
}
return _call.apply(null, argsArray);
}
function _stopKeepAliveInterval() {
if (_intervalId) {
window.clearInterval(_intervalId);
_intervalId = null;
}
}
function _startKeepAliveInterval() {
_stopKeepAliveInterval();
_intervalId = window.setInterval(function () {
call("keepAlive");
}, 1000);
}
// WebInspector Event: Page.frameNavigated
function _onFrameNavigated(event, res) {
// res = {frame}
// Re-inject RemoteFunctions when navigating to a new page, but not if an iframe was loaded
if (res.frame.parentId) {
return;
}
_stopKeepAliveInterval();
// inject RemoteFunctions
var command = "window._LD=" + RemoteFunctions + "(" + LiveDevelopment.config.experimental + ");";
Inspector.Runtime.evaluate(command, function onEvaluate(response) {
if (response.error || response.wasThrown) {
_load.reject(response.error);
} else {
_objectId = response.result.objectId;
_load.resolve();
_startKeepAliveInterval();
}
});
}
/** Initialize the agent */
function load() {
_load = new $.Deferred();
$(Inspector.Page).on("frameNavigated.RemoteAgent", _onFrameNavigated);
$(Inspector.Page).on("frameStartedLoading.RemoteAgent", _stopKeepAliveInterval);
$(Inspector.DOM).on("attributeModified.RemoteAgent", _onAttributeModified);
return _load.promise();
}
/** Clean up */
function unload() {
$(Inspector.Page).off(".RemoteAgent");
$(Inspector.DOM).off(".RemoteAgent");
_stopKeepAliveInterval();
}
// Export public functions
exports.call = call;
exports.load = load;
exports.unload = unload;
});
|
import Register from './Register';
export default Register;
|
import JasmineMatchers from '../../vendor/jasmine-expect/dist/jasmine-matchers';
import JasmineJQuery from '../../vendor/jasmine-jquery/lib/jasmine-jquery';
import $ from 'jquery';
import {module, inject} from '../mocks';
describe('playlistItem directive', function () {
let $compile;
let $rootScope;
let $httpBackend;
let playList;
function createRoot (html, scope) {
let el = $compile(html)(scope);
scope.$digest();
return el;
}
beforeEach(module('karma.templates'));
beforeEach(module('Application'));
beforeEach(inject((_$compile_, _$rootScope_, _$httpBackend_, _playList_) => {
$compile = _$compile_;
$rootScope = _$rootScope_;
$httpBackend = _$httpBackend_;
playList = _playList_;
}));
describe('events', () => {
it('can still toggle menu when [actions-open] is interpolated attr', () => {
let html = '<div><playlist-item ' +
'actions-open="open"' +
'></playlist-item></div>';
$rootScope.open = true;
let root = createRoot(html, $rootScope);
expect(root.find('.playlist-item')).toHaveClass('actions-open');
root.find('.actions-menu').click();
expect(root.find('.playlist-item')).not.toHaveClass('actions-open');
root.find('.actions-menu').click();
expect(root.find('.playlist-item')).toHaveClass('actions-open');
$rootScope.open = false;
$rootScope.$digest();
expect(root.find('.playlist-item')).not.toHaveClass('actions-open');
});
it('should $emit an actions-toggled(false) event when .actions-menu is closed', (done) => {
let html = '<div><playlist-item ' +
'></playlist-item></div>';
let root = createRoot(html, $rootScope);
root.find('.actions-menu').click();
$rootScope.$on('actions-toggled', (e, value) => {
expect(value).toBe(false);
done();
});
root.find('.actions-menu').click();
});
it('should $emit an actions-toggled(true) event when .actions-menu is opened', (done) => {
let html = '<div><playlist-item ' +
'></playlist-item></div>';
let root = createRoot(html, $rootScope);
$rootScope.$on('actions-toggled', (e, value) => {
expect(value).toBe(true);
done();
});
root.find('.actions-menu').click();
});
});
describe('playList actions', () => {
beforeEach(() => {
spyOn(playList, 'play');
spyOn(playList, 'togglePlay');
spyOn(playList, 'remove');
spyOn(playList, 'playNext');
spyOn(playList, 'stopAt');
spyOn(playList, 'repeatTrack');
});
it('should call playList.repeatTrack(null) once when repeat action clicked with repeat flag', () => {
let html = '<div><playlist-item repeat="true"></playlist-item></div>';
let rootEl = createRoot(html, $rootScope);
rootEl.find('.action.repeat').click();
expect(playList.repeatTrack).toHaveBeenCalledWith(null);
expect(playList.repeatTrack.calls.count()).toBe(1);
});
it('should call playList.repeatTrack(idx) when .repeat action is clicked', () => {
let html = '<div><playlist-item ' +
'index="3"' +
'></playlist-item></div>';
let root = createRoot(html, $rootScope);
root.find('.action.repeat').click();
expect(playList.repeatTrack).toHaveBeenCalledWith(3);
});
it('should call playList.stopAt(null) once when stop-here action clicked with stop-here flag', () => {
let html = '<div><playlist-item stop-here="true"></playlist-item></div>';
let rootEl = createRoot(html, $rootScope);
rootEl.find('.action.stop-here').click();
expect(playList.stopAt).toHaveBeenCalledWith(null);
expect(playList.stopAt.calls.count()).toBe(1);
});
it('should call playList.stopAt(idx) when .stop-here action is clicked', () => {
let html = '<div><playlist-item ' +
'index="3"' +
'></playlist-item></div>';
let root = createRoot(html, $rootScope);
root.find('.action.stop-here').click();
expect(playList.stopAt).toHaveBeenCalledWith(3);
});
it('should call playList.playNext(null) once when play-next action clicked with play-next flag', () => {
let html = '<div><playlist-item play-next="true"></playlist-item></div>';
let rootEl = createRoot(html, $rootScope);
rootEl.find('.action.play-next').click();
expect(playList.playNext).toHaveBeenCalledWith(null);
expect(playList.playNext.calls.count()).toBe(1);
});
it('should call playList.playNext(idx) when .play-next action is clicked', () => {
let html = '<div><playlist-item ' +
'index="3"' +
'></playlist-item></div>';
let root = createRoot(html, $rootScope);
root.find('.action.play-next').click();
expect(playList.playNext).toHaveBeenCalledWith(3);
});
it('should call playList.togglePlay when .toggler is clicked and progress > 0', () => {
let html = '<div><playlist-item ' +
'progress="10" ' +
'></playlist-item></div>';
let root = createRoot(html, $rootScope);
root.find('.toggler').click();
expect(playList.togglePlay).toHaveBeenCalled();
});
it('should call playList.play(idx) when .toggler is clicked', () => {
let html = '<div><playlist-item ' +
'index="1" ' +
'></playlist-item></div>';
let root = createRoot(html, $rootScope);
root.find('.toggler').click();
expect(playList.play).toHaveBeenCalledWith(1);
});
it('should call playList.remove(idx) when .remover is clicked', () => {
let html = '<div><playlist-item ' +
'index="1" ' +
'></playlist-item></div>';
let root = createRoot(html, $rootScope);
root.find('.remover').click();
expect(playList.remove).toHaveBeenCalledWith(1);
});
});
describe('action flags', () => {
it('removes .actions-open class on .playlist-item after .actions-menu is clicked twice', () => {
let html = '<div><playlist-item ' +
'></playlist-item></div>';
let root = createRoot(html, $rootScope);
root.find('.actions-menu').click();
expect(root.find('.playlist-item')).toHaveClass('actions-open');
root.find('.actions-menu').click();
expect(root.find('.playlist-item')).not.toHaveClass('actions-open');
});
it('sets .actions-open class on .playlist-item when .actions-menu is clicked', () => {
let html = '<div><playlist-item ' +
'></playlist-item></div>';
let root = createRoot(html, $rootScope);
root.find('.actions-menu').click();
expect(root.find('.playlist-item')).toHaveClass('actions-open');
});
it('displays repeat flag when repeat attr is true', () => {
let html = '<div><playlist-item ' +
'ng-attr-repeat="{{repeat}}">' +
'</playlist-item></div>';
let root = createRoot(html, $rootScope);
$rootScope.repeat = true;
$rootScope.$digest();
expect(root).toContainElement('.flags > .flag.repeat');
});
it('displays stop-here flag when stopHere attr is true', () => {
let html = '<div><playlist-item ' +
'ng-attr-stop-here="{{stopHere}}">' +
'</playlist-item></div>';
let root = createRoot(html, $rootScope);
$rootScope.stopHere = true;
$rootScope.$digest();
expect(root).toContainElement('.flags > .flag.stop-here');
});
it('displays play-next flag when playNext attr is true', () => {
let html = '<div><playlist-item ' +
'ng-attr-play-next="{{playNext}}">' +
'</playlist-item></div>';
let root = createRoot(html, $rootScope);
$rootScope.playNext = true;
$rootScope.$digest();
expect(root).toContainElement('.flags > .flag.play-next');
});
});
describe('elapsed time', () => {
it('"progress" part of .time updates when scope changes', () => {
let html = '<div><playlist-item ' +
'title="test bla"' +
'duration="PT3M21S"' +
'progress="{{progress}}"' +
'></playlist-item></div>';
$rootScope.progress = 0;
let root = createRoot(html, $rootScope);
expect(root.find('.time')).toHaveText(/^\s*03:21\s*$/);
$rootScope.progress = 60;
$rootScope.$apply();
expect(root.find('.time')).toHaveText(/^\s*01:00\s*\/\s*03:21\s*$/);
expect(root.find('.playlist-item').isolateScope().progress).toBe('60');
expect(root.find('.playlist-item').isolateScope().isPlaying()).toBe(true);
});
it('does not display "progress" part of .time when progress is 0', () => {
let html = '<div><playlist-item ' +
'title="test bla"' +
'duration="PT3M21S"' +
'progress="0"' +
'></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find('.time')).toHaveText(/^\s*03:21$/);
});
it('does not display "progress" part of .time when no progress is given', () => {
let html = '<div><playlist-item ' +
'title="test bla"' +
'duration="PT3M21S"' +
'></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find('.time')).toHaveText(/^\s*03:21$/);
});
it('contains current song progress', () => {
let html = '<div><playlist-item ' +
'title="test bla"' +
'duration="PT3M21S"' +
'progress="28"' +
'></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find('.time > .elapsed')).toHaveText('00:28');
expect(root.find('.time')).toHaveText(/^00:28\s*\/\s*03:21$/);
expect(root.find('.time')).toContainElement('.separator');
});
it('contains item duration in formatted form', () => {
let html = '<div><playlist-item ' +
'title="test bla"' +
'duration="PT3M21S"' +
'></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find('.time > .duration')).toHaveText('03:21');
});
});
describe('general markup', () => {
it('has .actions-open class when [actions-open] attr is set', () => {
let html = '<div><playlist-item ' +
'actions-open="open"' +
'></playlist-item></div>';
$rootScope.open = true;
let root = createRoot(html, $rootScope);
expect(root.find('.playlist-item')).toHaveClass('actions-open');
});
it('.action.repeat has .active class when repeat attr set', () => {
let html = '<div><playlist-item repeat="true"></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find(
'.playlist-item .actions-bar > .action.repeat')
).toHaveClass('active');
});
it('.action.repeat contains .text element with "Repeat"', () => {
let html = '<div><playlist-item></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find(
'.playlist-item .actions-bar > .action.repeat')
).toHaveLength(1);
expect(root.find(
'.playlist-item .actions-bar > .action.repeat')
).toHaveText('Repeat');
});
it('contains .actions-bar > .action.repeat element', () => {
let html = '<div><playlist-item></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find(
'.playlist-item .actions-bar > .action.repeat')
).toHaveLength(1);
});
it('.action.stop-here has .active class when stopHere attr set', () => {
let html = '<div><playlist-item stop-here="true"></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find(
'.playlist-item .actions-bar > .action.stop-here')
).toHaveClass('active');
});
it('.action.stop-here contains .text element with "Stop Here"', () => {
let html = '<div><playlist-item></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find(
'.playlist-item .actions-bar > .action.stop-here > .text')
).toHaveLength(1);
expect(root.find(
'.playlist-item .actions-bar > .action.stop-here > .text')
).toHaveText('Stop Here');
});
it('contains .actions-bar > .action.stop-here element', () => {
let html = '<div><playlist-item></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find(
'.playlist-item .actions-bar > .action.stop-here')
).toHaveLength(1);
});
it('.action.play-next has .active class when playNext attr set', () => {
let html = '<div><playlist-item play-next="true"></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find(
'.playlist-item .actions-bar > .action.play-next')
).toHaveClass('active');
});
it('.action.play-next contains .text element with "Play Next"', () => {
let html = '<div><playlist-item></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find(
'.playlist-item .actions-bar > .action.play-next > .text')
).toHaveLength(1);
expect(root.find(
'.playlist-item .actions-bar > .action.play-next > .text')
).toHaveText('Play Next');
});
it('contains .actions-bar > .action.play-next element', () => {
let html = '<div><playlist-item></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find(
'.playlist-item .actions-bar > .action.play-next')
).toHaveLength(1);
});
it('does not have .active class after [active] was removed', () => {
let html = '<div><playlist-item active="{{active}}"></playlist-item></div>';
$rootScope.active = true;
let root = createRoot(html, $rootScope);
expect(root.find('.playlist-item')).toHaveClass('active');
$rootScope.active = undefined;
$rootScope.$digest();
expect(root.find('.playlist-item')).not.toHaveClass('active');
});
it('has .active class when [active] exists on element', () => {
let html = '<div><playlist-item active="true"></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find('.playlist-item')).toHaveClass('active');
});
it('has .now-playing class when progress > 0', () => {
let html = '<div><playlist-item progress="1"></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find('.playlist-item')).toHaveClass('now-playing');
});
it('contains .actions-bar.bar element', () => {
let html = '<div><playlist-item title="test bla"></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find('.playlist-item .actions-bar.bar')).toHaveLength(1);
});
it('contains .actions-menu element', () => {
let html = '<div><playlist-item title="test bla"></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find('.playlist-item .actions-menu')).toHaveLength(1);
});
it('contains .remover element', () => {
let html = '<div><playlist-item title="test bla"></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find('.playlist-item .remover')).toHaveLength(1);
});
it('contains .flags element', () => {
let html = '<div><playlist-item title="test bla"></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find('.playlist-item .flags')).toHaveLength(1);
});
it('contains .toggler element', () => {
let html = '<div><playlist-item title="test bla"></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find('.playlist-item .toggler')).toHaveLength(1);
});
it('contains .mover element', () => {
let html = '<div><playlist-item title="test bla"></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find('.playlist-item .mover')).toHaveLength(1);
});
it('contains 2 .bar elements as a direct child of .playlist-item', () => {
let html = '<div><playlist-item title="test bla"></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find('.playlist-item > .bar')).toHaveLength(2);
});
it('contains item title inside the .title element', () => {
let html = '<div><playlist-item title="test bla"></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root.find('.title')).toHaveText("test bla");
});
it('contains a single .title element', () => {
let html = '<div><playlist-item></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root).toContainElement('.title');
expect(root.find('.title')).toHaveLength(1);
});
it('contains a .playlist-item element', () => {
let html = '<div><playlist-item></playlist-item></div>';
let root = createRoot(html, $rootScope);
expect(root).toContainElement('.playlist-item');
});
});
});
|
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var ImageHdrStrong = React.createClass({
displayName: 'ImageHdrStrong',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M17 6c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zM5 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z' })
);
}
});
module.exports = ImageHdrStrong; |
var searchData=
[
['carte',['Carte',['../class_carte.html#a06daaca86c31c80f8308f4a81d46dc9b',1,'Carte::Carte()'],['../class_carte.html#aa9dbe7013e77d06af96ed4e4e0c4d551',1,'Carte::Carte(int pdv, int pa, std::string nom, int coutmana, bool charge, bool provoc, bool sort, int f, std::string des)']]],
['chasseur',['Chasseur',['../class_chasseur.html#af4bca087f4380663c19cd91cf373cf50',1,'Chasseur']]],
['comportementpouvoirchasseur',['ComportementPouvoirChasseur',['../class_comportement_pouvoir_chasseur.html#a051c87d077549a7edb5eb1e8c9944aff',1,'ComportementPouvoirChasseur']]],
['comportementpouvoirdemoniste',['ComportementPouvoirDemoniste',['../class_comportement_pouvoir_demoniste.html#a1f6b2e5586c6c0e48cd2d88be22e730a',1,'ComportementPouvoirDemoniste']]],
['comportementpouvoirguerrier',['ComportementPouvoirGuerrier',['../class_comportement_pouvoir_guerrier.html#a5b4e19698e98c3d7a58a3859c6ca5118',1,'ComportementPouvoirGuerrier']]],
['comportementpouvoirjxr',['ComportementPouvoirJXR',['../class_comportement_pouvoir_j_x_r.html#a6bfa37111b1d6add5cabd1c5a433291b',1,'ComportementPouvoirJXR']]],
['comportementpouvoirmage',['ComportementPouvoirMage',['../class_comportement_pouvoir_mage.html#a981ec14dbba67cb5d5c709d84fd23d1d',1,'ComportementPouvoirMage']]],
['comportementpouvoirpretre',['ComportementPouvoirPretre',['../class_comportement_pouvoir_pretre.html#a997a0441eabec5c50a1cfa29d9aabdaa',1,'ComportementPouvoirPretre']]]
];
|
(function () {
angular.module('common.router',['common.logger','ui.router']);
})();
|
(function (root) {
var Module = function (parentID, fullscreenCallback, vrToggleCallback ) {
this.fullscreenCallback = fullscreenCallback;
this.vrToggleCallback = vrToggleCallback;
this.view = document.getElementById(parentID);
this.vrToggle = document.getElementById('vrToggle');
this.fullscreenToggle = document.getElementById('fullscreenToggle');
this.blocker = document.getElementById('controlsBlocker');
this.topBank = document.getElementById('topBank');
this.bottomBank = document.getElementById('bottomBank');
this.vrMode;
this.fullscreen;
this.isMenu;
this.menuDuration = 2500;
this.menuMaxDuration = 3500;
this.menuTimeIncrement = 1000;
this.menuEndTime;
// bound functions
this.pressButtonFn = pressButton.bind(this);
this.toggleButtonFn = toggleButton.bind(this);
}
function init (mode) {
// assign initial mode
this.vrMode = (mode == 'vrMode') ? true : false;
// set buttons
if (this.vrMode) {
this.vrToggle.children[0].style.display = 'block';
this.vrToggle.children[1].style.display = 'none';
} else {
this.vrToggle.children[1].style.display = 'block';
this.vrToggle.children[0].style.display = 'none';
}
// always starts off normal, within browser window
this.fullscreen = false;
this.fullscreenToggle.children[1].style.display = 'none';
// bring to display
this.view.style.display = 'block';
// always begin with menu open
this.isMenu = true;
// countdown for menu close
startTimer.call(this);
// listen for menu events
addListeners.call(this);
}
function addListeners () {
this.view.addEventListener('touchstart', function (e) {
show.call(this);
}.bind(this));
// block all interactions below this level
this.blocker.addEventListener('touchstart', function(e) {
e.stopPropgation();
e.preventDefault();
return;
});
this.vrToggle.addEventListener('touchstart', this.pressButtonFn);
this.fullscreenToggle.addEventListener('touchstart', this.pressButtonFn);
// TODO: Write an onTouchMove function that checks if finger is still over button
// this.fullscreenToggle.addEventListener('touchleave', function (e) {
// e.currentTarget.style.background = '#FFF';
// });
this.vrToggle.addEventListener('touchend', this.toggleButtonFn);
this.fullscreenToggle.addEventListener('touchend', this.toggleButtonFn);
}
// generic press behaviors for all buttons
function pressButton (e) {
e.currentTarget.style.background = '#DADADA';
e.preventDefault();
return;
}
function toggleButton (e) {
// reset button background
e.currentTarget.style.background = '#FFF';
// toggle image
if (e.currentTarget.children[0].style.display == 'none') {
e.currentTarget.children[0].style.display = 'block';
e.currentTarget.children[1].style.display = 'none';
} else {
e.currentTarget.children[1].style.display = 'block';
e.currentTarget.children[0].style.display = 'none';
}
// toggle behaviors
if (e.currentTarget.id == 'vrToggle') {
this.vrMode = !this.vrMode;
if (this.vrToggleCallback) this.vrToggleCallback(this.vrMode);
} else {
this.fullscreen = !this.fullscreen;
if (this.fullscreenCallback) this.fullscreenCallback(this.fullscreen);
}
return;
}
function show () {
if (this.isMenu) {
addToTimer.call(this);
return;
}
this.isMenu = true;
// menu animations
openBanks.call(this);
this.view.style.background = 'rgba(255, 255, 255, 0.3)';
startTimer.call(this);
}
function hide () {
if (!this.isMenu) return;
this.isMenu = false;
// menu animations
closeBanks.call(this);
this.view.style.background = 'rgba(255, 255, 255, 0)';
}
function openBanks () {
this.topBank.style['-webkit-transform'] = 'translateY(0px)';
this.bottomBank.style['-webkit-transform'] = 'translateY(0px)';
}
function closeBanks () {
this.topBank.style['-webkit-transform'] = 'translateY(-35px)';
this.bottomBank.style['-webkit-transform'] = 'translateY(50px)';
}
function startTimer () {
this.menuEndTime = Date.now() + this.menuDuration;
window.requestAnimationFrame(menuTimer.bind(this));
}
function addToTimer () {
if (Date.now() > this.menuEndTime) return;
// only add a little time on menu interactions
this.menuEndTime += this.menuTimeIncrement;
// max duration is capped
this.menuEndTime = Math.min(this.menuEndTime, Date.now() + this.menuMaxDuration);
}
function menuTimer () {
if (Date.now() < this.menuEndTime) {
window.requestAnimationFrame(menuTimer.bind(this));
} else {
hide.call(this);
}
}
function resize (w, h) {
this.videoBackground.resize(w, h);
}
Module.prototype.init = init;
Module.prototype.show = show;
Module.prototype.hide = hide;
Module.prototype.resize = resize;
root.ControlsOverlay = Module;
})(UI); |
{
step1Title:"Step 1: Select a Data Source",
step2Title:"Step 2: Make Selections",
step3Title:"Step 3: Customize Selections",
step4Title:"Step 4: Report Settings",
goBtnTxt:"Go",
okBtnTxt:"Ok",
cancelBtnTxt:"Cancel",
searchBtnTxt:"Search",
backBtnTxt:"Back",
nextBtnTxt:"Next",
saveBtnTxt:"Save",
saveAsBtnTxt:"Save As ...",
cancelBtnTxt:"Cancel",
invalidPageNum:"Not a valid page number: %{0}",
levelTitle:"Level %{0}",
addColumnsToGrps:"Add column(s) to Groups list",
addColumnsToDetails:"Add column(s) to Details list",
addColumnsToFilters:"Add column(s) to Filters list",
deleteFromFilters:"Delete from Filters list",
portraitBtnTxt:"Portrait",
landscapeBtnTxt:"Landscape",
letterSizeBtnTxt:"Letter",
legalSizeBtnTxt:"Legal",
waqrLoadFailed:"Unable to load Adhoc Reporting Interface: %{0}",
reportTemplateLoadFailed:"Unable to load the report template: %{0}",
invalidGrpListItem:"Invalid group list item.",
invalidGrpHdr:"Invalid Item type, expecting RSGroupHeader.",
invalidDetailItem:"Invalid Item type, expecting RSDetailItem.",
invalidFilterItem:"Invalid Item type, expecting RSFilterItem.",
invalidGrpItem:"Invalid Item type, expecting RSGroupItem.",
pg3SaveErrorMsg:"Error while writing wizard page 3 to ReportSpec: %{0}",
selectBusinessModelWarn:"Select a Data Source before proceeding",
selectBusinessModelMsg:"Select a Data Source from the Available Data Source(s).",
addDetailsMsg:"Add a column from the Available Items to the Details list.",
invalidFileName:"%{0} is an invalid filename. Valid filenames cannot include the characters: /\?%*:|\"<>",
invalidBranchElement:"Invalid element in document, branch element has isDir attribute set to false.",
searchDlgTitle:"Search",
availItemsTitle:"Select one or more columns and add them to the Groups, Details, or Filters list",
searchTooltip:"Search for column value",
addConstraintBtnTxt:"Add a Constraint",
constraintIdxOutOfRange:"Constraint index %{0} out of range.",
unknownComparator:"Unknown comparator in constraint: %{0}.",
addConstraintsBtnHoverTxt:"Select a Group, Detail, or Filter column, and click to add a constraint.",
deleteConstraintsBtnHoverTxt:"Select a column in the constraints table, and click to delete it.",
searchWildcardHelpMsg:"Use * in your search text to specify a wildcard.",
dragHereMsg:"[drag item here]",
alignGrpHdrDefaultBtnTxt:"Default",
alignGrpHdrTopBtnTxt:"Top",
alignGrpHdrMiddleBtnTxt:"Middle",
alignGrpHdrBottomBtnTxt:"Bottom",
alignGrpItemDefaultBtnTxt:"Default",
alignGrpItemLeftBtnTxt:"Left",
alignGrpItemCenterBtnTxt:"Center",
alignGrpItemRightBtnTxt:"Right",
noGrpPgBrkBtnTxt:"None",
alignDetailItemDefaultBtnTxt:"Default",
alignDetailItemLeftBtnTxt:"Left",
alignDetailItemCenterBtnTxt:"Center",
alignDetailItemRightBtnTxt:"Right",
pgBrkBeforeGrpBtnTxt:"Before Group",
pgBrkAfterGrpBtnTxt:"After Group",
unknownColumnType:"Unknown column type: %{0}",
invalidGroupNum:"Failed to locate group header for group num: %{0}",
selectModelTitle:"Select a Data Source",
step1DetailsTitle:"Business Model Details",
availModelsTitle:"Available",
loadingViewsProgressMsg:"Loading Data Source(s) ...",
businessViewTitle:"Business View",
descTitle:"Description",
defineTmpltTitle:"Apply a Template",
tmpltDetailsTitle:"Template Details",
availTmpltsTitle:"Templates",
thumbnailTitle:"Thumbnail",
step2AvailItemsTitle:"Available Items",
DISTINCT_SELECTIONS_LABEL:"Distinct Selections",
selectedItemsTitle:"Selected Items",
step2GroupsTitle:"Groups",
step2DetailsTitle:"Details",
step2FiltersTitle:"Filters",
step3GroupsTitle:"Groups",
step3DetailsTitle:"Details",
step3FiltersTitle:"Filters",
step3GrpsGeneralTitle:"General",
step3GrpsFormatTitle:"Formatting",
step3GrpsLvlNameTitle:"Level Name",
step3GrpOptionsTitle:"Options",
step3RepeatGrpHdr:"Repeat Group Header",
step3ShowTotals:"Show Totals",
step3PgBrkTitle:"Page Break",
step3GrpAlignTitle:"Alignment",
step3GrpsFormatTitle2:"Formatting",
step3FormatListNumericLabel:"Numeric Format",
step3FormatListDateLabel:"Date Format",
step3FormatListEmptyLabel:"",
step3GrpAlignTitle2:"Alignment",
step3DetailsFormatTitle:"Formatting",
step3CalcsTitle:"Calculation",
step3DetailsAlignTitle:"Alignment",
step3DetailsUseCalcFunc:"Use Function",
STEP3_GROUP_LEVEL_NAME_TOOLTIP: "Provide a label in the group header (optional)",
STEP3_GROUP_TOTAL_LABEL_TOOLTIP: "Provide a label for the summary row in the report.",
STEP3_SHOW_GROUP_SUMMARY_TOOLTIP: "Check to display summary information (count, sum, average, etc.) for Details columns.",
STEP3_REPEAT_GROUP_HEADER_TOOLTIP: "Check to repeat the group header on each page of a pdf report.",
STEP3_SELECT_AN_ITEM_TOOLTIP: "Select an item from the Groups, Details, or Filters list.",
STEP3_ADD_CONSTRAINT_TOOLTIP: "Select an item from the Groups, Details or Filters list, and then click 'Add a Constraint'",
STEP3_GROUPS_EDIT_SORT_COLUMN_TOOLTIP: "Select an item from the Groups list. Then select 'ascending' or 'descending'.",
STEP3_DETAILS_EDIT_SORT_COLUMN_TOOLTIP: "Select an item from the Details list. Click the 'Add' button. Then select 'ascending' or 'descending'.",
STEP3_ADD_DETAILS_SORT: "Select an item in the Details list, and click 'Add'",
STEP3_CANNOT_EDIT_GROUPS_SORT: "You can not add to, delete from, or reorder the Group sort columns.",
STEP3_DETAIL_EDITOR_TOOLTIP: "Configure the detail item's attributes.",
STEP3_GROUP_ITEM_EDITOR_TOOLTIP: "Configure the group item's attributes.",
STEP3_GROUP_HEADER_EDITOR_TOOLTIP: "Configure the group header's attributes.",
VALUE_MUST_BE_NUMERIC: "Value must be a number.",
VALUE_MUST_BE_NONEMPTY: "Value cannot be empty.",
/* begin aggregation functions */
aggrFuncNone:"None",
aggrFuncSum:"Sum",
aggrFuncCount:"Count",
aggrFuncAverage:"Average",
aggrFuncMin:"Min",
aggrFuncMax:"Max",
/* end aggregation functions */
step3ConstraintsTitle:"Constraints",
step3SortColumns:"Sort Columns",
step3ConstraintCurrSettings:"Current Settings",
step3GroupColumnSorterTitle:"Sort Group Columns",
step3DetailColumnSorterTitle:"Sort Detail Columns",
step4GeneralTitle:"General",
step4OrientationTitle:"Orientation",
step4PaperTitle:"Paper",
step4ReportDescTitle:"Report Description",
step4HdrTitle:"Header",
step4ReportTitle:"Report",
step4PgTitle:"Page",
step4FooterTitle:"Footer",
step4FooterRptTitle:"Report",
step4FooterPgTitle:"Page",
saveDlgSaveAsPrompt:"Save As:",
saveDlgWherePrompt:"Where:",
saveDlgSelectSltnTitle:"Select a Solution",
saveDlgOutputTypeTitle:"Output Type",
srchDlgResultsTitle:"Search Results",
previewFormatPrompt:"Preview As:",
CONSTRAINTS_INVALID:"The values for the highlighted constraints are invalid. Please hover the mouse pointer over the constraint for details.",
unableToLoadEmptyViewId:"Unable to load business view with an empty view Id.",
unableToLoadEmptyDomainId:"Unable to load business view with an empty domain Id.",
youMayContinue:"You may now continue.",
close:"close",
unableToSelectModel:"Unable to select a Data Source. The reportSpec document is missing either the domain Id or the model Id.",
loadingDescription: "Loading Model Description ...",
loadingView: "Loading Business View ...",
searching: "Searching ...",
saving: "Saving ...",
working: "Working ...",
badSortInfo:"ReportSpec load error: sort information specified for a column that is not in the Groups or Details columns.",
saveLabel:"Save",
openLabel:"Open",
ascLabel:"ascending",
descLabel:"descending",
ascLabelUpper:"Asc",
descLabelUpper:"Desc",
columnLabel:"Column",
tableLabel:"Table",
overwriteFile:"The solution file %{0} already exists. Would you like to overwrite?",
invalidColumnType:"Invalid column type requested for constraint control: %{0}.",
EXACTLY_MATCHES:"exactly matches",
CONTAINS:"contains",
ENDS_WITH:"ends with",
BEGINS_WITH:"begins with",
DOES_NOT_CONTAIN:"does not contain",
ON:"on",
ON_OR_AFTER:"on or after",
ON_OR_BEFORE:"on or before",
AFTER:"after",
BEFORE:"before",
NOT_ON:"not on",
STEP3_SHOW_GROUP_SUMMARY:"Show Group Summary",
STEP3_GROUP_TOTAL_LABEL:"Group Summary Label",
DEFAULT_GROUP_TOTAL_LABEL:"Total",
FREE_FORM:"Free Form",
BUILDER: "Builder",
MQL_PARSE_FAILED: "MQL Parser error: failed trying to parse: \"%{0}\".",
REPORT_FILE_FAILED_TO_LOAD: "Error: the report definition file contains invalid data. Reason: %{0}",
INVALID_COMPARATOR_NAME: "Invalid comparator function name: %{0}.",
UNRECOGNIZED_PAGE_BREAK_VALUE: "Unrecognized value for page break on group header: %{0}.",
INVALID_REPOSITORY_BROWSER_STATE: "RepositoryBrowser is in an invalid state. Cannot complete save operation.",
PARTIAL_MQL_PARSE_FAILURE: "The Builder was unable to parse parts of the MQL in the Free Form editor. Some or all of the MQL from the Free Form editor will be lost. Would you like to continue?",
/* begin number format */
NUMBER_FORMAT_NEG_MONEY_LABEL: "$ 1,234; -$ 1,234",
NUMBER_FORMAT_PAREN_MONEY_LABEL: "$ 1,234; ($ 1,234)",
NUMBER_FORMAT_NEG_DECIMAL_MONEY_LABEL: "$ 1,234.56; -$ 1,234.56",
NUMBER_FORMAT_NEG_MONEY: "$ #,###;-$ #,###",
NUMBER_FORMAT_PAREN_MONEY: "$ #,###;($ #,###)",
NUMBER_FORMAT_NEG_DECIMAL_MONEY: "$ #,###.##;-$ #,###.##",
/* end number format */
ERROR_NO_BUSINESS_MODELS: "There are either no Data Source(s) defined in the metadata, or you do not have permission to access any of the Data Source(s). Please create one or more Data Source(s) using the Metadata Editor and then publish them to the Pentaho server. Or, use the Metadata Editor to give the appropriate user permission to access to the Data Source.",
SOLUTION_REPOSITORY: "Solution Repository",
step1_div:"Select Data Source",
step2_div:"Make Selections",
step3_div:"Customize Selections",
step4_div:"Report Settings"
dataaccessAddButtonText:"Add",
dataaccessDeleteButtonText:"Delete",
deleteModelWarningMessage:"All content associated to selected Data Source will no longer work."
} |
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (c) Crossbar.io Technologies GmbH and contributors
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
var autobahn = require('./../index.js');
var testutil = require('./testutil.js');
exports.testRpcError = function (testcase) {
testcase.expect(1);
var test = new testutil.Testlog("test/test_rpc_error.txt");
var connection = new autobahn.Connection(testutil.config);
connection.onopen = function (session) {
test.log('Connected');
function sqrt(args) {
var x = args[0];
if (x === 0) {
throw "don't ask folly questions;)";
}
var res = Math.sqrt(x);
if (res !== res) {
//throw "cannot take sqrt of negative";
throw new autobahn.Error('com.myapp.error', ['fuck'], {a: 23, b: 9});
}
return res.toFixed(6);
}
var endpoints = {
'com.myapp.sqrt': sqrt
};
var pl1 = [];
for (var uri in endpoints) {
pl1.push(session.register(uri, endpoints[uri]));
}
autobahn.when.all(pl1).then(
function () {
test.log("All registered.");
var pl2 = [];
var vals1 = [2, 0, -2];
for (var i = 0; i < vals1.length; ++i) {
pl2.push(session.call('com.myapp.sqrt', [vals1[i]]).then(
function (res) {
test.log("Result:", res);
},
function (err) {
test.log("Error:", err.error, err.args, err.kwargs);
}
));
}
autobahn.when.all(pl2).then(function () {
test.log("All finished.");
connection.close();
var chk = test.check()
testcase.ok(!chk, chk);
testcase.done();
});
},
function () {
test.log("Registration failed!", arguments);
}
);
};
connection.open();
}
|
'use strict';
/**
* The config module is responsible for setting any constant variable that is needed in the application. There are
* 2 ways to set the configuration values for grasshopper.
*
* * Pass in the options to the function
* * Set an environment variable with GHCONFIG (soon to be deprecated) or GRASSHOPPER_CONFIG
*/
var Config = function(options){
var _ = require('lodash'),
defaultPageSize = 100000;
// Singleton snippet
if ( Config.prototype._singletonInstance ) {
return Config.prototype._singletonInstance;
}
Config.prototype._singletonInstance = this;
this.db = {
defaultPageSize: defaultPageSize
};
this.crypto = {};
this.cache = {};
this.assets = {
filenameSpaceReplacement: '-'
};
this.server = {
proxy: false,
maxFilesSize: (1024 * 1024 * 2), //2 megabytes
maxFieldsSize: (1024 * 1024 * 2), //2 megabytes
maxFields: 1000
};
this.logger = {
adapters:[{
type: 'console',
application: 'grasshopper',
machine: 'default'
}]
};
this.identities = {};
this.init = function(config){
if ( !_.isUndefined(config) ) {
_.assign( this.db, config.db );
_.assign( this.crypto, config.crypto );
_.assign( this.cache, config.cache );
_.assign( this.assets, config.assets );
_.assign( this.logger, config.logger );
_.assign( this.identities, config.identities );
_.assign( this.server, config.server );
}
return this;
};
// Initially set any environment variables.
if(process.env.GHCONFIG || process.env.GRASSHOPPER_CONFIG){
console.log('Configuration found in the environment. Using config set in process.env');
this.init(JSON.parse(process.env.GHCONFIG || process.env.GRASSHOPPER_CONFIG));
}
// Init object with anything that was passed in.
if(!_.isUndefined(options)){
console.log('Config options have been passed in applying...');
this.init(options);
}
};
module.exports = Config; |
//>>built
define({status:"${start}\u2013${end}/${total} tulemust",gotoFirst:"Liigu esimesele lehele",gotoNext:"Liigu j\u00e4rgmisele lehele",gotoPrev:"Liigu eelmisele lehele",gotoLast:"Liigu viimasele lehele",gotoPage:"Liigu lehele",jumpPage:"H\u00fcppa lehele"}); |
function RetailerBalanceController(
$scope,
$rootScope,
EthereumBalancesService
) {
EthereumBalancesService
.getFullRetailerBalances($rootScope.user)
.then(function (balances) {
$scope.balances = balances;
})
.catch(function (err) {
console.log(err);
})
}
export default ['$scope', '$rootScope', 'EthereumBalancesService', RetailerBalanceController]
|
/* ==========================================================================
Prototype Tools -- Version: 1.9.0.2 - Updated: 1/20/2014
========================================================================== */
// For DEMO site only - DO NOT EVER INGEST THESE !!
window.onload = getPageLoadTime;
// Calculate the viewport size on prototype site
$(window).resize(function() {
$('.viewport').empty().append($(window).width(), "x", $(window).height());
}).resize();
//calculate the time before calling the function in window.onload
var beforeload = (new Date()).getTime();
function getPageLoadTime() {
//calculate the current time in afterload
var afterload = (new Date()).getTime();
// now use the beforeload and afterload to calculate the seconds
var seconds = (afterload - beforeload) / 1000;
// Place the seconds in the innerHTML to show the results
$('.loadtime').text( + seconds + ' sec');
} |
module.exports={title:"Qgis",slug:"qgis",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Qgis icon</title><path d="M12.879 13.006v3.65l-3.004-3.048v-3.495h3.582l2.852 2.893h-3.43zm10.886 7.606V24h-3.654l-5.73-5.9v-3.55h3.354l6.03 6.062zm-10.828-1.448l3.372 3.371c-1.309.442-2.557.726-4.325.726C5.136 23.26 0 18.243 0 11.565 0 4.92 5.136 0 11.984 0 18.864 0 24 4.952 24 11.565c0 2.12-.523 4.076-1.457 5.759l-3.625-3.725a8.393 8.393 0 00.24-2.005c0-4.291-3.148-7.527-7.1-7.527-3.954 0-7.248 3.236-7.248 7.527s3.33 7.6 7.247 7.6c.548 0 .661.017.88-.03z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://www.qgis.org/en/site/getinvolved/styleguide.html",hex:"589632"}; |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M6.15 9.97c-.46-.46-.38-1.24.18-1.57.4-.22.88-.4 1.42-.4.8 0 1.39.39 1.81.67.31.21.51.33.69.33.13 0 .26-.05.39-.12.39-.22.88-.16 1.2.16.46.46.38 1.24-.18 1.56-.39.23-.87.4-1.41.4-.79 0-1.37-.38-1.79-.66-.33-.22-.52-.34-.71-.34-.13 0-.26.05-.39.12-.4.23-.89.16-1.21-.15zM7.75 15c.19 0 .38.12.71.34.42.28 1 .66 1.79.66.54 0 1.02-.17 1.41-.4.56-.32.64-1.1.18-1.56-.32-.32-.81-.38-1.2-.16-.13.07-.26.12-.39.12-.18 0-.38-.12-.69-.33-.42-.28-1.01-.67-1.81-.67-.54 0-1.02.18-1.42.4-.56.33-.64 1.11-.18 1.56.32.32.81.38 1.2.16.14-.07.27-.12.4-.12zM22 6v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2h16c1.1 0 2 .9 2 2zm-8 0H4v12h10V6zm5 10c0-.55-.45-1-1-1s-1 .45-1 1 .45 1 1 1 1-.45 1-1zm0-4c0-.55-.45-1-1-1s-1 .45-1 1 .45 1 1 1 1-.45 1-1zm0-5h-2v2h2V7z"
}), 'MicrowaveRounded'); |
describe("Sparc", function () {
var capstone = require("..");
var CODE_SPARC = new Buffer([
0x80, 0xa0, 0x40, 0x02, 0x85, 0xc2, 0x60, 0x08,
0x85, 0xe8, 0x20, 0x01, 0x81, 0xe8, 0x00, 0x00,
0x90, 0x10, 0x20, 0x01, 0xd5, 0xf6, 0x10, 0x16,
0x21, 0x00, 0x00, 0x0a, 0x86, 0x00, 0x40, 0x02,
0x01, 0x00, 0x00, 0x00, 0x12, 0xbf, 0xff, 0xff,
0x10, 0xbf, 0xff, 0xff, 0xa0, 0x02, 0x00, 0x09,
0x0d, 0xbf, 0xff, 0xff, 0xd4, 0x20, 0x60, 0x00,
0xd4, 0x4e, 0x00, 0x16, 0x2a, 0xc2, 0x80, 0x03
]);
var EXPECT_SPARC = [
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_CMP,
"address" : 0x1000,
"bytes" : [ 0x80, 0xa0, 0x40, 0x02 ],
"mnemonic" : "cmp",
"op_str" : "%g1, %g2"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_JMPL,
"address" : 0x1004,
"bytes" : [ 0x85, 0xc2, 0x60, 0x08 ],
"mnemonic" : "jmpl",
"op_str" : "%o1+8, %g2"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_RESTORE,
"address" : 0x1008,
"bytes" : [ 0x85, 0xe8, 0x20, 0x01 ],
"mnemonic" : "restore",
"op_str" : "%g0, 1, %g2"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_RESTORE,
"address" : 0x100c,
"bytes" : [ 0x81, 0xe8, 0x00, 0x00 ],
"mnemonic" : "restore",
"op_str" : ""
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_MOV,
"address" : 0x1010,
"bytes" : [ 0x90, 0x10, 0x20, 0x01 ],
"mnemonic" : "mov",
"op_str" : "1, %o0"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_CASX,
"address" : 0x1014,
"bytes" : [ 0xd5, 0xf6, 0x10, 0x16 ],
"mnemonic" : "casx",
"op_str" : "[%i0], %l6, %o2"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_SETHI,
"address" : 0x1018,
"bytes" : [ 0x21, 0x00, 0x00, 0x0a ],
"mnemonic" : "sethi",
"op_str" : "0xa, %l0"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_ADD,
"address" : 0x101c,
"bytes" : [ 0x86, 0x00, 0x40, 0x02 ],
"mnemonic" : "add",
"op_str" : "%g1, %g2, %g3"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_NOP,
"address" : 0x1020,
"bytes" : [ 0x01, 0x00, 0x00, 0x00 ],
"mnemonic" : "nop",
"op_str" : ""
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_B,
"address" : 0x1024,
"bytes" : [ 0x12, 0xbf, 0xff, 0xff ],
"mnemonic" : "bne",
"op_str" : "0x1020"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_B,
"address" : 0x1028,
"bytes" : [ 0x10, 0xbf, 0xff, 0xff ],
"mnemonic" : "ba",
"op_str" : "0x1024"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_ADD,
"address" : 0x102c,
"bytes" : [ 0xa0, 0x02, 0x00, 0x09 ],
"mnemonic" : "add",
"op_str" : "%o0, %o1, %l0"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_FB,
"address" : 0x1030,
"bytes" : [ 0x0d, 0xbf, 0xff, 0xff ],
"mnemonic" : "fbg",
"op_str" : "0x102c"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_ST,
"address" : 0x1034,
"bytes" : [ 0xd4, 0x20, 0x60, 0x00 ],
"mnemonic" : "st",
"op_str" : "%o2, [%g1]"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_LDSB,
"address" : 0x1038,
"bytes" : [ 0xd4, 0x4e, 0x00, 0x16 ],
"mnemonic" : "ldsb",
"op_str" : "[%i0+%l6], %o2"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_BRNZ,
"address" : 0x103c,
"bytes" : [ 0x2a, 0xc2, 0x80, 0x03 ],
"mnemonic" : "brnz,a,pn",
"op_str" : "%o2, 0x1048"
}
];
var EXPECT_SPARC_LITE = [
[ 0x1000, 4, "cmp", "%g1, %g2" ],
[ 0x1004, 4, "jmpl", "%o1+8, %g2" ],
[ 0x1008, 4, "restore", "%g0, 1, %g2" ],
[ 0x100c, 4, "restore", "" ],
[ 0x1010, 4, "mov", "1, %o0" ],
[ 0x1014, 4, "casx", "[%i0], %l6, %o2" ],
[ 0x1018, 4, "sethi", "0xa, %l0" ],
[ 0x101c, 4, "add", "%g1, %g2, %g3" ],
[ 0x1020, 4, "nop", "" ],
[ 0x1024, 4, "bne", "0x1020" ],
[ 0x1028, 4, "ba", "0x1024" ],
[ 0x102c, 4, "add", "%o0, %o1, %l0" ],
[ 0x1030, 4, "fbg", "0x102c" ],
[ 0x1034, 4, "st", "%o2, [%g1]" ],
[ 0x1038, 4, "ldsb", "[%i0+%l6], %o2" ],
[ 0x103c, 4, "brnz,a,pn", "%o2, 0x1048" ]
];
var EXPECT_SPARC_DETAIL = [
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_CMP,
"address" : 0x1000,
"bytes" : [ 0x80, 0xa0, 0x40, 0x02 ],
"mnemonic" : "cmp",
"op_str" : "%g1, %g2",
"detail" : {
"regs_read" : [],
"regs_write" : [ capstone.sparc.REG_ICC ],
"groups" : [],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_G1,
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_G2,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_JMPL,
"address" : 0x1004,
"bytes" : [ 0x85, 0xc2, 0x60, 0x08 ],
"mnemonic" : "jmpl",
"op_str" : "%o1+8, %g2",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_MEM,
"mem" : {
"base" : capstone.sparc.REG_O1,
"index" : 0,
"disp" : 8
}
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_G2,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_RESTORE,
"address" : 0x1008,
"bytes" : [ 0x85, 0xe8, 0x20, 0x01 ],
"mnemonic" : "restore",
"op_str" : "%g0, 1, %g2",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_G0,
},
{
"type" : capstone.sparc.OP_IMM,
"imm" : 1,
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_G2,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_RESTORE,
"address" : 0x100c,
"bytes" : [ 0x81, 0xe8, 0x00, 0x00 ],
"mnemonic" : "restore",
"op_str" : "",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : []
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_MOV,
"address" : 0x1010,
"bytes" : [ 0x90, 0x10, 0x20, 0x01 ],
"mnemonic" : "mov",
"op_str" : "1, %o0",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_IMM,
"imm" : 1,
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_O0,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_CASX,
"address" : 0x1014,
"bytes" : [ 0xd5, 0xf6, 0x10, 0x16 ],
"mnemonic" : "casx",
"op_str" : "[%i0], %l6, %o2",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [ capstone.sparc.GRP_64BIT ],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_MEM,
"mem" : {
"base" : capstone.sparc.REG_I0,
"index" : 0,
"disp" : 0,
}
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_L6,
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_O2,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_SETHI,
"address" : 0x1018,
"bytes" : [ 0x21, 0x00, 0x00, 0x0a ],
"mnemonic" : "sethi",
"op_str" : "0xa, %l0",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_IMM,
"imm" : 10,
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_L0,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_ADD,
"address" : 0x101c,
"bytes" : [ 0x86, 0x00, 0x40, 0x02 ],
"mnemonic" : "add",
"op_str" : "%g1, %g2, %g3",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_G1,
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_G2,
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_G3,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_NOP,
"address" : 0x1020,
"bytes" : [ 0x01, 0x00, 0x00, 0x00 ],
"mnemonic" : "nop",
"op_str" : "",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : []
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_B,
"address" : 0x1024,
"bytes" : [ 0x12, 0xbf, 0xff, 0xff ],
"mnemonic" : "bne",
"op_str" : "0x1020",
"detail" : {
"regs_read" : [ 69 ],
"regs_write" : [],
"groups" : [ capstone.sparc.GRP_JUMP ],
"sparc" : {
"cc" : 265,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_IMM,
"imm" : 0x1020,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_B,
"address" : 0x1028,
"bytes" : [ 0x10, 0xbf, 0xff, 0xff ],
"mnemonic" : "ba",
"op_str" : "0x1024",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [ capstone.sparc.GRP_JUMP ],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_IMM,
"imm" : 0x1024,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_ADD,
"address" : 0x102c,
"bytes" : [ 0xa0, 0x02, 0x00, 0x09 ],
"mnemonic" : "add",
"op_str" : "%o0, %o1, %l0",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_O0,
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_O1,
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_L0,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_FB,
"address" : 0x1030,
"bytes" : [ 0x0d, 0xbf, 0xff, 0xff ],
"mnemonic" : "fbg",
"op_str" : "0x102c",
"detail" : {
"regs_read" : [ capstone.sparc.REG_FCC0 ],
"regs_write" : [],
"groups" : [ capstone.sparc.GRP_JUMP ],
"sparc" : {
"cc" : 278,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_IMM,
"imm" : 0x102c,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_ST,
"address" : 0x1034,
"bytes" : [ 0xd4, 0x20, 0x60, 0x00 ],
"mnemonic" : "st",
"op_str" : "%o2, [%g1]",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_O2,
},
{
"type" : capstone.sparc.OP_MEM,
"mem" : {
"base" : capstone.sparc.REG_G1,
"index" : 0,
"disp" : 0,
}
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_LDSB,
"address" : 0x1038,
"bytes" : [ 0xd4, 0x4e, 0x00, 0x16 ],
"mnemonic" : "ldsb",
"op_str" : "[%i0+%l6], %o2",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_MEM,
"mem" : {
"base" : capstone.sparc.REG_I0,
"index" : capstone.sparc.REG_L6,
"disp" : 0,
}
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_O2,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_BRNZ,
"address" : 0x103c,
"bytes" : [ 0x2a, 0xc2, 0x80, 0x03 ],
"mnemonic" : "brnz,a,pn",
"op_str" : "%o2, 0x1048",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [
capstone.sparc.GRP_64BIT,
capstone.sparc.GRP_JUMP,
],
"sparc" : {
"cc" : 0,
"hint" : 5,
"operands" : [
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_O2,
},
{
"type" : capstone.sparc.OP_IMM,
"imm" : 0x1048,
}
]
}
}
}
];
var CODE_SPARCV9 = new Buffer([
0x81, 0xa8, 0x0a, 0x24, 0x89, 0xa0, 0x10, 0x20,
0x89, 0xa0, 0x1a, 0x60, 0x89, 0xa0, 0x00, 0xe0
]);
var EXPECT_SPARCV9 = [
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_FCMPS,
"address" : 0x1000,
"bytes" : [ 0x81, 0xa8, 0x0a, 0x24 ],
"mnemonic" : "fcmps",
"op_str" : "%f0, %f4"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_FSTOX,
"address" : 0x1004,
"bytes" : [ 0x89, 0xa0, 0x10, 0x20 ],
"mnemonic" : "fstox",
"op_str" : "%f0, %f4"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_FQTOI,
"address" : 0x1008,
"bytes" : [ 0x89, 0xa0, 0x1a, 0x60 ],
"mnemonic" : "fqtoi",
"op_str" : "%f0, %f4"
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_FNEGQ,
"address" : 0x100c,
"bytes" : [ 0x89, 0xa0, 0x00, 0xe0 ],
"mnemonic" : "fnegq",
"op_str" : "%f0, %f4"
}
];
var EXPECT_SPARCV9_LITE = [
[ 0x1000, 4, "fcmps", "%f0, %f4" ],
[ 0x1004, 4, "fstox", "%f0, %f4" ],
[ 0x1008, 4, "fqtoi", "%f0, %f4" ],
[ 0x100c, 4, "fnegq", "%f0, %f4" ]
];
var EXPECT_SPARCV9_DETAIL = [
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_FCMPS,
"address" : 0x1000,
"bytes" : [ 0x81, 0xa8, 0x0a, 0x24 ],
"mnemonic" : "fcmps",
"op_str" : "%f0, %f4",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_F0,
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_F4,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_FSTOX,
"address" : 0x1004,
"bytes" : [ 0x89, 0xa0, 0x10, 0x20 ],
"mnemonic" : "fstox",
"op_str" : "%f0, %f4",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [ capstone.sparc.GRP_64BIT ],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_F0,
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_F4,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_FQTOI,
"address" : 0x1008,
"bytes" : [ 0x89, 0xa0, 0x1a, 0x60 ],
"mnemonic" : "fqtoi",
"op_str" : "%f0, %f4",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [ capstone.sparc.GRP_HARDQUAD ],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_F0,
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_F4,
}
]
}
}
},
{
"arch" : capstone.ARCH_SPARC,
"id" : capstone.sparc.INS_FNEGQ,
"address" : 0x100c,
"bytes" : [ 0x89, 0xa0, 0x00, 0xe0 ],
"mnemonic" : "fnegq",
"op_str" : "%f0, %f4",
"detail" : {
"regs_read" : [],
"regs_write" : [],
"groups" : [ capstone.sparc.GRP_V9 ],
"sparc" : {
"cc" : 0,
"hint" : 0,
"operands" : [
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_F0,
},
{
"type" : capstone.sparc.OP_REG,
"reg" : capstone.sparc.REG_F4,
}
]
}
}
}
];
it("can print the correct register", function () {
var cs = new capstone.Cs(capstone.ARCH_SPARC, capstone.MODE_BIG_ENDIAN);
var output = cs.reg_name(capstone.sparc.REG_XCC);
cs.close();
expect(output).toEqual("xcc");
});
it("can print the correct instruction", function () {
var cs = new capstone.Cs(capstone.ARCH_SPARC, capstone.MODE_BIG_ENDIAN);
var output = cs.insn_name(capstone.sparc.INS_RETL);
cs.close();
expect(output).toEqual("retl");
});
it("can be disassembled", function () {
var cs = new capstone.Cs(capstone.ARCH_SPARC, capstone.MODE_BIG_ENDIAN);
var output = cs.disasm(CODE_SPARC, 0x1000);
cs.close();
expect(output).not.toBeDiff(EXPECT_SPARC);
});
it("can be disassembled quickly", function () {
var cs = new capstone.Cs(capstone.ARCH_SPARC, capstone.MODE_BIG_ENDIAN);
var output = cs.disasm_lite(CODE_SPARC, 0x1000);
cs.close();
expect(output).not.toBeDiff(EXPECT_SPARC_LITE);
});
it("can be disassembled with detail", function () {
var cs = new capstone.Cs(capstone.ARCH_SPARC, capstone.MODE_BIG_ENDIAN);
cs.detail = true;
var output = cs.disasm(CODE_SPARC, 0x1000);
cs.close();
expect(output).not.toBeDiff(EXPECT_SPARC_DETAIL);
});
it("V9 can be disassembled", function () {
var cs = new capstone.Cs(
capstone.ARCH_SPARC,
capstone.MODE_BIG_ENDIAN | capstone.MODE_V9
);
var output = cs.disasm(CODE_SPARCV9, 0x1000);
cs.close();
expect(output).not.toBeDiff(EXPECT_SPARCV9);
});
it("V9 can be disassembled quickly", function () {
var cs = new capstone.Cs(
capstone.ARCH_SPARC,
capstone.MODE_BIG_ENDIAN | capstone.MODE_V9
);
var output = cs.disasm_lite(CODE_SPARCV9, 0x1000);
cs.close();
expect(output).not.toBeDiff(EXPECT_SPARCV9_LITE);
});
it("V9 can be disassembled with detail", function () {
var cs = new capstone.Cs(
capstone.ARCH_SPARC,
capstone.MODE_BIG_ENDIAN | capstone.MODE_V9
);
cs.detail = true;
var output = cs.disasm(CODE_SPARCV9, 0x1000);
cs.close();
expect(output).not.toBeDiff(EXPECT_SPARCV9_DETAIL);
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:9099a238eba79d2c037abe040cd508b540bc99e4d5e2a7a1fa7b464990f53ed0
size 4883
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.BrowserESModuleLoader = factory());
}(this, (function () { 'use strict';
/*
* Environment
*/
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
var isNode = typeof process !== 'undefined' && process.versions && process.versions.node;
var isWindows = typeof process !== 'undefined' && typeof process.platform === 'string' && process.platform.match(/^win/);
var envGlobal = typeof self !== 'undefined' ? self : global;
/*
* Simple Symbol() shim
*/
var hasSymbol = typeof Symbol !== 'undefined';
function createSymbol (name) {
return hasSymbol ? Symbol() : '@@' + name;
}
/*
* Environment baseURI
*/
var baseURI;
// environent baseURI detection
if (typeof document != 'undefined' && document.getElementsByTagName) {
baseURI = document.baseURI;
if (!baseURI) {
var bases = document.getElementsByTagName('base');
baseURI = bases[0] && bases[0].href || window.location.href;
}
}
else if (typeof location != 'undefined') {
baseURI = location.href;
}
// sanitize out the hash and querystring
if (baseURI) {
baseURI = baseURI.split('#')[0].split('?')[0];
var slashIndex = baseURI.lastIndexOf('/');
if (slashIndex !== -1)
baseURI = baseURI.substr(0, slashIndex + 1);
}
else if (typeof process !== 'undefined' && process.cwd) {
baseURI = 'file://' + (isWindows ? '/' : '') + process.cwd();
if (isWindows)
baseURI = baseURI.replace(/\\/g, '/');
}
else {
throw new TypeError('No environment baseURI');
}
// ensure baseURI has trailing "/"
if (baseURI[baseURI.length - 1] !== '/')
baseURI += '/';
/*
* LoaderError with chaining for loader stacks
*/
var errArgs = new Error(0, '_').fileName == '_';
function LoaderError__Check_error_message_for_loader_stack (childErr, newMessage) {
// Convert file:/// URLs to paths in Node
if (!isBrowser)
newMessage = newMessage.replace(isWindows ? /file:\/\/\//g : /file:\/\//g, '');
var message = (childErr.message || childErr) + '\n ' + newMessage;
var err;
if (errArgs && childErr.fileName)
err = new Error(message, childErr.fileName, childErr.lineNumber);
else
err = new Error(message);
var stack = childErr.originalErr ? childErr.originalErr.stack : childErr.stack;
if (isNode)
// node doesn't show the message otherwise
err.stack = message + '\n ' + stack;
else
err.stack = stack;
err.originalErr = childErr.originalErr || childErr;
return err;
}
var resolvedPromise = Promise.resolve();
/*
* Simple Array values shim
*/
function arrayValues (arr) {
if (arr.values)
return arr.values();
if (typeof Symbol === 'undefined' || !Symbol.iterator)
throw new Error('Symbol.iterator not supported in this browser');
var iterable = {};
iterable[Symbol.iterator] = function () {
var keys = Object.keys(arr);
var keyIndex = 0;
return {
next: function () {
if (keyIndex < keys.length)
return {
value: arr[keys[keyIndex++]],
done: false
};
else
return {
value: undefined,
done: true
};
}
};
};
return iterable;
}
/*
* 3. Reflect.Loader
*
* We skip the entire native internal pipeline, just providing the bare API
*/
// 3.1.1
function Loader () {
this.registry = new Registry();
}
// 3.3.1
Loader.prototype.constructor = Loader;
function ensureInstantiated (module) {
if (!(module instanceof ModuleNamespace))
throw new TypeError('Module instantiation did not return a valid namespace object.');
return module;
}
// 3.3.2
Loader.prototype.import = function (key, parent) {
if (typeof key !== 'string')
throw new TypeError('Loader import method must be passed a module key string');
// custom resolveInstantiate combined hook for better perf
var loader = this;
return resolvedPromise
.then(function () {
return loader[RESOLVE_INSTANTIATE](key, parent);
})
.then(ensureInstantiated)
//.then(Module.evaluate)
.catch(function (err) {
throw LoaderError__Check_error_message_for_loader_stack(err, 'Loading ' + key + (parent ? ' from ' + parent : ''));
});
};
// 3.3.3
var RESOLVE = Loader.resolve = createSymbol('resolve');
/*
* Combined resolve / instantiate hook
*
* Not in current reduced spec, but necessary to separate RESOLVE from RESOLVE + INSTANTIATE as described
* in the spec notes of this repo to ensure that loader.resolve doesn't instantiate when not wanted.
*
* We implement RESOLVE_INSTANTIATE as a single hook instead of a separate INSTANTIATE in order to avoid
* the need for double registry lookups as a performance optimization.
*/
var RESOLVE_INSTANTIATE = Loader.resolveInstantiate = createSymbol('resolveInstantiate');
// default resolveInstantiate is just to call resolve and then get from the registry
// this provides compatibility for the resolveInstantiate optimization
Loader.prototype[RESOLVE_INSTANTIATE] = function (key, parent) {
var loader = this;
return loader.resolve(key, parent)
.then(function (resolved) {
return loader.registry.get(resolved);
});
};
function ensureResolution (resolvedKey) {
if (resolvedKey === undefined)
throw new RangeError('No resolution found.');
return resolvedKey;
}
Loader.prototype.resolve = function (key, parent) {
var loader = this;
return resolvedPromise
.then(function() {
return loader[RESOLVE](key, parent);
})
.then(ensureResolution)
.catch(function (err) {
throw LoaderError__Check_error_message_for_loader_stack(err, 'Resolving ' + key + (parent ? ' to ' + parent : ''));
});
};
// 3.3.4 (import without evaluate)
// this is not documented because the use of deferred evaluation as in Module.evaluate is not
// documented, as it is not considered a stable feature to be encouraged
// Loader.prototype.load may well be deprecated if this stays disabled
/* Loader.prototype.load = function (key, parent) {
return Promise.resolve(this[RESOLVE_INSTANTIATE](key, parent || this.key))
.catch(function (err) {
throw addToError(err, 'Loading ' + key + (parent ? ' from ' + parent : ''));
});
}; */
/*
* 4. Registry
*
* Instead of structuring through a Map, just use a dictionary object
* We throw for construction attempts so this doesn't affect the public API
*
* Registry has been adjusted to use Namespace objects over ModuleStatus objects
* as part of simplifying loader API implementation
*/
var iteratorSupport = typeof Symbol !== 'undefined' && Symbol.iterator;
var REGISTRY = createSymbol('registry');
function Registry() {
this[REGISTRY] = {};
this._registry = REGISTRY;
}
// 4.4.1
if (iteratorSupport) {
// 4.4.2
Registry.prototype[Symbol.iterator] = function () {
return this.entries()[Symbol.iterator]();
};
// 4.4.3
Registry.prototype.entries = function () {
var registry = this[REGISTRY];
return arrayValues(Object.keys(registry).map(function (key) {
return [key, registry[key]];
}));
};
}
// 4.4.4
Registry.prototype.keys = function () {
return arrayValues(Object.keys(this[REGISTRY]));
};
// 4.4.5
Registry.prototype.values = function () {
var registry = this[REGISTRY];
return arrayValues(Object.keys(registry).map(function (key) {
return registry[key];
}));
};
// 4.4.6
Registry.prototype.get = function (key) {
return this[REGISTRY][key];
};
// 4.4.7
Registry.prototype.set = function (key, namespace) {
if (!(namespace instanceof ModuleNamespace))
throw new Error('Registry must be set with an instance of Module Namespace');
this[REGISTRY][key] = namespace;
return this;
};
// 4.4.8
Registry.prototype.has = function (key) {
return Object.hasOwnProperty.call(this[REGISTRY], key);
};
// 4.4.9
Registry.prototype.delete = function (key) {
if (Object.hasOwnProperty.call(this[REGISTRY], key)) {
delete this[REGISTRY][key];
return true;
}
return false;
};
/*
* Simple ModuleNamespace Exotic object based on a baseObject
* We export this for allowing a fast-path for module namespace creation over Module descriptors
*/
// var EVALUATE = createSymbol('evaluate');
var BASE_OBJECT = createSymbol('baseObject');
// 8.3.1 Reflect.Module
/*
* Best-effort simplified non-spec implementation based on
* a baseObject referenced via getters.
*
* Allows:
*
* loader.registry.set('x', new Module({ default: 'x' }));
*
* Optional evaluation function provides experimental Module.evaluate
* support for non-executed modules in registry.
*/
function ModuleNamespace (baseObject/*, evaluate*/) {
Object.defineProperty(this, BASE_OBJECT, {
value: baseObject
});
// evaluate defers namespace population
/* if (evaluate) {
Object.defineProperty(this, EVALUATE, {
value: evaluate,
configurable: true,
writable: true
});
}
else { */
Object.keys(baseObject).forEach(extendNamespace, this);
//}
}
// 8.4.2
ModuleNamespace.prototype = Object.create(null);
if (typeof Symbol !== 'undefined' && Symbol.toStringTag)
Object.defineProperty(ModuleNamespace.prototype, Symbol.toStringTag, {
value: 'Module'
});
function extendNamespace (key) {
Object.defineProperty(this, key, {
enumerable: true,
get: function () {
return this[BASE_OBJECT][key];
}
});
}
/* function doEvaluate (evaluate, context) {
try {
evaluate.call(context);
}
catch (e) {
return e;
}
}
// 8.4.1 Module.evaluate... not documented or used because this is potentially unstable
Module.evaluate = function (ns) {
var evaluate = ns[EVALUATE];
if (evaluate) {
ns[EVALUATE] = undefined;
var err = doEvaluate(evaluate);
if (err) {
// cache the error
ns[EVALUATE] = function () {
throw err;
};
throw err;
}
Object.keys(ns[BASE_OBJECT]).forEach(extendNamespace, ns);
}
// make chainable
return ns;
}; */
/*
* Optimized URL normalization assuming a syntax-valid URL parent
*/
function throwResolveError (relUrl, parentUrl) {
throw new RangeError('Unable to resolve "' + relUrl + '" to ' + parentUrl);
}
function resolveIfNotPlain (relUrl, parentUrl) {
relUrl = relUrl.trim();
var parentProtocol = parentUrl && parentUrl.substr(0, parentUrl.indexOf(':') + 1);
var firstChar = relUrl[0];
var secondChar = relUrl[1];
// protocol-relative
if (firstChar === '/' && secondChar === '/') {
if (!parentProtocol)
throwResolveError(relUrl, parentUrl);
return parentProtocol + relUrl;
}
// relative-url
else if (firstChar === '.' && (secondChar === '/' || secondChar === '.' && (relUrl[2] === '/' || relUrl.length === 2) || relUrl.length === 1)
|| firstChar === '/') {
var parentIsPlain = !parentProtocol || parentUrl[parentProtocol.length] !== '/';
// read pathname from parent if a URL
// pathname taken to be part after leading "/"
var pathname;
if (parentIsPlain) {
// resolving to a plain parent -> skip standard URL prefix, and treat entire parent as pathname
if (parentUrl === undefined)
throwResolveError(relUrl, parentUrl);
pathname = parentUrl;
}
else if (parentUrl[parentProtocol.length + 1] === '/') {
// resolving to a :// so we need to read out the auth and host
if (parentProtocol !== 'file:') {
pathname = parentUrl.substr(parentProtocol.length + 2);
pathname = pathname.substr(pathname.indexOf('/') + 1);
}
else {
pathname = parentUrl.substr(8);
}
}
else {
// resolving to :/ so pathname is the /... part
pathname = parentUrl.substr(parentProtocol.length + 1);
}
if (firstChar === '/') {
if (parentIsPlain)
throwResolveError(relUrl, parentUrl);
else
return parentUrl.substr(0, parentUrl.length - pathname.length - 1) + relUrl;
}
// join together and split for removal of .. and . segments
// looping the string instead of anything fancy for perf reasons
// '../../../../../z' resolved to 'x/y' is just 'z' regardless of parentIsPlain
var segmented = pathname.substr(0, pathname.lastIndexOf('/') + 1) + relUrl;
var output = [];
var segmentIndex = undefined;
for (var i = 0; i < segmented.length; i++) {
// busy reading a segment - only terminate on '/'
if (segmentIndex !== undefined) {
if (segmented[i] === '/') {
output.push(segmented.substr(segmentIndex, i - segmentIndex + 1));
segmentIndex = undefined;
}
continue;
}
// new segment - check if it is relative
if (segmented[i] === '.') {
// ../ segment
if (segmented[i + 1] === '.' && (segmented[i + 2] === '/' || i === segmented.length - 2)) {
output.pop();
i += 2;
}
// ./ segment
else if (segmented[i + 1] === '/' || i === segmented.length - 1) {
i += 1;
}
else {
// the start of a new segment as below
segmentIndex = i;
continue;
}
// this is the plain URI backtracking error (../, package:x -> error)
if (parentIsPlain && output.length === 0)
throwResolveError(relUrl, parentUrl);
// trailing . or .. segment
if (i === segmented.length)
output.push('');
continue;
}
// it is the start of a new segment
segmentIndex = i;
}
// finish reading out the last segment
if (segmentIndex !== undefined)
output.push(segmented.substr(segmentIndex, segmented.length - segmentIndex));
return parentUrl.substr(0, parentUrl.length - pathname.length) + output.join('');
}
// sanitizes and verifies (by returning undefined if not a valid URL-like form)
// Windows filepath compatibility is an added convenience here
var protocolIndex = relUrl.indexOf(':');
if (protocolIndex !== -1) {
if (isNode) {
// C:\x becomes file:///c:/x (we don't support C|\x)
if (relUrl[1] === ':' && relUrl[2] === '\\' && relUrl[0].match(/[a-z]/i))
return 'file:///' + relUrl.replace(/\\/g, '/');
}
return relUrl;
}
}
/*
* Register Loader
*
* Builds directly on top of loader polyfill to provide:
* - loader.register support
* - hookable higher-level resolve
* - instantiate hook returning a ModuleNamespace or undefined for es module loading
* - loader error behaviour as in HTML and loader specs, clearing failed modules from registration cache synchronously
* - build tracing support by providing a .trace=true and .loads object format
*/
var REGISTER_INTERNAL = createSymbol('register-internal');
function RegisterLoader$1 () {
Loader.call(this);
var registryDelete = this.registry.delete;
this.registry.delete = function (key) {
var deleted = registryDelete.call(this, key);
// also delete from register registry if linked
if (records.hasOwnProperty(key) && !records[key].linkRecord)
delete records[key];
return deleted;
};
var records = {};
this[REGISTER_INTERNAL] = {
// last anonymous System.register call
lastRegister: undefined,
// in-flight es module load records
records: records
};
// tracing
this.trace = false;
}
RegisterLoader$1.prototype = Object.create(Loader.prototype);
RegisterLoader$1.prototype.constructor = RegisterLoader$1;
var INSTANTIATE = RegisterLoader$1.instantiate = createSymbol('instantiate');
// default normalize is the WhatWG style normalizer
RegisterLoader$1.prototype[RegisterLoader$1.resolve = Loader.resolve] = function (key, parentKey) {
return resolveIfNotPlain(key, parentKey || baseURI);
};
RegisterLoader$1.prototype[INSTANTIATE] = function (key, processAnonRegister) {};
// once evaluated, the linkRecord is set to undefined leaving just the other load record properties
// this allows tracking new binding listeners for es modules through importerSetters
// for dynamic modules, the load record is removed entirely.
function createLoadRecord (state, key, registration) {
return state.records[key] = {
key: key,
// defined System.register cache
registration: registration,
// module namespace object
module: undefined,
// es-only
// this sticks around so new module loads can listen to binding changes
// for already-loaded modules by adding themselves to their importerSetters
importerSetters: undefined,
// in-flight linking record
linkRecord: {
// promise for instantiated
instantiatePromise: undefined,
dependencies: undefined,
execute: undefined,
executingRequire: false,
// underlying module object bindings
moduleObj: undefined,
// es only, also indicates if es or not
setters: undefined,
// promise for instantiated dependencies (dependencyInstantiations populated)
depsInstantiatePromise: undefined,
// will be the array of dependency load record or a module namespace
dependencyInstantiations: undefined,
// indicates if the load and all its dependencies are instantiated and linked
// but not yet executed
// mostly just a performance shortpath to avoid rechecking the promises above
linked: false,
error: undefined
// NB optimization and way of ensuring module objects in setters
// indicates setters which should run pre-execution of that dependency
// setters is then just for completely executed module objects
// alternatively we just pass the partially filled module objects as
// arguments into the execute function
// hoisted: undefined
}
};
}
RegisterLoader$1.prototype[Loader.resolveInstantiate] = function (key, parentKey) {
var loader = this;
var state = this[REGISTER_INTERNAL];
var registry = loader.registry[loader.registry._registry];
return resolveInstantiate(loader, key, parentKey, registry, state)
.then(function (instantiated) {
if (instantiated instanceof ModuleNamespace)
return instantiated;
// if already beaten to linked, return
if (instantiated.module)
return instantiated.module;
// resolveInstantiate always returns a load record with a link record and no module value
if (instantiated.linkRecord.linked)
return ensureEvaluate(loader, instantiated, instantiated.linkRecord, registry, state, undefined);
return instantiateDeps(loader, instantiated, instantiated.linkRecord, registry, state, [instantiated])
.then(function () {
return ensureEvaluate(loader, instantiated, instantiated.linkRecord, registry, state, undefined);
})
.catch(function (err) {
clearLoadErrors(loader, instantiated);
throw err;
});
});
};
function resolveInstantiate (loader, key, parentKey, registry, state) {
// normalization shortpath for already-normalized key
// could add a plain name filter, but doesn't yet seem necessary for perf
var module = registry[key];
if (module)
return Promise.resolve(module);
var load = state.records[key];
// already linked but not in main registry is ignored
if (load && !load.module)
return instantiate(loader, load, load.linkRecord, registry, state);
return loader.resolve(key, parentKey)
.then(function (resolvedKey) {
// main loader registry always takes preference
module = registry[resolvedKey];
if (module)
return module;
load = state.records[resolvedKey];
// already has a module value but not already in the registry (load.module)
// means it was removed by registry.delete, so we should
// disgard the current load record creating a new one over it
// but keep any existing registration
if (!load || load.module)
load = createLoadRecord(state, resolvedKey, load && load.registration);
var link = load.linkRecord;
if (!link)
return load;
return instantiate(loader, load, link, registry, state);
});
}
function createProcessAnonRegister (loader, load, state) {
return function () {
var lastRegister = state.lastRegister;
if (!lastRegister)
return !!load.registration;
state.lastRegister = undefined;
load.registration = lastRegister;
return true;
};
}
function instantiate (loader, load, link, registry, state) {
return link.instantiatePromise || (link.instantiatePromise =
// if there is already an existing registration, skip running instantiate
(load.registration ? Promise.resolve() : Promise.resolve().then(function () {
state.lastRegister = undefined;
return loader[INSTANTIATE](load.key, loader[INSTANTIATE].length > 1 && createProcessAnonRegister(loader, load, state));
}))
.then(function (instantiation) {
// direct module return from instantiate -> we're done
if (instantiation !== undefined) {
if (!(instantiation instanceof ModuleNamespace))
throw new TypeError('Instantiate did not return a valid Module object.');
delete state.records[load.key];
if (loader.trace)
traceLoad(loader, load, link);
return registry[load.key] = instantiation;
}
// run the cached loader.register declaration if there is one
var registration = load.registration;
// clear to allow new registrations for future loads (combined with registry delete)
load.registration = undefined;
if (!registration)
throw new TypeError('Module instantiation did not call an anonymous or correctly named System.register.');
link.dependencies = registration[0];
load.importerSetters = [];
link.moduleObj = {};
// process System.registerDynamic declaration
if (registration[2]) {
link.moduleObj.default = {};
link.moduleObj.__useDefault = true;
link.executingRequire = registration[1];
link.execute = registration[2];
}
// process System.register declaration
else {
registerDeclarative(loader, load, link, registration[1]);
}
// shortpath to instantiateDeps
if (!link.dependencies.length) {
link.linked = true;
if (loader.trace)
traceLoad(loader, load, link);
}
return load;
})
.catch(function (err) {
throw link.error = LoaderError__Check_error_message_for_loader_stack(err, 'Instantiating ' + load.key);
}));
}
// like resolveInstantiate, but returning load records for linking
function resolveInstantiateDep (loader, key, parentKey, registry, state, traceDepMap) {
// normalization shortpaths for already-normalized key
// DISABLED to prioritise consistent resolver calls
// could add a plain name filter, but doesn't yet seem necessary for perf
/* var load = state.records[key];
var module = registry[key];
if (module) {
if (traceDepMap)
traceDepMap[key] = key;
// registry authority check in case module was deleted or replaced in main registry
if (load && load.module && load.module === module)
return load;
else
return module;
}
// already linked but not in main registry is ignored
if (load && !load.module) {
if (traceDepMap)
traceDepMap[key] = key;
return instantiate(loader, load, load.linkRecord, registry, state);
} */
return loader.resolve(key, parentKey)
.then(function (resolvedKey) {
if (traceDepMap)
traceDepMap[key] = resolvedKey;
// normalization shortpaths for already-normalized key
var load = state.records[resolvedKey];
var module = registry[resolvedKey];
// main loader registry always takes preference
if (module && (!load || load.module && module !== load.module))
return module;
// already has a module value but not already in the registry (load.module)
// means it was removed by registry.delete, so we should
// disgard the current load record creating a new one over it
// but keep any existing registration
if (!load || !module && load.module)
load = createLoadRecord(state, resolvedKey, load && load.registration);
var link = load.linkRecord;
if (!link)
return load;
return instantiate(loader, load, link, registry, state);
});
}
function traceLoad (loader, load, link) {
loader.loads = loader.loads || {};
loader.loads[load.key] = {
key: load.key,
deps: link.dependencies,
depMap: link.depMap || {}
};
}
/*
* Convert a CJS module.exports into a valid object for new Module:
*
* new Module(getEsModule(module.exports))
*
* Sets the default value to the module, while also reading off named exports carefully.
*/
function registerDeclarative (loader, load, link, declare) {
var moduleObj = link.moduleObj;
var importerSetters = load.importerSetters;
var locked = false;
// closure especially not based on link to allow link record disposal
var declared = declare.call(envGlobal, function (name, value) {
// export setter propogation with locking to avoid cycles
if (locked)
return;
if (typeof name === 'object') {
for (var p in name)
if (p !== '__useDefault')
moduleObj[p] = name[p];
}
else {
moduleObj[name] = value;
}
locked = true;
for (var i = 0; i < importerSetters.length; i++)
importerSetters[i](moduleObj);
locked = false;
return value;
}, new ContextualLoader(loader, load.key));
link.setters = declared.setters;
link.execute = declared.execute;
if (declared.exports)
link.moduleObj = moduleObj = declared.exports;
}
function instantiateDeps (loader, load, link, registry, state, seen) {
return (link.depsInstantiatePromise || (link.depsInstantiatePromise = Promise.resolve()
.then(function () {
var depsInstantiatePromises = Array(link.dependencies.length);
for (var i = 0; i < link.dependencies.length; i++)
depsInstantiatePromises[i] = resolveInstantiateDep(loader, link.dependencies[i], load.key, registry, state, loader.trace && link.depMap || (link.depMap = {}));
return Promise.all(depsInstantiatePromises);
})
.then(function (dependencyInstantiations) {
link.dependencyInstantiations = dependencyInstantiations;
// run setters to set up bindings to instantiated dependencies
if (link.setters) {
for (var i = 0; i < dependencyInstantiations.length; i++) {
var setter = link.setters[i];
if (setter) {
var instantiation = dependencyInstantiations[i];
if (instantiation instanceof ModuleNamespace) {
setter(instantiation);
}
else {
setter(instantiation.module || instantiation.linkRecord.moduleObj);
// this applies to both es and dynamic registrations
if (instantiation.importerSetters)
instantiation.importerSetters.push(setter);
}
}
}
}
})))
.then(function () {
// now deeply instantiateDeps on each dependencyInstantiation that is a load record
var deepDepsInstantiatePromises = [];
for (var i = 0; i < link.dependencies.length; i++) {
var depLoad = link.dependencyInstantiations[i];
var depLink = depLoad.linkRecord;
if (!depLink || depLink.linked)
continue;
if (seen.indexOf(depLoad) !== -1)
continue;
seen.push(depLoad);
deepDepsInstantiatePromises.push(instantiateDeps(loader, depLoad, depLoad.linkRecord, registry, state, seen));
}
return Promise.all(deepDepsInstantiatePromises);
})
.then(function () {
// as soon as all dependencies instantiated, we are ready for evaluation so can add to the registry
// this can run multiple times, but so what
link.linked = true;
if (loader.trace)
traceLoad(loader, load, link);
return load;
})
.catch(function (err) {
err = LoaderError__Check_error_message_for_loader_stack(err, 'Loading ' + load.key);
// throw up the instantiateDeps stack
// loads are then synchonously cleared at the top-level through the clearLoadErrors helper below
// this then ensures avoiding partially unloaded tree states
link.error = link.error || err;
throw err;
});
}
// clears an errored load and all its errored dependencies from the loads registry
function clearLoadErrors (loader, load) {
var state = loader[REGISTER_INTERNAL];
// clear from loads
if (state.records[load.key] === load)
delete state.records[load.key];
var link = load.linkRecord;
if (!link)
return;
if (link.dependencyInstantiations)
link.dependencyInstantiations.forEach(function (depLoad, index) {
if (!depLoad || depLoad instanceof ModuleNamespace)
return;
if (depLoad.linkRecord) {
if (depLoad.linkRecord.error) {
// provides a circular reference check
if (state.records[depLoad.key] === depLoad)
clearLoadErrors(loader, depLoad);
}
// unregister setters for es dependency load records that will remain
if (link.setters && depLoad.importerSetters) {
var setterIndex = depLoad.importerSetters.indexOf(link.setters[index]);
depLoad.importerSetters.splice(setterIndex, 1);
}
}
});
}
/*
* System.register
*/
RegisterLoader$1.prototype.register = function (key, deps, declare) {
var state = this[REGISTER_INTERNAL];
// anonymous modules get stored as lastAnon
if (declare === undefined) {
state.lastRegister = [key, deps, undefined];
}
// everything else registers into the register cache
else {
var load = state.records[key] || createLoadRecord(state, key, undefined);
load.registration = [deps, declare, undefined];
}
};
/*
* System.registerDyanmic
*/
RegisterLoader$1.prototype.registerDynamic = function (key, deps, executingRequire, execute) {
var state = this[REGISTER_INTERNAL];
// anonymous modules get stored as lastAnon
if (typeof key !== 'string') {
state.lastRegister = [key, deps, executingRequire];
}
// everything else registers into the register cache
else {
var load = state.records[key] || createLoadRecord(state, key, undefined);
load.registration = [deps, executingRequire, execute];
}
};
// ContextualLoader class
// backwards-compatible with previous System.register context argument by exposing .id
function ContextualLoader (loader, key) {
this.loader = loader;
this.key = this.id = key;
}
ContextualLoader.prototype.constructor = function () {
throw new TypeError('Cannot subclass the contextual loader only Reflect.Loader.');
};
ContextualLoader.prototype.import = function (key) {
return this.loader.import(key, this.key);
};
ContextualLoader.prototype.resolve = function (key) {
return this.loader.resolve(key, this.key);
};
ContextualLoader.prototype.load = function (key) {
return this.loader.load(key, this.key);
};
// this is the execution function bound to the Module namespace record
function ensureEvaluate (loader, load, link, registry, state, seen) {
if (load.module)
return load.module;
if (link.error)
throw link.error;
if (seen && seen.indexOf(load) !== -1)
return load.linkRecord.moduleObj;
// for ES loads we always run ensureEvaluate on top-level, so empty seen is passed regardless
// for dynamic loads, we pass seen if also dynamic
var err = doEvaluate(loader, load, link, registry, state, link.setters ? [] : seen || []);
if (err) {
clearLoadErrors(loader, load);
throw err;
}
return load.module;
}
function makeDynamicRequire (loader, key, dependencies, dependencyInstantiations, registry, state, seen) {
// we can only require from already-known dependencies
return function (name) {
for (var i = 0; i < dependencies.length; i++) {
if (dependencies[i] === name) {
var depLoad = dependencyInstantiations[i];
var module;
if (depLoad instanceof ModuleNamespace)
module = depLoad;
else
module = ensureEvaluate(loader, depLoad, depLoad.linkRecord, registry, state, seen);
return module.__useDefault ? module.default : module;
}
}
throw new Error('Module ' + name + ' not declared as a System.registerDynamic dependency of ' + key);
};
}
// ensures the given es load is evaluated
// returns the error if any
function doEvaluate (loader, load, link, registry, state, seen) {
seen.push(load);
var err;
// es modules evaluate dependencies first
// non es modules explicitly call moduleEvaluate through require
if (link.setters) {
var depLoad, depLink;
for (var i = 0; i < link.dependencies.length; i++) {
depLoad = link.dependencyInstantiations[i];
if (depLoad instanceof ModuleNamespace)
continue;
// custom Module returned from instantiate
depLink = depLoad.linkRecord;
if (depLink && seen.indexOf(depLoad) === -1) {
if (depLink.error)
err = depLink.error;
else
// dynamic / declarative boundaries clear the "seen" list
// we just let cross format circular throw as would happen in real implementations
err = doEvaluate(loader, depLoad, depLink, registry, state, depLink.setters ? seen : []);
}
if (err)
return link.error = LoaderError__Check_error_message_for_loader_stack(err, 'Evaluating ' + load.key);
}
}
// link.execute won't exist for Module returns from instantiate on top-level load
if (link.execute) {
// ES System.register execute
// "this" is null in ES
if (link.setters) {
err = declarativeExecute(link.execute);
}
// System.registerDynamic execute
// "this" is "exports" in CJS
else {
var module = { id: load.key };
var moduleObj = link.moduleObj;
Object.defineProperty(module, 'exports', {
configurable: true,
set: function (exports) {
moduleObj.default = exports;
},
get: function () {
return moduleObj.default;
}
});
var require = makeDynamicRequire(loader, load.key, link.dependencies, link.dependencyInstantiations, registry, state, seen);
// evaluate deps first
if (!link.executingRequire)
for (var i = 0; i < link.dependencies.length; i++)
require(link.dependencies[i]);
err = dynamicExecute(link.execute, require, moduleObj.default, module);
// pick up defineProperty calls to module.exports when we can
if (module.exports !== moduleObj.default)
moduleObj.default = module.exports;
var moduleDefault = moduleObj.default;
// __esModule flag extension support via lifting
if (moduleDefault && moduleDefault.__esModule) {
if (moduleObj.__useDefault)
delete moduleObj.__useDefault;
for (var p in moduleDefault) {
if (Object.hasOwnProperty.call(moduleDefault, p))
moduleObj[p] = moduleDefault[p];
}
moduleObj.__esModule = true;
}
}
}
if (err)
return link.error = LoaderError__Check_error_message_for_loader_stack(err, 'Evaluating ' + load.key);
registry[load.key] = load.module = new ModuleNamespace(link.moduleObj);
// if not an esm module, run importer setters and clear them
// this allows dynamic modules to update themselves into es modules
// as soon as execution has completed
if (!link.setters) {
if (load.importerSetters)
for (var i = 0; i < load.importerSetters.length; i++)
load.importerSetters[i](load.module);
load.importerSetters = undefined;
}
// dispose link record
load.linkRecord = undefined;
}
// {} is the closest we can get to call(undefined)
var nullContext = {};
if (Object.freeze)
Object.freeze(nullContext);
function declarativeExecute (execute) {
try {
execute.call(nullContext);
}
catch (e) {
return e;
}
}
function dynamicExecute (execute, require, exports, module) {
try {
var output = execute.call(envGlobal, require, exports, module);
if (output !== undefined)
module.exports = output;
}
catch (e) {
return e;
}
}
var loader;
// <script type="module"> support
var anonSources = {};
if (typeof document != 'undefined' && document.getElementsByTagName) {
var handleError = function(err) {
// dispatch an error event so that we can display in errors in browsers
// that don't yet support unhandledrejection
if (window.onunhandledrejection === undefined) {
try {
var evt = new Event('error');
} catch (_eventError) {
var evt = document.createEvent('Event');
evt.initEvent('error', true, true);
}
evt.message = err.message;
if (err.fileName) {
evt.filename = err.fileName;
evt.lineno = err.lineNumber;
evt.colno = err.columnNumber;
} else if (err.sourceURL) {
evt.filename = err.sourceURL;
evt.lineno = err.line;
evt.colno = err.column;
}
evt.error = err;
window.dispatchEvent(evt);
}
// throw so it still shows up in the console
throw err;
};
var ready = function() {
document.removeEventListener('DOMContentLoaded', ready, false );
var anonCnt = 0;
var scripts = document.getElementsByTagName('script');
for (var i = 0; i < scripts.length; i++) {
var script = scripts[i];
if (script.type == 'module' && !script.loaded) {
script.loaded = true;
if (script.src) {
loader.import(script.src).catch(handleError);
}
// anonymous modules supported via a custom naming scheme and registry
else {
var uri = './<anon' + ++anonCnt + '>';
if (script.id !== ""){
uri = "./" + script.id;
}
var anonName = resolveIfNotPlain(uri, baseURI);
anonSources[anonName] = script.innerHTML;
loader.import(anonName).catch(handleError);
}
}
}
};
// simple DOM ready
if (document.readyState === 'complete')
setTimeout(ready);
else
document.addEventListener('DOMContentLoaded', ready, false);
}
function BrowserESModuleLoader(baseKey) {
if (baseKey)
this.baseKey = resolveIfNotPlain(baseKey, baseURI) || resolveIfNotPlain('./' + baseKey, baseURI);
RegisterLoader$1.call(this);
var loader = this;
// ensure System.register is available
envGlobal.System = envGlobal.System || {};
if (typeof envGlobal.System.register == 'function')
var prevRegister = envGlobal.System.register;
envGlobal.System.register = function() {
loader.register.apply(loader, arguments);
if (prevRegister)
prevRegister.apply(this, arguments);
};
}
BrowserESModuleLoader.prototype = Object.create(RegisterLoader$1.prototype);
// normalize is never given a relative name like "./x", that part is already handled
BrowserESModuleLoader.prototype[RegisterLoader$1.resolve] = function(key, parent) {
var resolved = RegisterLoader$1.prototype[RegisterLoader$1.resolve].call(this, key, parent || this.baseKey) || key;
if (!resolved)
throw new RangeError('ES module loader does not resolve plain module names, resolving "' + key + '" to ' + parent);
return resolved;
};
function xhrFetch(url, resolve, reject) {
var xhr = new XMLHttpRequest();
var load = function(source) {
resolve(xhr.responseText);
};
var error = function() {
reject(new Error('XHR error' + (xhr.status ? ' (' + xhr.status + (xhr.statusText ? ' ' + xhr.statusText : '') + ')' : '') + ' loading ' + url));
};
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
// in Chrome on file:/// URLs, status is 0
if (xhr.status == 0) {
if (xhr.responseText) {
load();
}
else {
// when responseText is empty, wait for load or error event
// to inform if it is a 404 or empty file
xhr.addEventListener('error', error);
xhr.addEventListener('load', load);
}
}
else if (xhr.status === 200) {
load();
}
else {
error();
}
}
};
xhr.open("GET", url, true);
xhr.send(null);
}
var WorkerPool = function (script, size) {
script = document.currentScript.src.substr(0, document.currentScript.src.lastIndexOf("/")) + "/" + script;
this._workers = new Array(size);
this._ind = 0;
this._size = size;
this._jobs = 0;
this.onmessage = undefined;
this._stopTimeout = undefined;
for (var i = 0; i < size; i++) {
var wrkr = new Worker(script);
wrkr._count = 0;
wrkr._ind = i;
wrkr.onmessage = this._onmessage.bind(this, wrkr);
wrkr.onerror = this._onerror.bind(this);
this._workers[i] = wrkr;
}
this._checkJobs();
};
WorkerPool.prototype = {
postMessage: function (msg) {
if (this._stopTimeout !== undefined) {
clearTimeout(this._stopTimeout);
this._stopTimeout = undefined;
}
var wrkr = this._workers[this._ind % this._size];
wrkr._count++;
this._jobs++;
wrkr.postMessage(msg);
this._ind++;
},
_onmessage: function (wrkr, evt) {
wrkr._count--;
this._jobs--;
this.onmessage(evt, wrkr);
this._checkJobs();
},
_onerror: function(err) {
try {
var evt = new Event('error');
} catch (_eventError) {
var evt = document.createEvent('Event');
evt.initEvent('error', true, true);
}
evt.message = err.message;
evt.filename = err.filename;
evt.lineno = err.lineno;
evt.colno = err.colno;
evt.error = err.error;
window.dispatchEvent(evt);
},
_checkJobs: function () {
if (this._jobs === 0 && this._stopTimeout === undefined) {
// wait for 2s of inactivity before stopping (that should be enough for local loading)
this._stopTimeout = setTimeout(this._stop.bind(this), 2000);
}
},
_stop: function () {
this._workers.forEach(function(wrkr) {
wrkr.terminate();
});
}
};
var promiseMap = new Map();
var babelWorker = new WorkerPool('babel-worker.js', 3);
babelWorker.onmessage = function (evt) {
var promFuncs = promiseMap.get(evt.data.key);
promFuncs.resolve(evt.data);
promiseMap.delete(evt.data.key);
};
// instantiate just needs to run System.register
// so we fetch the source, convert into the Babel System module format, then evaluate it
BrowserESModuleLoader.prototype[RegisterLoader$1.instantiate] = function(key, processAnonRegister) {
var loader = this;
// load as ES with Babel converting into System.register
return new Promise(function(resolve, reject) {
// anonymous module
if (anonSources[key]) {
resolve(anonSources[key]);
anonSources[key] = undefined;
}
// otherwise we fetch
else {
xhrFetch(key, resolve, reject);
}
})
.then(function(source) {
// check our cache first
var cacheEntry = localStorage.getItem(key);
if (cacheEntry) {
cacheEntry = JSON.parse(cacheEntry);
// TODO: store a hash instead
if (cacheEntry.source === source) {
return Promise.resolve({key: key, code: cacheEntry.code, source: cacheEntry.source});
}
}
return new Promise(function (resolve, reject) {
promiseMap.set(key, {resolve: resolve, reject: reject});
babelWorker.postMessage({key: key, source: source});
});
}).then(function (data) {
// evaluate without require, exports and module variables
// we leave module in for now to allow module.require access
try {
var cacheEntry = JSON.stringify({source: data.source, code: data.code});
localStorage.setItem(key, cacheEntry);
} catch (e) {
if (window.console) {
window.console.warn('Unable to cache transpiled version of ' + key + ': ' + e);
}
}
(0, eval)(data.code + '\n//# sourceURL=' + data.key + '!transpiled');
processAnonRegister();
});
};
// create a default loader instance in the browser
if (isBrowser)
loader = new BrowserESModuleLoader();
return BrowserESModuleLoader;
})));
//# sourceMappingURL=browser-es-module-loader.js.map
|
var Scanner = require("../Scanner");
var Parser = require("../topDown/Parser");
var json = require("./json");
var fs = require("fs"), path = require("path"), zlib = require("zlib");
var scanner = new Scanner(),
parser = new Parser(json);
fs.readFile(path.resolve(__dirname, "sample.json.gz"), function(err, data){
if(err){
throw err;
}
zlib.gunzip(data, function(err, data){
if(err){
throw err;
}
// let's process the whole file
scanner.addBuffer(data, true);
// now let's loop over tokens
for(;;){
var expected = parser.getExpectedState();
if(!expected){
// we are done
break;
}
var token = scanner.getToken(expected);
if(token === true){
throw Error("Scanner requests more data, which is impossible.");
}
parser.putToken(token, scanner);
}
if(!scanner.isFinished()){
throw Error("Unprocessed symbols: " +
(scanner.buffer.length > 16 ? scanner.buffer.substring(0, 16) + "..." : scanner.buffer));
}
});
});
|
module.exports = function(app, express){
var router = express.Router(),
userRoutes = require('../routes/users')(router),
calorieRoutes = require('../routes/calories')(router);
router.use(function(req, res, next) {
next();
});
app.use('/api', router);
}; |
var printer = require("../lib"),
util = require('util'),
printerName = 'Foxit Reader PDF Printer',
printerFormat = 'TEXT';
printer.printDirect({
data:"print from Node.JS buffer", // or simple String: "some text"
printer:printerName, // printer name
type: printerFormat, // type: RAW, TEXT, PDF, JPEG, .. depends on platform
options: // supported page sizes may be retrieved using getPrinterDriverOptions, supports CUPS printing options
{
media: 'Letter',
'fit-to-page': true
},
success:function(jobID){
console.log("sent to printer with ID: "+jobID);
var jobInfo = printer.getJob(printerName, jobID);
console.log("current job info:"+util.inspect(jobInfo, {depth: 10, colors:true}));
if(jobInfo.status.indexOf('PRINTED') !== -1)
{
console.log('too late, already printed');
return;
}
console.log('cancelling...');
var is_ok = printer.setJob(printerName, jobID, 'CANCEL');
console.log("cancelled: "+is_ok);
try{
console.log("current job info:"+util.inspect(printer.getJob(printerName, jobID), {depth: 10, colors:true}));
}catch(err){
console.log('job deleted. err:'+err);
}
},
error:function(err){console.log(err);}
});
|
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
export default function (a, b, count) {
var step = tickStep(a, b, count);
a = Math.ceil(a / step) * step;
b = Math.floor(b / step) * step + step / 2;
// Add half a step here so that the array returned by `range` includes the last tick.
return range(a, b, step);
}
var e10 = Math.sqrt(50);
var e5 = Math.sqrt(10);
var e2 = Math.sqrt(2);
export function tickStep(a, b, count) {
var rawStep = Math.abs(b - a) / Math.max(0, count);
var step = Math.pow(10, Math.floor(Math.log(rawStep) / Math.LN10)); // = Math.log10(rawStep)
var error = rawStep / step;
if (error >= e10) {
step *= 10;
}
else if (error >= e5) {
step *= 5;
}
else if (error >= e2) {
step *= 2;
}
return b < a ? -step : step;
}
export function tickIncrement(a, b, count) {
var rawStep = (b - a) / Math.max(0, count);
var power = Math.floor(Math.log(rawStep) / Math.LN10);
var error = rawStep / Math.pow(10, power);
return power >= 0
? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)
: -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);
}
var NumericTicks = /** @class */ (function (_super) {
__extends(NumericTicks, _super);
function NumericTicks(fractionDigits, size) {
if (size === void 0) { size = 0; }
var _this = _super.call(this, size) || this;
_this.fractionDigits = fractionDigits;
return _this;
}
return NumericTicks;
}(Array));
export { NumericTicks };
function range(a, b, step) {
if (step === void 0) { step = 1; }
var absStep = Math.abs(step);
var fractionDigits = (absStep > 0 && absStep < 1)
? Math.abs(Math.floor(Math.log(absStep) / Math.LN10))
: 0;
var f = Math.pow(10, fractionDigits);
var n = Math.max(0, Math.ceil((b - a) / step)) || 0;
var values = new NumericTicks(fractionDigits, n);
for (var i = 0; i < n; i++) {
var value = a + step * i;
values[i] = Math.round(value * f) / f;
}
return values;
}
|
define(function() {
var Application = function() {
/*
this.data
this.node
*/
var node,
data,
init = function(_node, _data) {
this.node = _node;
this.data = _data;
var currExecute = $.proxy(this, "execute");
this.node.click(currExecute);
$("div.title", this.node).text(this.data.title).trunk8();
var tmpbg = $(this.node).css("background");
return this;
},
execute = function() {
confirm(this.data.title);
},
getData = function() {
},
updateData = function(_data) {
elucia.debug("### appliaction.updateData ###");
},
destroy = function() {
elucia.debug("### appliaction.destroy ###");
},
that = {
init: init,
execute: execute,
getData: getData,
updateData: updateData,
destroy: destroy
};
return that;
};
return Application;
}); |
module("callbacks", { teardown: moduleTeardown });
(function() {
var output,
addToOutput = function( string ) {
return function() {
output += string;
};
},
outputA = addToOutput( "A" ),
outputB = addToOutput( "B" ),
outputC = addToOutput( "C" ),
tests = {
"": "XABC X XABCABCC X XBB X XABA X",
"once": "XABC X X X X X XABA X",
"memory": "XABC XABC XABCABCCC XA XBB XB XABA XC",
"unique": "XABC X XABCA X XBB X XAB X",
"stopOnFalse": "XABC X XABCABCC X XBB X XA X",
"once memory": "XABC XABC X XA X XA XABA XC",
"once unique": "XABC X X X X X XAB X",
"once stopOnFalse": "XABC X X X X X XA X",
"memory unique": "XABC XA XABCA XA XBB XB XAB XC",
"memory stopOnFalse": "XABC XABC XABCABCCC XA XBB XB XA X",
"unique stopOnFalse": "XABC X XABCA X XBB X XA X"
},
filters = {
"no filter": undefined,
"filter": function( fn ) {
return function() {
return fn.apply( this, arguments );
};
}
};
function showFlags( flags ) {
if ( typeof flags === "string" ) {
return '"' + flags + '"';
}
var output = [], key;
for ( key in flags ) {
output.push( '"' + key + '": ' + flags[ key ] );
}
return "{ " + output.join( ", " ) + " }";
}
jQuery.each( tests, function( strFlags, resultString ) {
var objectFlags = {};
jQuery.each( strFlags.split( " " ), function() {
if ( this.length ) {
objectFlags[ this ] = true;
}
});
jQuery.each( filters, function( filterLabel, filter ) {
jQuery.each( { "string": strFlags, "object": objectFlags }, function( flagsTypes, flags ) {
test( "jQuery.Callbacks( " + showFlags( flags ) + " ) - " + filterLabel, function() {
expect( 20 );
// Give qunit a little breathing room
stop();
setTimeout( start, 0 );
var cblist,
results = resultString.split( /\s+/ );
// Basic binding and firing
output = "X";
cblist = jQuery.Callbacks( flags );
cblist.add(function( str ) {
output += str;
});
cblist.fire( "A" );
strictEqual( output, "XA", "Basic binding and firing" );
strictEqual( cblist.fired(), true, ".fired() detects firing" );
output = "X";
cblist.disable();
cblist.add(function( str ) {
output += str;
});
strictEqual( output, "X", "Adding a callback after disabling" );
cblist.fire( "A" );
strictEqual( output, "X", "Firing after disabling" );
// Basic binding and firing (context, arguments)
output = "X";
cblist = jQuery.Callbacks( flags );
cblist.add(function() {
equal( this, window, "Basic binding and firing (context)" );
output += Array.prototype.join.call( arguments, "" );
});
cblist.fireWith( window, [ "A", "B" ] );
strictEqual( output, "XAB", "Basic binding and firing (arguments)" );
// fireWith with no arguments
output = "";
cblist = jQuery.Callbacks( flags );
cblist.add(function() {
equal( this, window, "fireWith with no arguments (context is window)" );
strictEqual( arguments.length, 0, "fireWith with no arguments (no arguments)" );
});
cblist.fireWith();
// Basic binding, removing and firing
output = "X";
cblist = jQuery.Callbacks( flags );
cblist.add( outputA, outputB, outputC );
cblist.remove( outputB, outputC );
cblist.fire();
strictEqual( output, "XA", "Basic binding, removing and firing" );
// Empty
output = "X";
cblist = jQuery.Callbacks( flags );
cblist.add( outputA );
cblist.add( outputB );
cblist.add( outputC );
cblist.empty();
cblist.fire();
strictEqual( output, "X", "Empty" );
// Locking
output = "X";
cblist = jQuery.Callbacks( flags );
cblist.add( function( str ) {
output += str;
});
cblist.lock();
cblist.add( function( str ) {
output += str;
});
cblist.fire( "A" );
cblist.add( function( str ) {
output += str;
});
strictEqual( output, "X", "Lock early" );
// Ordering
output = "X";
cblist = jQuery.Callbacks( flags );
cblist.add( function() {
cblist.add( outputC );
outputA();
}, outputB );
cblist.fire();
strictEqual( output, results.shift(), "Proper ordering" );
// Add and fire again
output = "X";
cblist.add( function() {
cblist.add( outputC );
outputA();
}, outputB );
strictEqual( output, results.shift(), "Add after fire" );
output = "X";
cblist.fire();
strictEqual( output, results.shift(), "Fire again" );
// Multiple fire
output = "X";
cblist = jQuery.Callbacks( flags );
cblist.add( function( str ) {
output += str;
} );
cblist.fire( "A" );
strictEqual( output, "XA", "Multiple fire (first fire)" );
output = "X";
cblist.add( function( str ) {
output += str;
} );
strictEqual( output, results.shift(), "Multiple fire (first new callback)" );
output = "X";
cblist.fire( "B" );
strictEqual( output, results.shift(), "Multiple fire (second fire)" );
output = "X";
cblist.add( function( str ) {
output += str;
} );
strictEqual( output, results.shift(), "Multiple fire (second new callback)" );
// Return false
output = "X";
cblist = jQuery.Callbacks( flags );
cblist.add( outputA, function() { return false; }, outputB );
cblist.add( outputA );
cblist.fire();
strictEqual( output, results.shift(), "Callback returning false" );
// Add another callback (to control lists with memory do not fire anymore)
output = "X";
cblist.add( outputC );
strictEqual( output, results.shift(), "Adding a callback after one returned false" );
});
});
});
});
})();
test( "jQuery.Callbacks( options ) - options are copied", function() {
expect( 1 );
var options = {
"unique": true
},
cb = jQuery.Callbacks( options ),
count = 0,
fn = function() {
ok( !( count++ ), "called once" );
};
options["unique"] = false;
cb.add( fn, fn );
cb.fire();
});
test( "jQuery.Callbacks.fireWith - arguments are copied", function() {
expect( 1 );
var cb = jQuery.Callbacks( "memory" ),
args = [ "hello" ];
cb.fireWith( null, args );
args[ 0 ] = "world";
cb.add(function( hello ) {
strictEqual( hello, "hello", "arguments are copied internally" );
});
});
test( "jQuery.Callbacks.remove - should remove all instances", function() {
expect( 1 );
var cb = jQuery.Callbacks();
function fn() {
ok( false, "function wasn't removed" );
}
cb.add( fn, fn, function() {
ok( true, "end of test" );
}).remove( fn ).fire();
});
test( "jQuery.Callbacks() - adding a string doesn't cause a stack overflow", function() {
expect( 1 );
jQuery.Callbacks().add( "hello world" );
ok( true, "no stack overflow" );
});
|
this.primereact = this.primereact || {};
this.primereact.megamenu = (function (exports, React, utils, ripple) {
'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var propTypes = {exports: {}};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = ReactPropTypesSecret_1;
function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
var factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
} shim.isRequired = shim;
function getShim() {
return shim;
} // Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
elementType: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim,
checkPropTypes: emptyFunctionWithReset,
resetWarningCache: emptyFunction
};
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
propTypes.exports = factoryWithThrowingShims();
}
var PropTypes = propTypes.exports;
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var MegaMenu = /*#__PURE__*/function (_Component) {
_inherits(MegaMenu, _Component);
var _super = _createSuper(MegaMenu);
function MegaMenu(props) {
var _this;
_classCallCheck(this, MegaMenu);
_this = _super.call(this, props);
_this.state = {
activeItem: null
};
_this.onLeafClick = _this.onLeafClick.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(MegaMenu, [{
key: "onLeafClick",
value: function onLeafClick(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (!item.url) {
event.preventDefault();
}
if (item.command) {
item.command({
originalEvent: event,
item: item
});
}
this.setState({
activeItem: null
});
}
}, {
key: "onCategoryMouseEnter",
value: function onCategoryMouseEnter(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (this.state.activeItem) {
this.setState({
activeItem: item
});
}
}
}, {
key: "onCategoryClick",
value: function onCategoryClick(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (!item.url) {
event.preventDefault();
}
if (item.command) {
item.command({
originalEvent: event,
item: this.props.item
});
}
if (item.items) {
if (this.state.activeItem && this.state.activeItem === item) {
this.setState({
activeItem: null
});
} else {
this.setState({
activeItem: item
});
}
}
event.preventDefault();
}
}, {
key: "onCategoryKeyDown",
value: function onCategoryKeyDown(event, item) {
var listItem = event.currentTarget.parentElement;
switch (event.which) {
//down
case 40:
if (this.isHorizontal()) this.expandMenu(item);else this.navigateToNextItem(listItem);
event.preventDefault();
break;
//up
case 38:
if (this.isVertical()) this.navigateToPrevItem(listItem);else if (item.items && item === this.state.activeItem) this.collapseMenu();
event.preventDefault();
break;
//right
case 39:
if (this.isHorizontal()) this.navigateToNextItem(listItem);else this.expandMenu(item);
event.preventDefault();
break;
//left
case 37:
if (this.isHorizontal()) this.navigateToPrevItem(listItem);else if (item.items && item === this.state.activeItem) this.collapseMenu();
event.preventDefault();
break;
}
}
}, {
key: "expandMenu",
value: function expandMenu(item) {
if (item.items) {
this.setState({
activeItem: item
});
}
}
}, {
key: "collapseMenu",
value: function collapseMenu(item) {
this.setState({
activeItem: null
});
}
}, {
key: "findNextItem",
value: function findNextItem(item) {
var nextItem = item.nextElementSibling;
if (nextItem) return utils.DomHandler.hasClass(nextItem, 'p-disabled') || !utils.DomHandler.hasClass(nextItem, 'p-menuitem') ? this.findNextItem(nextItem) : nextItem;else return null;
}
}, {
key: "findPrevItem",
value: function findPrevItem(item) {
var prevItem = item.previousElementSibling;
if (prevItem) return utils.DomHandler.hasClass(prevItem, 'p-disabled') || !utils.DomHandler.hasClass(prevItem, 'p-menuitem') ? this.findPrevItem(prevItem) : prevItem;else return null;
}
}, {
key: "navigateToNextItem",
value: function navigateToNextItem(listItem) {
var nextItem = this.findNextItem(listItem);
if (nextItem) {
nextItem.children[0].focus();
}
}
}, {
key: "navigateToPrevItem",
value: function navigateToPrevItem(listItem) {
var prevItem = this.findPrevItem(listItem);
if (prevItem) {
prevItem.children[0].focus();
}
}
}, {
key: "isHorizontal",
value: function isHorizontal() {
return this.props.orientation === 'horizontal';
}
}, {
key: "isVertical",
value: function isVertical() {
return this.props.orientation === 'vertical';
}
}, {
key: "getColumnClassName",
value: function getColumnClassName(category) {
var length = category.items ? category.items.length : 0;
var columnClass;
switch (length) {
case 2:
columnClass = 'p-megamenu-col-6';
break;
case 3:
columnClass = 'p-megamenu-col-4';
break;
case 4:
columnClass = 'p-megamenu-col-3';
break;
case 6:
columnClass = 'p-megamenu-col-2';
break;
default:
columnClass = 'p-megamenu-col-12';
break;
}
return columnClass;
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
if (!this.documentClickListener) {
this.documentClickListener = function (event) {
if (_this2.container && !_this2.container.contains(event.target)) {
_this2.setState({
activeItem: null
});
}
};
document.addEventListener('click', this.documentClickListener);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.documentClickListener) {
document.removeEventListener('click', this.documentClickListener);
this.documentClickListener = null;
}
}
}, {
key: "renderSeparator",
value: function renderSeparator(index) {
return /*#__PURE__*/React__default['default'].createElement("li", {
key: 'separator_' + index,
className: "p-menu-separator",
role: "separator"
});
}
}, {
key: "renderSubmenuIcon",
value: function renderSubmenuIcon(item) {
if (item.items) {
var className = utils.classNames('p-submenu-icon pi', {
'pi-angle-down': this.isHorizontal(),
'pi-angle-right': this.isVertical()
});
return /*#__PURE__*/React__default['default'].createElement("span", {
className: className
});
}
return null;
}
}, {
key: "renderSubmenuItem",
value: function renderSubmenuItem(item, index) {
var _this3 = this;
if (item.separator) {
return this.renderSeparator(index);
} else {
var className = utils.classNames('p-menuitem', item.className);
var linkClassName = utils.classNames('p-menuitem-link', {
'p-disabled': item.disabled
});
var iconClassName = utils.classNames(item.icon, 'p-menuitem-icon');
var icon = item.icon && /*#__PURE__*/React__default['default'].createElement("span", {
className: iconClassName
});
var label = item.label && /*#__PURE__*/React__default['default'].createElement("span", {
className: "p-menuitem-text"
}, item.label);
var content = /*#__PURE__*/React__default['default'].createElement("a", {
href: item.url || '#',
className: linkClassName,
target: item.target,
onClick: function onClick(event) {
return _this3.onLeafClick(event, item);
},
role: "menuitem",
"aria-disabled": item.disabled
}, icon, label, /*#__PURE__*/React__default['default'].createElement(ripple.Ripple, null));
if (item.template) {
var defaultContentOptions = {
onClick: function onClick(event) {
return _this3.onLeafClick(event, item);
},
className: linkClassName,
labelClassName: 'p-menuitem-text',
iconClassName: iconClassName,
element: content,
props: this.props
};
content = utils.ObjectUtils.getJSXElement(item.template, item, defaultContentOptions);
}
return /*#__PURE__*/React__default['default'].createElement("li", {
key: item.label + '_' + index,
className: className,
style: item.style,
role: "none"
}, content);
}
}
}, {
key: "renderSubmenu",
value: function renderSubmenu(submenu) {
var _this4 = this;
var className = utils.classNames('p-megamenu-submenu-header', {
'p-disabled': submenu.disabled
}, submenu.className);
var items = submenu.items.map(function (item, index) {
return _this4.renderSubmenuItem(item, index);
});
return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, {
key: submenu.label
}, /*#__PURE__*/React__default['default'].createElement("li", {
className: className,
style: submenu.style,
role: "presentation",
"aria-disabled": submenu.disabled
}, submenu.label), items);
}
}, {
key: "renderSubmenus",
value: function renderSubmenus(column) {
var _this5 = this;
return column.map(function (submenu, index) {
return _this5.renderSubmenu(submenu, index);
});
}
}, {
key: "renderColumn",
value: function renderColumn(category, column, index, columnClassName) {
var submenus = this.renderSubmenus(column);
return /*#__PURE__*/React__default['default'].createElement("div", {
key: category.label + '_column_' + index,
className: columnClassName
}, /*#__PURE__*/React__default['default'].createElement("ul", {
className: "p-megamenu-submenu",
role: "menu"
}, submenus));
}
}, {
key: "renderColumns",
value: function renderColumns(category) {
var _this6 = this;
if (category.items) {
var columnClassName = this.getColumnClassName(category);
return category.items.map(function (column, index) {
return _this6.renderColumn(category, column, index, columnClassName);
});
}
return null;
}
}, {
key: "renderCategoryPanel",
value: function renderCategoryPanel(category) {
if (category.items) {
var columns = this.renderColumns(category);
return /*#__PURE__*/React__default['default'].createElement("div", {
className: "p-megamenu-panel"
}, /*#__PURE__*/React__default['default'].createElement("div", {
className: "p-megamenu-grid"
}, columns));
}
return null;
}
}, {
key: "renderCategory",
value: function renderCategory(category, index) {
var _this7 = this;
var className = utils.classNames('p-menuitem', {
'p-menuitem-active': category === this.state.activeItem
}, category.className);
var linkClassName = utils.classNames('p-menuitem-link', {
'p-disabled': category.disabled
});
var iconClassName = utils.classNames('p-menuitem-icon', category.icon);
var icon = category.icon && /*#__PURE__*/React__default['default'].createElement("span", {
className: iconClassName
});
var label = category.label && /*#__PURE__*/React__default['default'].createElement("span", {
className: "p-menuitem-text"
}, category.label);
var itemContent = category.template ? utils.ObjectUtils.getJSXElement(category.template, category) : null;
var submenuIcon = this.renderSubmenuIcon(category);
var panel = this.renderCategoryPanel(category);
return /*#__PURE__*/React__default['default'].createElement("li", {
key: category.label + '_' + index,
className: className,
style: category.style,
onMouseEnter: function onMouseEnter(e) {
return _this7.onCategoryMouseEnter(e, category);
},
role: "none"
}, /*#__PURE__*/React__default['default'].createElement("a", {
href: category.url || '#',
className: linkClassName,
target: category.target,
onClick: function onClick(e) {
return _this7.onCategoryClick(e, category);
},
onKeyDown: function onKeyDown(e) {
return _this7.onCategoryKeyDown(e, category);
},
role: "menuitem",
"aria-haspopup": category.items != null
}, icon, label, itemContent, submenuIcon, /*#__PURE__*/React__default['default'].createElement(ripple.Ripple, null)), panel);
}
}, {
key: "renderMenu",
value: function renderMenu() {
var _this8 = this;
if (this.props.model) {
return this.props.model.map(function (item, index) {
return _this8.renderCategory(item, index, true);
});
}
return null;
}
}, {
key: "renderCustomContent",
value: function renderCustomContent() {
if (this.props.children) {
return /*#__PURE__*/React__default['default'].createElement("div", {
className: "p-megamenu-custom"
}, this.props.children);
}
return null;
}
}, {
key: "render",
value: function render() {
var _this9 = this;
var className = utils.classNames('p-megamenu p-component', {
'p-megamenu-horizontal': this.props.orientation === 'horizontal',
'p-megamenu-vertical': this.props.orientation === 'vertical'
}, this.props.className);
var menu = this.renderMenu();
var customContent = this.renderCustomContent();
return /*#__PURE__*/React__default['default'].createElement("div", {
ref: function ref(el) {
return _this9.container = el;
},
id: this.props.id,
className: className,
style: this.props.style
}, /*#__PURE__*/React__default['default'].createElement("ul", {
className: "p-megamenu-root-list",
role: "menubar"
}, menu), customContent);
}
}]);
return MegaMenu;
}(React.Component);
_defineProperty(MegaMenu, "defaultProps", {
id: null,
model: null,
style: null,
className: null,
orientation: 'horizontal'
});
_defineProperty(MegaMenu, "propTypes", {
id: PropTypes.string,
model: PropTypes.array,
style: PropTypes.object,
className: PropTypes.string,
orientation: PropTypes.string
});
exports.MegaMenu = MegaMenu;
Object.defineProperty(exports, '__esModule', { value: true });
return exports;
}({}, React, primereact.utils, primereact.ripple));
|
import { __decorate, __metadata } from 'tslib';
import { ɵɵdefineInjectable, ɵɵinject, Injectable } from '@angular/core';
import { Angulartics2 } from 'angulartics2';
let Angulartics2Piwik = class Angulartics2Piwik {
constructor(angulartics2) {
this.angulartics2 = angulartics2;
if (typeof (_paq) === 'undefined') {
console.warn('Piwik not found');
}
this.angulartics2.setUsername
.subscribe((x) => this.setUsername(x));
this.angulartics2.setUserProperties
.subscribe((x) => this.setUserProperties(x));
}
startTracking() {
this.angulartics2.pageTrack
.pipe(this.angulartics2.filterDeveloperMode())
.subscribe((x) => this.pageTrack(x.path));
this.angulartics2.eventTrack
.pipe(this.angulartics2.filterDeveloperMode())
.subscribe((x) => this.eventTrack(x.action, x.properties));
}
pageTrack(path, location) {
try {
_paq.push(['setDocumentTitle', window.document.title]);
_paq.push(['setCustomUrl', path]);
_paq.push(['trackPageView']);
}
catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
}
/**
* Track a basic event in Piwik, or send an ecommerce event.
*
* @param action A string corresponding to the type of event that needs to be tracked.
* @param properties The properties that need to be logged with the event.
*/
eventTrack(action, properties = {}) {
let params = [];
switch (action) {
/**
* @description Sets the current page view as a product or category page view. When you call
* setEcommerceView it must be followed by a call to trackPageView to record the product or
* category page view.
*
* @link https://piwik.org/docs/ecommerce-analytics/#tracking-product-page-views-category-page-views-optional
* @link https://developer.piwik.org/api-reference/tracking-javascript#ecommerce
*
* @property productSKU (required) SKU: Product unique identifier
* @property productName (optional) Product name
* @property categoryName (optional) Product category, or array of up to 5 categories
* @property price (optional) Product Price as displayed on the page
*/
case 'setEcommerceView':
params = ['setEcommerceView',
properties.productSKU,
properties.productName,
properties.categoryName,
properties.price,
];
break;
/**
* @description Adds a product into the ecommerce order. Must be called for each product in
* the order.
*
* @link https://piwik.org/docs/ecommerce-analytics/#tracking-ecommerce-orders-items-purchased-required
* @link https://developer.piwik.org/api-reference/tracking-javascript#ecommerce
*
* @property productSKU (required) SKU: Product unique identifier
* @property productName (optional) Product name
* @property categoryName (optional) Product category, or array of up to 5 categories
* @property price (recommended) Product price
* @property quantity (optional, default to 1) Product quantity
*/
case 'addEcommerceItem':
params = [
'addEcommerceItem',
properties.productSKU,
properties.productName,
properties.productCategory,
properties.price,
properties.quantity,
];
break;
/**
* @description Tracks a shopping cart. Call this javascript function every time a user is
* adding, updating or deleting a product from the cart.
*
* @link https://piwik.org/docs/ecommerce-analytics/#tracking-add-to-cart-items-added-to-the-cart-optional
* @link https://developer.piwik.org/api-reference/tracking-javascript#ecommerce
*
* @property grandTotal (required) Cart amount
*/
case 'trackEcommerceCartUpdate':
params = ['trackEcommerceCartUpdate', properties.grandTotal];
break;
/**
* @description Tracks an Ecommerce order, including any ecommerce item previously added to
* the order. orderId and grandTotal (ie. revenue) are required parameters.
*
* @link https://piwik.org/docs/ecommerce-analytics/#tracking-ecommerce-orders-items-purchased-required
* @link https://developer.piwik.org/api-reference/tracking-javascript#ecommerce
*
* @property orderId (required) Unique Order ID
* @property grandTotal (required) Order Revenue grand total (includes tax, shipping, and subtracted discount)
* @property subTotal (optional) Order sub total (excludes shipping)
* @property tax (optional) Tax amount
* @property shipping (optional) Shipping amount
* @property discount (optional) Discount offered (set to false for unspecified parameter)
*/
case 'trackEcommerceOrder':
params = [
'trackEcommerceOrder',
properties.orderId,
properties.grandTotal,
properties.subTotal,
properties.tax,
properties.shipping,
properties.discount,
];
break;
/**
* @description Tracks an Ecommerce goal
*
* @link https://piwik.org/docs/tracking-goals-web-analytics/
* @link https://developer.piwik.org/guides/tracking-javascript-guide#manually-trigger-goal-conversions
*
* @property goalId (required) Unique Goal ID
* @property value (optional) passed to goal tracking
*/
case 'trackGoal':
params = [
'trackGoal',
properties.goalId,
properties.value,
];
break;
/**
* @description Tracks a site search
*
* @link https://piwik.org/docs/site-search/
* @link https://developer.piwik.org/guides/tracking-javascript-guide#internal-search-tracking
*
* @property keyword (required) Keyword searched for
* @property category (optional) Search category
* @property searchCount (optional) Number of results
*/
case 'trackSiteSearch':
params = [
'trackSiteSearch',
properties.keyword,
properties.category,
properties.searchCount,
];
break;
/**
* @description Logs an event with an event category (Videos, Music, Games...), an event
* action (Play, Pause, Duration, Add Playlist, Downloaded, Clicked...), and an optional
* event name and optional numeric value.
*
* @link https://piwik.org/docs/event-tracking/
* @link https://developer.piwik.org/api-reference/tracking-javascript#using-the-tracker-object
*
* @property category
* @property action
* @property name (optional, recommended)
* @property value (optional)
*/
default:
// PAQ requires that eventValue be an integer, see: http://piwik.org/docs/event-tracking
if (properties.value) {
const parsed = parseInt(properties.value, 10);
properties.value = isNaN(parsed) ? 0 : parsed;
}
params = [
'trackEvent',
properties.category,
action,
properties.name || properties.label,
properties.value,
];
}
try {
_paq.push(params);
}
catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
}
setUsername(userId) {
try {
_paq.push(['setUserId', userId]);
}
catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
}
/**
* Sets custom dimensions if at least one property has the key "dimension<n>",
* e.g. dimension10. If there are custom dimensions, any other property is ignored.
*
* If there are no custom dimensions in the given properties object, the properties
* object is saved as a custom variable.
*
* If in doubt, prefer custom dimensions.
* @link https://piwik.org/docs/custom-variables/
*/
setUserProperties(properties) {
const dimensions = this.setCustomDimensions(properties);
try {
if (dimensions.length === 0) {
_paq.push(['setCustomVariable', properties]);
}
}
catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
}
setCustomDimensions(properties) {
const dimensionRegex = /dimension[1-9]\d*/;
const dimensions = Object.keys(properties)
.filter(key => dimensionRegex.exec(key));
dimensions.forEach(dimension => {
const number = Number(dimension.substr(9));
_paq.push(['setCustomDimension', number, properties[dimension]]);
});
return dimensions;
}
};
Angulartics2Piwik.ngInjectableDef = ɵɵdefineInjectable({ factory: function Angulartics2Piwik_Factory() { return new Angulartics2Piwik(ɵɵinject(Angulartics2)); }, token: Angulartics2Piwik, providedIn: "root" });
Angulartics2Piwik = __decorate([
Injectable({ providedIn: 'root' }),
__metadata("design:paramtypes", [Angulartics2])
], Angulartics2Piwik);
export { Angulartics2Piwik };
//# sourceMappingURL=angulartics2-piwik.js.map
|
;(function(exports) {
// Written for Ludum Dare #31 (December 2014)
var WALL_COLOR = "#000";
var WHEEL_COLOR = "#000";
var BACKGROUND_COLOR = "#fff";
var TEXT_COLOR = "#000";
var COUNTDOWN_COLORS = ["#0f0", "#fc0", "#f00"];
function Game() {
this.size = { x: 1000, y: 500 };
this.c = new Coquette(this, "screen", this.size.x, this.size.y, BACKGROUND_COLOR);
this.state = "init";
this.states = {
"init": ["countingDown"],
"countingDown": ["racing"],
"racing": ["raceOver", "countingDown"],
"raceOver": ["countingDown"]
};
this.best = undefined;
this.restart();
makeEntities(this.c, Checkpoint, CHECKPOINTS);
makeEntities(this.c, Wall, WALLS);
this.c.entities.create(BridgeSurface); // ridiculous bridge
};
Game.prototype = {
update: function() {
if (this.state === "countingDown") {
this.countingDown();
} else if (this.state === "racing") {
this.racing();
} else if (this.state === "raceOver") {
this.raceOver();
}
},
draw: function(ctx) {
if (this.state === "raceOver") {
ctx.fillStyle = "#ff0";
ctx.fillRect(105, 200, 290, 200);
ctx.fillStyle = COUNTDOWN_COLORS[2];
ctx.fillRect(610, 100, 285, 200);
} else {
ctx.fillStyle = COUNTDOWN_COLORS[this.countdown];
ctx.fillRect(610, 100, 285, 200);
}
ctx.font = "20px Courier";
ctx.fillStyle = TEXT_COLOR;
ctx.fillText("BEST " + (this.best === undefined ? "" : formatTime(this.best)), 160, 277);
ctx.fillText("THIS " + formatTime(this.thisTime), 160, 307);
ctx.fillText("LAPS " + this.car.lapsToGo(), 160, 337);
},
transition: function(nextState) {
if (this.states[this.state].indexOf(nextState) !== -1) {
this.state = nextState;
} else {
throw "Tried to transition from " + this.state + " to " + nextState;
}
},
countingDown: function() {
this.thisTime = 0;
if (this.lastCountdownDecrement + 1000 < new Date().getTime()) {
this.countdown--;
this.lastCountdownDecrement = new Date().getTime();
if (this.countdown === 0) {
this.transition("racing");
this.started = new Date().getTime();
}
}
},
racing: function() {
this.thisTime = new Date().getTime() - this.started;
if (this.car.lapsToGo() === 0) {
this.stopped = new Date().getTime();
var time = this.stopped - this.started;
if (this.best === undefined || time < this.best) {
this.best = time;
}
this.transition("raceOver");
}
if (this.c.inputter.isPressed(this.c.inputter.R)) {
this.restart();
}
},
raceOver: function() {
this.thisTime = this.stopped - this.started;
if (this.c.inputter.isPressed(this.c.inputter.R)) {
this.restart();
}
},
restart: function() {
this.lastCountdownDecrement = new Date().getTime();
this.countdown = 2;
this.transition("countingDown");
this.started = new Date().getTime();
this.stopped = undefined;
if (this.car !== undefined) {
this.car.destroy();
}
this.car = this.c.entities.create(Car, {
center: { x: this.size.x * 0.95, y: this.size.y / 2 - 15 }
});
}
};
function Checkpoint(game, options) {
this.game = game;
this.center = options.center;
this.size = options.size;
this.angle = options.angle;
this.label = options.label || undefined;
this.color = "#000";
};
Checkpoint.prototype = {
draw: function(ctx) {
if (this.label === "bridge") {
ctx.restore(); // doing own rotation of drawing so stop framework doing it
var endPoints = util.objToLinePoints(this);
ctx.strokeStyle = this.color;
ctx.beginPath();
ctx.moveTo(endPoints[0].x, endPoints[0].y);
ctx.lineTo(endPoints[1].x, endPoints[1].y);
ctx.stroke();
ctx.closePath();
}
},
isHorizontal: function() {
return this.angle === 90;
},
collision: function(other) {
if (other instanceof Car) {
var car = other;
var latestPass = car.passes[car.passes.length - 1];
if (latestPass !== this &&
car.center.y < this.center.y) {
car.passes.push(this);
} else if (latestPass === this &&
car.center.y > this.center.y) {
car.passes.pop();
}
}
}
};
function Wall(game, options) {
this.game = game;
this.zindex = 0;
this.center = options.center;
this.size = options.size;
this.label = options.label;
this.invisible = options.invisible === true || false;
this.angle = options.angle;
};
Wall.prototype = {
draw: function(ctx) {
if (!this.invisible) {
util.fillRect(ctx, this, WALL_COLOR);
}
}
};
function FrontWheel(game, options) {
this.game = game;
this.zindex = 2;
this.car = options.car;
this.center = options.center;
this.size = { x: 4, y: 8 };
this.angle = 0;
this.wheelAngle = 0;
};
FrontWheel.prototype = {
turnRate: 0,
update: function(delta) {
if (this.game.state === "countingDown") { return; }
var TURN_ACCRETION = 0.007 * delta;
var MAX_WHEEL_ANGLE = 30;
var WHEEL_RECENTER_RATE = 2;
if (this.game.c.inputter.isDown(this.game.c.inputter.LEFT_ARROW)) {
this.turnRate -= TURN_ACCRETION
} else if (this.game.c.inputter.isDown(this.game.c.inputter.RIGHT_ARROW)) {
this.turnRate += TURN_ACCRETION;
} else {
this.turnRate = 0;
}
if (this.turnRate < 0 && this.wheelAngle > -MAX_WHEEL_ANGLE ||
this.turnRate > 0 && this.wheelAngle < MAX_WHEEL_ANGLE) {
this.wheelAngle += this.turnRate;
} else if (this.turnRate === 0) {
if (Math.abs(this.wheelAngle) < 0.5) {
this.wheelAngle = 0;
} else if (this.wheelAngle > 0) {
this.wheelAngle -= WHEEL_RECENTER_RATE;
} else if (this.wheelAngle < 0) {
this.wheelAngle += WHEEL_RECENTER_RATE;
}
}
this.angle = this.car.angle + this.wheelAngle;
},
draw: function(ctx) {
util.fillRect(ctx, this, WHEEL_COLOR);
},
collision: function(other) {
this.car.handleCollision(this, other);
}
};
function BackWheel(game, options) {
this.game = game;
this.zindex = 2;
this.car = options.car;
this.center = options.center;
this.size = { x: 4, y: 8 };
this.angle = 0;
};
BackWheel.prototype = {
draw: function(ctx) {
util.fillRect(ctx, this, WHEEL_COLOR);
},
collision: function(other) {
this.car.handleCollision(this, other);
}
};
function BridgeSurface(game) {
this.game = game;
this.zindex = 3;
};
BridgeSurface.prototype = {
draw: function(ctx) {
if (this.game.car.label() === "tunnel") {
util.fillRect(ctx, { center: { x: 450, y: 150 }, size: { x: 90, y: 90 } },
BACKGROUND_COLOR);
}
util.fillRect(ctx, { center: { x: 400, y: 150 }, size: { x: 10, y: 90 } }, WALL_COLOR);
util.fillRect(ctx, { center: { x: 500, y: 150 }, size: { x: 10, y: 90 } }, WALL_COLOR);
}
};
function Car(game, options) {
this.game = game;
this.zindex = 1;
this.center = options.center;
this.color = options.color;
this.size = { x: 10, y: 24 };
this.angle = 0;
this.velocity = { x: 0, y: 0 };
this.passes = [];
this.frontLeft = this.game.c.entities.create(FrontWheel, {
center: { x: this.center.x - this.size.x / 2, y: this.center.y - this.size.y / 2.5 },
car: this
});
this.frontRight = this.game.c.entities.create(FrontWheel, {
center: { x: this.center.x + this.size.x / 2, y: this.center.y - this.size.y / 2.5 },
car: this
});
this.backLeft = this.game.c.entities.create(BackWheel, {
center: { x: this.center.x - this.size.x / 2, y: this.center.y + this.size.y / 2.5 },
car: this
});
this.backRight = this.game.c.entities.create(BackWheel, {
center: { x: this.center.x + this.size.x / 2, y: this.center.y + this.size.y / 2.5 },
car: this
});
};
function angleDiff(a, b) {
return Math.atan2(Math.sin(a - b), Math.cos(a - b)) * util.DEGREES_TO_RADIANS;
};
Car.prototype = {
update: function(delta) {
if (this.game.state === "countingDown") { return; }
var ACCELERATION_ACCRETION = 0.002 * delta;
var MAX_SPEED = 5;
if (this.frontLeft.wheelAngle !== 0) {
var turnRadius = this.size.y * 90 / this.frontLeft.wheelAngle;
var turnCircumference = 2 * Math.PI * turnRadius;
var rotateProportion = util.magnitude(this.velocity) / turnCircumference;
var dir;
if (this.game.c.inputter.isDown(this.game.c.inputter.UP_ARROW)) {
dir = 1;
} else if (this.game.c.inputter.isDown(this.game.c.inputter.DOWN_ARROW)) {
dir = -1;
} else {
var velocityAngle = util.vectorToAngle(this.velocity);
var orientationAngle = util.vectorToAngle(util.angleToVector(this.angle));
var reversing = Math.abs(angleDiff(velocityAngle, orientationAngle)) > 90;
dir = reversing ? -1 : 1;
}
var rotateAngleDelta = rotateProportion * 360 * dir;
this.velocity = util.rotate(this.velocity, { x: 0, y: 0 }, rotateAngleDelta);
this.wheels().concat(this).forEach(function(o) { o.angle += rotateAngleDelta; });
this.wheels().forEach(function(w) {
w.center = util.rotate(w.center, this.center, rotateAngleDelta);
}, this);
}
var ratio = MAX_SPEED - util.magnitude(this.velocity);
if (this.game.c.inputter.isDown(this.game.c.inputter.UP_ARROW)) {
var headingVector = util.angleToVector(this.angle);
this.velocity.x += headingVector.x * ACCELERATION_ACCRETION * ratio;
this.velocity.y += headingVector.y * ACCELERATION_ACCRETION * ratio;
} else if (this.game.c.inputter.isDown(this.game.c.inputter.DOWN_ARROW)) {
var headingVector = util.angleToVector(this.angle + 180);
this.velocity.x += headingVector.x * ACCELERATION_ACCRETION * ratio;
this.velocity.y += headingVector.y * ACCELERATION_ACCRETION * ratio;
}
this.move();
// friction
this.velocity = util.multiply(this.velocity, { x: 0.99, y: 0.99 });
},
wheels: function() {
return [this.frontLeft, this.frontRight, this.backLeft, this.backRight];
},
lapsToGo: function() {
return 3 - Math.floor((this.passes.length - 1) / 2);
},
label: function() {
var lastPass = this.passes[this.passes.length - 1];
if (lastPass !== undefined) {
return lastPass.label;
}
},
move: function() {
this.wheels().concat(this).forEach(function(o) {
o.center.x += this.velocity.x;
o.center.y += this.velocity.y;
}, this);
},
draw: function(ctx) {
util.fillRect(ctx, this, "#000");
},
collision: function(other) {
this.handleCollision(this, other);
},
handleCollision: function(carPiece, other) {
if (other instanceof Wall) {
var car = carPiece.car || carPiece;
if (other.label === undefined || car.label() !== other.label) {
var bounceRatio = 0.4;
var otherNormal = util.bounceLineNormal(car, other);
function carInWall(car) {
return [car].concat(car.wheels())
.filter(function(p) {
return this.game.c.collider.isIntersecting(p, other)
}).length > 0
};
// get out of wall
var oldVelocity = this.velocity;
car.velocity = util.unitVector(otherNormal);
var i = 0;
while(carInWall(car)) {
i++;
car.move();
if (i > 100) {
break;
}
}
car.velocity = oldVelocity;
// bounce off wall
var dot = util.dotProduct(car.velocity, otherNormal);
car.velocity.x -= 2 * dot * otherNormal.x;
car.velocity.y -= 2 * dot * otherNormal.y;
car.velocity = util.multiply(car.velocity, { x: bounceRatio, y: bounceRatio });
var i = 0;
while (carInWall(car)) {
i++;
car.move();
if (i > 100) {
break;
}
}
}
}
},
destroy: function() {
var c = this.game.c;
c.entities.destroy(this);
this.wheels().forEach(function(w) { c.entities.destroy(w); });
}
};
var util = {
RADIANS_TO_DEGREES: Math.PI / 180,
DEGREES_TO_RADIANS: 180 / Math.PI,
angleToVector: function(angle) {
var r = angle * 0.01745;
return this.unitVector({ x: Math.sin(r), y: -Math.cos(r) });
},
objToLinePoints: function(obj) {
return [
util.rotate({ x: obj.center.x, y: obj.center.y + obj.size.y / 2 },
obj.center,
obj.angle),
util.rotate({ x: obj.center.x, y: obj.center.y - obj.size.y / 2 },
obj.center,
obj.angle)
]
},
vectorToAngle: function(v) {
var unitVec = this.unitVector(v);
var uncorrectedDeg = Math.atan2(unitVec.x, -unitVec.y) * this.DEGREES_TO_RADIANS;
var angle = uncorrectedDeg;
if(uncorrectedDeg < 0) {
angle = 360 + uncorrectedDeg;
}
return angle;
},
magnitude: function(vector) {
return Math.sqrt(vector.x * vector.x + vector.y * vector.y);
},
unitVector: function(vector) {
return {
x: vector.x / this.magnitude(vector),
y: vector.y / this.magnitude(vector)
};
},
dotProduct: function(vector1, vector2) {
return vector1.x * vector2.x + vector1.y * vector2.y;
},
rotate: function(point, pivot, angle) {
angle *= this.RADIANS_TO_DEGREES;
return {
x: (point.x - pivot.x) * Math.cos(angle) -
(point.y - pivot.y) * Math.sin(angle) +
pivot.x,
y: (point.x - pivot.x) * Math.sin(angle) +
(point.y - pivot.y) * Math.cos(angle) +
pivot.y
};
},
bounceLineNormal: function(obj, line) {
var objToClosestPointOnLineVector =
util.vectorBetween(
util.pointOnLineClosestToObj(obj, line),
obj.center);
return util.unitVector(objToClosestPointOnLineVector);
},
pointOnLineClosestToObj: function(obj, line) {
var endPoints = util.objToLinePoints(line);
var lineEndPoint1 = endPoints[0]
var lineEndPoint2 = endPoints[1];
var lineUnitVector = util.unitVector(util.angleToVector(line.angle));
var lineEndToObjVector = util.vectorBetween(lineEndPoint1, obj.center);
var projection = util.dotProduct(lineEndToObjVector, lineUnitVector);
if (projection <= 0) {
return lineEndPoint1;
} else if (projection >= line.len) {
return lineEndPoint2;
} else {
return {
x: lineEndPoint1.x + lineUnitVector.x * projection,
y: lineEndPoint1.y + lineUnitVector.y * projection
};
}
},
vectorBetween: function(startPoint, endPoint) {
return {
x: endPoint.x - startPoint.x,
y: endPoint.y - startPoint.y
};
},
add: function(v1, v2) {
return { x: v1.x + v2.x, y: v1.y + v2.y };
},
multiply: function(v1, v2) {
return { x: v1.x * v2.x, y: v1.y * v2.y };
},
fillRect: function(ctx, obj, color) {
ctx.fillStyle = color;
ctx.fillRect(obj.center.x - obj.size.x / 2,
obj.center.y - obj.size.y / 2,
obj.size.x,
obj.size.y);
}
};
function formatTime(millis) {
if (millis !== undefined) {
return (millis / 1000).toFixed(3);
} else {
return "";
}
};
function makeEntities(c, Constructor, optionsArray) {
for (var i = 0; i < optionsArray.length; i++) {
c.entities.create(Constructor, optionsArray[i]);
}
};
var CHECKPOINTS = [
{ center: { x: 950, y: 240 }, size: { x: 10, y: 100 }, angle: 90, label: "bridge" },
{ center: { x: 55, y: 300 }, size: { x: 10, y: 100 }, angle: 90, label: "tunnel" }
];
var WALLS = [
{ center: { x: 900, y: 200 }, size: { x: 10, y: 210 }, angle: 180 },
{ center: { x: 995, y: 200 }, size: { x: 10, y: 400 }, angle: 180 },
{ center: { x: 700, y: 5 }, size: { x: 10, y: 600 }, angle: 90 },
{ center: { x: 700, y: 100 }, size: { x: 10, y: 410 }, angle: 90 },
{ center: { x: 400, y: 50 }, size: { x: 10, y: 100 }, angle: 0 },
{ center: { x: 400, y: 300 }, size: { x: 10, y: 200 }, angle: 0 },
{ center: { x: 500, y: 350 }, size: { x: 10, y: 310 }, angle: 0 },
{ center: { x: 250, y: 400 }, size: { x: 10, y: 310 }, angle: 270 },
{ center: { x: 5, y: 300 }, size: { x: 10, y: 400 }, angle: 0 },
{ center: { x: 100, y: 300 }, size: { x: 10, y: 200 }, angle: 0 },
{ center: { x: 200, y: 100 }, size: { x: 10, y: 410 }, angle: 90 },
{ center: { x: 250, y: 200 }, size: { x: 10, y: 310 }, angle: 90 },
{ center: { x: 610, y: 200 }, size: { x: 10, y: 210 }, angle: 180 },
{ center: { x: 750, y: 300 }, size: { x: 10, y: 290 }, angle: 90 },
{ center: { x: 750, y: 400 }, size: { x: 10, y: 510 }, angle: 90 },
{ center: { x: 250, y: 495 }, size: { x: 10, y: 500 }, angle: 270 },
{ center: { x: 400, y: 150 }, size: { x: 10, y: 90 }, angle: 0, label: "tunnel",
invisible: true },
{ center: { x: 500, y: 150 }, size: { x: 10, y: 90 }, angle: 0, label: "tunnel",
invisible: true },
{ center: { x: 450, y: 100 }, size: { x: 10, y: 90 }, angle: 90, label: "bridge",
invisible: true },
{ center: { x: 450, y: 200 }, size: { x: 10, y: 90 }, angle: 90, label: "bridge",
invisible: true }
];
exports.Game = Game;
})(this);
|
/*
* Globalize Culture vi-VN
*
* 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
*/
(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( "vi-VN", "default", {
name: "vi-VN",
englishName: "Vietnamese (Vietnam)",
nativeName: "Tiếng Việt (Việt Nam)",
language: "vi",
numberFormat: {
",": ".",
".": ",",
percent: {
",": ".",
".": ","
},
currency: {
pattern: ["-n $","n $"],
",": ".",
".": ",",
symbol: "₫"
}
},
calendars: {
standard: {
firstDay: 1,
days: {
names: ["Chủ Nhật","Thứ Hai","Thứ Ba","Thứ Tư","Thứ Năm","Thứ Sáu","Thứ Bảy"],
namesAbbr: ["CN","Hai","Ba","Tư","Năm","Sáu","Bảy"],
namesShort: ["C","H","B","T","N","S","B"]
},
months: {
names: ["Tháng Giêng","Tháng Hai","Tháng Ba","Tháng Tư","Tháng Năm","Tháng Sáu","Tháng Bảy","Tháng Tám","Tháng Chín","Tháng Mười","Tháng Mười Một","Tháng Mười Hai",""],
namesAbbr: ["Thg1","Thg2","Thg3","Thg4","Thg5","Thg6","Thg7","Thg8","Thg9","Thg10","Thg11","Thg12",""]
},
AM: ["SA","sa","SA"],
PM: ["CH","ch","CH"],
patterns: {
d: "dd/MM/yyyy",
D: "dd MMMM yyyy",
f: "dd MMMM yyyy h:mm tt",
F: "dd MMMM yyyy h:mm:ss tt",
M: "dd MMMM",
Y: "MMMM yyyy"
}
}
}
});
}( this ));
|
import React from 'react';
import {BaseMixin, ElementaryMixin, ColorSchemaMixin, ContentMixin, Tools} from '../common/common.js';
import Environment from '../environment/environment.js';
import './block.less';
export const Block = React.createClass({
//@@viewOn:mixins
mixins: [
BaseMixin,
ElementaryMixin,
ColorSchemaMixin,
ContentMixin
],
//@@viewOff:mixins
//@@viewOn:statics
statics: {
tagName: 'UU5.Bricks.Block',
classNames: {
main: 'uu5-bricks-block',
bg: 'uu5-bricks-block-bg'
}
},
//@@viewOff:statics
//@@viewOn:propTypes
propTypes: {
background: React.PropTypes.bool
},
//@@viewOff:propTypes
//@@viewOn:getDefaultProps
getDefaultProps: function () {
return {
background: false
};
},
//@@viewOff:getDefaultProps
//@@viewOn:standardComponentLifeCycle
//@@viewOff:standardComponentLifeCycle
//@@viewOn:interface
//@@viewOff:interface
//@@viewOn:overridingMethods
//@@viewOff:overridingMethods
//@@viewOn:componentSpecificHelpers
_buildMainAttrs: function () {
var mainAttrs = this.buildMainAttrs();
this.props.background && (mainAttrs.className += ' ' + this.getClassName().bg);
return mainAttrs;
},
//@@viewOff:componentSpecificHelpers
//@@viewOn:render
render: function () {
return (
<div {...this._buildMainAttrs()}>
{this.getChildren()}
{this.getDisabledCover()}
</div>
);
}
//@@viewOff:render
});
var createColoredBlock = function (colorSchema, background) {
return (
React.createClass({
render: function () {
return (
<Block {...this.props} colorSchema={colorSchema} background={background}>
{this.props.children && React.Children.toArray(this.props.children)}
</Block>
);
}
})
)
};
Environment.colorSchema.forEach(function (colorSchema) {
var colorSchemaCapitalize = Tools.getCamelCase(colorSchema);
Block[colorSchema] = createColoredBlock(colorSchema);
Block['bg' + colorSchemaCapitalize] = createColoredBlock(colorSchema, true);
});
export default Block; |
(function () {
var text = 'A name that identifies an electronic post office box on a network where e-mail can be sent. Different types of networks have different formats for e-mail addresses. On the Internet, all e-mail addresses have the form: For example, webmaster@sandybay.com, "pesho_e_pich@gosho.com" or "pisha@domashno.ch". Every user on the Internet has a "unique" e-mail address. The term e-addressis commonly used as an abbreviation for e-mail address';
console.log(text);
console.log("Extracted in array:");
extractEmails(text);
}());
function extractEmails(text) {
var pattern = new RegExp(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/gi);
var emails = text.match(pattern);
console.log(emails);
} |
export default {
entry: '../../dist/packages-dist/core/mojiito/core.es5.js',
dest: '../../dist/packages-dist/core/bundles/core.umd.js',
format: 'umd',
exports: 'named',
moduleName: 'mj.core',
context: 'this'
};
|
Package.describe({
name: 'orionjs:dictionary',
summary: 'Meteor collection with some magic',
version: '1.1.0',
git: 'https://github.com/orionjs/orion'
});
Package.onUse(function(api) {
api.versionsFrom('1.0');
api.use([
'orionjs:base@1.1.0',
'aldeed:simple-schema@1.3.2',
'aldeed:collection2@2.3.3',
]);
api.imply([
'aldeed:simple-schema',
'aldeed:collection2'
]);
api.addFiles([
'dictionary.js',
'admin.js',
]);
api.addFiles([
'dictionary_server.js',
], 'server');
api.addFiles([
'dictionary_client.js',
], 'client');
api.export('orion');
});
Package.onTest(function(api) {
api.use('tinytest');
api.use('orionjs:core');
});
|
var through = require('through2');
var deploy = require("gulp-gh-pages");
var shell = require("gulp-shell");
var gulp = require('gulp');
var webpack = require('gulp-webpack');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');
var uglify = require('gulp-uglify');
var _ = require("./src/util.js");
var karma = require("karma").server;
var translate = require("./scripts/gulp-trans.js")
var pkg = require("./package.json");
// release
require("./scripts/release.js")(gulp);
var wpConfig = {
output: {
filename: "stateman.js",
library: "StateMan",
libraryTarget: "umd"
}
}
var testConfig = {
output: {
filename: "dom.bundle.js"
}
}
var karmaCommonConf = {
browsers: ['Chrome', 'Firefox', 'IE', 'IE9', 'IE8', 'IE7', 'PhantomJS'],
frameworks: ['mocha', 'commonjs'],
files: [
'test/runner/vendor/expect.js',
'src/**/*.js',
'test/spec/test-*.js',
'test/spec/dom-*.js'
],
client: {
mocha: {ui: 'bdd'}
},
customLaunchers: {
IE9: {
base: 'IE',
'x-ua-compatible': 'IE=EmulateIE9'
},
IE8: {
base: 'IE',
'x-ua-compatible': 'IE=EmulateIE8'
},
IE7: {
base: 'IE',
'x-ua-compatible': 'IE=EmulateIE7'
}
},
preprocessors: {
'src/**/*.js': ['commonjs', 'coverage'],
'test/spec/test-*.js': ['commonjs'],
'test/spec/dom-*.js': ['commonjs'],
'test/runner/vendor/expect.js': ['commonjs']
},
// coverage reporter generates the coverage
reporters: ['progress', 'coverage'],
// preprocessors: {
// // source files, that you wanna generate coverage for
// // do not include tests or libraries
// // (these files will be instrumented by Istanbul)
// // 'test/regular.js': ['coverage']
// },
// optionally, configure the reporter
coverageReporter: {
type: 'html'
}
};
gulp.task('jshint', function(){
// jshint
gulp.src(['src/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'))
})
gulp.task('build', ['jshint'], function() {
gulp.src("src/index.js")
.pipe(webpack(wpConfig))
.pipe(wrap(signatrue))
.pipe(gulp.dest('./'))
.pipe(wrap(mini))
.pipe(uglify())
.pipe(gulp.dest('./'))
.on("error", function(err){
throw err
})
});
gulp.task('testbundle', function(){
gulp.src("test/spec/dom.exports.js")
.pipe(webpack(testConfig))
.pipe(gulp.dest('test/runner'))
.on("error", function(err){
throw err
})
})
gulp.task('mocha', function(){
return gulp.src(['test/spec/test-*.js'])
.pipe(mocha({reporter: 'spec' }) )
.on('error', function(err){
console.log(err)
console.log('\u0007');
})
.on('end', function(){
// before_mocha.clean();
});
})
gulp.task('watch', ["build", 'testbundle'], function(){
gulp.watch(['src/**/*.js'], ['build']);
gulp.watch(['docs/src/*.md'], ['doc']);
gulp.watch(['test/spec/*.js', 'src/**/*.js'], ['testbundle'])
})
gulp.task('default', [ 'watch']);
gulp.task('mocha', function() {
return gulp.src(['test/spec/test-*.js', 'test/spec/node-*.js' ])
.pipe(mocha({reporter: 'spec' }) )
.on('error', function(){
// gutil.log.apply(this, arguments);
console.log('\u0007');
})
.on('end', function(){
global.expect = null;
});
});
gulp.task('karma', function (done) {
var config = _.extend({}, karmaCommonConf);
if(process.argv[3] === '--phantomjs'){
config.browsers=["PhantomJS"]
config.coverageReporter = {type : 'text-summary'}
karma.start(_.extend(config, {singleRun: true}), done);
}else if(process.argv[3] === '--browser'){
config.browsers = null;
karma.start(_.extend(config, {singleRun: true}), done);
}else{
karma.start(_.extend(config, {singleRun: true}), done);
}
});
gulp.task("test", ["mocha", "karma"])
gulp.task('doc', function(){
return gulp.src(["docs/src/API*.md"])
.pipe(translate({}))
.pipe(gulp.dest("docs/pages/document"))
})
//
gulp.task("release", ["tag"])
gulp.task('travis', ['jshint' ,'build','mocha', 'karma']);
gulp.task('server', ['build'], shell.task([
"./node_modules/puer/bin/puer"
]))
gulp.task('example', function(){
gulp.src("example/*.html")
.pipe(
gulp.dest('docs/pages/example')
);
gulp.src("./stateman.js")
.pipe(
gulp.dest('docs/pages')
);
})
gulp.task('gh-pages', ['example', 'doc'], function () {
gulp.src("docs/pages/**/*.*")
.pipe(deploy({
remoteUrl: "git@github.com:leeluolee/stateman",
branch: "gh-pages"
}))
.on("error", function(err){
console.log(err)
})
});
function wrap(fn){
return through.obj(fn);
}
function signatrue(file, enc, cb){
var sign = '/**\n'+ '@author\t'+ pkg.author.name + '\n'+ '@version\t'+ pkg.version +
'\n'+ '@homepage\t'+ pkg.homepage + '\n*/\n';
file.contents = Buffer.concat([new Buffer(sign), file.contents]);
cb(null, file);
}
function mini(file, enc, cb){
file.path = file.path.replace('.js', '.min.js');
cb(null, file)
}
|
import {set} from 'cerebral/operators'
import {state, props} from 'cerebral/tags'
import {startTimer, stopTimer} from './actions'
export const mounted = [
startTimer,
set(state`clock.light`, true)
]
export const unMounted = stopTimer
export const secondTicked = set(state`clock.lastUpdate`, props`now`)
|
/**
* Created by Hendrik Strobelt (hendrik.strobelt.com) on 3/1/15.
*/
// DO NOT MODIFY
testSuite = function(){
this.t1a_Selector = "#t1a"
this.t1b_Selector = "#t1b"
}
testSuite.prototype.allLoaded =function(perDayData, metaData){
var passed = false;
if (perDayData != null && perDayData.length > 300) {
if (metaData && metaData.hasOwnProperty("priorities")) {
// DO NOT CHANGE
d3.select(this.t1a_Selector).attr({
class:"panel panel-success"
}).selectAll(".panel-heading").text("Task 1a seems to be solved")
passed=true;
}
}
if (!passed){
d3.select(this.t1a_Selector).attr({
class:"panel panel-danger"
}).selectAll(".panel-heading").text("Task 1a not solved")
}
}
testSuite.prototype.checkCount = function(count)
{
// DO NOT CHANGE
if (count==21835){
d3.select(this.t1b_Selector).attr({
class:"panel panel-success"
}).selectAll(".panel-heading").text("Task 1b seems to be solved")
}else if (count>=20100 && count<21835){
d3.select(this.t1b_Selector).attr({
class:"panel panel-warning"
}).selectAll(".panel-heading").text("Task 1b -- have you included Jan 1 and Jan 31 as counts?")
}else{
d3.select(this.t1b_Selector).attr({
class:"panel panel-danger"
}).selectAll(".panel-heading").text("Task 1b -- not yet there..")
}
}
testSuite.prototype.simpleTest = function(){
d3.select("#t4a1").attr({
class:"panel panel-success"
}).selectAll(".panel-heading").text("Task 4a - simple Test seems to be solved")
}
testSuite.prototype.sumTest = function(x){
if (x==30){
d3.select("#t4a2").attr({
class:"panel panel-success"
}).selectAll(".panel-heading").text("Task 4b - sum Test seems to be solved")
}else{
d3.select("#t4a2").attr({
class:"panel panel-danger"
}).selectAll(".panel-heading").text("Task 4b - not yet there")
}
}
tester = new testSuite();
|
import commonUrl from 'shared/constants/commonLinks';
const questions = {
general: [
{
question: 'When was Operation Code founded?',
answer:
'The first line of code for the Operation Code site was pushed on August 21, 2014. Operation Code formally became a 501(c)3 nonprofit on May 4, 2016.'
},
{
question: 'How was Operation Code founded?',
answer:
'Operation Code was founded in Portland, Oregon by ex-Army Captain David Molina, who took action and built operationcode.org to petition Congress to expand the New GI Bill to include code schools.'
},
{
question: 'Is Operation Code a 501(c)(3) nonprofit organization?',
answer:
'Yes. Operation Code was granted tax-exempt status by the Internal Revenue Service, functioning as a charity under 501(c)(3) of the Internal Revenue Code, effective 4 May 2016, with retroactive status to 15 June 2015. Donations to the organization are deductible as charitable contributions.'
},
{
question: 'Where is Operation Code based? Do you have a location near me?',
answer:
"Operation Code, much like software, is built from anywhere with an internet connection, and is not based in one location. While we're headquartered in Portland, the entire organization is decentralized, including the board of directors and the core team. This allows us to more effectively serve the entire military community, whether they're veterans or military spouses, whether they're OCONUS or in-country. We have chapters all over the nation. Use Slack chat and join the closest town to you!"
},
{
question: 'Who does Operation Code serve?',
answer:
"Operation Code serves our nation's finest who've worn the uniform and their families who are interested in coding and software development. Our programs are offered at no cost to the military community, including veterans, transitioning service members, and military spouses and families."
},
{
question:
'What do I need to start learning software development and how much is this going to cost?',
answer:
'First off, you will need access to a solid computer, a good browser (ex. Chrome), and a strong internet connection. It costs nothing to start learning to code and receive software mentorship through Operation Code, you just need a positive attitude, persistence and grit, and a thirst for new knowledge. We have over a dozen channels, from Ruby to JavaScript, iOS to Android, and from Free Code Camp to edX study groups.'
},
{
question: 'What is available to start learning to code today?',
answer:
"Our friends at the New York City-based, The Flatiron School created <a href='https://learn.co/'>Learn.co</a>, an online platform to get introduced to web development and the popular web framework, Ruby on Rails. Request an invite <a href='https://learn.co/join/operation-code'>here</a> and then join the #learn-dot-co channel in our Slack. Another resource is <a href='https://www.learnhowtoprogram.com/courses'>learnhowtoprogram.com</a>, a resource maintained by Epicodus."
},
{
question: 'What are the hours of operation for Operation Code?',
answer:
"Operation Code is different in that we don't have regular business office hours. The team can usually be found in our <a href='http://operation-code.slack.com'>Slack channel</a>, or on <a href='https://github.com/OperationCode/operationcode'>GitHub</a> fixing bugs and implementing new features."
},
{
question: "How can I help, if I can't afford to donate to Operation Code?",
answer: `In addition to requiring financial support, we also need <a href='http://op.co.de/volunteer' target='_blank'>volunteers</a> and interns. The larger our community, the more we can spread the word about our work. Also, remember that every <a href=${
commonUrl.donateLink
}>donation</a>, no matter how modest, brings us closer to our goals.`
},
{
question:
'I would like to receive Operation Code updates and news. How can I receive these communications?',
answer:
"We primarily use <a href='https://twitter.com/operation_code'>Twitter</a> and <a href='http://facebook.com/operationcode.org'>Facebook</a> to put out updates and news since it's faster to put out info and respond. Given our chosen craft, we don't do regular emails as often."
},
{
question: "My question isn't listed. How do I contact Operation Code?",
answer:
"If you have a question that isn't listed here on our FAQ or our <a href='https://medium.com/@operation_code'>blog</a>, write to <a href='mailto:staff@operationcode.org'>staff@operationcode.org</a> and we'll get back to you as soon as we can."
}
],
donation: [
{
question: 'What is the fastest way to make a donation?',
answer: `The fastest way to make a donation is through our secured online form <a href=${
commonUrl.donateLink
}>here</a>.`
},
{
question: 'I would rather mail a check. To whom do I make it out and where do I send it?',
answer:
"It's less administrative work to accept online donations. Get in touch so we can assess your situation and contribution commitment."
},
{
question: 'When will I receive a receipt for my contribution?',
answer:
'When you make a donation to Operation Code online, you will receive an receipt by email.'
},
{
question: 'What percentage of my donation goes directly to helping the military community?',
answer:
'Our goal is to direct 100 percent of online donations for programs and services, and keep administrative costs low while our annual fundraiser, grants and services fund operations.'
},
{
question: 'Can I donate items as gift in-kind?',
answer:
"As a program-based nonprofit organization, Operation Code welcomes in-kind donations to directly benefit the organization, transitioning military, citizen-soldiers, veterans and their families in learning to code and building software to change the world. Items that are needed, include (but not limited to): frequent flyer miles, Adobe Cloud, used or new MacBook Air's, and grant writers."
},
{
question:
"I'd like to donate my software conference pass to an Operation Code member. How do I do that?",
answer:
"Get in touch, and we'll make an announcement in our Slack, tweet and/or write a blog post, and find a veteran to take your spot. Even then, travel and lodging is often a barrier."
},
{
question: 'Can I make donations to a particular veteran or their family learning to code?',
answer:
"<a href='mailto:staff@operationcode.org'>Please get in touch with us directly,</a> so we can ensure we find a good match."
},
{
question: 'What is AmazonSmile and how can buying at Amazon help Operation Code?',
answer:
"When you visit <a href='https://smile.amazon.com/ch/47-4247572'>https://smile.amazon.com</a>, you continue to have the same shopping experience as the same and most products available on amazon.com but you help Operation Code realize it's mission. Once you’ve selected 'Operation Code' everything else functions the same. Shop for your favorite products or the perfect gift. Most products are eligible on Amazon Smile, if not, you’ll be notified. You can checkout normally as well. No extra cost is passed onto you–Amazon will donate 0.5% of your purchase to Operation Code! After you’ve successfully completed a purchase on AmazonSmile you can share the news with your friends on Facebook, Twitter or via email. This option appears on the confirmation page after your order is complete."
}
],
volunteer: [
{
question: 'How to Volunteer?',
answer:
"If you would like to become a volunteer, please apply <a href='http://op.co.de/volunteer' target='_blank'>here</a>."
},
{
question: 'What volunteer opportunities are there at Operation Code?',
answer: 'Currently, fundraising, community leaders, and grant writers are our current needs.'
}
]
};
export default questions;
|
YUI.add("gallery-user-patch-2532141",function(a){a.Plugin.ResizeConstrained.ATTRS.constrain={setter:function(b){if(b&&(b instanceof a.Node||b.nodeType||(a.Lang.isString(b)&&b!=="view"))){b=a.one(b);}return b;}};},"gallery-2012.04.18-20-14",{requires:["resize"]}); |
exports.myParent = module.parent;
|
// CubeGeometry
THREE._CubeGeometry = THREE.CubeGeometry;
THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, flipped, sides ) {
var geometry = new THREE._CubeGeometry( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, flipped, sides );
geometry.gui = {
parameters: {
width: width,
height: height,
depth: depth,
segmentsWidth: segmentsWidth,
segmentsHeight: segmentsHeight,
segmentsDepth: segmentsDepth,
materials: materials,
flipped: flipped,
sides: sides
},
getCode: function () {
return 'new THREE.CubeGeometry( ' + [
geometry.gui.parameters.width,
geometry.gui.parameters.height,
geometry.gui.parameters.depth,
geometry.gui.parameters.segmentsWidth,
geometry.gui.parameters.segmentsHeight,
geometry.gui.parameters.segmentsDepth
// ,
// geometry.gui.parameters.materials,
// geometry.gui.parameters.flipped,
// geometry.gui.parameters.sides
].join( ', ' ) + ' )';
}
}
return geometry;
};
// SphereGeometry
THREE._SphereGeometry = THREE.SphereGeometry;
THREE.SphereGeometry = function ( radius, segmentsWidth, segmentsHeight ) {
var geometry = new THREE._SphereGeometry( radius, segmentsWidth, segmentsHeight );
geometry.gui = {
parameters: {
radius: radius,
segmentsWidth: segmentsWidth,
segmentsHeight: segmentsHeight
},
getCode: function () {
return 'new THREE.SphereGeometry( ' + [
geometry.gui.parameters.radius,
geometry.gui.parameters.segmentsWidth,
geometry.gui.parameters.segmentsHeight
].join( ', ' ) + ' )';
}
}
return geometry;
};
// TorusGeometry
THREE._TorusGeometry = THREE.TorusGeometry;
THREE.TorusGeometry = function ( radius, tube, segmentsR, segmentsT, arc ) {
var geometry = new THREE._TorusGeometry( radius, tube, segmentsR, segmentsT, arc );
geometry.gui = {
parameters: {
radius: radius,
tube: tube,
segmentsR: segmentsR,
segmentsT: segmentsT,
arc: arc
},
getCode: function () {
return 'new THREE.TorusGeometry( ' + [
geometry.gui.parameters.radius,
geometry.gui.parameters.tube,
geometry.gui.parameters.segmentsR,
geometry.gui.parameters.segmentsT
].join( ', ' ) + ' )';
}
}
return geometry;
};
// MeshBasicMaterial
THREE.MeshBasicMaterial.prototype.gui = {
getCode: function () {
return 'new THREE.MeshBasicMaterial( { ' + [
'color: 0x' + material.color.getHex().toString(16)
].join( ', ' ) + ' } )';
}
};
|
$(function() {
function fix_header(){
header_width = Math.round($('header').width());
name_width = Math.round($('header h1').outerWidth());
bio_width = (header_width - name_width) - 20;
bio = $('header p');
bio.css('width', bio_width);
}
fix_header();
function fix_milestone_height(){
$('#career_timeline').find('li').each(
function(){
div_title = $(this).find('.title');
div_from_to = $(this).find('.from_to');
getHeight = Math.round(div_title.height());
div_title.css('height', getHeight)
div_from_to.css('height', getHeight)
// console.log(getHeight);
}
)
}
// initiate fix_milestone_height
fix_milestone_height();
function fix_timeline_height() {
point_A = Math.round($('.timeline > li:first').offset().top);
point_B = Math.round($('.timeline > li:first .arrow').offset().top);
point_C = Math.round($('.timeline > li:last').offset().top);
vline_height = (point_C - point_A) + 5;
$('.vline').css({height: vline_height, top: point_B});
// console.log(point_B);
// console.log(point_C);
}
// initiate fix_timeline_height
fix_timeline_height();
// on windows resize
$(window).resize(function() {
fix_header();
fix_milestone_height();
fix_timeline_height();
});
//initiate pop easy modal + settings
$('.modalLink').modal({
trigger: '.modalLink', // id or class of link or button to trigger modal
olay:'div.overlay', // id or class of overlay
modals:'div.modal', // id or class of modal
animationEffect: 'slideDown', // overlay effect | slideDown or fadeIn | default=fadeIn
animationSpeed: 400, // speed of overlay in milliseconds | default=400
moveModalSpeed: 'slow', // speed of modal movement when window is resized | slow or fast | default=false
background: 'e74c3c', // hexidecimal color code - DONT USE #
opacity: 0.9, // opacity of modal | 0 - 1 | default = 0.8
openOnLoad: false, // open modal on page load | true or false | default=false
docClose: true, // click document to close | true or false | default=true
closeByEscape: true, // close modal by escape key | true or false | default=true
moveOnScroll: false, // move modal when window is scrolled | true or false | default=false
resizeWindow: true, // move modal when window is resized | true or false | default=false
close:'.closeBtn' // id or class of close button
});
// end of doc ready
});
|
(function(){var g,h,f,c;g=function(){var a;a={};Error.captureStackTrace(a,g);return a.stack};f=function(a){var b;b=a.length;return".js"===a.slice(b-3)?a.slice(0,b-3):".coffee"===a.slice(b-7)?a.slice(0,b-7):a};c=window.twoside=function(a){var b,d,e;b=a.lastIndexOf("/");0<=b?(e=a.slice(0,b),d=f(a.slice(b+1))):(e=a,d="");a=f(h(a));b={};a=c._modules[a]={exports:b};"index"===d&&(c._modules[e]=a);return{require:function(a){var b;if(b=c._modules[a])return b.exports;a=h(e+"/"+f(a));b=c._modules[a];if(!b)throw console.log(g()),
a+" is a wrong twoside module path.";return b.exports},exports:b,module:a}};c._modules={};c.alias=function(a,b){return c._modules[a]=b};return h=function(a){var b,d,e,c,f;if(!a||"/"===a)return"/";b=[];f=a.split("/");e=0;for(c=f.length;e<c;e++)d=f[e],".."===d?b.pop():""!==d&&"."!==d&&b.push(d);return("/"===a.charAt(0)||"."===a.charAt(0)?"/":"")+b.join("/").replace(/[\/]{2,}/g,"/")}})();
|
/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
/*global module, require*/
module.exports = function (grunt) {
'use strict';
// load dependencies
require('load-grunt-tasks')(grunt, {pattern: ['grunt-contrib-*', 'grunt-targethtml', 'grunt-usemin']});
grunt.loadTasks('tasks');
// Project configuration.
grunt.initConfig({
pkg : grunt.file.readJSON("package.json"),
clean: {
dist: {
files: [{
dot: true,
src: [
'dist',
'src/.index.html',
'src/styles/brackets.css'
]
}]
}
},
copy: {
dist: {
files: [
{
'dist/index.html': 'src/.index.html'
},
/* static files */
{
expand: true,
dest: 'dist/',
cwd: 'src/',
src: [
'nls/{,*/}*.js',
'xorigin.js',
'dependencies.js',
'thirdparty/requirejs/require.js',
'LiveDevelopment/launch.html',
'LiveDevelopment/MultiBrowserImpl/transports/**',
'LiveDevelopment/MultiBrowserImpl/launchers/**'
]
},
/* node domains are not minified and must be copied to dist */
{
expand: true,
dest: 'dist/',
cwd: 'src/',
src: [
'extensibility/node/**',
'!extensibility/node/spec/**',
'filesystem/impls/appshell/node/**',
'!filesystem/impls/appshell/node/spec/**'
]
},
/* extensions and CodeMirror modes */
{
expand: true,
dest: 'dist/',
cwd: 'src/',
src: [
'!extensions/default/*/unittest-files/**/*',
'!extensions/default/*/unittests.js',
'extensions/default/*/**/*',
'extensions/dev/*',
'extensions/samples/**/*',
'thirdparty/CodeMirror2/addon/{,*/}*',
'thirdparty/CodeMirror2/keymap/{,*/}*',
'thirdparty/CodeMirror2/lib/{,*/}*',
'thirdparty/CodeMirror2/mode/{,*/}*',
'thirdparty/CodeMirror2/theme/{,*/}*',
'thirdparty/i18n/*.js',
'thirdparty/text/*.js'
]
},
/* styles, fonts and images */
{
expand: true,
dest: 'dist/styles',
cwd: 'src/styles',
src: ['jsTreeTheme.css', 'fonts/{,*/}*.*', 'images/*', 'brackets.min.css*']
}
]
}
},
less: {
dist: {
files: {
"src/styles/brackets.min.css": "src/styles/brackets.less"
},
options: {
compress: true,
sourceMap: true,
sourceMapFilename: 'src/styles/brackets.min.css.map',
outputSourceFiles: true,
sourceMapRootpath: '',
sourceMapBasepath: 'src/styles'
}
}
},
requirejs: {
dist: {
// Options: https://github.com/jrburke/r.js/blob/master/build/example.build.js
options: {
// `name` and `out` is set by grunt-usemin
baseUrl: 'src',
optimize: 'uglify2',
// brackets.js should not be loaded until after polyfills defined in "utils/Compatibility"
// so explicitly include it in main.js
include: ["utils/Compatibility", "brackets"],
// TODO: Figure out how to make sourcemaps work with grunt-usemin
// https://github.com/yeoman/grunt-usemin/issues/30
generateSourceMaps: true,
useSourceUrl: true,
// required to support SourceMaps
// http://requirejs.org/docs/errors.html#sourcemapcomments
preserveLicenseComments: false,
useStrict: true,
// Disable closure, we want define/require to be globals
wrap: false,
exclude: ["text!config.json"],
uglify2: {} // https://github.com/mishoo/UglifyJS2
}
}
},
targethtml: {
dist: {
files: {
'src/.index.html': 'src/index.html'
}
}
},
useminPrepare: {
options: {
dest: 'dist'
},
html: 'src/.index.html'
},
usemin: {
options: {
dirs: ['dist']
},
html: ['dist/{,*/}*.html']
},
htmlmin: {
dist: {
options: {
/*removeCommentsFromCDATA: true,
// https://github.com/yeoman/grunt-usemin/issues/44
//collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeOptionalTags: true*/
},
files: [{
expand: true,
cwd: 'src',
src: '*.html',
dest: 'dist'
}]
}
},
meta : {
src : [
'src/**/*.js',
'!src/thirdparty/**',
'!src/widgets/bootstrap-*.js',
'!src/extensions/**/unittest-files/**/*.js',
'!src/extensions/**/thirdparty/**/*.js',
'!src/extensions/dev/**',
'!src/extensions/disabled/**',
'!**/node_modules/**/*.js',
'!src/**/*-min.js',
'!src/**/*.min.js'
],
test : [
'test/**/*.js',
'!test/perf/*-files/**/*.js',
'!test/spec/*-files/**/*.js',
'!test/spec/*-known-goods/**/*.js',
'!test/spec/FindReplace-test-files-*/**/*.js',
'!test/smokes/**',
'!test/temp/**',
'!test/thirdparty/**',
'!test/**/node_modules/**/*.js'
],
grunt: [
'Gruntfile.js',
'tasks/**/*.js'
],
/* specs that can run in phantom.js */
specs : [
'test/spec/CommandManager-test.js',
//'test/spec/LanguageManager-test.js',
//'test/spec/PreferencesManager-test.js',
'test/spec/ViewUtils-test.js'
]
},
watch: {
all : {
files: ['**/*', '!**/node_modules/**'],
tasks: ['jshint']
},
grunt : {
files: ['<%= meta.grunt %>', 'tasks/**/*'],
tasks: ['jshint:grunt']
},
src : {
files: ['<%= meta.src %>', 'src/**/*'],
tasks: ['jshint:src']
},
test : {
files: ['<%= meta.test %>', 'test/**/*'],
tasks: ['jshint:test']
}
},
/* FIXME (jasonsanjose): how to handle extension tests */
jasmine : {
src : 'undefined.js', /* trick the default runner to run without importing src files */
options : {
junit : {
path: 'test/results',
consolidate: true
},
specs : '<%= meta.specs %>',
/* Keep in sync with test/SpecRunner.html dependencies */
vendor : [
'test/polyfills.js', /* For reference to why this polyfill is needed see Issue #7951. The need for this should go away once the version of phantomjs gets upgraded to 2.0 */
'src/thirdparty/jquery-2.1.3.min.js',
'src/thirdparty/CodeMirror2/lib/codemirror.js',
'src/thirdparty/CodeMirror2/lib/util/dialog.js',
'src/thirdparty/CodeMirror2/lib/util/searchcursor.js',
'src/thirdparty/CodeMirror2/addon/edit/closetag.js',
'src/thirdparty/CodeMirror2/addon/selection/active-line.js',
'src/thirdparty/mustache/mustache.js',
'src/thirdparty/path-utils/path-utils.min',
'src/thirdparty/less-1.7.5.min.js'
],
helpers : [
'test/spec/PhantomHelper.js'
],
template : require('grunt-template-jasmine-requirejs'),
templateOptions: {
requireConfig : {
baseUrl: 'src',
paths: {
'test' : '../test',
'perf' : '../test/perf',
'spec' : '../test/spec',
'text' : 'thirdparty/text/text',
'i18n' : 'thirdparty/i18n/i18n'
}
}
}
}
},
'jasmine_node': {
projectRoot: 'src/extensibility/node/spec/'
},
jshint: {
all: [
'<%= meta.grunt %>',
'<%= meta.src %>',
'<%= meta.test %>'
],
grunt: '<%= meta.grunt %>',
src: '<%= meta.src %>',
test: '<%= meta.test %>',
/* use strict options to mimic JSLINT until we migrate to JSHINT in Brackets */
options: {
jshintrc: '.jshintrc'
}
},
shell: {
repo: grunt.option("shell-repo") || "../brackets-shell",
mac: "<%= shell.repo %>/installer/mac/staging/<%= pkg.name %>.app",
win: "<%= shell.repo %>/installer/win/staging/<%= pkg.name %>.exe",
linux: "<%= shell.repo %>/installer/linux/debian/package-root/opt/brackets/brackets"
}
});
// task: install
grunt.registerTask('install', ['write-config', 'less']);
// task: test
grunt.registerTask('test', ['jshint:all', 'jasmine']);
// grunt.registerTask('test', ['jshint:all', 'jasmine', 'jasmine_node']);
// task: set-release
// Update version number in package.json and rewrite src/config.json
grunt.registerTask('set-release', ['update-release-number', 'write-config']);
// task: build
grunt.registerTask('build', [
'jshint:src',
'jasmine',
'clean',
'less',
'targethtml',
'useminPrepare',
'htmlmin',
'requirejs',
'concat',
/*'cssmin',*/
/*'uglify',*/
'copy',
'usemin',
'build-config'
]);
// Default task.
grunt.registerTask('default', ['test']);
};
|
var User = require('../models/user')
var when = require('when')
var _ = require('lodash')
function AssetService(assetModel) {
this._model = assetModel
}
AssetService.prototype.list = function() {
return this.find()
}
AssetService.prototype.count = function(filter) {
var dfd = when.defer()
this._model.count(filter, function(err, count) {
if (err)
return dfd.reject(err)
dfd.resolve(count)
})
return dfd.promise
}
AssetService.prototype.countAndFind = function(filter, sort, select, paging) {
var that = this
paging = paging || {limit: 0, offset: 0}
var limit = paging.limit || 0
var offset = paging.offset || 0
var totalCount
return this.count(filter)
.then(function(count) {
totalCount = count
return that._model.find(filter)
.sort(sort)
.skip(offset)
.limit(limit)
.select(select)
})
.then(function(list) {
return {
meta: _.extend(paging, {
totalCount: totalCount,
listCount: list.length,
limit: limit,
offset: offset,
displayStart: 1 + offset,
displayEnd: offset + list.length
}),
list: list
}
})
}
AssetService.prototype.buildQuery = function(find, options) {
var query = this._model.find(find)
if (options && options.limit)
query = query.limit(options.limit)
if (options && options.offset)
query = query.skip(options.offset)
return query
}
AssetService.prototype.find = function(q, paging) {
var dfd = when.defer()
paging = paging || { offset: 0, limit: 0 }
this._model.find(q)
.sort('-updatedAt')
.skip(paging.offset || 0)
.limit(paging.limit || 0)
.exec((err, list) => {
if (err)
return dfd.reject(err)
dfd.resolve(list)
})
return dfd.promise
}
AssetService.prototype.findByCreatorName = function(username) {
var that = this
var dfd = when.defer()
User.findOne({ username: username })
.exec(function(err, user) {
if (err)
return dfd.reject(err)
if (!user)
return dfd.resolve([])
dfd.resolve(that.find({ '_creator': user._id }))
})
return dfd.promise
}
AssetService.prototype.findByCreatorId = function(userId) {
return this.find({
'_creator': userId
})
}
AssetService.prototype.canWrite = function(user, path) {
return this.findByPath(path)
.then(function(asset) {
if (!asset)
return true
var creator = asset._creator
if (creator._id)
creator = creator._id
return !asset ||
creator.toString() === user.id.toString()
})
}
AssetService.prototype.canWriteAnonymous = function(path) {
return this.findByPath(path)
.then(function(asset) {
// Asset is null, doesn't exist, we can write
if (!asset) {
return true
}
// Asset already found, can't overwrite
return false
})
}
AssetService.prototype.findOne = function(q) {
var dfd = when.defer()
this._model
.findOne(q)
.populate('_creator', 'username profile')
.exec(function(err, item)
{
if (err)
return dfd.reject(err)
dfd.resolve(item)
})
return dfd.promise
}
AssetService.prototype.findByTagAndUserId = function(tag, userId) {
return this.find({
tags: tag.replace(/[^a-zA-Z0-9]/g, ''),
_creator: userId
})
}
AssetService.prototype.findByPath = function(path) {
return this.findOne({path: path})
}
AssetService.prototype.save = function(data, user) {
var that = this
return this.findByPath(data.path)
.then(function(asset) {
if (!asset) {
asset = new that._model(data)
asset._creator = user.id
}
// update model with everything from data
_.assign(asset, data)
asset.updatedAt = Date.now()
var dfd = when.defer()
asset.save(function(err) {
if (err) {
console.error(err)
return dfd.reject(err)
}
dfd.resolve(asset)
})
return dfd.promise
})
}
module.exports = AssetService
|
'use strict';
const Controller = require('trails-controller');
const Boom = require('boom');
/**
* @module CategoryController
* @description TODO Category Controller.
*/
module.exports = class CategoryController extends Controller {
getAll (request, reply) {
this.app.services.CategoryService.getAll()
.then(response => {
reply(response);
})
.catch(error => {
reply(Boom.badRequest('Could not get the categories.'));
});
}
};
|
// Copyright 2012 Mark Cavage, Inc. All rights reserved.
'use strict';
/**
* Return a shallow copy of the given object
*
* @public
* @function shallowCopy
* @param {Object} obj - the object to copy
* @returns {Object} the new copy of the object
*/
function shallowCopy(obj) {
if (!obj) {
return obj;
}
var copy = {};
Object.keys(obj).forEach(function forEach(k) {
copy[k] = obj[k];
});
return copy;
}
///--- Exports
module.exports = shallowCopy;
|
'use strict';
module.exports = function (grunt) {
// load all grunt tasks
require('load-grunt-tasks')(grunt);
var config = {
pkg: grunt.file.readJSON('package.json'),
env: process.env
};
grunt.util._.extend(config, loadConfig('./tasks/options/'));
grunt.initConfig(config);
grunt.loadTasks('tasks');
};
function loadConfig(path) {
var glob = require('glob');
var object = {};
var key;
glob.sync('*', {
cwd: path
}).forEach(function (option) {
key = option.replace(/\.js$/, '');
object[key] = require(path + option);
});
return object;
}
|
/*
* # Semantic - Modal
* http://github.com/jlukic/semantic-ui/
*
*
* Copyright 2013 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
$.fn.modal = function(parameters) {
var
$allModals = $(this),
$document = $(document),
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.modal.settings, parameters)
: $.fn.modal.settings,
selector = settings.selector,
className = settings.className,
namespace = settings.namespace,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
moduleSelector = $allModals.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
invokedResponse
;
$allModals
.each(function() {
var
$modal = $(this),
$context = $(settings.context),
$otherModals = $allModals.not($modal),
$closeButton = $modal.find(selector.closeButton),
$dimmer,
element = this,
instance = $modal.data(moduleNamespace),
modal
;
modal = {
initialize: function() {
modal.verbose('Attaching events');
$closeButton
.on('click', modal.event.close)
;
modal.cache.sizes();
modal.verbose('Creating dimmer');
$context
.dimmer({
closable: settings.closable,
duration: settings.duration,
onShow: function() {
modal.add.keyboardShortcuts();
$.proxy(settings.onShow, this)();
},
onHide: function() {
if($modal.is(':visible')) {
$context.off('.dimmer');
modal.hide();
$.proxy(settings.onHide, this)();
}
modal.remove.keyboardShortcuts();
}
})
;
$dimmer = $context.children(selector.dimmer);
if( $modal.parent()[0] !== $dimmer[0] ) {
modal.debug('Moving element inside dimmer', $context);
$modal = $modal
.detach()
.appendTo($dimmer)
;
}
modal.instantiate();
},
instantiate: function() {
modal.verbose('Storing instance of modal');
instance = modal;
$modal
.data(moduleNamespace, instance)
;
},
destroy: function() {
modal.verbose('Destroying previous modal');
$modal
.off(eventNamespace)
;
},
event: {
close: function() {
modal.verbose('Close button pressed');
$context.dimmer('hide');
},
keyboard: function(event) {
var
keyCode = event.which,
escapeKey = 27
;
if(keyCode == escapeKey) {
modal.debug('Escape key pressed hiding modal');
$context.dimmer('hide');
event.preventDefault();
}
},
resize: function() {
modal.cache.sizes();
if( $modal.is(':visible') ) {
modal.set.type();
modal.set.position();
}
}
},
toggle: function() {
if( modal.is.active() ) {
modal.hide();
}
else {
modal.show();
}
},
show: function() {
modal.debug('Showing modal');
modal.set.type();
modal.set.position();
modal.hideAll();
if(settings.transition && $.fn.transition !== undefined) {
$modal
.transition(settings.transition + ' in', settings.duration, modal.set.active)
;
}
else {
$modal
.fadeIn(settings.duration, settings.easing, modal.set.active)
;
}
modal.debug('Triggering dimmer');
$context.dimmer('show');
},
hide: function() {
modal.debug('Hiding modal');
// remove keyboard detection
$document
.off('keyup.' + namespace)
;
if(settings.transition && $.fn.transition !== undefined) {
$modal
.transition(settings.transition + ' out', settings.duration, modal.remove.active)
;
}
else {
$modal
.fadeOut(settings.duration, settings.easing, modal.remove.active)
;
}
},
hideAll: function() {
$otherModals
.filter(':visible')
.modal('hide')
;
},
add: {
keyboardShortcuts: function() {
modal.verbose('Adding keyboard shortcuts');
$document
.on('keyup' + eventNamespace, modal.event.keyboard)
;
}
},
remove: {
active: function() {
$modal.removeClass(className.active);
},
keyboardShortcuts: function() {
modal.verbose('Removing keyboard shortcuts');
$document
.off('keyup' + eventNamespace)
;
}
},
cache: {
sizes: function() {
modal.cache = {
height : $modal.outerHeight() + settings.offset,
contextHeight : (settings.context == 'body')
? $(window).height()
: $context.height()
};
console.log($modal);
modal.debug('Caching modal and container sizes', modal.cache);
}
},
can: {
fit: function() {
return (modal.cache.height < modal.cache.contextHeight);
}
},
is: {
active: function() {
return $modal.hasClass(className.active);
}
},
set: {
active: function() {
$modal.addClass('active');
},
type: function() {
if(modal.can.fit()) {
modal.verbose('Modal fits on screen');
$modal.removeClass(className.scrolling);
}
else {
modal.verbose('Modal cannot fit on screen setting to scrolling');
$modal.addClass(className.scrolling);
}
},
position: function() {
modal.verbose('Centering modal on page', modal.cache.height / 2);
if(modal.can.fit()) {
$modal
.css({
marginTop: -(modal.cache.height / 2)
})
;
}
else {
$modal
.css({
top: $context.prop('scrollTop')
})
;
}
}
},
setting: function(name, value) {
if(value !== undefined) {
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else {
settings[name] = value;
}
}
else {
return settings[name];
}
},
internal: function(name, value) {
if(value !== undefined) {
if( $.isPlainObject(name) ) {
$.extend(true, modal, name);
}
else {
modal[name] = value;
}
}
else {
return modal[name];
}
},
debug: function() {
if(settings.debug) {
if(settings.performance) {
modal.performance.log(arguments);
}
else {
modal.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
modal.debug.apply(console, arguments);
}
}
},
verbose: function() {
if(settings.verbose && settings.debug) {
if(settings.performance) {
modal.performance.log(arguments);
}
else {
modal.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
modal.verbose.apply(console, arguments);
}
}
},
error: function() {
modal.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
modal.error.apply(console, arguments);
},
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Element' : element,
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Execution Time' : executionTime
});
}
clearTimeout(modal.performance.timer);
modal.performance.timer = setTimeout(modal.performance.display, 100);
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(modal.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
invoke: function(query, passedArguments, context) {
var
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && instance !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( instance[value] ) && (depth != maxDepth) ) {
instance = instance[value];
}
else if( $.isPlainObject( instance[camelCaseValue] ) && (depth != maxDepth) ) {
instance = instance[camelCaseValue];
}
else if( instance[value] !== undefined ) {
found = instance[value];
return false;
}
else if( instance[camelCaseValue] !== undefined ) {
found = instance[camelCaseValue];
return false;
}
else {
modal.error(error.method);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(invokedResponse)) {
invokedResponse.push(response);
}
else if(typeof invokedResponse == 'string') {
invokedResponse = [invokedResponse, response];
}
else if(response !== undefined) {
invokedResponse = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
modal.initialize();
}
invokedResponse = modal.invoke(query);
}
else {
if(instance !== undefined) {
modal.destroy();
}
modal.initialize();
}
})
;
return (invokedResponse !== undefined)
? invokedResponse
: this
;
};
$.fn.modal.settings = {
name : 'Modal',
namespace : 'modal',
verbose : true,
debug : true,
performance : true,
offset : 0,
transition : 'scale',
duration : 500,
easing : 'easeOutExpo',
closable : true,
context : 'body',
onShow : function(){},
onHide : function(){},
selector : {
closeButton : '.close, .actions .button',
dimmer: '.ui.dimmer'
},
error : {
method : 'The method you called is not defined.'
},
className : {
scrolling : 'scrolling'
},
};
})( jQuery, window , document ); |
(function (global, module) {
var exports = module.exports;
/**
* Exports.
*/
module.exports = expect;
expect.Assertion = Assertion;
/**
* Exports version.
*/
expect.version = '0.3.1';
/**
* Possible assertion flags.
*/
var flags = {
not: ['to', 'be', 'have', 'include', 'only']
, to: ['be', 'have', 'include', 'only', 'not']
, only: ['have']
, have: ['own']
, be: ['an']
};
function expect (obj) {
return new Assertion(obj);
}
/**
* Constructor
*
* @api private
*/
function Assertion (obj, flag, parent) {
this.obj = obj;
this.flags = {};
if (undefined != parent) {
this.flags[flag] = true;
for (var i in parent.flags) {
if (parent.flags.hasOwnProperty(i)) {
this.flags[i] = true;
}
}
}
var $flags = flag ? flags[flag] : keys(flags)
, self = this;
if ($flags) {
for (var i = 0, l = $flags.length; i < l; i++) {
// avoid recursion
if (this.flags[$flags[i]]) continue;
var name = $flags[i]
, assertion = new Assertion(this.obj, name, this)
if ('function' == typeof Assertion.prototype[name]) {
// clone the function, make sure we dont touch the prot reference
var old = this[name];
this[name] = function () {
return old.apply(self, arguments);
};
for (var fn in Assertion.prototype) {
if (Assertion.prototype.hasOwnProperty(fn) && fn != name) {
this[name][fn] = bind(assertion[fn], assertion);
}
}
} else {
this[name] = assertion;
}
}
}
}
/**
* Performs an assertion
*
* @api private
*/
Assertion.prototype.assert = function (truth, msg, error, expected) {
var msg = this.flags.not ? error : msg
, ok = this.flags.not ? !truth : truth
, err;
if (!ok) {
err = new Error(msg.call(this));
if (arguments.length > 3) {
err.actual = this.obj;
err.expected = expected;
err.showDiff = true;
}
throw err;
}
this.and = new Assertion(this.obj);
};
/**
* Check if the value is truthy
*
* @api public
*/
Assertion.prototype.ok = function () {
this.assert(
!!this.obj
, function(){ return 'expected ' + i(this.obj) + ' to be truthy' }
, function(){ return 'expected ' + i(this.obj) + ' to be falsy' });
};
/**
* Creates an anonymous function which calls fn with arguments.
*
* @api public
*/
Assertion.prototype.withArgs = function() {
expect(this.obj).to.be.a('function');
var fn = this.obj;
var args = Array.prototype.slice.call(arguments);
return expect(function() { fn.apply(null, args); });
};
/**
* Assert that the function throws.
*
* @param {Function|RegExp} callback, or regexp to match error string against
* @api public
*/
Assertion.prototype['throw'] =
Assertion.prototype.throwError =
Assertion.prototype.throwException = function (fn) {
expect(this.obj).to.be.a('function');
var thrown = false
, not = this.flags.not;
try {
this.obj();
} catch (e) {
if (isRegExp(fn)) {
var subject = 'string' == typeof e ? e : e.message;
if (not) {
expect(subject).to.not.match(fn);
} else {
expect(subject).to.match(fn);
}
} else if ('function' == typeof fn) {
fn(e);
}
thrown = true;
}
if (isRegExp(fn) && not) {
// in the presence of a matcher, ensure the `not` only applies to
// the matching.
this.flags.not = false;
}
var name = this.obj.name || 'fn';
this.assert(
thrown
, function(){ return 'expected ' + name + ' to throw an exception' }
, function(){ return 'expected ' + name + ' not to throw an exception' });
};
/**
* Checks if the array is empty.
*
* @api public
*/
Assertion.prototype.empty = function () {
var expectation;
if ('object' == typeof this.obj && null !== this.obj && !isArray(this.obj)) {
if ('number' == typeof this.obj.length) {
expectation = !this.obj.length;
} else {
expectation = !keys(this.obj).length;
}
} else {
if ('string' != typeof this.obj) {
expect(this.obj).to.be.an('object');
}
expect(this.obj).to.have.property('length');
expectation = !this.obj.length;
}
this.assert(
expectation
, function(){ return 'expected ' + i(this.obj) + ' to be empty' }
, function(){ return 'expected ' + i(this.obj) + ' to not be empty' });
return this;
};
/**
* Checks if the obj exactly equals another.
*
* @api public
*/
Assertion.prototype.be =
Assertion.prototype.equal = function (obj) {
this.assert(
obj === this.obj
, function(){ return 'expected ' + i(this.obj) + ' to equal ' + i(obj) }
, function(){ return 'expected ' + i(this.obj) + ' to not equal ' + i(obj) });
return this;
};
/**
* Checks if the obj sortof equals another.
*
* @api public
*/
Assertion.prototype.eql = function (obj) {
this.assert(
expect.eql(this.obj, obj)
, function(){ return 'expected ' + i(this.obj) + ' to sort of equal ' + i(obj) }
, function(){ return 'expected ' + i(this.obj) + ' to sort of not equal ' + i(obj) }
, obj);
return this;
};
/**
* Assert within start to finish (inclusive).
*
* @param {Number} start
* @param {Number} finish
* @api public
*/
Assertion.prototype.within = function (start, finish) {
var range = start + '..' + finish;
this.assert(
this.obj >= start && this.obj <= finish
, function(){ return 'expected ' + i(this.obj) + ' to be within ' + range }
, function(){ return 'expected ' + i(this.obj) + ' to not be within ' + range });
return this;
};
/**
* Assert typeof / instance of
*
* @api public
*/
Assertion.prototype.a =
Assertion.prototype.an = function (type) {
if ('string' == typeof type) {
// proper english in error msg
var n = /^[aeiou]/.test(type) ? 'n' : '';
// typeof with support for 'array'
this.assert(
'array' == type ? isArray(this.obj) :
'regexp' == type ? isRegExp(this.obj) :
'object' == type
? 'object' == typeof this.obj && null !== this.obj
: type == typeof this.obj
, function(){ return 'expected ' + i(this.obj) + ' to be a' + n + ' ' + type }
, function(){ return 'expected ' + i(this.obj) + ' not to be a' + n + ' ' + type });
} else {
// instanceof
var name = type.name || 'supplied constructor';
this.assert(
this.obj instanceof type
, function(){ return 'expected ' + i(this.obj) + ' to be an instance of ' + name }
, function(){ return 'expected ' + i(this.obj) + ' not to be an instance of ' + name });
}
return this;
};
/**
* Assert numeric value above _n_.
*
* @param {Number} n
* @api public
*/
Assertion.prototype.greaterThan =
Assertion.prototype.above = function (n) {
this.assert(
this.obj > n
, function(){ return 'expected ' + i(this.obj) + ' to be above ' + n }
, function(){ return 'expected ' + i(this.obj) + ' to be below ' + n });
return this;
};
/**
* Assert numeric value below _n_.
*
* @param {Number} n
* @api public
*/
Assertion.prototype.lessThan =
Assertion.prototype.below = function (n) {
this.assert(
this.obj < n
, function(){ return 'expected ' + i(this.obj) + ' to be below ' + n }
, function(){ return 'expected ' + i(this.obj) + ' to be above ' + n });
return this;
};
/**
* Assert string value matches _regexp_.
*
* @param {RegExp} regexp
* @api public
*/
Assertion.prototype.match = function (regexp) {
this.assert(
regexp.exec(this.obj)
, function(){ return 'expected ' + i(this.obj) + ' to match ' + regexp }
, function(){ return 'expected ' + i(this.obj) + ' not to match ' + regexp });
return this;
};
/**
* Assert property "length" exists and has value of _n_.
*
* @param {Number} n
* @api public
*/
Assertion.prototype.length = function (n) {
expect(this.obj).to.have.property('length');
var len = this.obj.length;
this.assert(
n == len
, function(){ return 'expected ' + i(this.obj) + ' to have a length of ' + n + ' but got ' + len }
, function(){ return 'expected ' + i(this.obj) + ' to not have a length of ' + len });
return this;
};
/**
* Assert property _name_ exists, with optional _val_.
*
* @param {String} name
* @param {Mixed} val
* @api public
*/
Assertion.prototype.property = function (name, val) {
if (this.flags.own) {
this.assert(
Object.prototype.hasOwnProperty.call(this.obj, name)
, function(){ return 'expected ' + i(this.obj) + ' to have own property ' + i(name) }
, function(){ return 'expected ' + i(this.obj) + ' to not have own property ' + i(name) });
return this;
}
if (this.flags.not && undefined !== val) {
if (undefined === this.obj[name]) {
throw new Error(i(this.obj) + ' has no property ' + i(name));
}
} else {
var hasProp;
try {
hasProp = name in this.obj
} catch (e) {
hasProp = undefined !== this.obj[name]
}
this.assert(
hasProp
, function(){ return 'expected ' + i(this.obj) + ' to have a property ' + i(name) }
, function(){ return 'expected ' + i(this.obj) + ' to not have a property ' + i(name) });
}
if (undefined !== val) {
this.assert(
val === this.obj[name]
, function(){ return 'expected ' + i(this.obj) + ' to have a property ' + i(name)
+ ' of ' + i(val) + ', but got ' + i(this.obj[name]) }
, function(){ return 'expected ' + i(this.obj) + ' to not have a property ' + i(name)
+ ' of ' + i(val) });
}
this.obj = this.obj[name];
return this;
};
/**
* Assert that the array contains _obj_ or string contains _obj_.
*
* @param {Mixed} obj|string
* @api public
*/
Assertion.prototype.string =
Assertion.prototype.contain = function (obj) {
if ('string' == typeof this.obj) {
this.assert(
~this.obj.indexOf(obj)
, function(){ return 'expected ' + i(this.obj) + ' to contain ' + i(obj) }
, function(){ return 'expected ' + i(this.obj) + ' to not contain ' + i(obj) });
} else {
this.assert(
~indexOf(this.obj, obj)
, function(){ return 'expected ' + i(this.obj) + ' to contain ' + i(obj) }
, function(){ return 'expected ' + i(this.obj) + ' to not contain ' + i(obj) });
}
return this;
};
/**
* Assert exact keys or inclusion of keys by using
* the `.own` modifier.
*
* @param {Array|String ...} keys
* @api public
*/
Assertion.prototype.key =
Assertion.prototype.keys = function ($keys) {
var str
, ok = true;
$keys = isArray($keys)
? $keys
: Array.prototype.slice.call(arguments);
if (!$keys.length) throw new Error('keys required');
var actual = keys(this.obj)
, len = $keys.length;
// Inclusion
ok = every($keys, function (key) {
return ~indexOf(actual, key);
});
// Strict
if (!this.flags.not && this.flags.only) {
ok = ok && $keys.length == actual.length;
}
// Key string
if (len > 1) {
$keys = map($keys, function (key) {
return i(key);
});
var last = $keys.pop();
str = $keys.join(', ') + ', and ' + last;
} else {
str = i($keys[0]);
}
// Form
str = (len > 1 ? 'keys ' : 'key ') + str;
// Have / include
str = (!this.flags.only ? 'include ' : 'only have ') + str;
// Assertion
this.assert(
ok
, function(){ return 'expected ' + i(this.obj) + ' to ' + str }
, function(){ return 'expected ' + i(this.obj) + ' to not ' + str });
return this;
};
/**
* Assert a failure.
*
* @param {String ...} custom message
* @api public
*/
Assertion.prototype.fail = function (msg) {
var error = function() { return msg || "explicit failure"; }
this.assert(false, error, error);
return this;
};
/**
* Function bind implementation.
*/
function bind (fn, scope) {
return function () {
return fn.apply(scope, arguments);
}
}
/**
* Array every compatibility
*
* @see bit.ly/5Fq1N2
* @api public
*/
function every (arr, fn, thisObj) {
var scope = thisObj || global;
for (var i = 0, j = arr.length; i < j; ++i) {
if (!fn.call(scope, arr[i], i, arr)) {
return false;
}
}
return true;
}
/**
* Array indexOf compatibility.
*
* @see bit.ly/a5Dxa2
* @api public
*/
function indexOf (arr, o, i) {
if (Array.prototype.indexOf) {
return Array.prototype.indexOf.call(arr, o, i);
}
if (arr.length === undefined) {
return -1;
}
for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0
; i < j && arr[i] !== o; i++);
return j <= i ? -1 : i;
}
// https://gist.github.com/1044128/
var getOuterHTML = function(element) {
if ('outerHTML' in element) return element.outerHTML;
var ns = "http://www.w3.org/1999/xhtml";
var container = document.createElementNS(ns, '_');
var xmlSerializer = new XMLSerializer();
var html;
if (document.xmlVersion) {
return xmlSerializer.serializeToString(element);
} else {
container.appendChild(element.cloneNode(false));
html = container.innerHTML.replace('><', '>' + element.innerHTML + '<');
container.innerHTML = '';
return html;
}
};
// Returns true if object is a DOM element.
var isDOMElement = function (object) {
if (typeof HTMLElement === 'object') {
return object instanceof HTMLElement;
} else {
return object &&
typeof object === 'object' &&
object.nodeType === 1 &&
typeof object.nodeName === 'string';
}
};
/**
* Inspects an object.
*
* @see taken from node.js `util` module (copyright Joyent, MIT license)
* @api private
*/
function i (obj, showHidden, depth) {
var seen = [];
function stylize (str) {
return str;
}
function format (value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (value && typeof value.inspect === 'function' &&
// Filter out the util module, it's inspect function is special
value !== exports &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
return value.inspect(recurseTimes);
}
// Primitive types cannot have properties
switch (typeof value) {
case 'undefined':
return stylize('undefined', 'undefined');
case 'string':
var simple = '\'' + json.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return stylize(simple, 'string');
case 'number':
return stylize('' + value, 'number');
case 'boolean':
return stylize('' + value, 'boolean');
}
// For some reason typeof null is "object", so special case here.
if (value === null) {
return stylize('null', 'null');
}
if (isDOMElement(value)) {
return getOuterHTML(value);
}
// Look up the keys of the object.
var visible_keys = keys(value);
var $keys = showHidden ? Object.getOwnPropertyNames(value) : visible_keys;
// Functions without properties can be shortcutted.
if (typeof value === 'function' && $keys.length === 0) {
if (isRegExp(value)) {
return stylize('' + value, 'regexp');
} else {
var name = value.name ? ': ' + value.name : '';
return stylize('[Function' + name + ']', 'special');
}
}
// Dates without properties can be shortcutted
if (isDate(value) && $keys.length === 0) {
return stylize(value.toUTCString(), 'date');
}
// Error objects can be shortcutted
if (value instanceof Error) {
return stylize("["+value.toString()+"]", 'Error');
}
var base, type, braces;
// Determine the object type
if (isArray(value)) {
type = 'Array';
braces = ['[', ']'];
} else {
type = 'Object';
braces = ['{', '}'];
}
// Make functions say that they are functions
if (typeof value === 'function') {
var n = value.name ? ': ' + value.name : '';
base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']';
} else {
base = '';
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + value.toUTCString();
}
if ($keys.length === 0) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return stylize('' + value, 'regexp');
} else {
return stylize('[Object]', 'special');
}
}
seen.push(value);
var output = map($keys, function (key) {
var name, str;
if (value.__lookupGetter__) {
if (value.__lookupGetter__(key)) {
if (value.__lookupSetter__(key)) {
str = stylize('[Getter/Setter]', 'special');
} else {
str = stylize('[Getter]', 'special');
}
} else {
if (value.__lookupSetter__(key)) {
str = stylize('[Setter]', 'special');
}
}
}
if (indexOf(visible_keys, key) < 0) {
name = '[' + key + ']';
}
if (!str) {
if (indexOf(seen, value[key]) < 0) {
if (recurseTimes === null) {
str = format(value[key]);
} else {
str = format(value[key], recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (isArray(value)) {
str = map(str.split('\n'), function (line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + map(str.split('\n'), function (line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = stylize('[Circular]', 'special');
}
}
if (typeof name === 'undefined') {
if (type === 'Array' && key.match(/^\d+$/)) {
return str;
}
name = json.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = stylize(name, 'string');
}
}
return name + ': ' + str;
});
seen.pop();
var numLinesEst = 0;
var length = reduce(output, function (prev, cur) {
numLinesEst++;
if (indexOf(cur, '\n') >= 0) numLinesEst++;
return prev + cur.length + 1;
}, 0);
if (length > 50) {
output = braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
} else {
output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
return output;
}
return format(obj, (typeof depth === 'undefined' ? 2 : depth));
}
expect.stringify = i;
function isArray (ar) {
return Object.prototype.toString.call(ar) === '[object Array]';
}
function isRegExp(re) {
var s;
try {
s = '' + re;
} catch (e) {
return false;
}
return re instanceof RegExp || // easy case
// duck-type for context-switching evalcx case
typeof(re) === 'function' &&
re.constructor.name === 'RegExp' &&
re.compile &&
re.test &&
re.exec &&
s.match(/^\/.*\/[gim]{0,3}$/);
}
function isDate(d) {
return d instanceof Date;
}
function keys (obj) {
if (Object.keys) {
return Object.keys(obj);
}
var keys = [];
for (var i in obj) {
if (Object.prototype.hasOwnProperty.call(obj, i)) {
keys.push(i);
}
}
return keys;
}
function map (arr, mapper, that) {
if (Array.prototype.map) {
return Array.prototype.map.call(arr, mapper, that);
}
var other= new Array(arr.length);
for (var i= 0, n = arr.length; i<n; i++)
if (i in arr)
other[i] = mapper.call(that, arr[i], i, arr);
return other;
}
function reduce (arr, fun) {
if (Array.prototype.reduce) {
return Array.prototype.reduce.apply(
arr
, Array.prototype.slice.call(arguments, 1)
);
}
var len = +this.length;
if (typeof fun !== "function")
throw new TypeError();
// no value to return if no initial value and an empty array
if (len === 0 && arguments.length === 1)
throw new TypeError();
var i = 0;
if (arguments.length >= 2) {
var rv = arguments[1];
} else {
do {
if (i in this) {
rv = this[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= len)
throw new TypeError();
} while (true);
}
for (; i < len; i++) {
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
}
/**
* Asserts deep equality
*
* @see taken from node.js `assert` module (copyright Joyent, MIT license)
* @api private
*/
expect.eql = function eql(actual, expected) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if ('undefined' != typeof Buffer
&& Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) {
if (actual.length != expected.length) return false;
for (var i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) return false;
}
return true;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
// 7.3. Other pairs that do not both pass typeof value == "object",
// equivalence is determined by ==.
} else if (typeof actual != 'object' && typeof expected != 'object') {
return actual == expected;
// If both are regular expression use the special `regExpEquiv` method
// to determine equivalence.
} else if (isRegExp(actual) && isRegExp(expected)) {
return regExpEquiv(actual, expected);
// 7.4. For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical "prototype" property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected);
}
};
function isUndefinedOrNull (value) {
return value === null || value === undefined;
}
function isArguments (object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function regExpEquiv (a, b) {
return a.source === b.source && a.global === b.global &&
a.ignoreCase === b.ignoreCase && a.multiline === b.multiline;
}
function objEquiv (a, b) {
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
// an identical "prototype" property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return expect.eql(a, b);
}
try{
var ka = keys(a),
kb = keys(b),
key, i;
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!expect.eql(a[key], b[key]))
return false;
}
return true;
}
var json = (function () {
"use strict";
if ('object' == typeof JSON && JSON.parse && JSON.stringify) {
return {
parse: nativeJSON.parse
, stringify: nativeJSON.stringify
}
}
var JSON = {};
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
function date(d, key) {
return isFinite(d.valueOf()) ?
d.getUTCFullYear() + '-' +
f(d.getUTCMonth() + 1) + '-' +
f(d.getUTCDate()) + 'T' +
f(d.getUTCHours()) + ':' +
f(d.getUTCMinutes()) + ':' +
f(d.getUTCSeconds()) + 'Z' : null;
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value instanceof Date) {
value = date(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? '[]' : gap ?
'[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' : gap ?
'{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
'{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
// If the JSON object does not yet have a parse method, give it one.
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
return JSON;
})();
if ('undefined' != typeof window) {
window.expect = module.exports;
}
})(
this
, 'undefined' != typeof module ? module : {exports: {}}
); |
import React from 'react';
import { StyleSheet, View, Text, ScrollView } from 'react-native';
class CollapsingHeader extends React.Component {
static navigatorStyle = {
drawUnderTabBar: true,
navBarButtonColor: '#ffffff',
navBarTextColor: '#ffffff',
collapsingToolBarImage: require('../../../img/gyro_header.jpg'),
collapsingToolBarCollapsedColor: '#0f2362',
navBarBackgroundColor: '#eeeeee'
};
render() {
return (
<ScrollView style={styles.container}>
<View>
{[...new Array(40)].map((a, index) => (
<Text key={`row_${index}`} style={styles.button}>Row {index}</Text>
))}
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
});
export default CollapsingHeader;
|
(function () {
var autoresize = (function () {
'use strict';
var Cell = function (initial) {
var value = initial;
var get = function () {
return value;
};
var set = function (v) {
value = v;
};
var clone = function () {
return Cell(get());
};
return {
get: get,
set: set,
clone: clone
};
};
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var global$1 = tinymce.util.Tools.resolve('tinymce.Env');
var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
var getAutoResizeMinHeight = function (editor) {
return parseInt(editor.getParam('autoresize_min_height', editor.getElement().offsetHeight), 10);
};
var getAutoResizeMaxHeight = function (editor) {
return parseInt(editor.getParam('autoresize_max_height', 0), 10);
};
var getAutoResizeOverflowPadding = function (editor) {
return editor.getParam('autoresize_overflow_padding', 1);
};
var getAutoResizeBottomMargin = function (editor) {
return editor.getParam('autoresize_bottom_margin', 50);
};
var shouldAutoResizeOnInit = function (editor) {
return editor.getParam('autoresize_on_init', true);
};
var $_azyemt8qjh8lpue0 = {
getAutoResizeMinHeight: getAutoResizeMinHeight,
getAutoResizeMaxHeight: getAutoResizeMaxHeight,
getAutoResizeOverflowPadding: getAutoResizeOverflowPadding,
getAutoResizeBottomMargin: getAutoResizeBottomMargin,
shouldAutoResizeOnInit: shouldAutoResizeOnInit
};
var isFullscreen = function (editor) {
return editor.plugins.fullscreen && editor.plugins.fullscreen.isFullscreen();
};
var wait = function (editor, oldSize, times, interval, callback) {
global$2.setEditorTimeout(editor, function () {
resize(editor, oldSize);
if (times--) {
wait(editor, oldSize, times, interval, callback);
} else if (callback) {
callback();
}
}, interval);
};
var toggleScrolling = function (editor, state) {
var body = editor.getBody();
if (body) {
body.style.overflowY = state ? '' : 'hidden';
if (!state) {
body.scrollTop = 0;
}
}
};
var resize = function (editor, oldSize) {
var deltaSize, doc, body, resizeHeight, myHeight;
var marginTop, marginBottom, paddingTop, paddingBottom, borderTop, borderBottom;
var dom = editor.dom;
doc = editor.getDoc();
if (!doc) {
return;
}
if (isFullscreen(editor)) {
toggleScrolling(editor, true);
return;
}
body = doc.body;
resizeHeight = $_azyemt8qjh8lpue0.getAutoResizeMinHeight(editor);
marginTop = dom.getStyle(body, 'margin-top', true);
marginBottom = dom.getStyle(body, 'margin-bottom', true);
paddingTop = dom.getStyle(body, 'padding-top', true);
paddingBottom = dom.getStyle(body, 'padding-bottom', true);
borderTop = dom.getStyle(body, 'border-top-width', true);
borderBottom = dom.getStyle(body, 'border-bottom-width', true);
myHeight = body.offsetHeight + parseInt(marginTop, 10) + parseInt(marginBottom, 10) + parseInt(paddingTop, 10) + parseInt(paddingBottom, 10) + parseInt(borderTop, 10) + parseInt(borderBottom, 10);
if (isNaN(myHeight) || myHeight <= 0) {
myHeight = global$1.ie ? body.scrollHeight : global$1.webkit && body.clientHeight === 0 ? 0 : body.offsetHeight;
}
if (myHeight > $_azyemt8qjh8lpue0.getAutoResizeMinHeight(editor)) {
resizeHeight = myHeight;
}
var maxHeight = $_azyemt8qjh8lpue0.getAutoResizeMaxHeight(editor);
if (maxHeight && myHeight > maxHeight) {
resizeHeight = maxHeight;
toggleScrolling(editor, true);
} else {
toggleScrolling(editor, false);
}
if (resizeHeight !== oldSize.get()) {
deltaSize = resizeHeight - oldSize.get();
dom.setStyle(editor.iframeElement, 'height', resizeHeight + 'px');
oldSize.set(resizeHeight);
if (global$1.webkit && deltaSize < 0) {
resize(editor, oldSize);
}
}
};
var setup = function (editor, oldSize) {
editor.on('init', function () {
var overflowPadding, bottomMargin;
var dom = editor.dom;
overflowPadding = $_azyemt8qjh8lpue0.getAutoResizeOverflowPadding(editor);
bottomMargin = $_azyemt8qjh8lpue0.getAutoResizeBottomMargin(editor);
if (overflowPadding !== false) {
dom.setStyles(editor.getBody(), {
paddingLeft: overflowPadding,
paddingRight: overflowPadding
});
}
if (bottomMargin !== false) {
dom.setStyles(editor.getBody(), { paddingBottom: bottomMargin });
}
});
editor.on('nodechange setcontent keyup FullscreenStateChanged', function (e) {
resize(editor, oldSize);
});
if ($_azyemt8qjh8lpue0.shouldAutoResizeOnInit(editor)) {
editor.on('init', function () {
wait(editor, oldSize, 20, 100, function () {
wait(editor, oldSize, 5, 1000);
});
});
}
};
var $_rs2t18njh8lpudw = {
setup: setup,
resize: resize
};
var register = function (editor, oldSize) {
editor.addCommand('mceAutoResize', function () {
$_rs2t18njh8lpudw.resize(editor, oldSize);
});
};
var $_b0t1u48mjh8lpudv = { register: register };
global.add('autoresize', function (editor) {
if (!editor.inline) {
var oldSize = Cell(0);
$_b0t1u48mjh8lpudv.register(editor, oldSize);
$_rs2t18njh8lpudw.setup(editor, oldSize);
}
});
function Plugin () {
}
return Plugin;
}());
})();
|
module.exports = determinant
/**
* Calculates the determinant of a mat2
*
* @alias mat2.determinant
* @param {mat2} a the source matrix
* @returns {Number} determinant of a
*/
function determinant(a) {
return a[0] * a[3] - a[2] * a[1]
}
|
/*global describe, it*/
'use strict';
var assert = require('assert');
var helpers = require('./helpers');
var pako_utils = require('../lib/utils/common');
var pako = require('../index');
var samples = helpers.loadSamples();
function randomBuf(size) {
var buf = new pako_utils.Buf8(size);
for (var i = 0; i < size; i++) {
buf[i] = Math.round(Math.random() * 256);
}
return buf;
}
function testChunk(buf, expected, packer, chunkSize) {
var i, _in, count, pos, size, expFlushCount;
var onData = packer.onData;
var flushCount = 0;
packer.onData = function() {
flushCount++;
onData.apply(this, arguments);
};
count = Math.ceil(buf.length / chunkSize);
pos = 0;
for (i = 0; i < count; i++) {
size = (buf.length - pos) < chunkSize ? buf.length - pos : chunkSize;
_in = new pako_utils.Buf8(size);
pako_utils.arraySet(_in, buf, pos, size, 0);
packer.push(_in, i === count - 1);
pos += chunkSize;
}
//expected count of onData calls. 16384 output chunk size
expFlushCount = Math.ceil(packer.result.length / 16384);
assert(!packer.err, 'Packer error: ' + packer.err);
assert(helpers.cmpBuf(packer.result, expected), 'Result is different');
assert.equal(flushCount, expFlushCount, 'onData called ' + flushCount + 'times, expected: ' + expFlushCount);
}
describe('Small input chunks', function () {
it('deflate 100b by 1b chunk', function () {
var buf = randomBuf(100);
var deflated = pako.deflate(buf);
testChunk(buf, deflated, new pako.Deflate(), 1);
});
it('deflate 20000b by 10b chunk', function () {
var buf = randomBuf(20000);
var deflated = pako.deflate(buf);
testChunk(buf, deflated, new pako.Deflate(), 10);
});
it('inflate 100b result by 1b chunk', function () {
var buf = randomBuf(100);
var deflated = pako.deflate(buf);
testChunk(deflated, buf, new pako.Inflate(), 1);
});
it('inflate 20000b result by 10b chunk', function () {
var buf = randomBuf(20000);
var deflated = pako.deflate(buf);
testChunk(deflated, buf, new pako.Inflate(), 10);
});
});
describe('Dummy push (force end)', function () {
it('deflate end', function () {
var data = samples.lorem_utf_100k;
var deflator = new pako.Deflate();
deflator.push(data);
deflator.push([], true);
assert(helpers.cmpBuf(deflator.result, pako.deflate(data)));
});
it('inflate end', function () {
var data = pako.deflate(samples.lorem_utf_100k);
var inflator = new pako.Inflate();
inflator.push(data);
inflator.push([], true);
assert(helpers.cmpBuf(inflator.result, pako.inflate(data)));
});
});
describe('Edge condition', function () {
it('should be ok on buffer border', function () {
var i;
var data = new Uint8Array(1024 * 16 + 1);
for (i = 0; i < data.length; i++) {
data[i] = Math.floor(Math.random() * 255.999);
}
var deflated = pako.deflate(data);
var inflator = new pako.Inflate();
for (i = 0; i < deflated.length; i++) {
inflator.push(deflated.subarray(i, i+1), false);
assert.ok(!inflator.err, 'Inflate failed with status ' + inflator.err);
}
inflator.push(new Uint8Array(0), true);
assert.ok(!inflator.err, 'Inflate failed with status ' + inflator.err);
assert(helpers.cmpBuf(data, inflator.result));
});
});
|
'use strict';
var
coveralls = require('gulp-coveralls'),
del = require('del'),
gulp = require('gulp'),
istanbul = require('gulp-istanbul'),
jshint = require('gulp-jshint'),
mocha = require('gulp-mocha'),
sequence = require('run-sequence');
gulp.task('clean', function (callback) {
return del(['coverage'], callback);
});
gulp.task('coveralls', function () {
return gulp
.src('./reports/lcov.info')
.pipe(coveralls());
});
gulp.task('jshint', function () {
return gulp
.src(['lib/**/*.js', 'test/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('test-all', function (callback) {
sequence('clean', 'jshint', 'test-coverage', callback);
});
gulp.task('test-coverage', ['clean'], function () {
return gulp
.src(['./lib/*.js'])
.pipe(istanbul())
.pipe(istanbul.hookRequire())
.on('finish', function () {
gulp
.src(['./test/lib/*.js'])
.pipe(mocha({
reporter : 'spec'
}))
.pipe(istanbul.writeReports('./reports'));
});
});
gulp.task('test-unit', function () {
return gulp
.src(['./test/lib/**/*.js'], { read : false })
.pipe(mocha({
checkLeaks : true,
reporter : 'spec',
ui : 'bdd'
}));
});
|
angular.module('app', [
'ngRoute',
'config',
'base',
'signup',
'login',
'account',
'admin',
'services.i18nNotifications',
'services.httpRequestTracker',
'security',
'templates.app',
'templates.common',
'ui.bootstrap'
]);
// Node.js Express backend csurf module csrf/xsrf token cookie name
angular.module('app').config(['$httpProvider', 'XSRF_COOKIE_NAME', function($httpProvider, XSRF_COOKIE_NAME){
$httpProvider.defaults.xsrfCookieName = XSRF_COOKIE_NAME;
}]);
angular.module('app').config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$routeProvider
.when('/', {
templateUrl: 'main.tpl.html',
controller: 'AppCtrl'
})
.when('/contact', {
templateUrl: 'contact.tpl.html',
controller: 'ContactCtrl',
title: 'Contact Us'
})
.when('/about', {
templateUrl: 'about.tpl.html',
title: 'About Us'
})
.otherwise({
templateUrl: '404.tpl.html',
title: 'Page Not Found'
});
}]);
angular.module('app').run(['$location', '$rootScope', 'security', function($location, $rootScope, security) {
// Get the current user when the application starts
// (in case they are still logged in from a previous session)
security.requestCurrentUser();
// add a listener to $routeChangeSuccess
$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
$rootScope.title = current.$$route && current.$$route.title? current.$$route.title: 'Drywall is Running';
});
}]);
angular.module('app').controller('AppCtrl', ['$scope', 'i18nNotifications', 'localizedMessages', function($scope, i18nNotifications, localizedMessages) {
$scope.notifications = i18nNotifications;
$scope.removeNotification = function (notification) {
i18nNotifications.remove(notification);
};
$scope.$on('$routeChangeError', function(event, current, previous, rejection){
i18nNotifications.pushForCurrentRoute('errors.route.changeError', 'error', {}, {rejection: rejection});
});
}]);
|
step1list = new Array();
step1list["ΦΑΓΙΑ"] = "ΦΑ";
step1list["ΦΑΓΙΟΥ"] = "ΦΑ";
step1list["ΦΑΓΙΩΝ"] = "ΦΑ";
step1list["ΣΚΑΓΙΑ"] = "ΣΚΑ";
step1list["ΣΚΑΓΙΟΥ"] = "ΣΚΑ";
step1list["ΣΚΑΓΙΩΝ"] = "ΣΚΑ";
step1list["ΟΛΟΓΙΟΥ"] = "ΟΛΟ";
step1list["ΟΛΟΓΙΑ"] = "ΟΛΟ";
step1list["ΟΛΟΓΙΩΝ"] = "ΟΛΟ";
step1list["ΣΟΓΙΟΥ"] = "ΣΟ";
step1list["ΣΟΓΙΑ"] = "ΣΟ";
step1list["ΣΟΓΙΩΝ"] = "ΣΟ";
step1list["ΤΑΤΟΓΙΑ"] = "ΤΑΤΟ";
step1list["ΤΑΤΟΓΙΟΥ"] = "ΤΑΤΟ";
step1list["ΤΑΤΟΓΙΩΝ"] = "ΤΑΤΟ";
step1list["ΚΡΕΑΣ"] = "ΚΡΕ";
step1list["ΚΡΕΑΤΟΣ"] = "ΚΡΕ";
step1list["ΚΡΕΑΤΑ"] = "ΚΡΕ";
step1list["ΚΡΕΑΤΩΝ"] = "ΚΡΕ";
step1list["ΠΕΡΑΣ"] = "ΠΕΡ";
step1list["ΠΕΡΑΤΟΣ"] = "ΠΕΡ";
step1list["ΠΕΡΑΤΑ"] = "ΠΕΡ";
step1list["ΠΕΡΑΤΩΝ"] = "ΠΕΡ";
step1list["ΤΕΡΑΣ"] = "ΤΕΡ";
step1list["ΤΕΡΑΤΟΣ"] = "ΤΕΡ";
step1list["ΤΕΡΑΤΑ"] = "ΤΕΡ";
step1list["ΤΕΡΑΤΩΝ"] = "ΤΕΡ";
step1list["ΦΩΣ"] = "ΦΩ";
step1list["ΦΩΤΟΣ"] = "ΦΩ";
step1list["ΦΩΤΑ"] = "ΦΩ";
step1list["ΦΩΤΩΝ"] = "ΦΩ";
step1list["ΚΑΘΕΣΤΩΣ"] = "ΚΑΘΕΣΤ";
step1list["ΚΑΘΕΣΤΩΤΟΣ"] = "ΚΑΘΕΣΤ";
step1list["ΚΑΘΕΣΤΩΤΑ"] = "ΚΑΘΕΣΤ";
step1list["ΚΑΘΕΣΤΩΤΩΝ"] = "ΚΑΘΕΣΤ";
step1list["ΓΕΓΟΝΟΣ"] = "ΓΕΓΟΝ";
step1list["ΓΕΓΟΝΟΤΟΣ"] = "ΓΕΓΟΝ";
step1list["ΓΕΓΟΝΟΤΑ"] = "ΓΕΓΟΝ";
step1list["ΓΕΓΟΝΟΤΩΝ"] = "ΓΕΓΟΝ";
v = "[ΑΕΗΙΟΥΩ]";
v2 = "[ΑΕΗΙΟΩ]"
function stemWord(w) {
var stem;
var suffix;
var firstch;
var origword = w;
test1 = new Boolean(true);
if(w.length < 4) {
return w;
}
var re;
var re2;
var re3;
var re4;
re = /(.*)(ΦΑΓΙΑ|ΦΑΓΙΟΥ|ΦΑΓΙΩΝ|ΣΚΑΓΙΑ|ΣΚΑΓΙΟΥ|ΣΚΑΓΙΩΝ|ΟΛΟΓΙΟΥ|ΟΛΟΓΙΑ|ΟΛΟΓΙΩΝ|ΣΟΓΙΟΥ|ΣΟΓΙΑ|ΣΟΓΙΩΝ|ΤΑΤΟΓΙΑ|ΤΑΤΟΓΙΟΥ|ΤΑΤΟΓΙΩΝ|ΚΡΕΑΣ|ΚΡΕΑΤΟΣ|ΚΡΕΑΤΑ|ΚΡΕΑΤΩΝ|ΠΕΡΑΣ|ΠΕΡΑΤΟΣ|ΠΕΡΑΤΑ|ΠΕΡΑΤΩΝ|ΤΕΡΑΣ|ΤΕΡΑΤΟΣ|ΤΕΡΑΤΑ|ΤΕΡΑΤΩΝ|ΦΩΣ|ΦΩΤΟΣ|ΦΩΤΑ|ΦΩΤΩΝ|ΚΑΘΕΣΤΩΣ|ΚΑΘΕΣΤΩΤΟΣ|ΚΑΘΕΣΤΩΤΑ|ΚΑΘΕΣΤΩΤΩΝ|ΓΕΓΟΝΟΣ|ΓΕΓΟΝΟΤΟΣ|ΓΕΓΟΝΟΤΑ|ΓΕΓΟΝΟΤΩΝ)$/;
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
suffix = fp[2];
w = stem + step1list[suffix];
test1 = false;
}
re = /^(.+?)(ΑΔΕΣ|ΑΔΩΝ)$/;
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
reg1 = /(ΟΚ|ΜΑΜ|ΜΑΝ|ΜΠΑΜΠ|ΠΑΤΕΡ|ΓΙΑΓΙ|ΝΤΑΝΤ|ΚΥΡ|ΘΕΙ|ΠΕΘΕΡ)$/;
if(!(reg1.test(w))) {
w = w + "ΑΔ";
}
}
re2 = /^(.+?)(ΕΔΕΣ|ΕΔΩΝ)$/;
if(re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1];
w = stem;
exept2 = /(ΟΠ|ΙΠ|ΕΜΠ|ΥΠ|ΓΗΠ|ΔΑΠ|ΚΡΑΣΠ|ΜΙΛ)$/;
if(exept2.test(w)) {
w = w + "ΕΔ";
}
}
re3 = /^(.+?)(ΟΥΔΕΣ|ΟΥΔΩΝ)$/;
if(re3.test(w)) {
var fp = re3.exec(w);
stem = fp[1];
w = stem;
exept3 = /(ΑΡΚ|ΚΑΛΙΑΚ|ΠΕΤΑΛ|ΛΙΧ|ΠΛΕΞ|ΣΚ|Σ|ΦΛ|ΦΡ|ΒΕΛ|ΛΟΥΛ|ΧΝ|ΣΠ|ΤΡΑΓ|ΦΕ)$/;
if(exept3.test(w)) {
w = w + "ΟΥΔ";
}
}
re4 = /^(.+?)(ΕΩΣ|ΕΩΝ)$/;
if(re4.test(w)) {
var fp = re4.exec(w);
stem = fp[1];
w = stem;
test1 = false;
exept4 = /^(Θ|Δ|ΕΛ|ΓΑΛ|Ν|Π|ΙΔ|ΠΑΡ)$/;
if(exept4.test(w)) {
w = w + "Ε";
}
}
re = /^(.+?)(ΙΑ|ΙΟΥ|ΙΩΝ)$/;
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
re2 = new RegExp(v + "$");
test1 = false;
if(re2.test(w)) {
w = stem + "Ι";
}
}
re = /^(.+?)(ΙΚΑ|ΙΚΟ|ΙΚΟΥ|ΙΚΩΝ)$/;
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
test1 = false;
re2 = new RegExp(v + "$");
exept5 = /^(ΑΛ|ΑΔ|ΕΝΔ|ΑΜΑΝ|ΑΜΜΟΧΑΛ|ΗΘ|ΑΝΗΘ|ΑΝΤΙΔ|ΦΥΣ|ΒΡΩΜ|ΓΕΡ|ΕΞΩΔ|ΚΑΛΠ|ΚΑΛΛΙΝ|ΚΑΤΑΔ|ΜΟΥΛ|ΜΠΑΝ|ΜΠΑΓΙΑΤ|ΜΠΟΛ|ΜΠΟΣ|ΝΙΤ|ΞΙΚ|ΣΥΝΟΜΗΛ|ΠΕΤΣ|ΠΙΤΣ|ΠΙΚΑΝΤ|ΠΛΙΑΤΣ|ΠΟΣΤΕΛΝ|ΠΡΩΤΟΔ|ΣΕΡΤ|ΣΥΝΑΔ|ΤΣΑΜ|ΥΠΟΔ|ΦΙΛΟΝ|ΦΥΛΟΔ|ΧΑΣ)$/;
if((exept5.test(w)) || (re2.test(w))) {
w = w + "ΙΚ";
}
}
re = /^(.+?)(ΑΜΕ)$/;
re2 = /^(.+?)(ΑΓΑΜΕ|ΗΣΑΜΕ|ΟΥΣΑΜΕ|ΗΚΑΜΕ|ΗΘΗΚΑΜΕ)$/;
if(w == "ΑΓΑΜΕ") {
w = "ΑΓΑΜ";
}
if(re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1];
w = stem;
test1 = false;
}
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
test1 = false;
exept6 = /^(ΑΝΑΠ|ΑΠΟΘ|ΑΠΟΚ|ΑΠΟΣΤ|ΒΟΥΒ|ΞΕΘ|ΟΥΛ|ΠΕΘ|ΠΙΚΡ|ΠΟΤ|ΣΙΧ|Χ)$/;
if(exept6.test(w)) {
w = w + "ΑΜ";
}
}
re2 = /^(.+?)(ΑΝΕ)$/;
re3 = /^(.+?)(ΑΓΑΝΕ|ΗΣΑΝΕ|ΟΥΣΑΝΕ|ΙΟΝΤΑΝΕ|ΙΟΤΑΝΕ|ΙΟΥΝΤΑΝΕ|ΟΝΤΑΝΕ|ΟΤΑΝΕ|ΟΥΝΤΑΝΕ|ΗΚΑΝΕ|ΗΘΗΚΑΝΕ)$/;
if(re3.test(w)) {
var fp = re3.exec(w);
stem = fp[1];
w = stem;
test1 = false;
re3 = /^(ΤΡ|ΤΣ)$/;
if(re3.test(w)) {
w = w + "ΑΓΑΝ";
}
}
if(re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1];
w = stem;
test1 = false;
re2 = new RegExp(v2 + "$");
exept7 = /^(ΒΕΤΕΡ|ΒΟΥΛΚ|ΒΡΑΧΜ|Γ|ΔΡΑΔΟΥΜ|Θ|ΚΑΛΠΟΥΖ|ΚΑΣΤΕΛ|ΚΟΡΜΟΡ|ΛΑΟΠΛ|ΜΩΑΜΕΘ|Μ|ΜΟΥΣΟΥΛΜ|Ν|ΟΥΛ|Π|ΠΕΛΕΚ|ΠΛ|ΠΟΛΙΣ|ΠΟΡΤΟΛ|ΣΑΡΑΚΑΤΣ|ΣΟΥΛΤ|ΤΣΑΡΛΑΤ|ΟΡΦ|ΤΣΙΓΓ|ΤΣΟΠ|ΦΩΤΟΣΤΕΦ|Χ|ΨΥΧΟΠΛ|ΑΓ|ΟΡΦ|ΓΑΛ|ΓΕΡ|ΔΕΚ|ΔΙΠΛ|ΑΜΕΡΙΚΑΝ|ΟΥΡ|ΠΙΘ|ΠΟΥΡΙΤ|Σ|ΖΩΝΤ|ΙΚ|ΚΑΣΤ|ΚΟΠ|ΛΙΧ|ΛΟΥΘΗΡ|ΜΑΙΝΤ|ΜΕΛ|ΣΙΓ|ΣΠ|ΣΤΕΓ|ΤΡΑΓ|ΤΣΑΓ|Φ|ΕΡ|ΑΔΑΠ|ΑΘΙΓΓ|ΑΜΗΧ|ΑΝΙΚ|ΑΝΟΡΓ|ΑΠΗΓ|ΑΠΙΘ|ΑΤΣΙΓΓ|ΒΑΣ|ΒΑΣΚ|ΒΑΘΥΓΑΛ|ΒΙΟΜΗΧ|ΒΡΑΧΥΚ|ΔΙΑΤ|ΔΙΑΦ|ΕΝΟΡΓ|ΘΥΣ|ΚΑΠΝΟΒΙΟΜΗΧ|ΚΑΤΑΓΑΛ|ΚΛΙΒ|ΚΟΙΛΑΡΦ|ΛΙΒ|ΜΕΓΛΟΒΙΟΜΗΧ|ΜΙΚΡΟΒΙΟΜΗΧ|ΝΤΑΒ|ΞΗΡΟΚΛΙΒ|ΟΛΙΓΟΔΑΜ|ΟΛΟΓΑΛ|ΠΕΝΤΑΡΦ|ΠΕΡΗΦ|ΠΕΡΙΤΡ|ΠΛΑΤ|ΠΟΛΥΔΑΠ|ΠΟΛΥΜΗΧ|ΣΤΕΦ|ΤΑΒ|ΤΕΤ|ΥΠΕΡΗΦ|ΥΠΟΚΟΠ|ΧΑΜΗΛΟΔΑΠ|ΨΗΛΟΤΑΒ)$/;
if((re2.test(w)) || (exept7.test(w))) {
w = w + "ΑΝ";
}
}
re3 = /^(.+?)(ΕΤΕ)$/;
re4 = /^(.+?)(ΗΣΕΤΕ)$/;
if(re4.test(w)) {
var fp = re4.exec(w);
stem = fp[1];
w = stem;
test1 = false;
}
if(re3.test(w)) {
var fp = re3.exec(w);
stem = fp[1];
w = stem;
test1 = false;
re3 = new RegExp(v2 + "$");
exept8 = /(ΟΔ|ΑΙΡ|ΦΟΡ|ΤΑΘ|ΔΙΑΘ|ΣΧ|ΕΝΔ|ΕΥΡ|ΤΙΘ|ΥΠΕΡΘ|ΡΑΘ|ΕΝΘ|ΡΟΘ|ΣΘ|ΠΥΡ|ΑΙΝ|ΣΥΝΔ|ΣΥΝ|ΣΥΝΘ|ΧΩΡ|ΠΟΝ|ΒΡ|ΚΑΘ|ΕΥΘ|ΕΚΘ|ΝΕΤ|ΡΟΝ|ΑΡΚ|ΒΑΡ|ΒΟΛ|ΩΦΕΛ)$/;
exept9 = /^(ΑΒΑΡ|ΒΕΝ|ΕΝΑΡ|ΑΒΡ|ΑΔ|ΑΘ|ΑΝ|ΑΠΛ|ΒΑΡΟΝ|ΝΤΡ|ΣΚ|ΚΟΠ|ΜΠΟΡ|ΝΙΦ|ΠΑΓ|ΠΑΡΑΚΑΛ|ΣΕΡΠ|ΣΚΕΛ|ΣΥΡΦ|ΤΟΚ|Υ|Δ|ΕΜ|ΘΑΡΡ|Θ)$/;
if((re3.test(w)) || (exept8.test(w)) || (exept9.test(w))) {
w = w + "ΕΤ";
}
}
re = /^(.+?)(ΟΝΤΑΣ|ΩΝΤΑΣ)$/;
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
test1 = false;
exept10 = /^(ΑΡΧ)$/;
exept11 = /(ΚΡΕ)$/;
if(exept10.test(w)) {
w = w + "ΟΝΤ";
}
if(exept11.test(w)) {
w = w + "ΩΝΤ";
}
}
re = /^(.+?)(ΟΜΑΣΤΕ|ΙΟΜΑΣΤΕ)$/;
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
test1 = false;
exept11 = /^(ΟΝ)$/;
if(exept11.test(w)) {
w = w + "ΟΜΑΣΤ";
}
}
re = /^(.+?)(ΕΣΤΕ)$/;
re2 = /^(.+?)(ΙΕΣΤΕ)$/;
if(re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1];
w = stem;
test1 = false;
re2 = /^(Π|ΑΠ|ΣΥΜΠ|ΑΣΥΜΠ|ΑΚΑΤΑΠ|ΑΜΕΤΑΜΦ)$/;
if(re2.test(w)) {
w = w + "ΙΕΣΤ";
}
}
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
test1 = false;
exept12 = /^(ΑΛ|ΑΡ|ΕΚΤΕΛ|Ζ|Μ|Ξ|ΠΑΡΑΚΑΛ|ΑΡ|ΠΡΟ|ΝΙΣ)$/;
if(exept12.test(w)) {
w = w + "ΕΣΤ";
}
}
re = /^(.+?)(ΗΚΑ|ΗΚΕΣ|ΗΚΕ)$/;
re2 = /^(.+?)(ΗΘΗΚΑ|ΗΘΗΚΕΣ|ΗΘΗΚΕ)$/;
if(re2.test(w)) {
var fp = re2.exec(w);
stem = fp[1];
w = stem;
test1 = false;
}
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
test1 = false;
exept13 = /(ΣΚΩΛ|ΣΚΟΥΛ|ΝΑΡΘ|ΣΦ|ΟΘ|ΠΙΘ)$/;
exept14 = /^(ΔΙΑΘ|Θ|ΠΑΡΑΚΑΤΑΘ|ΠΡΟΣΘ|ΣΥΝΘ|)$/;
if((exept13.test(w)) || (exept14.test(w))) {
w = w + "ΗΚ";
}
}
re = /^(.+?)(ΟΥΣΑ|ΟΥΣΕΣ|ΟΥΣΕ)$/;
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
test1 = false;
exept15 = /^(ΦΑΡΜΑΚ|ΧΑΔ|ΑΓΚ|ΑΝΑΡΡ|ΒΡΟΜ|ΕΚΛΙΠ|ΛΑΜΠΙΔ|ΛΕΧ|Μ|ΠΑΤ|Ρ|Λ|ΜΕΔ|ΜΕΣΑΖ|ΥΠΟΤΕΙΝ|ΑΜ|ΑΙΘ|ΑΝΗΚ|ΔΕΣΠΟΖ|ΕΝΔΙΑΦΕΡ|ΔΕ|ΔΕΥΤΕΡΕΥ|ΚΑΘΑΡΕΥ|ΠΛΕ|ΤΣΑ)$/;
exept16 = /(ΠΟΔΑΡ|ΒΛΕΠ|ΠΑΝΤΑΧ|ΦΡΥΔ|ΜΑΝΤΙΛ|ΜΑΛΛ|ΚΥΜΑΤ|ΛΑΧ|ΛΗΓ|ΦΑΓ|ΟΜ|ΠΡΩΤ)$/;
if((exept15.test(w)) || (exept16.test(w))) {
w = w + "ΟΥΣ";
}
}
re = /^(.+?)(ΑΓΑ|ΑΓΕΣ|ΑΓΕ)$/;
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
test1 = false;
exept17 = /^(ΨΟΦ|ΝΑΥΛΟΧ)$/;
exept20 = /(ΚΟΛΛ)$/;
exept18 = /^(ΑΒΑΣΤ|ΠΟΛΥΦ|ΑΔΗΦ|ΠΑΜΦ|Ρ|ΑΣΠ|ΑΦ|ΑΜΑΛ|ΑΜΑΛΛΙ|ΑΝΥΣΤ|ΑΠΕΡ|ΑΣΠΑΡ|ΑΧΑΡ|ΔΕΡΒΕΝ|ΔΡΟΣΟΠ|ΞΕΦ|ΝΕΟΠ|ΝΟΜΟΤ|ΟΛΟΠ|ΟΜΟΤ|ΠΡΟΣΤ|ΠΡΟΣΩΠΟΠ|ΣΥΜΠ|ΣΥΝΤ|Τ|ΥΠΟΤ|ΧΑΡ|ΑΕΙΠ|ΑΙΜΟΣΤ|ΑΝΥΠ|ΑΠΟΤ|ΑΡΤΙΠ|ΔΙΑΤ|ΕΝ|ΕΠΙΤ|ΚΡΟΚΑΛΟΠ|ΣΙΔΗΡΟΠ|Λ|ΝΑΥ|ΟΥΛΑΜ|ΟΥΡ|Π|ΤΡ|Μ)$/;
exept19 = /(ΟΦ|ΠΕΛ|ΧΟΡΤ|ΛΛ|ΣΦ|ΡΠ|ΦΡ|ΠΡ|ΛΟΧ|ΣΜΗΝ)$/;
if(((exept18.test(w)) || (exept19.test(w))) && !((exept17.test(w)) || (exept20.test(w)))) {
w = w + "ΑΓ";
}
}
re = /^(.+?)(ΗΣΕ|ΗΣΟΥ|ΗΣΑ)$/;
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
test1 = false;
exept21 = /^(Ν|ΧΕΡΣΟΝ|ΔΩΔΕΚΑΝ|ΕΡΗΜΟΝ|ΜΕΓΑΛΟΝ|ΕΠΤΑΝ)$/;
if(exept21.test(w)) {
w = w + "ΗΣ";
}
}
re = /^(.+?)(ΗΣΤΕ)$/;
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
test1 = false;
exept22 = /^(ΑΣΒ|ΣΒ|ΑΧΡ|ΧΡ|ΑΠΛ|ΑΕΙΜΝ|ΔΥΣΧΡ|ΕΥΧΡ|ΚΟΙΝΟΧΡ|ΠΑΛΙΜΨ)$/;
if(exept22.test(w)) {
w = w + "ΗΣΤ";
}
}
re = /^(.+?)(ΟΥΝΕ|ΗΣΟΥΝΕ|ΗΘΟΥΝΕ)$/;
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
test1 = false;
exept23 = /^(Ν|Ρ|ΣΠΙ|ΣΤΡΑΒΟΜΟΥΤΣ|ΚΑΚΟΜΟΥΤΣ|ΕΞΩΝ)$/;
if(exept23.test(w)) {
w = w + "ΟΥΝ";
}
}
re = /^(.+?)(ΟΥΜΕ|ΗΣΟΥΜΕ|ΗΘΟΥΜΕ)$/;
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
test1 = false;
exept24 = /^(ΠΑΡΑΣΟΥΣ|Φ|Χ|ΩΡΙΟΠΛ|ΑΖ|ΑΛΛΟΣΟΥΣ|ΑΣΟΥΣ)$/;
if(exept24.test(w)) {
w = w + "ΟΥΜ";
}
}
re = /^(.+?)(ΜΑΤΑ|ΜΑΤΩΝ|ΜΑΤΟΣ)$/;
re2 = /^(.+?)(Α|ΑΓΑΤΕ|ΑΓΑΝ|ΑΕΙ|ΑΜΑΙ|ΑΝ|ΑΣ|ΑΣΑΙ|ΑΤΑΙ|ΑΩ|Ε|ΕΙ|ΕΙΣ|ΕΙΤΕ|ΕΣΑΙ|ΕΣ|ΕΤΑΙ|Ι|ΙΕΜΑΙ|ΙΕΜΑΣΤΕ|ΙΕΤΑΙ|ΙΕΣΑΙ|ΙΕΣΑΣΤΕ|ΙΟΜΑΣΤΑΝ|ΙΟΜΟΥΝ|ΙΟΜΟΥΝΑ|ΙΟΝΤΑΝ|ΙΟΝΤΟΥΣΑΝ|ΙΟΣΑΣΤΑΝ|ΙΟΣΑΣΤΕ|ΙΟΣΟΥΝ|ΙΟΣΟΥΝΑ|ΙΟΤΑΝ|ΙΟΥΜΑ|ΙΟΥΜΑΣΤΕ|ΙΟΥΝΤΑΙ|ΙΟΥΝΤΑΝ|Η|ΗΔΕΣ|ΗΔΩΝ|ΗΘΕΙ|ΗΘΕΙΣ|ΗΘΕΙΤΕ|ΗΘΗΚΑΤΕ|ΗΘΗΚΑΝ|ΗΘΟΥΝ|ΗΘΩ|ΗΚΑΤΕ|ΗΚΑΝ|ΗΣ|ΗΣΑΝ|ΗΣΑΤΕ|ΗΣΕΙ|ΗΣΕΣ|ΗΣΟΥΝ|ΗΣΩ|Ο|ΟΙ|ΟΜΑΙ|ΟΜΑΣΤΑΝ|ΟΜΟΥΝ|ΟΜΟΥΝΑ|ΟΝΤΑΙ|ΟΝΤΑΝ|ΟΝΤΟΥΣΑΝ|ΟΣ|ΟΣΑΣΤΑΝ|ΟΣΑΣΤΕ|ΟΣΟΥΝ|ΟΣΟΥΝΑ|ΟΤΑΝ|ΟΥ|ΟΥΜΑΙ|ΟΥΜΑΣΤΕ|ΟΥΝ|ΟΥΝΤΑΙ|ΟΥΝΤΑΝ|ΟΥΣ|ΟΥΣΑΝ|ΟΥΣΑΤΕ|Υ|ΥΣ|Ω|ΩΝ)$/;
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem + "ΜΑ";
}
if((re2.test(w)) && (test1)) {
var fp = re2.exec(w);
stem = fp[1];
w = stem;
}
re = /^(.+?)(ΕΣΤΕΡ|ΕΣΤΑΤ|ΟΤΕΡ|ΟΤΑΤ|ΥΤΕΡ|ΥΤΑΤ|ΩΤΕΡ|ΩΤΑΤ)$/;
if(re.test(w)) {
var fp = re.exec(w);
stem = fp[1];
w = stem;
}
return w;
};
var greekStemmer = function (token) {
return token.update(function (word) {
return stemWord(word);
})
}
var idx = lunr(function () {
this.field('title')
this.field('excerpt')
this.field('categories')
this.field('tags')
this.ref('id')
this.pipeline.remove(lunr.trimmer)
this.pipeline.add(greekStemmer)
this.pipeline.remove(lunr.stemmer)
for (var item in store) {
this.add({
title: store[item].title,
excerpt: store[item].excerpt,
categories: store[item].categories,
tags: store[item].tags,
id: item
})
}
});
console.log( jQuery.type(idx) );
$(document).ready(function() {
$('input#search').on('keyup', function () {
var resultdiv = $('#results');
var query = $(this).val().toLowerCase();
var result =
idx.query(function (q) {
query.split(lunr.tokenizer.separator).forEach(function (term) {
q.term(term, { boost: 100 })
if(query.lastIndexOf(" ") != query.length-1){
q.term(term, { usePipeline: false, wildcard: lunr.Query.wildcard.TRAILING, boost: 10 })
}
if (term != ""){
q.term(term, { usePipeline: false, editDistance: 1, boost: 1 })
}
})
});
resultdiv.empty();
resultdiv.prepend('<p class="results__found">'+result.length+' Result(s) found</p>');
for (var item in result) {
var ref = result[item].ref;
if(store[ref].teaser){
var searchitem =
'<div class="list__item">'+
'<article class="archive__item" itemscope itemtype="https://schema.org/CreativeWork">'+
'<h2 class="archive__item-title" itemprop="headline">'+
'<a href="'+store[ref].url+'" rel="permalink">'+store[ref].title+'</a>'+
'</h2>'+
'<div class="archive__item-teaser">'+
'<img src="'+store[ref].teaser+'" alt="">'+
'</div>'+
'<p class="archive__item-excerpt" itemprop="description">'+store[ref].excerpt.split(" ").splice(0,20).join(" ")+'...</p>'+
'</article>'+
'</div>';
}
else{
var searchitem =
'<div class="list__item">'+
'<article class="archive__item" itemscope itemtype="https://schema.org/CreativeWork">'+
'<h2 class="archive__item-title" itemprop="headline">'+
'<a href="'+store[ref].url+'" rel="permalink">'+store[ref].title+'</a>'+
'</h2>'+
'<p class="archive__item-excerpt" itemprop="description">'+store[ref].excerpt.split(" ").splice(0,20).join(" ")+'...</p>'+
'</article>'+
'</div>';
}
resultdiv.append(searchitem);
}
});
});
|
(function() {
var ThreeUVModifierPlugin = E2.plugins.three_uv_modifier = function(core, node) {
Plugin.apply(this, arguments)
this.desc = 'Adjust a texture\'s UV coordinates'
this.input_slots = [{
name: 'texture',
dt: core.datatypes.TEXTURE,
def: new THREE.Texture()
}, {
name: 'u offset',
dt: core.datatypes.FLOAT,
def: 0.0
}, {
name: 'v offset',
dt: core.datatypes.FLOAT,
def: 0.0
}, {
name: 'u repeat',
dt: core.datatypes.FLOAT,
def: 1.0
}, {
name: 'v repeat',
dt: core.datatypes.FLOAT,
def: 1.0
}, {
name: 'filter',
dt: core.datatypes.FLOAT,
def: 1.0,
desc: 'Texture Filter - (0: nearest, 1: linear)'
}]
this.output_slots = [{
name: 'texture',
dt: core.datatypes.TEXTURE
}]
}
ThreeUVModifierPlugin.prototype = Object.create(Plugin.prototype)
ThreeUVModifierPlugin.prototype.reset = function() {
this.texture = undefined
this.uOffset = 0
this.vOffset = 0
this.uRepeat = 1
this.vRepeat = 1
this.dirty = false
}
ThreeUVModifierPlugin.prototype.update_input = function(slot, data) {
if (slot.name === 'texture') { // texture
if (data) {
this.texture = data.clone()
this.dirty = true
}
else {
this.texture = undefined
}
}
else if (slot.name === 'u offset') { // u offset
this.uOffset = data
this.dirty = true
}
else if (slot.name === 'v offset') { // v offset
this.vOffset = data
this.dirty = true
}
else if (slot.name === 'u repeat') { // u repeat
this.uRepeat = data
this.dirty = true
}
else if (slot.name === 'v repeat') { // v repeat
this.vRepeat = data
this.dirty = true
}
else if (slot.name === 'filter') { // filter
this.filter = data
this.dirty = true
}
}
ThreeUVModifierPlugin.prototype.state_changed = function(ui) {
if (ui) {
return
}
}
ThreeUVModifierPlugin.prototype.update_state = function() {
if (this.dirty && this.texture) {
this.texture.offset.set(this.uOffset, this.vOffset)
this.texture.repeat.set(this.uRepeat, this.vRepeat)
this.texture.magFilter = this.filter === 0 ? THREE.NearestFilter : THREE.LinearFilter
this.texture.needsUpdate = true
this.dirty = false
}
}
ThreeUVModifierPlugin.prototype.update_output = function() {
return this.texture
}
})() |
API_DEFINITION = {
'1.3.2': API_1_3_2('1.3.2', '1.3.1'),
'1.3.1': API_1_3_1('1.3.1'),
'1.3.0': API_1_3_0('1.3.0', '1.2.2'),
'1.2.2': API_1_2_2('1.2.2'),
'1.2.1': API_1_2_2('1.2.1', '1.2.2'),
'1.2.0': API_1_2_2('1.2.0', '1.2.2')
};
DEFAULT_API = '1.3.2'; |
import { expect } from 'chai';
import sinon from 'sinon';
global.expect = expect;
global.sinon = sinon;
|
/*global Stem, describe, it */
describe('Content Model', function () {
'use strict';
it('should provide the correct API for a full content profile', function() {
var ContentModel = new Stem.Models.Content({id: 'c:si:QkWTIFXev'});
ContentModel.url().should.equal(
Stem.config.oae.protocol + '//' +
Stem.config.oae.host +
'/api/content/c:si:QkWTIFXev'
);
});
it('should parse response from results and profile', function() {
new Stem.Models.Content({displayName: 'Name'}, {parse: true}).get('displayName').should.equal('Name');
new Stem.Models.Content({results: {displayName: 'Name'}}, {parse: true}).get('displayName').should.equal('Name');
new Stem.Models.Content({profile: {displayName: 'Name'}}, {parse: true}).get('displayName').should.equal('Name');
new Stem.Models.Content({results: {profile: {displayName: 'Name'}}}, {parse: true}).get('displayName').should.equal('Name');
});
it('should promote small picture to stand in for missing thumbnail', function() {
new Stem.Models.Content({}, {parse: true}).get('thumbnailUrl').should.equal('');
new Stem.Models.Content({thumbnailUrl: 'URL'}, {parse: true}).get('thumbnailUrl').should.equal('URL');
new Stem.Models.Content({picture: {small: 'URL'}}, {parse: true}).get('thumbnailUrl').should.equal('URL');
});
});
|
/**
* Created by tranvietthang on 12/4/16.
*/
var sessions = {};
var hash = window.location.hash;
var page = 1;
var numberOfPages = $("#number-of-pages").text();
$(document).ready(function () {
if (hash && hash.substring(0, 5) == '#page') {
page = parseInt(hash.substring(6));
}
$('#pagination').pagination({
items: numberOfPages,
itemOnPage: 8,
currentPage: page,
cssStyle: '',
prevText: '<span aria-hidden="true">«</span>',
nextText: '<span aria-hidden="true">»</span>',
onInit: function () {
// fire first page loading
getData();
},
onPageClick: function (currentPage, evt) {
// some code
page = currentPage;
window.location.hash = "#page-" + page;
console.log(page);
if (sessions[page] == null) {
getData();
} else {
setDataToTable();
}
}
});
$(".unit-search-item.link").click(function (e) {
var a = $(this);
// set text for drop-down menu
$("#category-search-drop-menu-button").html(a.attr("data-name") + " <span class=\"caret\"></span>");
if (a.attr("data-id") != null) {
// set value for form
$(".unit-id").val(a.attr("data-id"));
} else {
$(".unit_id").val(null);
}
e.preventDefault();
});
$(".form-control.category-search.input").keyup(function () {
var input = $(".form-control.category-search.input");
var searchText = input.val();
console.log("keyup with text: " + searchText);
$(".unit-search-item").each(function (index) {
var item = $(this);
if (item.text().toLowerCase().indexOf(searchText.toLowerCase()) >= 0) {
item.show();
} else {
item.hide();
}
})
});
});
var success = function (response) {
if (response.status == true) {
console.log(response);
sessions[page] = [];
response.data.forEach(function (session) {
sessions[page].push(session);
});
setDataToTable((page - 1) * 10, response.data.length);
} else {
showError(response.message)
}
};
var getData = function () {
var data = {
page: page
};
if ($("#current-role").text() == "moderator") {
data.faculty_id = $("#current-facultyID").text();
}
$.ajax({
url: "/admin/theses/api/sessions",
method: "GET",
data: data,
success: success,
error: errorHandler
});
};
var setDataToTable = function () {
$('.table.table-body').children().remove();
if (!sessions[page]) {
return;
}
sessions[page].forEach(function (session) {
$('#table-sessions').append('<tr>' +
'<td>' + session.name + '</td>' +
'<td>' + formatDate(session.from) + '</td>' +
'<td>' + formatDate(session.to) + '</td>' +
'<td>' + session.faculty.name + '</td>' +
'<td>' + '</td>' +
'<td><a href="#" onclick="notify(event, \'' + session.id + '\')">Send Notifications</a></td>' +
'</tr>'
)
});
};
var notify = function (e, sessionID) {
e.preventDefault();
bootbox.confirm({
message: "Send email for all thesis-registrable students about this session?",
buttons: {
confirm: {
label: 'Yes',
className: 'btn-success'
},
cancel: {
label: 'No',
className: 'btn-danger'
}
},
callback: function (result) {
if (result == true) {
$.ajax({
url: "/admin/theses/api/sessions/notify",
method: "POST",
data: {
session_id: sessionID
},
success: function (response) {
if (response.status == true) {
bootbox.alert({
message: "Send notifications successfully!",
size: 'small'
});
} else {
showError(response.message)
}
},
error: errorHandler
});
}
}
});
};
|
tinymce.PluginManager.add("code",function(e){function t(){e.windowManager.open({title:"Source code",body:{type:"textbox",name:"code",multiline:!0,minWidth:e.getParam("code_dialog_width",600),minHeight:e.getParam("code_dialog_height",500),value:e.getContent({source_view:!0}),spellcheck:!1},onSubmit:function(t){e.undoManager.transact(function(){e.setContent(t.data.code)}),e.nodeChanged()}})}e.addButton("code",{icon:"code",tooltip:"Source code",onclick:t}),e.addMenuItem("code",{icon:"code",text:"Source code",context:"tools",onclick:t})}); |
var path = require("path");
var webpack = require("webpack");
var exec = require("child_process").exec;
var execSync = require("child_process").execSync;
var webpack = require("webpack");
var fs = require("fs");
var FarmBotRenderer = require("./farmBotRenderer");
// WEBPACK BASE CONFIG
exec("mkdir -p public/app");
exec("echo -n > public/app/index.html");
exec("touch public/app/index.html");
exec("touch public/app/index.html");
exec("rm -rf public/dist");
exec("rm -rf public/*.eot");
var isProd = !!(global.WEBPACK_ENV === "production");
module.exports = function() {
return {
entry: {
"bundle": path.resolve(__dirname, "../src/entry.tsx"),
"front_page": "./src/front_page/index.tsx",
"verification": "./src/verification.ts",
"password_reset": "./src/password_reset/index.tsx",
"tos_update": "./src/tos_update/index.tsx"
},
output: {
path: path.resolve(__dirname, "../public"),
libraryTarget: "umd",
publicPath: "/",
devtoolLineToLine: true
},
devtool: "eval",
// Allows imports without file extensions.
resolve: {
extensions: [".js", ".ts", ".tsx", ".css", ".scss", ".json", ".hbs"]
},
// Shared loaders for prod and dev.
module: {
rules: [
{ test: /\.tsx?$/, use: "ts-loader" },
{
test: [/\.woff$/, /\.woff2$/, /\.ttf$/],
use: "url-loader"
},
{
test: [/\.eot$/, /\.svg(\?v=\d+\.\d+\.\d+)?$/],
use: "file-loader"
}
]
},
// Shared plugins for prod and dev.
plugins: [
new webpack.DefinePlugin({
"process.env.REVISION": JSON.stringify(execSync(
"git log --pretty=format:'%h%n%ad%n%f' -1").toString())
}),
new webpack.DefinePlugin({
"process.env.SHORT_REVISION": JSON.stringify(execSync(
"git log --pretty=format:'%h' -1").toString())
}),
// FarmBot Inc related.
new webpack.DefinePlugin({
"process.env.NPM_ADDON": JSON.stringify(
process.env.NPM_ADDON || false).toString()
}),
// Conditionally add "terms of service"
// Eg: Servers run by FarmBot, Inc.
new webpack.DefinePlugin({
"process.env.TOS_URL": JSON
.stringify(process.env.TOS_URL || false).toString()
}),
// Conditionally add privacy policy.
// Eg: Servers run by FarmBot, Inc.
new webpack.DefinePlugin({
"process.env.PRIV_URL": JSON
.stringify(process.env.PRIV_URL || false).toString()
}),
new FarmBotRenderer({
isProd: isProd,
path: path.resolve(__dirname, "../src/static/app_index.hbs"),
filename: "index.html",
outputPath: path.resolve(__dirname, "../public/app/")
}),
new FarmBotRenderer({
isProd: isProd,
path: path.resolve(__dirname, "../src/static/front_page.hbs"),
filename: "index.html",
outputPath: path.resolve(__dirname, "../public/"),
include: "front_page"
}),
new FarmBotRenderer({
isProd: isProd,
path: path.resolve(__dirname, "../src/static/verification.hbs"),
filename: "verify.html",
outputPath: path.resolve(__dirname, "../public/"),
include: "verification"
}),
new FarmBotRenderer({
isProd: isProd,
path: path.resolve(__dirname, "../src/static/password_reset.hbs"),
filename: "password_reset.html",
outputPath: path.resolve(__dirname, "../public/"),
include: "password_reset"
}),
new FarmBotRenderer({
isProd: isProd,
path: path.resolve(__dirname, "../src/static/tos_update.hbs"),
filename: "tos_update.html",
outputPath: path.resolve(__dirname, "../public/"),
include: "tos_update"
})
],
// Webpack Dev Server.
devServer: {
historyApiFallback: {
rewrites: [
{ from: /\/app\//, to: "/app/index.html" },
{ from: /password_reset/, to: "password_reset.html" },
]
}
}
}
} |
/**
* @license Angular v2.2.3
* (c) 2010-2016 Google, Inc. https://angular.io/
* License: MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('rxjs/operator/toPromise'), require('rxjs/Subject'), require('rxjs/Observable'), require('rxjs/observable/fromPromise')) :
typeof define === 'function' && define.amd ? define(['exports', '@angular/core', 'rxjs/operator/toPromise', 'rxjs/Subject', 'rxjs/Observable', 'rxjs/observable/fromPromise'], factory) :
(factory((global.ng = global.ng || {}, global.ng.forms = global.ng.forms || {}),global.ng.core,global.Rx.Observable.prototype,global.Rx,global.Rx,global.Rx.Observable));
}(this, function (exports,_angular_core,rxjs_operator_toPromise,rxjs_Subject,rxjs_Observable,rxjs_observable_fromPromise) { 'use strict';
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Base class for control directives.
*
* Only used internally in the forms module.
*
* @stable
*/
var AbstractControlDirective = (function () {
function AbstractControlDirective() {
}
Object.defineProperty(AbstractControlDirective.prototype, "control", {
get: function () { throw new Error('unimplemented'); },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "value", {
get: function () { return this.control ? this.control.value : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "valid", {
get: function () { return this.control ? this.control.valid : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "invalid", {
get: function () { return this.control ? this.control.invalid : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "pending", {
get: function () { return this.control ? this.control.pending : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "errors", {
get: function () { return this.control ? this.control.errors : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "pristine", {
get: function () { return this.control ? this.control.pristine : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "dirty", {
get: function () { return this.control ? this.control.dirty : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "touched", {
get: function () { return this.control ? this.control.touched : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "untouched", {
get: function () { return this.control ? this.control.untouched : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "disabled", {
get: function () { return this.control ? this.control.disabled : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "enabled", {
get: function () { return this.control ? this.control.enabled : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "statusChanges", {
get: function () { return this.control ? this.control.statusChanges : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "valueChanges", {
get: function () { return this.control ? this.control.valueChanges : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "path", {
get: function () { return null; },
enumerable: true,
configurable: true
});
AbstractControlDirective.prototype.reset = function (value) {
if (value === void 0) { value = undefined; }
if (this.control)
this.control.reset(value);
};
AbstractControlDirective.prototype.hasError = function (errorCode, path) {
if (path === void 0) { path = null; }
return this.control ? this.control.hasError(errorCode, path) : false;
};
AbstractControlDirective.prototype.getError = function (errorCode, path) {
if (path === void 0) { path = null; }
return this.control ? this.control.getError(errorCode, path) : null;
};
return AbstractControlDirective;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __extends$1 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* A directive that contains multiple {@link NgControl}s.
*
* Only used by the forms module.
*
* @stable
*/
var ControlContainer = (function (_super) {
__extends$1(ControlContainer, _super);
function ControlContainer() {
_super.apply(this, arguments);
}
Object.defineProperty(ControlContainer.prototype, "formDirective", {
/**
* Get the form to which this container belongs.
*/
get: function () { return null; },
enumerable: true,
configurable: true
});
Object.defineProperty(ControlContainer.prototype, "path", {
/**
* Get the path to this container.
*/
get: function () { return null; },
enumerable: true,
configurable: true
});
return ControlContainer;
}(AbstractControlDirective));
function isPresent(obj) {
return obj != null;
}
function isBlank(obj) {
return obj == null;
}
// JS has NaN !== NaN
function looseIdentical(a, b) {
return a === b || typeof a === 'number' && typeof b === 'number' && isNaN(a) && isNaN(b);
}
function isJsObject(o) {
return o !== null && (typeof o === 'function' || typeof o === 'object');
}
function isPrimitive(obj) {
return !isJsObject(obj);
}
/**
* Wraps Javascript Objects
*/
var StringMapWrapper = (function () {
function StringMapWrapper() {
}
StringMapWrapper.merge = function (m1, m2) {
var m = {};
for (var _i = 0, _a = Object.keys(m1); _i < _a.length; _i++) {
var k = _a[_i];
m[k] = m1[k];
}
for (var _b = 0, _c = Object.keys(m2); _b < _c.length; _b++) {
var k = _c[_b];
m[k] = m2[k];
}
return m;
};
StringMapWrapper.equals = function (m1, m2) {
var k1 = Object.keys(m1);
var k2 = Object.keys(m2);
if (k1.length != k2.length) {
return false;
}
for (var i = 0; i < k1.length; i++) {
var key = k1[i];
if (m1[key] !== m2[key]) {
return false;
}
}
return true;
};
return StringMapWrapper;
}());
var ListWrapper = (function () {
function ListWrapper() {
}
ListWrapper.removeAll = function (list, items) {
for (var i = 0; i < items.length; ++i) {
var index = list.indexOf(items[i]);
if (index > -1) {
list.splice(index, 1);
}
}
};
ListWrapper.remove = function (list, el) {
var index = list.indexOf(el);
if (index > -1) {
list.splice(index, 1);
return true;
}
return false;
};
ListWrapper.equals = function (a, b) {
if (a.length != b.length)
return false;
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i])
return false;
}
return true;
};
ListWrapper.flatten = function (list) {
return list.reduce(function (flat, item) {
var flatItem = Array.isArray(item) ? ListWrapper.flatten(item) : item;
return flat.concat(flatItem);
}, []);
};
return ListWrapper;
}());
var isPromise = _angular_core.__core_private__.isPromise;
function isEmptyInputValue(value) {
return value == null || typeof value === 'string' && value.length === 0;
}
/**
* Providers for validators to be used for {@link FormControl}s in a form.
*
* Provide this using `multi: true` to add validators.
*
* ### Example
*
* {@example core/forms/ts/ng_validators/ng_validators.ts region='ng_validators'}
* @stable
*/
var NG_VALIDATORS = new _angular_core.OpaqueToken('NgValidators');
/**
* Providers for asynchronous validators to be used for {@link FormControl}s
* in a form.
*
* Provide this using `multi: true` to add validators.
*
* See {@link NG_VALIDATORS} for more details.
*
* @stable
*/
var NG_ASYNC_VALIDATORS = new _angular_core.OpaqueToken('NgAsyncValidators');
/**
* Provides a set of validators used by form controls.
*
* A validator is a function that processes a {@link FormControl} or collection of
* controls and returns a map of errors. A null map means that validation has passed.
*
* ### Example
*
* ```typescript
* var loginControl = new FormControl("", Validators.required)
* ```
*
* @stable
*/
var Validators = (function () {
function Validators() {
}
/**
* Validator that requires controls to have a non-empty value.
*/
Validators.required = function (control) {
return isEmptyInputValue(control.value) ? { 'required': true } : null;
};
/**
* Validator that requires controls to have a value of a minimum length.
*/
Validators.minLength = function (minLength) {
return function (control) {
if (isEmptyInputValue(control.value)) {
return null; // don't validate empty values to allow optional controls
}
var length = typeof control.value === 'string' ? control.value.length : 0;
return length < minLength ?
{ 'minlength': { 'requiredLength': minLength, 'actualLength': length } } :
null;
};
};
/**
* Validator that requires controls to have a value of a maximum length.
*/
Validators.maxLength = function (maxLength) {
return function (control) {
var length = typeof control.value === 'string' ? control.value.length : 0;
return length > maxLength ?
{ 'maxlength': { 'requiredLength': maxLength, 'actualLength': length } } :
null;
};
};
/**
* Validator that requires a control to match a regex to its value.
*/
Validators.pattern = function (pattern) {
if (!pattern)
return Validators.nullValidator;
var regex;
var regexStr;
if (typeof pattern === 'string') {
regexStr = "^" + pattern + "$";
regex = new RegExp(regexStr);
}
else {
regexStr = pattern.toString();
regex = pattern;
}
return function (control) {
if (isEmptyInputValue(control.value)) {
return null; // don't validate empty values to allow optional controls
}
var value = control.value;
return regex.test(value) ? null :
{ 'pattern': { 'requiredPattern': regexStr, 'actualValue': value } };
};
};
/**
* No-op validator.
*/
Validators.nullValidator = function (c) { return null; };
/**
* Compose multiple validators into a single function that returns the union
* of the individual error maps.
*/
Validators.compose = function (validators) {
if (!validators)
return null;
var presentValidators = validators.filter(isPresent);
if (presentValidators.length == 0)
return null;
return function (control) {
return _mergeErrors(_executeValidators(control, presentValidators));
};
};
Validators.composeAsync = function (validators) {
if (!validators)
return null;
var presentValidators = validators.filter(isPresent);
if (presentValidators.length == 0)
return null;
return function (control) {
var promises = _executeAsyncValidators(control, presentValidators).map(_convertToPromise);
return Promise.all(promises).then(_mergeErrors);
};
};
return Validators;
}());
function _convertToPromise(obj) {
return isPromise(obj) ? obj : rxjs_operator_toPromise.toPromise.call(obj);
}
function _executeValidators(control, validators) {
return validators.map(function (v) { return v(control); });
}
function _executeAsyncValidators(control, validators) {
return validators.map(function (v) { return v(control); });
}
function _mergeErrors(arrayOfErrors) {
var res = arrayOfErrors.reduce(function (res, errors) {
return isPresent(errors) ? StringMapWrapper.merge(res, errors) : res;
}, {});
return Object.keys(res).length === 0 ? null : res;
}
/**
* Used to provide a {@link ControlValueAccessor} for form controls.
*
* See {@link DefaultValueAccessor} for how to implement one.
* @stable
*/
var NG_VALUE_ACCESSOR = new _angular_core.OpaqueToken('NgValueAccessor');
var CHECKBOX_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: _angular_core.forwardRef(function () { return CheckboxControlValueAccessor; }),
multi: true,
};
/**
* The accessor for writing a value and listening to changes on a checkbox input element.
*
* ### Example
* ```
* <input type="checkbox" name="rememberLogin" ngModel>
* ```
*
* @stable
*/
var CheckboxControlValueAccessor = (function () {
function CheckboxControlValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this.onChange = function (_) { };
this.onTouched = function () { };
}
CheckboxControlValueAccessor.prototype.writeValue = function (value) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', value);
};
CheckboxControlValueAccessor.prototype.registerOnChange = function (fn) { this.onChange = fn; };
CheckboxControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
CheckboxControlValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
CheckboxControlValueAccessor.decorators = [
{ type: _angular_core.Directive, args: [{
selector: 'input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]',
host: { '(change)': 'onChange($event.target.checked)', '(blur)': 'onTouched()' },
providers: [CHECKBOX_VALUE_ACCESSOR]
},] },
];
/** @nocollapse */
CheckboxControlValueAccessor.ctorParameters = [
{ type: _angular_core.Renderer, },
{ type: _angular_core.ElementRef, },
];
return CheckboxControlValueAccessor;
}());
var DEFAULT_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: _angular_core.forwardRef(function () { return DefaultValueAccessor; }),
multi: true
};
/**
* The default accessor for writing a value and listening to changes that is used by the
* {@link NgModel}, {@link FormControlDirective}, and {@link FormControlName} directives.
*
* ### Example
* ```
* <input type="text" name="searchQuery" ngModel>
* ```
*
* @stable
*/
var DefaultValueAccessor = (function () {
function DefaultValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this.onChange = function (_) { };
this.onTouched = function () { };
}
DefaultValueAccessor.prototype.writeValue = function (value) {
var normalizedValue = value == null ? '' : value;
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue);
};
DefaultValueAccessor.prototype.registerOnChange = function (fn) { this.onChange = fn; };
DefaultValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
DefaultValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
DefaultValueAccessor.decorators = [
{ type: _angular_core.Directive, args: [{
selector: 'input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]',
// TODO: vsavkin replace the above selector with the one below it once
// https://github.com/angular/angular/issues/3011 is implemented
// selector: '[ngControl],[ngModel],[ngFormControl]',
host: { '(input)': 'onChange($event.target.value)', '(blur)': 'onTouched()' },
providers: [DEFAULT_VALUE_ACCESSOR]
},] },
];
/** @nocollapse */
DefaultValueAccessor.ctorParameters = [
{ type: _angular_core.Renderer, },
{ type: _angular_core.ElementRef, },
];
return DefaultValueAccessor;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function normalizeValidator(validator) {
if (validator.validate) {
return function (c) { return validator.validate(c); };
}
else {
return validator;
}
}
function normalizeAsyncValidator(validator) {
if (validator.validate) {
return function (c) { return validator.validate(c); };
}
else {
return validator;
}
}
var NUMBER_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: _angular_core.forwardRef(function () { return NumberValueAccessor; }),
multi: true
};
/**
* The accessor for writing a number value and listening to changes that is used by the
* {@link NgModel}, {@link FormControlDirective}, and {@link FormControlName} directives.
*
* ### Example
* ```
* <input type="number" [(ngModel)]="age">
* ```
*/
var NumberValueAccessor = (function () {
function NumberValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this.onChange = function (_) { };
this.onTouched = function () { };
}
NumberValueAccessor.prototype.writeValue = function (value) {
// The value needs to be normalized for IE9, otherwise it is set to 'null' when null
var normalizedValue = value == null ? '' : value;
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue);
};
NumberValueAccessor.prototype.registerOnChange = function (fn) {
this.onChange = function (value) { fn(value == '' ? null : parseFloat(value)); };
};
NumberValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
NumberValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
NumberValueAccessor.decorators = [
{ type: _angular_core.Directive, args: [{
selector: 'input[type=number][formControlName],input[type=number][formControl],input[type=number][ngModel]',
host: {
'(change)': 'onChange($event.target.value)',
'(input)': 'onChange($event.target.value)',
'(blur)': 'onTouched()'
},
providers: [NUMBER_VALUE_ACCESSOR]
},] },
];
/** @nocollapse */
NumberValueAccessor.ctorParameters = [
{ type: _angular_core.Renderer, },
{ type: _angular_core.ElementRef, },
];
return NumberValueAccessor;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __extends$2 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
function unimplemented() {
throw new Error('unimplemented');
}
/**
* A base class that all control directive extend.
* It binds a {@link FormControl} object to a DOM element.
*
* Used internally by Angular forms.
*
* @stable
*/
var NgControl = (function (_super) {
__extends$2(NgControl, _super);
function NgControl() {
_super.apply(this, arguments);
/** @internal */
this._parent = null;
this.name = null;
this.valueAccessor = null;
/** @internal */
this._rawValidators = [];
/** @internal */
this._rawAsyncValidators = [];
}
Object.defineProperty(NgControl.prototype, "validator", {
get: function () { return unimplemented(); },
enumerable: true,
configurable: true
});
Object.defineProperty(NgControl.prototype, "asyncValidator", {
get: function () { return unimplemented(); },
enumerable: true,
configurable: true
});
return NgControl;
}(AbstractControlDirective));
var RADIO_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: _angular_core.forwardRef(function () { return RadioControlValueAccessor; }),
multi: true
};
/**
* Internal class used by Angular to uncheck radio buttons with the matching name.
*/
var RadioControlRegistry = (function () {
function RadioControlRegistry() {
this._accessors = [];
}
RadioControlRegistry.prototype.add = function (control, accessor) {
this._accessors.push([control, accessor]);
};
RadioControlRegistry.prototype.remove = function (accessor) {
for (var i = this._accessors.length - 1; i >= 0; --i) {
if (this._accessors[i][1] === accessor) {
this._accessors.splice(i, 1);
return;
}
}
};
RadioControlRegistry.prototype.select = function (accessor) {
var _this = this;
this._accessors.forEach(function (c) {
if (_this._isSameGroup(c, accessor) && c[1] !== accessor) {
c[1].fireUncheck(accessor.value);
}
});
};
RadioControlRegistry.prototype._isSameGroup = function (controlPair, accessor) {
if (!controlPair[0].control)
return false;
return controlPair[0]._parent === accessor._control._parent &&
controlPair[1].name === accessor.name;
};
RadioControlRegistry.decorators = [
{ type: _angular_core.Injectable },
];
/** @nocollapse */
RadioControlRegistry.ctorParameters = [];
return RadioControlRegistry;
}());
/**
* @whatItDoes Writes radio control values and listens to radio control changes.
*
* Used by {@link NgModel}, {@link FormControlDirective}, and {@link FormControlName}
* to keep the view synced with the {@link FormControl} model.
*
* @howToUse
*
* If you have imported the {@link FormsModule} or the {@link ReactiveFormsModule}, this
* value accessor will be active on any radio control that has a form directive. You do
* **not** need to add a special selector to activate it.
*
* ### How to use radio buttons with form directives
*
* To use radio buttons in a template-driven form, you'll want to ensure that radio buttons
* in the same group have the same `name` attribute. Radio buttons with different `name`
* attributes do not affect each other.
*
* {@example forms/ts/radioButtons/radio_button_example.ts region='TemplateDriven'}
*
* When using radio buttons in a reactive form, radio buttons in the same group should have the
* same `formControlName`. You can also add a `name` attribute, but it's optional.
*
* {@example forms/ts/reactiveRadioButtons/reactive_radio_button_example.ts region='Reactive'}
*
* * **npm package**: `@angular/forms`
*
* @stable
*/
var RadioControlValueAccessor = (function () {
function RadioControlValueAccessor(_renderer, _elementRef, _registry, _injector) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this._registry = _registry;
this._injector = _injector;
this.onChange = function () { };
this.onTouched = function () { };
}
RadioControlValueAccessor.prototype.ngOnInit = function () {
this._control = this._injector.get(NgControl);
this._checkName();
this._registry.add(this._control, this);
};
RadioControlValueAccessor.prototype.ngOnDestroy = function () { this._registry.remove(this); };
RadioControlValueAccessor.prototype.writeValue = function (value) {
this._state = value === this.value;
this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', this._state);
};
RadioControlValueAccessor.prototype.registerOnChange = function (fn) {
var _this = this;
this._fn = fn;
this.onChange = function () {
fn(_this.value);
_this._registry.select(_this);
};
};
RadioControlValueAccessor.prototype.fireUncheck = function (value) { this.writeValue(value); };
RadioControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
RadioControlValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
RadioControlValueAccessor.prototype._checkName = function () {
if (this.name && this.formControlName && this.name !== this.formControlName) {
this._throwNameError();
}
if (!this.name && this.formControlName)
this.name = this.formControlName;
};
RadioControlValueAccessor.prototype._throwNameError = function () {
throw new Error("\n If you define both a name and a formControlName attribute on your radio button, their values\n must match. Ex: <input type=\"radio\" formControlName=\"food\" name=\"food\">\n ");
};
RadioControlValueAccessor.decorators = [
{ type: _angular_core.Directive, args: [{
selector: 'input[type=radio][formControlName],input[type=radio][formControl],input[type=radio][ngModel]',
host: { '(change)': 'onChange()', '(blur)': 'onTouched()' },
providers: [RADIO_VALUE_ACCESSOR]
},] },
];
/** @nocollapse */
RadioControlValueAccessor.ctorParameters = [
{ type: _angular_core.Renderer, },
{ type: _angular_core.ElementRef, },
{ type: RadioControlRegistry, },
{ type: _angular_core.Injector, },
];
RadioControlValueAccessor.propDecorators = {
'name': [{ type: _angular_core.Input },],
'formControlName': [{ type: _angular_core.Input },],
'value': [{ type: _angular_core.Input },],
};
return RadioControlValueAccessor;
}());
var RANGE_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: _angular_core.forwardRef(function () { return RangeValueAccessor; }),
multi: true
};
/**
* The accessor for writing a range value and listening to changes that is used by the
* {@link NgModel}, {@link FormControlDirective}, and {@link FormControlName} directives.
*
* ### Example
* ```
* <input type="range" [(ngModel)]="age" >
* ```
*/
var RangeValueAccessor = (function () {
function RangeValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this.onChange = function (_) { };
this.onTouched = function () { };
}
RangeValueAccessor.prototype.writeValue = function (value) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', parseFloat(value));
};
RangeValueAccessor.prototype.registerOnChange = function (fn) {
this.onChange = function (value) { fn(value == '' ? null : parseFloat(value)); };
};
RangeValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
RangeValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
RangeValueAccessor.decorators = [
{ type: _angular_core.Directive, args: [{
selector: 'input[type=range][formControlName],input[type=range][formControl],input[type=range][ngModel]',
host: {
'(change)': 'onChange($event.target.value)',
'(input)': 'onChange($event.target.value)',
'(blur)': 'onTouched()'
},
providers: [RANGE_VALUE_ACCESSOR]
},] },
];
/** @nocollapse */
RangeValueAccessor.ctorParameters = [
{ type: _angular_core.Renderer, },
{ type: _angular_core.ElementRef, },
];
return RangeValueAccessor;
}());
var SELECT_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: _angular_core.forwardRef(function () { return SelectControlValueAccessor; }),
multi: true
};
function _buildValueString(id, value) {
if (id == null)
return "" + value;
if (!isPrimitive(value))
value = 'Object';
return (id + ": " + value).slice(0, 50);
}
function _extractId(valueString) {
return valueString.split(':')[0];
}
/**
* @whatItDoes Writes values and listens to changes on a select element.
*
* Used by {@link NgModel}, {@link FormControlDirective}, and {@link FormControlName}
* to keep the view synced with the {@link FormControl} model.
*
* @howToUse
*
* If you have imported the {@link FormsModule} or the {@link ReactiveFormsModule}, this
* value accessor will be active on any select control that has a form directive. You do
* **not** need to add a special selector to activate it.
*
* ### How to use select controls with form directives
*
* To use a select in a template-driven form, simply add an `ngModel` and a `name`
* attribute to the main `<select>` tag.
*
* If your option values are simple strings, you can bind to the normal `value` property
* on the option. If your option values happen to be objects (and you'd like to save the
* selection in your form as an object), use `ngValue` instead:
*
* {@example forms/ts/selectControl/select_control_example.ts region='Component'}
*
* In reactive forms, you'll also want to add your form directive (`formControlName` or
* `formControl`) on the main `<select>` tag. Like in the former example, you have the
* choice of binding to the `value` or `ngValue` property on the select's options.
*
* {@example forms/ts/reactiveSelectControl/reactive_select_control_example.ts region='Component'}
*
* Note: We listen to the 'change' event because 'input' events aren't fired
* for selects in Firefox and IE:
* https://bugzilla.mozilla.org/show_bug.cgi?id=1024350
* https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/4660045/
*
* * **npm package**: `@angular/forms`
*
* @stable
*/
var SelectControlValueAccessor = (function () {
function SelectControlValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
/** @internal */
this._optionMap = new Map();
/** @internal */
this._idCounter = 0;
this.onChange = function (_) { };
this.onTouched = function () { };
}
SelectControlValueAccessor.prototype.writeValue = function (value) {
this.value = value;
var valueString = _buildValueString(this._getOptionId(value), value);
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', valueString);
};
SelectControlValueAccessor.prototype.registerOnChange = function (fn) {
var _this = this;
this.onChange = function (valueString) {
_this.value = valueString;
fn(_this._getOptionValue(valueString));
};
};
SelectControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
SelectControlValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
/** @internal */
SelectControlValueAccessor.prototype._registerOption = function () { return (this._idCounter++).toString(); };
/** @internal */
SelectControlValueAccessor.prototype._getOptionId = function (value) {
for (var _i = 0, _a = Array.from(this._optionMap.keys()); _i < _a.length; _i++) {
var id = _a[_i];
if (looseIdentical(this._optionMap.get(id), value))
return id;
}
return null;
};
/** @internal */
SelectControlValueAccessor.prototype._getOptionValue = function (valueString) {
var id = _extractId(valueString);
return this._optionMap.has(id) ? this._optionMap.get(id) : valueString;
};
SelectControlValueAccessor.decorators = [
{ type: _angular_core.Directive, args: [{
selector: 'select:not([multiple])[formControlName],select:not([multiple])[formControl],select:not([multiple])[ngModel]',
host: { '(change)': 'onChange($event.target.value)', '(blur)': 'onTouched()' },
providers: [SELECT_VALUE_ACCESSOR]
},] },
];
/** @nocollapse */
SelectControlValueAccessor.ctorParameters = [
{ type: _angular_core.Renderer, },
{ type: _angular_core.ElementRef, },
];
return SelectControlValueAccessor;
}());
/**
* @whatItDoes Marks `<option>` as dynamic, so Angular can be notified when options change.
*
* @howToUse
*
* See docs for {@link SelectControlValueAccessor} for usage examples.
*
* @stable
*/
var NgSelectOption = (function () {
function NgSelectOption(_element, _renderer, _select) {
this._element = _element;
this._renderer = _renderer;
this._select = _select;
if (this._select)
this.id = this._select._registerOption();
}
Object.defineProperty(NgSelectOption.prototype, "ngValue", {
set: function (value) {
if (this._select == null)
return;
this._select._optionMap.set(this.id, value);
this._setElementValue(_buildValueString(this.id, value));
this._select.writeValue(this._select.value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(NgSelectOption.prototype, "value", {
set: function (value) {
this._setElementValue(value);
if (this._select)
this._select.writeValue(this._select.value);
},
enumerable: true,
configurable: true
});
/** @internal */
NgSelectOption.prototype._setElementValue = function (value) {
this._renderer.setElementProperty(this._element.nativeElement, 'value', value);
};
NgSelectOption.prototype.ngOnDestroy = function () {
if (this._select) {
this._select._optionMap.delete(this.id);
this._select.writeValue(this._select.value);
}
};
NgSelectOption.decorators = [
{ type: _angular_core.Directive, args: [{ selector: 'option' },] },
];
/** @nocollapse */
NgSelectOption.ctorParameters = [
{ type: _angular_core.ElementRef, },
{ type: _angular_core.Renderer, },
{ type: SelectControlValueAccessor, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Host },] },
];
NgSelectOption.propDecorators = {
'ngValue': [{ type: _angular_core.Input, args: ['ngValue',] },],
'value': [{ type: _angular_core.Input, args: ['value',] },],
};
return NgSelectOption;
}());
var SELECT_MULTIPLE_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: _angular_core.forwardRef(function () { return SelectMultipleControlValueAccessor; }),
multi: true
};
function _buildValueString$1(id, value) {
if (id == null)
return "" + value;
if (typeof value === 'string')
value = "'" + value + "'";
if (!isPrimitive(value))
value = 'Object';
return (id + ": " + value).slice(0, 50);
}
function _extractId$1(valueString) {
return valueString.split(':')[0];
}
/**
* The accessor for writing a value and listening to changes on a select element.
*
* @stable
*/
var SelectMultipleControlValueAccessor = (function () {
function SelectMultipleControlValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
/** @internal */
this._optionMap = new Map();
/** @internal */
this._idCounter = 0;
this.onChange = function (_) { };
this.onTouched = function () { };
}
SelectMultipleControlValueAccessor.prototype.writeValue = function (value) {
var _this = this;
this.value = value;
if (value == null)
return;
var values = value;
// convert values to ids
var ids = values.map(function (v) { return _this._getOptionId(v); });
this._optionMap.forEach(function (opt, o) { opt._setSelected(ids.indexOf(o.toString()) > -1); });
};
SelectMultipleControlValueAccessor.prototype.registerOnChange = function (fn) {
var _this = this;
this.onChange = function (_) {
var selected = [];
if (_.hasOwnProperty('selectedOptions')) {
var options = _.selectedOptions;
for (var i = 0; i < options.length; i++) {
var opt = options.item(i);
var val = _this._getOptionValue(opt.value);
selected.push(val);
}
}
else {
var options = _.options;
for (var i = 0; i < options.length; i++) {
var opt = options.item(i);
if (opt.selected) {
var val = _this._getOptionValue(opt.value);
selected.push(val);
}
}
}
fn(selected);
};
};
SelectMultipleControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
SelectMultipleControlValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
/** @internal */
SelectMultipleControlValueAccessor.prototype._registerOption = function (value) {
var id = (this._idCounter++).toString();
this._optionMap.set(id, value);
return id;
};
/** @internal */
SelectMultipleControlValueAccessor.prototype._getOptionId = function (value) {
for (var _i = 0, _a = Array.from(this._optionMap.keys()); _i < _a.length; _i++) {
var id = _a[_i];
if (looseIdentical(this._optionMap.get(id)._value, value))
return id;
}
return null;
};
/** @internal */
SelectMultipleControlValueAccessor.prototype._getOptionValue = function (valueString) {
var id = _extractId$1(valueString);
return this._optionMap.has(id) ? this._optionMap.get(id)._value : valueString;
};
SelectMultipleControlValueAccessor.decorators = [
{ type: _angular_core.Directive, args: [{
selector: 'select[multiple][formControlName],select[multiple][formControl],select[multiple][ngModel]',
host: { '(change)': 'onChange($event.target)', '(blur)': 'onTouched()' },
providers: [SELECT_MULTIPLE_VALUE_ACCESSOR]
},] },
];
/** @nocollapse */
SelectMultipleControlValueAccessor.ctorParameters = [
{ type: _angular_core.Renderer, },
{ type: _angular_core.ElementRef, },
];
return SelectMultipleControlValueAccessor;
}());
/**
* Marks `<option>` as dynamic, so Angular can be notified when options change.
*
* ### Example
*
* ```
* <select multiple name="city" ngModel>
* <option *ngFor="let c of cities" [value]="c"></option>
* </select>
* ```
*/
var NgSelectMultipleOption = (function () {
function NgSelectMultipleOption(_element, _renderer, _select) {
this._element = _element;
this._renderer = _renderer;
this._select = _select;
if (this._select) {
this.id = this._select._registerOption(this);
}
}
Object.defineProperty(NgSelectMultipleOption.prototype, "ngValue", {
set: function (value) {
if (this._select == null)
return;
this._value = value;
this._setElementValue(_buildValueString$1(this.id, value));
this._select.writeValue(this._select.value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(NgSelectMultipleOption.prototype, "value", {
set: function (value) {
if (this._select) {
this._value = value;
this._setElementValue(_buildValueString$1(this.id, value));
this._select.writeValue(this._select.value);
}
else {
this._setElementValue(value);
}
},
enumerable: true,
configurable: true
});
/** @internal */
NgSelectMultipleOption.prototype._setElementValue = function (value) {
this._renderer.setElementProperty(this._element.nativeElement, 'value', value);
};
/** @internal */
NgSelectMultipleOption.prototype._setSelected = function (selected) {
this._renderer.setElementProperty(this._element.nativeElement, 'selected', selected);
};
NgSelectMultipleOption.prototype.ngOnDestroy = function () {
if (this._select) {
this._select._optionMap.delete(this.id);
this._select.writeValue(this._select.value);
}
};
NgSelectMultipleOption.decorators = [
{ type: _angular_core.Directive, args: [{ selector: 'option' },] },
];
/** @nocollapse */
NgSelectMultipleOption.ctorParameters = [
{ type: _angular_core.ElementRef, },
{ type: _angular_core.Renderer, },
{ type: SelectMultipleControlValueAccessor, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Host },] },
];
NgSelectMultipleOption.propDecorators = {
'ngValue': [{ type: _angular_core.Input, args: ['ngValue',] },],
'value': [{ type: _angular_core.Input, args: ['value',] },],
};
return NgSelectMultipleOption;
}());
function controlPath(name, parent) {
return parent.path.concat([name]);
}
function setUpControl(control, dir) {
if (!control)
_throwError(dir, 'Cannot find control with');
if (!dir.valueAccessor)
_throwError(dir, 'No value accessor for form control with');
control.validator = Validators.compose([control.validator, dir.validator]);
control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]);
dir.valueAccessor.writeValue(control.value);
// view -> model
dir.valueAccessor.registerOnChange(function (newValue) {
dir.viewToModelUpdate(newValue);
control.markAsDirty();
control.setValue(newValue, { emitModelToViewChange: false });
});
// touched
dir.valueAccessor.registerOnTouched(function () { return control.markAsTouched(); });
control.registerOnChange(function (newValue, emitModelEvent) {
// control -> view
dir.valueAccessor.writeValue(newValue);
// control -> ngModel
if (emitModelEvent)
dir.viewToModelUpdate(newValue);
});
if (dir.valueAccessor.setDisabledState) {
control.registerOnDisabledChange(function (isDisabled) { dir.valueAccessor.setDisabledState(isDisabled); });
}
// re-run validation when validator binding changes, e.g. minlength=3 -> minlength=4
dir._rawValidators.forEach(function (validator) {
if (validator.registerOnValidatorChange)
validator.registerOnValidatorChange(function () { return control.updateValueAndValidity(); });
});
dir._rawAsyncValidators.forEach(function (validator) {
if (validator.registerOnValidatorChange)
validator.registerOnValidatorChange(function () { return control.updateValueAndValidity(); });
});
}
function cleanUpControl(control, dir) {
dir.valueAccessor.registerOnChange(function () { return _noControlError(dir); });
dir.valueAccessor.registerOnTouched(function () { return _noControlError(dir); });
dir._rawValidators.forEach(function (validator) {
if (validator.registerOnValidatorChange) {
validator.registerOnValidatorChange(null);
}
});
dir._rawAsyncValidators.forEach(function (validator) {
if (validator.registerOnValidatorChange) {
validator.registerOnValidatorChange(null);
}
});
if (control)
control._clearChangeFns();
}
function setUpFormContainer(control, dir) {
if (isBlank(control))
_throwError(dir, 'Cannot find control with');
control.validator = Validators.compose([control.validator, dir.validator]);
control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]);
}
function _noControlError(dir) {
return _throwError(dir, 'There is no FormControl instance attached to form control element with');
}
function _throwError(dir, message) {
var messageEnd;
if (dir.path.length > 1) {
messageEnd = "path: '" + dir.path.join(' -> ') + "'";
}
else if (dir.path[0]) {
messageEnd = "name: '" + dir.path + "'";
}
else {
messageEnd = 'unspecified name attribute';
}
throw new Error(message + " " + messageEnd);
}
function composeValidators(validators) {
return isPresent(validators) ? Validators.compose(validators.map(normalizeValidator)) : null;
}
function composeAsyncValidators(validators) {
return isPresent(validators) ? Validators.composeAsync(validators.map(normalizeAsyncValidator)) :
null;
}
function isPropertyUpdated(changes, viewModel) {
if (!changes.hasOwnProperty('model'))
return false;
var change = changes['model'];
if (change.isFirstChange())
return true;
return !looseIdentical(viewModel, change.currentValue);
}
var BUILTIN_ACCESSORS = [
CheckboxControlValueAccessor,
RangeValueAccessor,
NumberValueAccessor,
SelectControlValueAccessor,
SelectMultipleControlValueAccessor,
RadioControlValueAccessor,
];
function isBuiltInAccessor(valueAccessor) {
return BUILTIN_ACCESSORS.some(function (a) { return valueAccessor.constructor === a; });
}
// TODO: vsavkin remove it once https://github.com/angular/angular/issues/3011 is implemented
function selectValueAccessor(dir, valueAccessors) {
if (!valueAccessors)
return null;
var defaultAccessor;
var builtinAccessor;
var customAccessor;
valueAccessors.forEach(function (v) {
if (v.constructor === DefaultValueAccessor) {
defaultAccessor = v;
}
else if (isBuiltInAccessor(v)) {
if (builtinAccessor)
_throwError(dir, 'More than one built-in value accessor matches form control with');
builtinAccessor = v;
}
else {
if (customAccessor)
_throwError(dir, 'More than one custom value accessor matches form control with');
customAccessor = v;
}
});
if (customAccessor)
return customAccessor;
if (builtinAccessor)
return builtinAccessor;
if (defaultAccessor)
return defaultAccessor;
_throwError(dir, 'No valid value accessor for form control with');
return null;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* This is a base class for code shared between {@link NgModelGroup} and {@link FormGroupName}.
*
* @stable
*/
var AbstractFormGroupDirective = (function (_super) {
__extends(AbstractFormGroupDirective, _super);
function AbstractFormGroupDirective() {
_super.apply(this, arguments);
}
AbstractFormGroupDirective.prototype.ngOnInit = function () {
this._checkParentType();
this.formDirective.addFormGroup(this);
};
AbstractFormGroupDirective.prototype.ngOnDestroy = function () {
if (this.formDirective) {
this.formDirective.removeFormGroup(this);
}
};
Object.defineProperty(AbstractFormGroupDirective.prototype, "control", {
/**
* Get the {@link FormGroup} backing this binding.
*/
get: function () { return this.formDirective.getFormGroup(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractFormGroupDirective.prototype, "path", {
/**
* Get the path to this control group.
*/
get: function () { return controlPath(this.name, this._parent); },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractFormGroupDirective.prototype, "formDirective", {
/**
* Get the {@link Form} to which this group belongs.
*/
get: function () { return this._parent ? this._parent.formDirective : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractFormGroupDirective.prototype, "validator", {
get: function () { return composeValidators(this._validators); },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractFormGroupDirective.prototype, "asyncValidator", {
get: function () { return composeAsyncValidators(this._asyncValidators); },
enumerable: true,
configurable: true
});
/** @internal */
AbstractFormGroupDirective.prototype._checkParentType = function () { };
return AbstractFormGroupDirective;
}(ControlContainer));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __extends$3 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var AbstractControlStatus = (function () {
function AbstractControlStatus(cd) {
this._cd = cd;
}
Object.defineProperty(AbstractControlStatus.prototype, "ngClassUntouched", {
get: function () { return this._cd.control ? this._cd.control.untouched : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassTouched", {
get: function () { return this._cd.control ? this._cd.control.touched : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassPristine", {
get: function () { return this._cd.control ? this._cd.control.pristine : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassDirty", {
get: function () { return this._cd.control ? this._cd.control.dirty : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassValid", {
get: function () { return this._cd.control ? this._cd.control.valid : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassInvalid", {
get: function () { return this._cd.control ? this._cd.control.invalid : false; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassPending", {
get: function () { return this._cd.control ? this._cd.control.pending : false; },
enumerable: true,
configurable: true
});
return AbstractControlStatus;
}());
var ngControlStatusHost = {
'[class.ng-untouched]': 'ngClassUntouched',
'[class.ng-touched]': 'ngClassTouched',
'[class.ng-pristine]': 'ngClassPristine',
'[class.ng-dirty]': 'ngClassDirty',
'[class.ng-valid]': 'ngClassValid',
'[class.ng-invalid]': 'ngClassInvalid',
'[class.ng-pending]': 'ngClassPending',
};
/**
* Directive automatically applied to Angular form controls that sets CSS classes
* based on control status (valid/invalid/dirty/etc).
*
* @stable
*/
var NgControlStatus = (function (_super) {
__extends$3(NgControlStatus, _super);
function NgControlStatus(cd) {
_super.call(this, cd);
}
NgControlStatus.decorators = [
{ type: _angular_core.Directive, args: [{ selector: '[formControlName],[ngModel],[formControl]', host: ngControlStatusHost },] },
];
/** @nocollapse */
NgControlStatus.ctorParameters = [
{ type: NgControl, decorators: [{ type: _angular_core.Self },] },
];
return NgControlStatus;
}(AbstractControlStatus));
/**
* Directive automatically applied to Angular form groups that sets CSS classes
* based on control status (valid/invalid/dirty/etc).
*
* @stable
*/
var NgControlStatusGroup = (function (_super) {
__extends$3(NgControlStatusGroup, _super);
function NgControlStatusGroup(cd) {
_super.call(this, cd);
}
NgControlStatusGroup.decorators = [
{ type: _angular_core.Directive, args: [{
selector: '[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]',
host: ngControlStatusHost
},] },
];
/** @nocollapse */
NgControlStatusGroup.ctorParameters = [
{ type: ControlContainer, decorators: [{ type: _angular_core.Self },] },
];
return NgControlStatusGroup;
}(AbstractControlStatus));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __extends$5 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* Use by directives and components to emit custom Events.
*
* ### Examples
*
* In the following example, `Zippy` alternatively emits `open` and `close` events when its
* title gets clicked:
*
* ```
* @Component({
* selector: 'zippy',
* template: `
* <div class="zippy">
* <div (click)="toggle()">Toggle</div>
* <div [hidden]="!visible">
* <ng-content></ng-content>
* </div>
* </div>`})
* export class Zippy {
* visible: boolean = true;
* @Output() open: EventEmitter<any> = new EventEmitter();
* @Output() close: EventEmitter<any> = new EventEmitter();
*
* toggle() {
* this.visible = !this.visible;
* if (this.visible) {
* this.open.emit(null);
* } else {
* this.close.emit(null);
* }
* }
* }
* ```
*
* The events payload can be accessed by the parameter `$event` on the components output event
* handler:
*
* ```
* <zippy (open)="onOpen($event)" (close)="onClose($event)"></zippy>
* ```
*
* Uses Rx.Observable but provides an adapter to make it work as specified here:
* https://github.com/jhusain/observable-spec
*
* Once a reference implementation of the spec is available, switch to it.
* @stable
*/
var EventEmitter = (function (_super) {
__extends$5(EventEmitter, _super);
/**
* Creates an instance of [EventEmitter], which depending on [isAsync],
* delivers events synchronously or asynchronously.
*/
function EventEmitter(isAsync) {
if (isAsync === void 0) { isAsync = false; }
_super.call(this);
this.__isAsync = isAsync;
}
EventEmitter.prototype.emit = function (value) { _super.prototype.next.call(this, value); };
EventEmitter.prototype.subscribe = function (generatorOrNext, error, complete) {
var schedulerFn;
var errorFn = function (err) { return null; };
var completeFn = function () { return null; };
if (generatorOrNext && typeof generatorOrNext === 'object') {
schedulerFn = this.__isAsync ? function (value) {
setTimeout(function () { return generatorOrNext.next(value); });
} : function (value) { generatorOrNext.next(value); };
if (generatorOrNext.error) {
errorFn = this.__isAsync ? function (err) { setTimeout(function () { return generatorOrNext.error(err); }); } :
function (err) { generatorOrNext.error(err); };
}
if (generatorOrNext.complete) {
completeFn = this.__isAsync ? function () { setTimeout(function () { return generatorOrNext.complete(); }); } :
function () { generatorOrNext.complete(); };
}
}
else {
schedulerFn = this.__isAsync ? function (value) { setTimeout(function () { return generatorOrNext(value); }); } :
function (value) { generatorOrNext(value); };
if (error) {
errorFn =
this.__isAsync ? function (err) { setTimeout(function () { return error(err); }); } : function (err) { error(err); };
}
if (complete) {
completeFn =
this.__isAsync ? function () { setTimeout(function () { return complete(); }); } : function () { complete(); };
}
}
return _super.prototype.subscribe.call(this, schedulerFn, errorFn, completeFn);
};
return EventEmitter;
}(rxjs_Subject.Subject));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __extends$6 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* Indicates that a FormControl is valid, i.e. that no errors exist in the input value.
*/
var VALID = 'VALID';
/**
* Indicates that a FormControl is invalid, i.e. that an error exists in the input value.
*/
var INVALID = 'INVALID';
/**
* Indicates that a FormControl is pending, i.e. that async validation is occurring and
* errors are not yet available for the input value.
*/
var PENDING = 'PENDING';
/**
* Indicates that a FormControl is disabled, i.e. that the control is exempt from ancestor
* calculations of validity or value.
*/
var DISABLED = 'DISABLED';
function _find(control, path, delimiter) {
if (path == null)
return null;
if (!(path instanceof Array)) {
path = path.split(delimiter);
}
if (path instanceof Array && (path.length === 0))
return null;
return path.reduce(function (v, name) {
if (v instanceof FormGroup) {
return v.controls[name] || null;
}
if (v instanceof FormArray) {
return v.at(name) || null;
}
return null;
}, control);
}
function toObservable(r) {
return isPromise(r) ? rxjs_observable_fromPromise.fromPromise(r) : r;
}
function coerceToValidator(validator) {
return Array.isArray(validator) ? composeValidators(validator) : validator;
}
function coerceToAsyncValidator(asyncValidator) {
return Array.isArray(asyncValidator) ? composeAsyncValidators(asyncValidator) : asyncValidator;
}
/**
* @whatItDoes This is the base class for {@link FormControl}, {@link FormGroup}, and
* {@link FormArray}.
*
* It provides some of the shared behavior that all controls and groups of controls have, like
* running validators, calculating status, and resetting state. It also defines the properties
* that are shared between all sub-classes, like `value`, `valid`, and `dirty`. It shouldn't be
* instantiated directly.
*
* @stable
*/
var AbstractControl = (function () {
function AbstractControl(validator, asyncValidator) {
this.validator = validator;
this.asyncValidator = asyncValidator;
/** @internal */
this._onCollectionChange = function () { };
this._pristine = true;
this._touched = false;
/** @internal */
this._onDisabledChange = [];
}
Object.defineProperty(AbstractControl.prototype, "value", {
/**
* The value of the control.
*/
get: function () { return this._value; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "parent", {
/**
* The parent control.
*/
get: function () { return this._parent; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "status", {
/**
* The validation status of the control. There are four possible
* validation statuses:
*
* * **VALID**: control has passed all validation checks
* * **INVALID**: control has failed at least one validation check
* * **PENDING**: control is in the midst of conducting a validation check
* * **DISABLED**: control is exempt from validation checks
*
* These statuses are mutually exclusive, so a control cannot be
* both valid AND invalid or invalid AND disabled.
*/
get: function () { return this._status; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "valid", {
/**
* A control is `valid` when its `status === VALID`.
*
* In order to have this status, the control must have passed all its
* validation checks.
*/
get: function () { return this._status === VALID; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "invalid", {
/**
* A control is `invalid` when its `status === INVALID`.
*
* In order to have this status, the control must have failed
* at least one of its validation checks.
*/
get: function () { return this._status === INVALID; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "pending", {
/**
* A control is `pending` when its `status === PENDING`.
*
* In order to have this status, the control must be in the
* middle of conducting a validation check.
*/
get: function () { return this._status == PENDING; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "disabled", {
/**
* A control is `disabled` when its `status === DISABLED`.
*
* Disabled controls are exempt from validation checks and
* are not included in the aggregate value of their ancestor
* controls.
*/
get: function () { return this._status === DISABLED; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "enabled", {
/**
* A control is `enabled` as long as its `status !== DISABLED`.
*
* In other words, it has a status of `VALID`, `INVALID`, or
* `PENDING`.
*/
get: function () { return this._status !== DISABLED; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "errors", {
/**
* Returns any errors generated by failing validation. If there
* are no errors, it will return null.
*/
get: function () { return this._errors; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "pristine", {
/**
* A control is `pristine` if the user has not yet changed
* the value in the UI.
*
* Note that programmatic changes to a control's value will
* *not* mark it dirty.
*/
get: function () { return this._pristine; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "dirty", {
/**
* A control is `dirty` if the user has changed the value
* in the UI.
*
* Note that programmatic changes to a control's value will
* *not* mark it dirty.
*/
get: function () { return !this.pristine; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "touched", {
/**
* A control is marked `touched` once the user has triggered
* a `blur` event on it.
*/
get: function () { return this._touched; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "untouched", {
/**
* A control is `untouched` if the user has not yet triggered
* a `blur` event on it.
*/
get: function () { return !this._touched; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "valueChanges", {
/**
* Emits an event every time the value of the control changes, in
* the UI or programmatically.
*/
get: function () { return this._valueChanges; },
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractControl.prototype, "statusChanges", {
/**
* Emits an event every time the validation status of the control
* is re-calculated.
*/
get: function () { return this._statusChanges; },
enumerable: true,
configurable: true
});
/**
* Sets the synchronous validators that are active on this control. Calling
* this will overwrite any existing sync validators.
*/
AbstractControl.prototype.setValidators = function (newValidator) {
this.validator = coerceToValidator(newValidator);
};
/**
* Sets the async validators that are active on this control. Calling this
* will overwrite any existing async validators.
*/
AbstractControl.prototype.setAsyncValidators = function (newValidator) {
this.asyncValidator = coerceToAsyncValidator(newValidator);
};
/**
* Empties out the sync validator list.
*/
AbstractControl.prototype.clearValidators = function () { this.validator = null; };
/**
* Empties out the async validator list.
*/
AbstractControl.prototype.clearAsyncValidators = function () { this.asyncValidator = null; };
/**
* Marks the control as `touched`.
*
* This will also mark all direct ancestors as `touched` to maintain
* the model.
*/
AbstractControl.prototype.markAsTouched = function (_a) {
var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
this._touched = true;
if (this._parent && !onlySelf) {
this._parent.markAsTouched({ onlySelf: onlySelf });
}
};
/**
* Marks the control as `untouched`.
*
* If the control has any children, it will also mark all children as `untouched`
* to maintain the model, and re-calculate the `touched` status of all parent
* controls.
*/
AbstractControl.prototype.markAsUntouched = function (_a) {
var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
this._touched = false;
this._forEachChild(function (control) { control.markAsUntouched({ onlySelf: true }); });
if (this._parent && !onlySelf) {
this._parent._updateTouched({ onlySelf: onlySelf });
}
};
/**
* Marks the control as `dirty`.
*
* This will also mark all direct ancestors as `dirty` to maintain
* the model.
*/
AbstractControl.prototype.markAsDirty = function (_a) {
var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
this._pristine = false;
if (this._parent && !onlySelf) {
this._parent.markAsDirty({ onlySelf: onlySelf });
}
};
/**
* Marks the control as `pristine`.
*
* If the control has any children, it will also mark all children as `pristine`
* to maintain the model, and re-calculate the `pristine` status of all parent
* controls.
*/
AbstractControl.prototype.markAsPristine = function (_a) {
var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
this._pristine = true;
this._forEachChild(function (control) { control.markAsPristine({ onlySelf: true }); });
if (this._parent && !onlySelf) {
this._parent._updatePristine({ onlySelf: onlySelf });
}
};
/**
* Marks the control as `pending`.
*/
AbstractControl.prototype.markAsPending = function (_a) {
var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
this._status = PENDING;
if (this._parent && !onlySelf) {
this._parent.markAsPending({ onlySelf: onlySelf });
}
};
/**
* Disables the control. This means the control will be exempt from validation checks and
* excluded from the aggregate value of any parent. Its status is `DISABLED`.
*
* If the control has children, all children will be disabled to maintain the model.
*/
AbstractControl.prototype.disable = function (_a) {
var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent;
this._status = DISABLED;
this._errors = null;
this._forEachChild(function (control) { control.disable({ onlySelf: true }); });
this._updateValue();
if (emitEvent !== false) {
this._valueChanges.emit(this._value);
this._statusChanges.emit(this._status);
}
this._updateAncestors(onlySelf);
this._onDisabledChange.forEach(function (changeFn) { return changeFn(true); });
};
/**
* Enables the control. This means the control will be included in validation checks and
* the aggregate value of its parent. Its status is re-calculated based on its value and
* its validators.
*
* If the control has children, all children will be enabled.
*/
AbstractControl.prototype.enable = function (_a) {
var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent;
this._status = VALID;
this._forEachChild(function (control) { control.enable({ onlySelf: true }); });
this.updateValueAndValidity({ onlySelf: true, emitEvent: emitEvent });
this._updateAncestors(onlySelf);
this._onDisabledChange.forEach(function (changeFn) { return changeFn(false); });
};
AbstractControl.prototype._updateAncestors = function (onlySelf) {
if (this._parent && !onlySelf) {
this._parent.updateValueAndValidity();
this._parent._updatePristine();
this._parent._updateTouched();
}
};
AbstractControl.prototype.setParent = function (parent) { this._parent = parent; };
/**
* Re-calculates the value and validation status of the control.
*
* By default, it will also update the value and validity of its ancestors.
*/
AbstractControl.prototype.updateValueAndValidity = function (_a) {
var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent;
this._setInitialStatus();
this._updateValue();
if (this.enabled) {
this._errors = this._runValidator();
this._status = this._calculateStatus();
if (this._status === VALID || this._status === PENDING) {
this._runAsyncValidator(emitEvent);
}
}
if (emitEvent !== false) {
this._valueChanges.emit(this._value);
this._statusChanges.emit(this._status);
}
if (this._parent && !onlySelf) {
this._parent.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent });
}
};
/** @internal */
AbstractControl.prototype._updateTreeValidity = function (_a) {
var emitEvent = (_a === void 0 ? { emitEvent: true } : _a).emitEvent;
this._forEachChild(function (ctrl) { return ctrl._updateTreeValidity({ emitEvent: emitEvent }); });
this.updateValueAndValidity({ onlySelf: true, emitEvent: emitEvent });
};
AbstractControl.prototype._setInitialStatus = function () { this._status = this._allControlsDisabled() ? DISABLED : VALID; };
AbstractControl.prototype._runValidator = function () {
return this.validator ? this.validator(this) : null;
};
AbstractControl.prototype._runAsyncValidator = function (emitEvent) {
var _this = this;
if (this.asyncValidator) {
this._status = PENDING;
this._cancelExistingSubscription();
var obs = toObservable(this.asyncValidator(this));
this._asyncValidationSubscription =
obs.subscribe({ next: function (res) { return _this.setErrors(res, { emitEvent: emitEvent }); } });
}
};
AbstractControl.prototype._cancelExistingSubscription = function () {
if (this._asyncValidationSubscription) {
this._asyncValidationSubscription.unsubscribe();
}
};
/**
* Sets errors on a form control.
*
* This is used when validations are run manually by the user, rather than automatically.
*
* Calling `setErrors` will also update the validity of the parent control.
*
* ### Example
*
* ```
* const login = new FormControl("someLogin");
* login.setErrors({
* "notUnique": true
* });
*
* expect(login.valid).toEqual(false);
* expect(login.errors).toEqual({"notUnique": true});
*
* login.setValue("someOtherLogin");
*
* expect(login.valid).toEqual(true);
* ```
*/
AbstractControl.prototype.setErrors = function (errors, _a) {
var emitEvent = (_a === void 0 ? {} : _a).emitEvent;
this._errors = errors;
this._updateControlsErrors(emitEvent !== false);
};
/**
* Retrieves a child control given the control's name or path.
*
* Paths can be passed in as an array or a string delimited by a dot.
*
* To get a control nested within a `person` sub-group:
*
* * `this.form.get('person.name');`
*
* -OR-
*
* * `this.form.get(['person', 'name']);`
*/
AbstractControl.prototype.get = function (path) { return _find(this, path, '.'); };
/**
* Returns true if the control with the given path has the error specified. Otherwise
* returns null or undefined.
*
* If no path is given, it checks for the error on the present control.
*/
AbstractControl.prototype.getError = function (errorCode, path) {
if (path === void 0) { path = null; }
var control = path ? this.get(path) : this;
return control && control._errors ? control._errors[errorCode] : null;
};
/**
* Returns true if the control with the given path has the error specified. Otherwise
* returns false.
*
* If no path is given, it checks for the error on the present control.
*/
AbstractControl.prototype.hasError = function (errorCode, path) {
if (path === void 0) { path = null; }
return !!this.getError(errorCode, path);
};
Object.defineProperty(AbstractControl.prototype, "root", {
/**
* Retrieves the top-level ancestor of this control.
*/
get: function () {
var x = this;
while (x._parent) {
x = x._parent;
}
return x;
},
enumerable: true,
configurable: true
});
/** @internal */
AbstractControl.prototype._updateControlsErrors = function (emitEvent) {
this._status = this._calculateStatus();
if (emitEvent) {
this._statusChanges.emit(this._status);
}
if (this._parent) {
this._parent._updateControlsErrors(emitEvent);
}
};
/** @internal */
AbstractControl.prototype._initObservables = function () {
this._valueChanges = new EventEmitter();
this._statusChanges = new EventEmitter();
};
AbstractControl.prototype._calculateStatus = function () {
if (this._allControlsDisabled())
return DISABLED;
if (this._errors)
return INVALID;
if (this._anyControlsHaveStatus(PENDING))
return PENDING;
if (this._anyControlsHaveStatus(INVALID))
return INVALID;
return VALID;
};
/** @internal */
AbstractControl.prototype._anyControlsHaveStatus = function (status) {
return this._anyControls(function (control) { return control.status === status; });
};
/** @internal */
AbstractControl.prototype._anyControlsDirty = function () {
return this._anyControls(function (control) { return control.dirty; });
};
/** @internal */
AbstractControl.prototype._anyControlsTouched = function () {
return this._anyControls(function (control) { return control.touched; });
};
/** @internal */
AbstractControl.prototype._updatePristine = function (_a) {
var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
this._pristine = !this._anyControlsDirty();
if (this._parent && !onlySelf) {
this._parent._updatePristine({ onlySelf: onlySelf });
}
};
/** @internal */
AbstractControl.prototype._updateTouched = function (_a) {
var onlySelf = (_a === void 0 ? {} : _a).onlySelf;
this._touched = this._anyControlsTouched();
if (this._parent && !onlySelf) {
this._parent._updateTouched({ onlySelf: onlySelf });
}
};
/** @internal */
AbstractControl.prototype._isBoxedValue = function (formState) {
return typeof formState === 'object' && formState !== null &&
Object.keys(formState).length === 2 && 'value' in formState && 'disabled' in formState;
};
/** @internal */
AbstractControl.prototype._registerOnCollectionChange = function (fn) { this._onCollectionChange = fn; };
return AbstractControl;
}());
/**
* @whatItDoes Tracks the value and validation status of an individual form control.
*
* It is one of the three fundamental building blocks of Angular forms, along with
* {@link FormGroup} and {@link FormArray}.
*
* @howToUse
*
* When instantiating a {@link FormControl}, you can pass in an initial value as the
* first argument. Example:
*
* ```ts
* const ctrl = new FormControl('some value');
* console.log(ctrl.value); // 'some value'
*```
*
* You can also initialize the control with a form state object on instantiation,
* which includes both the value and whether or not the control is disabled.
* You can't use the value key without the disabled key; both are required
* to use this way of initialization.
*
* ```ts
* const ctrl = new FormControl({value: 'n/a', disabled: true});
* console.log(ctrl.value); // 'n/a'
* console.log(ctrl.status); // 'DISABLED'
* ```
*
* To include a sync validator (or an array of sync validators) with the control,
* pass it in as the second argument. Async validators are also supported, but
* have to be passed in separately as the third arg.
*
* ```ts
* const ctrl = new FormControl('', Validators.required);
* console.log(ctrl.value); // ''
* console.log(ctrl.status); // 'INVALID'
* ```
*
* See its superclass, {@link AbstractControl}, for more properties and methods.
*
* * **npm package**: `@angular/forms`
*
* @stable
*/
var FormControl = (function (_super) {
__extends$6(FormControl, _super);
function FormControl(formState, validator, asyncValidator) {
if (formState === void 0) { formState = null; }
if (validator === void 0) { validator = null; }
if (asyncValidator === void 0) { asyncValidator = null; }
_super.call(this, coerceToValidator(validator), coerceToAsyncValidator(asyncValidator));
/** @internal */
this._onChange = [];
this._applyFormState(formState);
this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
this._initObservables();
}
/**
* Set the value of the form control to `value`.
*
* If `onlySelf` is `true`, this change will only affect the validation of this `FormControl`
* and not its parent component. This defaults to false.
*
* If `emitEvent` is `true`, this
* change will cause a `valueChanges` event on the `FormControl` to be emitted. This defaults
* to true (as it falls through to `updateValueAndValidity`).
*
* If `emitModelToViewChange` is `true`, the view will be notified about the new value
* via an `onChange` event. This is the default behavior if `emitModelToViewChange` is not
* specified.
*
* If `emitViewToModelChange` is `true`, an ngModelChange event will be fired to update the
* model. This is the default behavior if `emitViewToModelChange` is not specified.
*/
FormControl.prototype.setValue = function (value, _a) {
var _this = this;
var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent, emitModelToViewChange = _b.emitModelToViewChange, emitViewToModelChange = _b.emitViewToModelChange;
this._value = value;
if (this._onChange.length && emitModelToViewChange !== false) {
this._onChange.forEach(function (changeFn) { return changeFn(_this._value, emitViewToModelChange !== false); });
}
this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent });
};
/**
* Patches the value of a control.
*
* This function is functionally the same as {@link FormControl.setValue} at this level.
* It exists for symmetry with {@link FormGroup.patchValue} on `FormGroups` and `FormArrays`,
* where it does behave differently.
*/
FormControl.prototype.patchValue = function (value, options) {
if (options === void 0) { options = {}; }
this.setValue(value, options);
};
/**
* Resets the form control. This means by default:
*
* * it is marked as `pristine`
* * it is marked as `untouched`
* * value is set to null
*
* You can also reset to a specific form state by passing through a standalone
* value or a form state object that contains both a value and a disabled state
* (these are the only two properties that cannot be calculated).
*
* Ex:
*
* ```ts
* this.control.reset('Nancy');
*
* console.log(this.control.value); // 'Nancy'
* ```
*
* OR
*
* ```
* this.control.reset({value: 'Nancy', disabled: true});
*
* console.log(this.control.value); // 'Nancy'
* console.log(this.control.status); // 'DISABLED'
* ```
*/
FormControl.prototype.reset = function (formState, _a) {
if (formState === void 0) { formState = null; }
var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent;
this._applyFormState(formState);
this.markAsPristine({ onlySelf: onlySelf });
this.markAsUntouched({ onlySelf: onlySelf });
this.setValue(this._value, { onlySelf: onlySelf, emitEvent: emitEvent });
};
/**
* @internal
*/
FormControl.prototype._updateValue = function () { };
/**
* @internal
*/
FormControl.prototype._anyControls = function (condition) { return false; };
/**
* @internal
*/
FormControl.prototype._allControlsDisabled = function () { return this.disabled; };
/**
* Register a listener for change events.
*/
FormControl.prototype.registerOnChange = function (fn) { this._onChange.push(fn); };
/**
* @internal
*/
FormControl.prototype._clearChangeFns = function () {
this._onChange = [];
this._onDisabledChange = [];
this._onCollectionChange = function () { };
};
/**
* Register a listener for disabled events.
*/
FormControl.prototype.registerOnDisabledChange = function (fn) {
this._onDisabledChange.push(fn);
};
/**
* @internal
*/
FormControl.prototype._forEachChild = function (cb) { };
FormControl.prototype._applyFormState = function (formState) {
if (this._isBoxedValue(formState)) {
this._value = formState.value;
formState.disabled ? this.disable({ onlySelf: true, emitEvent: false }) :
this.enable({ onlySelf: true, emitEvent: false });
}
else {
this._value = formState;
}
};
return FormControl;
}(AbstractControl));
/**
* @whatItDoes Tracks the value and validity state of a group of {@link FormControl}
* instances.
*
* A `FormGroup` aggregates the values of each child {@link FormControl} into one object,
* with each control name as the key. It calculates its status by reducing the statuses
* of its children. For example, if one of the controls in a group is invalid, the entire
* group becomes invalid.
*
* `FormGroup` is one of the three fundamental building blocks used to define forms in Angular,
* along with {@link FormControl} and {@link FormArray}.
*
* @howToUse
*
* When instantiating a {@link FormGroup}, pass in a collection of child controls as the first
* argument. The key for each child will be the name under which it is registered.
*
* ### Example
*
* ```
* const form = new FormGroup({
* first: new FormControl('Nancy', Validators.minLength(2)),
* last: new FormControl('Drew'),
* });
*
* console.log(form.value); // {first: 'Nancy', last; 'Drew'}
* console.log(form.status); // 'VALID'
* ```
*
* You can also include group-level validators as the second arg, or group-level async
* validators as the third arg. These come in handy when you want to perform validation
* that considers the value of more than one child control.
*
* ### Example
*
* ```
* const form = new FormGroup({
* password: new FormControl('', Validators.minLength(2)),
* passwordConfirm: new FormControl('', Validators.minLength(2)),
* }, passwordMatchValidator);
*
*
* function passwordMatchValidator(g: FormGroup) {
* return g.get('password').value === g.get('passwordConfirm').value
* ? null : {'mismatch': true};
* }
* ```
*
* * **npm package**: `@angular/forms`
*
* @stable
*/
var FormGroup = (function (_super) {
__extends$6(FormGroup, _super);
function FormGroup(controls, validator, asyncValidator) {
if (validator === void 0) { validator = null; }
if (asyncValidator === void 0) { asyncValidator = null; }
_super.call(this, validator, asyncValidator);
this.controls = controls;
this._initObservables();
this._setUpControls();
this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
}
/**
* Registers a control with the group's list of controls.
*
* This method does not update value or validity of the control, so for
* most cases you'll want to use {@link FormGroup.addControl} instead.
*/
FormGroup.prototype.registerControl = function (name, control) {
if (this.controls[name])
return this.controls[name];
this.controls[name] = control;
control.setParent(this);
control._registerOnCollectionChange(this._onCollectionChange);
return control;
};
/**
* Add a control to this group.
*/
FormGroup.prototype.addControl = function (name, control) {
this.registerControl(name, control);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Remove a control from this group.
*/
FormGroup.prototype.removeControl = function (name) {
if (this.controls[name])
this.controls[name]._registerOnCollectionChange(function () { });
delete (this.controls[name]);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Replace an existing control.
*/
FormGroup.prototype.setControl = function (name, control) {
if (this.controls[name])
this.controls[name]._registerOnCollectionChange(function () { });
delete (this.controls[name]);
if (control)
this.registerControl(name, control);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Check whether there is an enabled control with the given name in the group.
*
* It will return false for disabled controls. If you'd like to check for
* existence in the group only, use {@link AbstractControl.get} instead.
*/
FormGroup.prototype.contains = function (controlName) {
return this.controls.hasOwnProperty(controlName) && this.controls[controlName].enabled;
};
/**
* Sets the value of the {@link FormGroup}. It accepts an object that matches
* the structure of the group, with control names as keys.
*
* This method performs strict checks, so it will throw an error if you try
* to set the value of a control that doesn't exist or if you exclude the
* value of a control.
*
* ### Example
*
* ```
* const form = new FormGroup({
* first: new FormControl(),
* last: new FormControl()
* });
* console.log(form.value); // {first: null, last: null}
*
* form.setValue({first: 'Nancy', last: 'Drew'});
* console.log(form.value); // {first: 'Nancy', last: 'Drew'}
*
* ```
*/
FormGroup.prototype.setValue = function (value, _a) {
var _this = this;
var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent;
this._checkAllValuesPresent(value);
Object.keys(value).forEach(function (name) {
_this._throwIfControlMissing(name);
_this.controls[name].setValue(value[name], { onlySelf: true, emitEvent: emitEvent });
});
this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent });
};
/**
* Patches the value of the {@link FormGroup}. It accepts an object with control
* names as keys, and will do its best to match the values to the correct controls
* in the group.
*
* It accepts both super-sets and sub-sets of the group without throwing an error.
*
* ### Example
*
* ```
* const form = new FormGroup({
* first: new FormControl(),
* last: new FormControl()
* });
* console.log(form.value); // {first: null, last: null}
*
* form.patchValue({first: 'Nancy'});
* console.log(form.value); // {first: 'Nancy', last: null}
*
* ```
*/
FormGroup.prototype.patchValue = function (value, _a) {
var _this = this;
var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent;
Object.keys(value).forEach(function (name) {
if (_this.controls[name]) {
_this.controls[name].patchValue(value[name], { onlySelf: true, emitEvent: emitEvent });
}
});
this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent });
};
/**
* Resets the {@link FormGroup}. This means by default:
*
* * The group and all descendants are marked `pristine`
* * The group and all descendants are marked `untouched`
* * The value of all descendants will be null or null maps
*
* You can also reset to a specific form state by passing in a map of states
* that matches the structure of your form, with control names as keys. The state
* can be a standalone value or a form state object with both a value and a disabled
* status.
*
* ### Example
*
* ```ts
* this.form.reset({first: 'name', last: 'last name'});
*
* console.log(this.form.value); // {first: 'name', last: 'last name'}
* ```
*
* - OR -
*
* ```
* this.form.reset({
* first: {value: 'name', disabled: true},
* last: 'last'
* });
*
* console.log(this.form.value); // {first: 'name', last: 'last name'}
* console.log(this.form.get('first').status); // 'DISABLED'
* ```
*/
FormGroup.prototype.reset = function (value, _a) {
if (value === void 0) { value = {}; }
var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent;
this._forEachChild(function (control, name) {
control.reset(value[name], { onlySelf: true, emitEvent: emitEvent });
});
this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent });
this._updatePristine({ onlySelf: onlySelf });
this._updateTouched({ onlySelf: onlySelf });
};
/**
* The aggregate value of the {@link FormGroup}, including any disabled controls.
*
* If you'd like to include all values regardless of disabled status, use this method.
* Otherwise, the `value` property is the best way to get the value of the group.
*/
FormGroup.prototype.getRawValue = function () {
return this._reduceChildren({}, function (acc, control, name) {
acc[name] = control.value;
return acc;
});
};
/** @internal */
FormGroup.prototype._throwIfControlMissing = function (name) {
if (!Object.keys(this.controls).length) {
throw new Error("\n There are no form controls registered with this group yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n ");
}
if (!this.controls[name]) {
throw new Error("Cannot find form control with name: " + name + ".");
}
};
/** @internal */
FormGroup.prototype._forEachChild = function (cb) {
var _this = this;
Object.keys(this.controls).forEach(function (k) { return cb(_this.controls[k], k); });
};
/** @internal */
FormGroup.prototype._setUpControls = function () {
var _this = this;
this._forEachChild(function (control) {
control.setParent(_this);
control._registerOnCollectionChange(_this._onCollectionChange);
});
};
/** @internal */
FormGroup.prototype._updateValue = function () { this._value = this._reduceValue(); };
/** @internal */
FormGroup.prototype._anyControls = function (condition) {
var _this = this;
var res = false;
this._forEachChild(function (control, name) {
res = res || (_this.contains(name) && condition(control));
});
return res;
};
/** @internal */
FormGroup.prototype._reduceValue = function () {
var _this = this;
return this._reduceChildren({}, function (acc, control, name) {
if (control.enabled || _this.disabled) {
acc[name] = control.value;
}
return acc;
});
};
/** @internal */
FormGroup.prototype._reduceChildren = function (initValue, fn) {
var res = initValue;
this._forEachChild(function (control, name) { res = fn(res, control, name); });
return res;
};
/** @internal */
FormGroup.prototype._allControlsDisabled = function () {
for (var _i = 0, _a = Object.keys(this.controls); _i < _a.length; _i++) {
var controlName = _a[_i];
if (this.controls[controlName].enabled) {
return false;
}
}
return Object.keys(this.controls).length > 0 || this.disabled;
};
/** @internal */
FormGroup.prototype._checkAllValuesPresent = function (value) {
this._forEachChild(function (control, name) {
if (value[name] === undefined) {
throw new Error("Must supply a value for form control with name: '" + name + "'.");
}
});
};
return FormGroup;
}(AbstractControl));
/**
* @whatItDoes Tracks the value and validity state of an array of {@link FormControl}
* instances.
*
* A `FormArray` aggregates the values of each child {@link FormControl} into an array.
* It calculates its status by reducing the statuses of its children. For example, if one of
* the controls in a `FormArray` is invalid, the entire array becomes invalid.
*
* `FormArray` is one of the three fundamental building blocks used to define forms in Angular,
* along with {@link FormControl} and {@link FormGroup}.
*
* @howToUse
*
* When instantiating a {@link FormArray}, pass in an array of child controls as the first
* argument.
*
* ### Example
*
* ```
* const arr = new FormArray([
* new FormControl('Nancy', Validators.minLength(2)),
* new FormControl('Drew'),
* ]);
*
* console.log(arr.value); // ['Nancy', 'Drew']
* console.log(arr.status); // 'VALID'
* ```
*
* You can also include array-level validators as the second arg, or array-level async
* validators as the third arg. These come in handy when you want to perform validation
* that considers the value of more than one child control.
*
* ### Adding or removing controls
*
* To change the controls in the array, use the `push`, `insert`, or `removeAt` methods
* in `FormArray` itself. These methods ensure the controls are properly tracked in the
* form's hierarchy. Do not modify the array of `AbstractControl`s used to instantiate
* the `FormArray` directly, as that will result in strange and unexpected behavior such
* as broken change detection.
*
* * **npm package**: `@angular/forms`
*
* @stable
*/
var FormArray = (function (_super) {
__extends$6(FormArray, _super);
function FormArray(controls, validator, asyncValidator) {
if (validator === void 0) { validator = null; }
if (asyncValidator === void 0) { asyncValidator = null; }
_super.call(this, validator, asyncValidator);
this.controls = controls;
this._initObservables();
this._setUpControls();
this.updateValueAndValidity({ onlySelf: true, emitEvent: false });
}
/**
* Get the {@link AbstractControl} at the given `index` in the array.
*/
FormArray.prototype.at = function (index) { return this.controls[index]; };
/**
* Insert a new {@link AbstractControl} at the end of the array.
*/
FormArray.prototype.push = function (control) {
this.controls.push(control);
this._registerControl(control);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Insert a new {@link AbstractControl} at the given `index` in the array.
*/
FormArray.prototype.insert = function (index, control) {
this.controls.splice(index, 0, control);
this._registerControl(control);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Remove the control at the given `index` in the array.
*/
FormArray.prototype.removeAt = function (index) {
if (this.controls[index])
this.controls[index]._registerOnCollectionChange(function () { });
this.controls.splice(index, 1);
this.updateValueAndValidity();
this._onCollectionChange();
};
/**
* Replace an existing control.
*/
FormArray.prototype.setControl = function (index, control) {
if (this.controls[index])
this.controls[index]._registerOnCollectionChange(function () { });
this.controls.splice(index, 1);
if (control) {
this.controls.splice(index, 0, control);
this._registerControl(control);
}
this.updateValueAndValidity();
this._onCollectionChange();
};
Object.defineProperty(FormArray.prototype, "length", {
/**
* Length of the control array.
*/
get: function () { return this.controls.length; },
enumerable: true,
configurable: true
});
/**
* Sets the value of the {@link FormArray}. It accepts an array that matches
* the structure of the control.
*
* This method performs strict checks, so it will throw an error if you try
* to set the value of a control that doesn't exist or if you exclude the
* value of a control.
*
* ### Example
*
* ```
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* console.log(arr.value); // [null, null]
*
* arr.setValue(['Nancy', 'Drew']);
* console.log(arr.value); // ['Nancy', 'Drew']
* ```
*/
FormArray.prototype.setValue = function (value, _a) {
var _this = this;
var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent;
this._checkAllValuesPresent(value);
value.forEach(function (newValue, index) {
_this._throwIfControlMissing(index);
_this.at(index).setValue(newValue, { onlySelf: true, emitEvent: emitEvent });
});
this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent });
};
/**
* Patches the value of the {@link FormArray}. It accepts an array that matches the
* structure of the control, and will do its best to match the values to the correct
* controls in the group.
*
* It accepts both super-sets and sub-sets of the array without throwing an error.
*
* ### Example
*
* ```
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* console.log(arr.value); // [null, null]
*
* arr.patchValue(['Nancy']);
* console.log(arr.value); // ['Nancy', null]
* ```
*/
FormArray.prototype.patchValue = function (value, _a) {
var _this = this;
var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent;
value.forEach(function (newValue, index) {
if (_this.at(index)) {
_this.at(index).patchValue(newValue, { onlySelf: true, emitEvent: emitEvent });
}
});
this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent });
};
/**
* Resets the {@link FormArray}. This means by default:
*
* * The array and all descendants are marked `pristine`
* * The array and all descendants are marked `untouched`
* * The value of all descendants will be null or null maps
*
* You can also reset to a specific form state by passing in an array of states
* that matches the structure of the control. The state can be a standalone value
* or a form state object with both a value and a disabled status.
*
* ### Example
*
* ```ts
* this.arr.reset(['name', 'last name']);
*
* console.log(this.arr.value); // ['name', 'last name']
* ```
*
* - OR -
*
* ```
* this.arr.reset([
* {value: 'name', disabled: true},
* 'last'
* ]);
*
* console.log(this.arr.value); // ['name', 'last name']
* console.log(this.arr.get(0).status); // 'DISABLED'
* ```
*/
FormArray.prototype.reset = function (value, _a) {
if (value === void 0) { value = []; }
var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent;
this._forEachChild(function (control, index) {
control.reset(value[index], { onlySelf: true, emitEvent: emitEvent });
});
this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent });
this._updatePristine({ onlySelf: onlySelf });
this._updateTouched({ onlySelf: onlySelf });
};
/**
* The aggregate value of the array, including any disabled controls.
*
* If you'd like to include all values regardless of disabled status, use this method.
* Otherwise, the `value` property is the best way to get the value of the array.
*/
FormArray.prototype.getRawValue = function () { return this.controls.map(function (control) { return control.value; }); };
/** @internal */
FormArray.prototype._throwIfControlMissing = function (index) {
if (!this.controls.length) {
throw new Error("\n There are no form controls registered with this array yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n ");
}
if (!this.at(index)) {
throw new Error("Cannot find form control at index " + index);
}
};
/** @internal */
FormArray.prototype._forEachChild = function (cb) {
this.controls.forEach(function (control, index) { cb(control, index); });
};
/** @internal */
FormArray.prototype._updateValue = function () {
var _this = this;
this._value = this.controls.filter(function (control) { return control.enabled || _this.disabled; })
.map(function (control) { return control.value; });
};
/** @internal */
FormArray.prototype._anyControls = function (condition) {
return this.controls.some(function (control) { return control.enabled && condition(control); });
};
/** @internal */
FormArray.prototype._setUpControls = function () {
var _this = this;
this._forEachChild(function (control) { return _this._registerControl(control); });
};
/** @internal */
FormArray.prototype._checkAllValuesPresent = function (value) {
this._forEachChild(function (control, i) {
if (value[i] === undefined) {
throw new Error("Must supply a value for form control at index: " + i + ".");
}
});
};
/** @internal */
FormArray.prototype._allControlsDisabled = function () {
for (var _i = 0, _a = this.controls; _i < _a.length; _i++) {
var control = _a[_i];
if (control.enabled)
return false;
}
return this.controls.length > 0 || this.disabled;
};
FormArray.prototype._registerControl = function (control) {
control.setParent(this);
control._registerOnCollectionChange(this._onCollectionChange);
};
return FormArray;
}(AbstractControl));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __extends$4 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var formDirectiveProvider = {
provide: ControlContainer,
useExisting: _angular_core.forwardRef(function () { return NgForm; })
};
var resolvedPromise = Promise.resolve(null);
/**
* @whatItDoes Creates a top-level {@link FormGroup} instance and binds it to a form
* to track aggregate form value and validation status.
*
* @howToUse
*
* As soon as you import the `FormsModule`, this directive becomes active by default on
* all `<form>` tags. You don't need to add a special selector.
*
* You can export the directive into a local template variable using `ngForm` as the key
* (ex: `#myForm="ngForm"`). This is optional, but useful. Many properties from the underlying
* {@link FormGroup} instance are duplicated on the directive itself, so a reference to it
* will give you access to the aggregate value and validity status of the form, as well as
* user interaction properties like `dirty` and `touched`.
*
* To register child controls with the form, you'll want to use {@link NgModel} with a
* `name` attribute. You can also use {@link NgModelGroup} if you'd like to create
* sub-groups within the form.
*
* You can listen to the directive's `ngSubmit` event to be notified when the user has
* triggered a form submission. The `ngSubmit` event will be emitted with the original form
* submission event.
*
* {@example forms/ts/simpleForm/simple_form_example.ts region='Component'}
*
* * **npm package**: `@angular/forms`
*
* * **NgModule**: `FormsModule`
*
* @stable
*/
var NgForm = (function (_super) {
__extends$4(NgForm, _super);
function NgForm(validators, asyncValidators) {
_super.call(this);
this._submitted = false;
this.ngSubmit = new EventEmitter();
this.form =
new FormGroup({}, composeValidators(validators), composeAsyncValidators(asyncValidators));
}
Object.defineProperty(NgForm.prototype, "submitted", {
get: function () { return this._submitted; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgForm.prototype, "formDirective", {
get: function () { return this; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgForm.prototype, "control", {
get: function () { return this.form; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgForm.prototype, "path", {
get: function () { return []; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgForm.prototype, "controls", {
get: function () { return this.form.controls; },
enumerable: true,
configurable: true
});
NgForm.prototype.addControl = function (dir) {
var _this = this;
resolvedPromise.then(function () {
var container = _this._findContainer(dir.path);
dir._control = container.registerControl(dir.name, dir.control);
setUpControl(dir.control, dir);
dir.control.updateValueAndValidity({ emitEvent: false });
});
};
NgForm.prototype.getControl = function (dir) { return this.form.get(dir.path); };
NgForm.prototype.removeControl = function (dir) {
var _this = this;
resolvedPromise.then(function () {
var container = _this._findContainer(dir.path);
if (container) {
container.removeControl(dir.name);
}
});
};
NgForm.prototype.addFormGroup = function (dir) {
var _this = this;
resolvedPromise.then(function () {
var container = _this._findContainer(dir.path);
var group = new FormGroup({});
setUpFormContainer(group, dir);
container.registerControl(dir.name, group);
group.updateValueAndValidity({ emitEvent: false });
});
};
NgForm.prototype.removeFormGroup = function (dir) {
var _this = this;
resolvedPromise.then(function () {
var container = _this._findContainer(dir.path);
if (container) {
container.removeControl(dir.name);
}
});
};
NgForm.prototype.getFormGroup = function (dir) { return this.form.get(dir.path); };
NgForm.prototype.updateModel = function (dir, value) {
var _this = this;
resolvedPromise.then(function () {
var ctrl = _this.form.get(dir.path);
ctrl.setValue(value);
});
};
NgForm.prototype.setValue = function (value) { this.control.setValue(value); };
NgForm.prototype.onSubmit = function ($event) {
this._submitted = true;
this.ngSubmit.emit($event);
return false;
};
NgForm.prototype.onReset = function () { this.resetForm(); };
NgForm.prototype.resetForm = function (value) {
if (value === void 0) { value = undefined; }
this.form.reset(value);
this._submitted = false;
};
/** @internal */
NgForm.prototype._findContainer = function (path) {
path.pop();
return path.length ? this.form.get(path) : this.form;
};
NgForm.decorators = [
{ type: _angular_core.Directive, args: [{
selector: 'form:not([ngNoForm]):not([formGroup]),ngForm,[ngForm]',
providers: [formDirectiveProvider],
host: { '(submit)': 'onSubmit($event)', '(reset)': 'onReset()' },
outputs: ['ngSubmit'],
exportAs: 'ngForm'
},] },
];
/** @nocollapse */
NgForm.ctorParameters = [
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] },
];
return NgForm;
}(ControlContainer));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var Examples = {
formControlName: "\n <div [formGroup]=\"myGroup\">\n <input formControlName=\"firstName\">\n </div>\n\n In your class:\n\n this.myGroup = new FormGroup({\n firstName: new FormControl()\n });",
formGroupName: "\n <div [formGroup]=\"myGroup\">\n <div formGroupName=\"person\">\n <input formControlName=\"firstName\">\n </div>\n </div>\n\n In your class:\n\n this.myGroup = new FormGroup({\n person: new FormGroup({ firstName: new FormControl() })\n });",
formArrayName: "\n <div [formGroup]=\"myGroup\">\n <div formArrayName=\"cities\">\n <div *ngFor=\"let city of cityArray.controls; let i=index\">\n <input [formControlName]=\"i\">\n </div>\n </div>\n </div>\n\n In your class:\n\n this.cityArray = new FormArray([new FormControl('SF')]);\n this.myGroup = new FormGroup({\n cities: this.cityArray\n });",
ngModelGroup: "\n <form>\n <div ngModelGroup=\"person\">\n <input [(ngModel)]=\"person.name\" name=\"firstName\">\n </div>\n </form>",
ngModelWithFormGroup: "\n <div [formGroup]=\"myGroup\">\n <input formControlName=\"firstName\">\n <input [(ngModel)]=\"showMoreControls\" [ngModelOptions]=\"{standalone: true}\">\n </div>\n "
};
var TemplateDrivenErrors = (function () {
function TemplateDrivenErrors() {
}
TemplateDrivenErrors.modelParentException = function () {
throw new Error("\n ngModel cannot be used to register form controls with a parent formGroup directive. Try using\n formGroup's partner directive \"formControlName\" instead. Example:\n\n " + Examples.formControlName + "\n\n Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:\n\n Example:\n\n " + Examples.ngModelWithFormGroup);
};
TemplateDrivenErrors.formGroupNameException = function () {
throw new Error("\n ngModel cannot be used to register form controls with a parent formGroupName or formArrayName directive.\n\n Option 1: Use formControlName instead of ngModel (reactive strategy):\n\n " + Examples.formGroupName + "\n\n Option 2: Update ngModel's parent be ngModelGroup (template-driven strategy):\n\n " + Examples.ngModelGroup);
};
TemplateDrivenErrors.missingNameException = function () {
throw new Error("If ngModel is used within a form tag, either the name attribute must be set or the form\n control must be defined as 'standalone' in ngModelOptions.\n\n Example 1: <input [(ngModel)]=\"person.firstName\" name=\"first\">\n Example 2: <input [(ngModel)]=\"person.firstName\" [ngModelOptions]=\"{standalone: true}\">");
};
TemplateDrivenErrors.modelGroupParentException = function () {
throw new Error("\n ngModelGroup cannot be used with a parent formGroup directive.\n\n Option 1: Use formGroupName instead of ngModelGroup (reactive strategy):\n\n " + Examples.formGroupName + "\n\n Option 2: Use a regular form tag instead of the formGroup directive (template-driven strategy):\n\n " + Examples.ngModelGroup);
};
return TemplateDrivenErrors;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __extends$8 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var modelGroupProvider = {
provide: ControlContainer,
useExisting: _angular_core.forwardRef(function () { return NgModelGroup; })
};
/**
* @whatItDoes Creates and binds a {@link FormGroup} instance to a DOM element.
*
* @howToUse
*
* This directive can only be used as a child of {@link NgForm} (or in other words,
* within `<form>` tags).
*
* Use this directive if you'd like to create a sub-group within a form. This can
* come in handy if you want to validate a sub-group of your form separately from
* the rest of your form, or if some values in your domain model make more sense to
* consume together in a nested object.
*
* Pass in the name you'd like this sub-group to have and it will become the key
* for the sub-group in the form's full value. You can also export the directive into
* a local template variable using `ngModelGroup` (ex: `#myGroup="ngModelGroup"`).
*
* {@example forms/ts/ngModelGroup/ng_model_group_example.ts region='Component'}
*
* * **npm package**: `@angular/forms`
*
* * **NgModule**: `FormsModule`
*
* @stable
*/
var NgModelGroup = (function (_super) {
__extends$8(NgModelGroup, _super);
function NgModelGroup(parent, validators, asyncValidators) {
_super.call(this);
this._parent = parent;
this._validators = validators;
this._asyncValidators = asyncValidators;
}
/** @internal */
NgModelGroup.prototype._checkParentType = function () {
if (!(this._parent instanceof NgModelGroup) && !(this._parent instanceof NgForm)) {
TemplateDrivenErrors.modelGroupParentException();
}
};
NgModelGroup.decorators = [
{ type: _angular_core.Directive, args: [{ selector: '[ngModelGroup]', providers: [modelGroupProvider], exportAs: 'ngModelGroup' },] },
];
/** @nocollapse */
NgModelGroup.ctorParameters = [
{ type: ControlContainer, decorators: [{ type: _angular_core.Host }, { type: _angular_core.SkipSelf },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] },
];
NgModelGroup.propDecorators = {
'name': [{ type: _angular_core.Input, args: ['ngModelGroup',] },],
};
return NgModelGroup;
}(AbstractFormGroupDirective));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __extends$7 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var formControlBinding = {
provide: NgControl,
useExisting: _angular_core.forwardRef(function () { return NgModel; })
};
/**
* `ngModel` forces an additional change detection run when its inputs change:
* E.g.:
* ```
* <div>{{myModel.valid}}</div>
* <input [(ngModel)]="myValue" #myModel="ngModel">
* ```
* I.e. `ngModel` can export itself on the element and then be used in the template.
* Normally, this would result in expressions before the `input` that use the exported directive
* to have and old value as they have been
* dirty checked before. As this is a very common case for `ngModel`, we added this second change
* detection run.
*
* Notes:
* - this is just one extra run no matter how many `ngModel` have been changed.
* - this is a general problem when using `exportAs` for directives!
*/
var resolvedPromise$1 = Promise.resolve(null);
/**
* @whatItDoes Creates a {@link FormControl} instance from a domain model and binds it
* to a form control element.
*
* The {@link FormControl} instance will track the value, user interaction, and
* validation status of the control and keep the view synced with the model. If used
* within a parent form, the directive will also register itself with the form as a child
* control.
*
* @howToUse
*
* This directive can be used by itself or as part of a larger form. All you need is the
* `ngModel` selector to activate it.
*
* It accepts a domain model as an optional {@link @Input}. If you have a one-way binding
* to `ngModel` with `[]` syntax, changing the value of the domain model in the component
* class will set the value in the view. If you have a two-way binding with `[()]` syntax
* (also known as 'banana-box syntax'), the value in the UI will always be synced back to
* the domain model in your class as well.
*
* If you wish to inspect the properties of the associated {@link FormControl} (like
* validity state), you can also export the directive into a local template variable using
* `ngModel` as the key (ex: `#myVar="ngModel"`). You can then access the control using the
* directive's `control` property, but most properties you'll need (like `valid` and `dirty`)
* will fall through to the control anyway, so you can access them directly. You can see a
* full list of properties directly available in {@link AbstractControlDirective}.
*
* The following is an example of a simple standalone control using `ngModel`:
*
* {@example forms/ts/simpleNgModel/simple_ng_model_example.ts region='Component'}
*
* When using the `ngModel` within `<form>` tags, you'll also need to supply a `name` attribute
* so that the control can be registered with the parent form under that name.
*
* It's worth noting that in the context of a parent form, you often can skip one-way or
* two-way binding because the parent form will sync the value for you. You can access
* its properties by exporting it into a local template variable using `ngForm` (ex:
* `#f="ngForm"`). Then you can pass it where it needs to go on submit.
*
* If you do need to populate initial values into your form, using a one-way binding for
* `ngModel` tends to be sufficient as long as you use the exported form's value rather
* than the domain model's value on submit.
*
* Take a look at an example of using `ngModel` within a form:
*
* {@example forms/ts/simpleForm/simple_form_example.ts region='Component'}
*
* To see `ngModel` examples with different form control types, see:
*
* * Radio buttons: {@link RadioControlValueAccessor}
* * Selects: {@link SelectControlValueAccessor}
*
* **npm package**: `@angular/forms`
*
* **NgModule**: `FormsModule`
*
* @stable
*/
var NgModel = (function (_super) {
__extends$7(NgModel, _super);
function NgModel(parent, validators, asyncValidators, valueAccessors) {
_super.call(this);
/** @internal */
this._control = new FormControl();
/** @internal */
this._registered = false;
this.update = new EventEmitter();
this._parent = parent;
this._rawValidators = validators || [];
this._rawAsyncValidators = asyncValidators || [];
this.valueAccessor = selectValueAccessor(this, valueAccessors);
}
NgModel.prototype.ngOnChanges = function (changes) {
this._checkForErrors();
if (!this._registered)
this._setUpControl();
if ('isDisabled' in changes) {
this._updateDisabled(changes);
}
if (isPropertyUpdated(changes, this.viewModel)) {
this._updateValue(this.model);
this.viewModel = this.model;
}
};
NgModel.prototype.ngOnDestroy = function () { this.formDirective && this.formDirective.removeControl(this); };
Object.defineProperty(NgModel.prototype, "control", {
get: function () { return this._control; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgModel.prototype, "path", {
get: function () {
return this._parent ? controlPath(this.name, this._parent) : [this.name];
},
enumerable: true,
configurable: true
});
Object.defineProperty(NgModel.prototype, "formDirective", {
get: function () { return this._parent ? this._parent.formDirective : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(NgModel.prototype, "validator", {
get: function () { return composeValidators(this._rawValidators); },
enumerable: true,
configurable: true
});
Object.defineProperty(NgModel.prototype, "asyncValidator", {
get: function () {
return composeAsyncValidators(this._rawAsyncValidators);
},
enumerable: true,
configurable: true
});
NgModel.prototype.viewToModelUpdate = function (newValue) {
this.viewModel = newValue;
this.update.emit(newValue);
};
NgModel.prototype._setUpControl = function () {
this._isStandalone() ? this._setUpStandalone() :
this.formDirective.addControl(this);
this._registered = true;
};
NgModel.prototype._isStandalone = function () {
return !this._parent || (this.options && this.options.standalone);
};
NgModel.prototype._setUpStandalone = function () {
setUpControl(this._control, this);
this._control.updateValueAndValidity({ emitEvent: false });
};
NgModel.prototype._checkForErrors = function () {
if (!this._isStandalone()) {
this._checkParentType();
}
this._checkName();
};
NgModel.prototype._checkParentType = function () {
if (!(this._parent instanceof NgModelGroup) &&
this._parent instanceof AbstractFormGroupDirective) {
TemplateDrivenErrors.formGroupNameException();
}
else if (!(this._parent instanceof NgModelGroup) && !(this._parent instanceof NgForm)) {
TemplateDrivenErrors.modelParentException();
}
};
NgModel.prototype._checkName = function () {
if (this.options && this.options.name)
this.name = this.options.name;
if (!this._isStandalone() && !this.name) {
TemplateDrivenErrors.missingNameException();
}
};
NgModel.prototype._updateValue = function (value) {
var _this = this;
resolvedPromise$1.then(function () { _this.control.setValue(value, { emitViewToModelChange: false }); });
};
NgModel.prototype._updateDisabled = function (changes) {
var _this = this;
var disabledValue = changes['isDisabled'].currentValue;
var isDisabled = disabledValue === '' || (disabledValue && disabledValue !== 'false');
resolvedPromise$1.then(function () {
if (isDisabled && !_this.control.disabled) {
_this.control.disable();
}
else if (!isDisabled && _this.control.disabled) {
_this.control.enable();
}
});
};
NgModel.decorators = [
{ type: _angular_core.Directive, args: [{
selector: '[ngModel]:not([formControlName]):not([formControl])',
providers: [formControlBinding],
exportAs: 'ngModel'
},] },
];
/** @nocollapse */
NgModel.ctorParameters = [
{ type: ControlContainer, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Host },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALUE_ACCESSOR,] },] },
];
NgModel.propDecorators = {
'name': [{ type: _angular_core.Input },],
'isDisabled': [{ type: _angular_core.Input, args: ['disabled',] },],
'model': [{ type: _angular_core.Input, args: ['ngModel',] },],
'options': [{ type: _angular_core.Input, args: ['ngModelOptions',] },],
'update': [{ type: _angular_core.Output, args: ['ngModelChange',] },],
};
return NgModel;
}(NgControl));
var ReactiveErrors = (function () {
function ReactiveErrors() {
}
ReactiveErrors.controlParentException = function () {
throw new Error("formControlName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n " + Examples.formControlName);
};
ReactiveErrors.ngModelGroupException = function () {
throw new Error("formControlName cannot be used with an ngModelGroup parent. It is only compatible with parents\n that also have a \"form\" prefix: formGroupName, formArrayName, or formGroup.\n\n Option 1: Update the parent to be formGroupName (reactive form strategy)\n\n " + Examples.formGroupName + "\n\n Option 2: Use ngModel instead of formControlName (template-driven strategy)\n\n " + Examples.ngModelGroup);
};
ReactiveErrors.missingFormException = function () {
throw new Error("formGroup expects a FormGroup instance. Please pass one in.\n\n Example:\n\n " + Examples.formControlName);
};
ReactiveErrors.groupParentException = function () {
throw new Error("formGroupName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n " + Examples.formGroupName);
};
ReactiveErrors.arrayParentException = function () {
throw new Error("formArrayName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n " + Examples.formArrayName);
};
ReactiveErrors.disabledAttrWarning = function () {
console.warn("\n It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true\n when you set up this control in your component class, the disabled attribute will actually be set in the DOM for\n you. We recommend using this approach to avoid 'changed after checked' errors.\n \n Example: \n form = new FormGroup({\n first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),\n last: new FormControl('Drew', Validators.required)\n });\n ");
};
return ReactiveErrors;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __extends$9 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var formControlBinding$1 = {
provide: NgControl,
useExisting: _angular_core.forwardRef(function () { return FormControlDirective; })
};
/**
* @whatItDoes Syncs a standalone {@link FormControl} instance to a form control element.
*
* In other words, this directive ensures that any values written to the {@link FormControl}
* instance programmatically will be written to the DOM element (model -> view). Conversely,
* any values written to the DOM element through user input will be reflected in the
* {@link FormControl} instance (view -> model).
*
* @howToUse
*
* Use this directive if you'd like to create and manage a {@link FormControl} instance directly.
* Simply create a {@link FormControl}, save it to your component class, and pass it into the
* {@link FormControlDirective}.
*
* This directive is designed to be used as a standalone control. Unlike {@link FormControlName},
* it does not require that your {@link FormControl} instance be part of any parent
* {@link FormGroup}, and it won't be registered to any {@link FormGroupDirective} that
* exists above it.
*
* **Get the value**: the `value` property is always synced and available on the
* {@link FormControl} instance. See a full list of available properties in
* {@link AbstractControl}.
*
* **Set the value**: You can pass in an initial value when instantiating the {@link FormControl},
* or you can set it programmatically later using {@link AbstractControl.setValue} or
* {@link AbstractControl.patchValue}.
*
* **Listen to value**: If you want to listen to changes in the value of the control, you can
* subscribe to the {@link AbstractControl.valueChanges} event. You can also listen to
* {@link AbstractControl.statusChanges} to be notified when the validation status is
* re-calculated.
*
* ### Example
*
* {@example forms/ts/simpleFormControl/simple_form_control_example.ts region='Component'}
*
* * **npm package**: `@angular/forms`
*
* * **NgModule**: `ReactiveFormsModule`
*
* @stable
*/
var FormControlDirective = (function (_super) {
__extends$9(FormControlDirective, _super);
function FormControlDirective(validators, asyncValidators, valueAccessors) {
_super.call(this);
this.update = new EventEmitter();
this._rawValidators = validators || [];
this._rawAsyncValidators = asyncValidators || [];
this.valueAccessor = selectValueAccessor(this, valueAccessors);
}
Object.defineProperty(FormControlDirective.prototype, "isDisabled", {
set: function (isDisabled) { ReactiveErrors.disabledAttrWarning(); },
enumerable: true,
configurable: true
});
FormControlDirective.prototype.ngOnChanges = function (changes) {
if (this._isControlChanged(changes)) {
setUpControl(this.form, this);
if (this.control.disabled && this.valueAccessor.setDisabledState) {
this.valueAccessor.setDisabledState(true);
}
this.form.updateValueAndValidity({ emitEvent: false });
}
if (isPropertyUpdated(changes, this.viewModel)) {
this.form.setValue(this.model);
this.viewModel = this.model;
}
};
Object.defineProperty(FormControlDirective.prototype, "path", {
get: function () { return []; },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlDirective.prototype, "validator", {
get: function () { return composeValidators(this._rawValidators); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlDirective.prototype, "asyncValidator", {
get: function () {
return composeAsyncValidators(this._rawAsyncValidators);
},
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlDirective.prototype, "control", {
get: function () { return this.form; },
enumerable: true,
configurable: true
});
FormControlDirective.prototype.viewToModelUpdate = function (newValue) {
this.viewModel = newValue;
this.update.emit(newValue);
};
FormControlDirective.prototype._isControlChanged = function (changes) {
return changes.hasOwnProperty('form');
};
FormControlDirective.decorators = [
{ type: _angular_core.Directive, args: [{ selector: '[formControl]', providers: [formControlBinding$1], exportAs: 'ngForm' },] },
];
/** @nocollapse */
FormControlDirective.ctorParameters = [
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALUE_ACCESSOR,] },] },
];
FormControlDirective.propDecorators = {
'form': [{ type: _angular_core.Input, args: ['formControl',] },],
'model': [{ type: _angular_core.Input, args: ['ngModel',] },],
'update': [{ type: _angular_core.Output, args: ['ngModelChange',] },],
'isDisabled': [{ type: _angular_core.Input, args: ['disabled',] },],
};
return FormControlDirective;
}(NgControl));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __extends$11 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var formDirectiveProvider$1 = {
provide: ControlContainer,
useExisting: _angular_core.forwardRef(function () { return FormGroupDirective; })
};
/**
* @whatItDoes Binds an existing {@link FormGroup} to a DOM element.
*
* @howToUse
*
* This directive accepts an existing {@link FormGroup} instance. It will then use this
* {@link FormGroup} instance to match any child {@link FormControl}, {@link FormGroup},
* and {@link FormArray} instances to child {@link FormControlName}, {@link FormGroupName},
* and {@link FormArrayName} directives.
*
* **Set value**: You can set the form's initial value when instantiating the
* {@link FormGroup}, or you can set it programmatically later using the {@link FormGroup}'s
* {@link AbstractControl.setValue} or {@link AbstractControl.patchValue} methods.
*
* **Listen to value**: If you want to listen to changes in the value of the form, you can subscribe
* to the {@link FormGroup}'s {@link AbstractControl.valueChanges} event. You can also listen to
* its {@link AbstractControl.statusChanges} event to be notified when the validation status is
* re-calculated.
*
* Furthermore, you can listen to the directive's `ngSubmit` event to be notified when the user has
* triggered a form submission. The `ngSubmit` event will be emitted with the original form
* submission event.
*
* ### Example
*
* In this example, we create form controls for first name and last name.
*
* {@example forms/ts/simpleFormGroup/simple_form_group_example.ts region='Component'}
*
* **npm package**: `@angular/forms`
*
* **NgModule**: {@link ReactiveFormsModule}
*
* @stable
*/
var FormGroupDirective = (function (_super) {
__extends$11(FormGroupDirective, _super);
function FormGroupDirective(_validators, _asyncValidators) {
_super.call(this);
this._validators = _validators;
this._asyncValidators = _asyncValidators;
this._submitted = false;
this.directives = [];
this.form = null;
this.ngSubmit = new EventEmitter();
}
FormGroupDirective.prototype.ngOnChanges = function (changes) {
this._checkFormPresent();
if (changes.hasOwnProperty('form')) {
this._updateValidators();
this._updateDomValue();
this._updateRegistrations();
}
};
Object.defineProperty(FormGroupDirective.prototype, "submitted", {
get: function () { return this._submitted; },
enumerable: true,
configurable: true
});
Object.defineProperty(FormGroupDirective.prototype, "formDirective", {
get: function () { return this; },
enumerable: true,
configurable: true
});
Object.defineProperty(FormGroupDirective.prototype, "control", {
get: function () { return this.form; },
enumerable: true,
configurable: true
});
Object.defineProperty(FormGroupDirective.prototype, "path", {
get: function () { return []; },
enumerable: true,
configurable: true
});
FormGroupDirective.prototype.addControl = function (dir) {
var ctrl = this.form.get(dir.path);
setUpControl(ctrl, dir);
ctrl.updateValueAndValidity({ emitEvent: false });
this.directives.push(dir);
return ctrl;
};
FormGroupDirective.prototype.getControl = function (dir) { return this.form.get(dir.path); };
FormGroupDirective.prototype.removeControl = function (dir) { ListWrapper.remove(this.directives, dir); };
FormGroupDirective.prototype.addFormGroup = function (dir) {
var ctrl = this.form.get(dir.path);
setUpFormContainer(ctrl, dir);
ctrl.updateValueAndValidity({ emitEvent: false });
};
FormGroupDirective.prototype.removeFormGroup = function (dir) { };
FormGroupDirective.prototype.getFormGroup = function (dir) { return this.form.get(dir.path); };
FormGroupDirective.prototype.addFormArray = function (dir) {
var ctrl = this.form.get(dir.path);
setUpFormContainer(ctrl, dir);
ctrl.updateValueAndValidity({ emitEvent: false });
};
FormGroupDirective.prototype.removeFormArray = function (dir) { };
FormGroupDirective.prototype.getFormArray = function (dir) { return this.form.get(dir.path); };
FormGroupDirective.prototype.updateModel = function (dir, value) {
var ctrl = this.form.get(dir.path);
ctrl.setValue(value);
};
FormGroupDirective.prototype.onSubmit = function ($event) {
this._submitted = true;
this.ngSubmit.emit($event);
return false;
};
FormGroupDirective.prototype.onReset = function () { this.resetForm(); };
FormGroupDirective.prototype.resetForm = function (value) {
if (value === void 0) { value = undefined; }
this.form.reset(value);
this._submitted = false;
};
/** @internal */
FormGroupDirective.prototype._updateDomValue = function () {
var _this = this;
this.directives.forEach(function (dir) {
var newCtrl = _this.form.get(dir.path);
if (dir._control !== newCtrl) {
cleanUpControl(dir._control, dir);
if (newCtrl)
setUpControl(newCtrl, dir);
dir._control = newCtrl;
}
});
this.form._updateTreeValidity({ emitEvent: false });
};
FormGroupDirective.prototype._updateRegistrations = function () {
var _this = this;
this.form._registerOnCollectionChange(function () { return _this._updateDomValue(); });
if (this._oldForm)
this._oldForm._registerOnCollectionChange(function () { });
this._oldForm = this.form;
};
FormGroupDirective.prototype._updateValidators = function () {
var sync = composeValidators(this._validators);
this.form.validator = Validators.compose([this.form.validator, sync]);
var async = composeAsyncValidators(this._asyncValidators);
this.form.asyncValidator = Validators.composeAsync([this.form.asyncValidator, async]);
};
FormGroupDirective.prototype._checkFormPresent = function () {
if (!this.form) {
ReactiveErrors.missingFormException();
}
};
FormGroupDirective.decorators = [
{ type: _angular_core.Directive, args: [{
selector: '[formGroup]',
providers: [formDirectiveProvider$1],
host: { '(submit)': 'onSubmit($event)', '(reset)': 'onReset()' },
exportAs: 'ngForm'
},] },
];
/** @nocollapse */
FormGroupDirective.ctorParameters = [
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] },
];
FormGroupDirective.propDecorators = {
'form': [{ type: _angular_core.Input, args: ['formGroup',] },],
'ngSubmit': [{ type: _angular_core.Output },],
};
return FormGroupDirective;
}(ControlContainer));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __extends$12 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var formGroupNameProvider = {
provide: ControlContainer,
useExisting: _angular_core.forwardRef(function () { return FormGroupName; })
};
/**
* @whatItDoes Syncs a nested {@link FormGroup} to a DOM element.
*
* @howToUse
*
* This directive can only be used with a parent {@link FormGroupDirective} (selector:
* `[formGroup]`).
*
* It accepts the string name of the nested {@link FormGroup} you want to link, and
* will look for a {@link FormGroup} registered with that name in the parent
* {@link FormGroup} instance you passed into {@link FormGroupDirective}.
*
* Nested form groups can come in handy when you want to validate a sub-group of a
* form separately from the rest or when you'd like to group the values of certain
* controls into their own nested object.
*
* **Access the group**: You can access the associated {@link FormGroup} using the
* {@link AbstractControl.get} method. Ex: `this.form.get('name')`.
*
* You can also access individual controls within the group using dot syntax.
* Ex: `this.form.get('name.first')`
*
* **Get the value**: the `value` property is always synced and available on the
* {@link FormGroup}. See a full list of available properties in {@link AbstractControl}.
*
* **Set the value**: You can set an initial value for each child control when instantiating
* the {@link FormGroup}, or you can set it programmatically later using
* {@link AbstractControl.setValue} or {@link AbstractControl.patchValue}.
*
* **Listen to value**: If you want to listen to changes in the value of the group, you can
* subscribe to the {@link AbstractControl.valueChanges} event. You can also listen to
* {@link AbstractControl.statusChanges} to be notified when the validation status is
* re-calculated.
*
* ### Example
*
* {@example forms/ts/nestedFormGroup/nested_form_group_example.ts region='Component'}
*
* * **npm package**: `@angular/forms`
*
* * **NgModule**: `ReactiveFormsModule`
*
* @stable
*/
var FormGroupName = (function (_super) {
__extends$12(FormGroupName, _super);
function FormGroupName(parent, validators, asyncValidators) {
_super.call(this);
this._parent = parent;
this._validators = validators;
this._asyncValidators = asyncValidators;
}
/** @internal */
FormGroupName.prototype._checkParentType = function () {
if (_hasInvalidParent(this._parent)) {
ReactiveErrors.groupParentException();
}
};
FormGroupName.decorators = [
{ type: _angular_core.Directive, args: [{ selector: '[formGroupName]', providers: [formGroupNameProvider] },] },
];
/** @nocollapse */
FormGroupName.ctorParameters = [
{ type: ControlContainer, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Host }, { type: _angular_core.SkipSelf },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] },
];
FormGroupName.propDecorators = {
'name': [{ type: _angular_core.Input, args: ['formGroupName',] },],
};
return FormGroupName;
}(AbstractFormGroupDirective));
var formArrayNameProvider = {
provide: ControlContainer,
useExisting: _angular_core.forwardRef(function () { return FormArrayName; })
};
/**
* @whatItDoes Syncs a nested {@link FormArray} to a DOM element.
*
* @howToUse
*
* This directive is designed to be used with a parent {@link FormGroupDirective} (selector:
* `[formGroup]`).
*
* It accepts the string name of the nested {@link FormArray} you want to link, and
* will look for a {@link FormArray} registered with that name in the parent
* {@link FormGroup} instance you passed into {@link FormGroupDirective}.
*
* Nested form arrays can come in handy when you have a group of form controls but
* you're not sure how many there will be. Form arrays allow you to create new
* form controls dynamically.
*
* **Access the array**: You can access the associated {@link FormArray} using the
* {@link AbstractControl.get} method on the parent {@link FormGroup}.
* Ex: `this.form.get('cities')`.
*
* **Get the value**: the `value` property is always synced and available on the
* {@link FormArray}. See a full list of available properties in {@link AbstractControl}.
*
* **Set the value**: You can set an initial value for each child control when instantiating
* the {@link FormArray}, or you can set the value programmatically later using the
* {@link FormArray}'s {@link AbstractControl.setValue} or {@link AbstractControl.patchValue}
* methods.
*
* **Listen to value**: If you want to listen to changes in the value of the array, you can
* subscribe to the {@link FormArray}'s {@link AbstractControl.valueChanges} event. You can also
* listen to its {@link AbstractControl.statusChanges} event to be notified when the validation
* status is re-calculated.
*
* **Add new controls**: You can add new controls to the {@link FormArray} dynamically by
* calling its {@link FormArray.push} method.
* Ex: `this.form.get('cities').push(new FormControl());`
*
* ### Example
*
* {@example forms/ts/nestedFormArray/nested_form_array_example.ts region='Component'}
*
* * **npm package**: `@angular/forms`
*
* * **NgModule**: `ReactiveFormsModule`
*
* @stable
*/
var FormArrayName = (function (_super) {
__extends$12(FormArrayName, _super);
function FormArrayName(parent, validators, asyncValidators) {
_super.call(this);
this._parent = parent;
this._validators = validators;
this._asyncValidators = asyncValidators;
}
FormArrayName.prototype.ngOnInit = function () {
this._checkParentType();
this.formDirective.addFormArray(this);
};
FormArrayName.prototype.ngOnDestroy = function () {
if (this.formDirective) {
this.formDirective.removeFormArray(this);
}
};
Object.defineProperty(FormArrayName.prototype, "control", {
get: function () { return this.formDirective.getFormArray(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormArrayName.prototype, "formDirective", {
get: function () {
return this._parent ? this._parent.formDirective : null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FormArrayName.prototype, "path", {
get: function () { return controlPath(this.name, this._parent); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormArrayName.prototype, "validator", {
get: function () { return composeValidators(this._validators); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormArrayName.prototype, "asyncValidator", {
get: function () { return composeAsyncValidators(this._asyncValidators); },
enumerable: true,
configurable: true
});
FormArrayName.prototype._checkParentType = function () {
if (_hasInvalidParent(this._parent)) {
ReactiveErrors.arrayParentException();
}
};
FormArrayName.decorators = [
{ type: _angular_core.Directive, args: [{ selector: '[formArrayName]', providers: [formArrayNameProvider] },] },
];
/** @nocollapse */
FormArrayName.ctorParameters = [
{ type: ControlContainer, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Host }, { type: _angular_core.SkipSelf },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] },
];
FormArrayName.propDecorators = {
'name': [{ type: _angular_core.Input, args: ['formArrayName',] },],
};
return FormArrayName;
}(ControlContainer));
function _hasInvalidParent(parent) {
return !(parent instanceof FormGroupName) && !(parent instanceof FormGroupDirective) &&
!(parent instanceof FormArrayName);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __extends$10 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var controlNameBinding = {
provide: NgControl,
useExisting: _angular_core.forwardRef(function () { return FormControlName; })
};
/**
* @whatItDoes Syncs a {@link FormControl} in an existing {@link FormGroup} to a form control
* element by name.
*
* In other words, this directive ensures that any values written to the {@link FormControl}
* instance programmatically will be written to the DOM element (model -> view). Conversely,
* any values written to the DOM element through user input will be reflected in the
* {@link FormControl} instance (view -> model).
*
* @howToUse
*
* This directive is designed to be used with a parent {@link FormGroupDirective} (selector:
* `[formGroup]`).
*
* It accepts the string name of the {@link FormControl} instance you want to
* link, and will look for a {@link FormControl} registered with that name in the
* closest {@link FormGroup} or {@link FormArray} above it.
*
* **Access the control**: You can access the {@link FormControl} associated with
* this directive by using the {@link AbstractControl.get} method.
* Ex: `this.form.get('first');`
*
* **Get value**: the `value` property is always synced and available on the {@link FormControl}.
* See a full list of available properties in {@link AbstractControl}.
*
* **Set value**: You can set an initial value for the control when instantiating the
* {@link FormControl}, or you can set it programmatically later using
* {@link AbstractControl.setValue} or {@link AbstractControl.patchValue}.
*
* **Listen to value**: If you want to listen to changes in the value of the control, you can
* subscribe to the {@link AbstractControl.valueChanges} event. You can also listen to
* {@link AbstractControl.statusChanges} to be notified when the validation status is
* re-calculated.
*
* ### Example
*
* In this example, we create form controls for first name and last name.
*
* {@example forms/ts/simpleFormGroup/simple_form_group_example.ts region='Component'}
*
* To see `formControlName` examples with different form control types, see:
*
* * Radio buttons: {@link RadioControlValueAccessor}
* * Selects: {@link SelectControlValueAccessor}
*
* **npm package**: `@angular/forms`
*
* **NgModule**: {@link ReactiveFormsModule}
*
* @stable
*/
var FormControlName = (function (_super) {
__extends$10(FormControlName, _super);
function FormControlName(parent, validators, asyncValidators, valueAccessors) {
_super.call(this);
this._added = false;
this.update = new EventEmitter();
this._parent = parent;
this._rawValidators = validators || [];
this._rawAsyncValidators = asyncValidators || [];
this.valueAccessor = selectValueAccessor(this, valueAccessors);
}
Object.defineProperty(FormControlName.prototype, "isDisabled", {
set: function (isDisabled) { ReactiveErrors.disabledAttrWarning(); },
enumerable: true,
configurable: true
});
FormControlName.prototype.ngOnChanges = function (changes) {
if (!this._added)
this._setUpControl();
if (isPropertyUpdated(changes, this.viewModel)) {
this.viewModel = this.model;
this.formDirective.updateModel(this, this.model);
}
};
FormControlName.prototype.ngOnDestroy = function () {
if (this.formDirective) {
this.formDirective.removeControl(this);
}
};
FormControlName.prototype.viewToModelUpdate = function (newValue) {
this.viewModel = newValue;
this.update.emit(newValue);
};
Object.defineProperty(FormControlName.prototype, "path", {
get: function () { return controlPath(this.name, this._parent); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlName.prototype, "formDirective", {
get: function () { return this._parent ? this._parent.formDirective : null; },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlName.prototype, "validator", {
get: function () { return composeValidators(this._rawValidators); },
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlName.prototype, "asyncValidator", {
get: function () {
return composeAsyncValidators(this._rawAsyncValidators);
},
enumerable: true,
configurable: true
});
Object.defineProperty(FormControlName.prototype, "control", {
get: function () { return this._control; },
enumerable: true,
configurable: true
});
FormControlName.prototype._checkParentType = function () {
if (!(this._parent instanceof FormGroupName) &&
this._parent instanceof AbstractFormGroupDirective) {
ReactiveErrors.ngModelGroupException();
}
else if (!(this._parent instanceof FormGroupName) && !(this._parent instanceof FormGroupDirective) &&
!(this._parent instanceof FormArrayName)) {
ReactiveErrors.controlParentException();
}
};
FormControlName.prototype._setUpControl = function () {
this._checkParentType();
this._control = this.formDirective.addControl(this);
if (this.control.disabled && this.valueAccessor.setDisabledState) {
this.valueAccessor.setDisabledState(true);
}
this._added = true;
};
FormControlName.decorators = [
{ type: _angular_core.Directive, args: [{ selector: '[formControlName]', providers: [controlNameBinding] },] },
];
/** @nocollapse */
FormControlName.ctorParameters = [
{ type: ControlContainer, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Host }, { type: _angular_core.SkipSelf },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] },
{ type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALUE_ACCESSOR,] },] },
];
FormControlName.propDecorators = {
'name': [{ type: _angular_core.Input, args: ['formControlName',] },],
'model': [{ type: _angular_core.Input, args: ['ngModel',] },],
'update': [{ type: _angular_core.Output, args: ['ngModelChange',] },],
'isDisabled': [{ type: _angular_core.Input, args: ['disabled',] },],
};
return FormControlName;
}(NgControl));
var REQUIRED_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: _angular_core.forwardRef(function () { return RequiredValidator; }),
multi: true
};
/**
* A Directive that adds the `required` validator to any controls marked with the
* `required` attribute, via the {@link NG_VALIDATORS} binding.
*
* ### Example
*
* ```
* <input name="fullName" ngModel required>
* ```
*
* @stable
*/
var RequiredValidator = (function () {
function RequiredValidator() {
}
Object.defineProperty(RequiredValidator.prototype, "required", {
get: function () { return this._required; },
set: function (value) {
this._required = value != null && value !== false && "" + value !== 'false';
if (this._onChange)
this._onChange();
},
enumerable: true,
configurable: true
});
RequiredValidator.prototype.validate = function (c) {
return this.required ? Validators.required(c) : null;
};
RequiredValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; };
RequiredValidator.decorators = [
{ type: _angular_core.Directive, args: [{
selector: '[required][formControlName],[required][formControl],[required][ngModel]',
providers: [REQUIRED_VALIDATOR],
host: { '[attr.required]': 'required ? "" : null' }
},] },
];
/** @nocollapse */
RequiredValidator.ctorParameters = [];
RequiredValidator.propDecorators = {
'required': [{ type: _angular_core.Input },],
};
return RequiredValidator;
}());
/**
* Provider which adds {@link MinLengthValidator} to {@link NG_VALIDATORS}.
*
* ## Example:
*
* {@example common/forms/ts/validators/validators.ts region='min'}
*/
var MIN_LENGTH_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: _angular_core.forwardRef(function () { return MinLengthValidator; }),
multi: true
};
/**
* A directive which installs the {@link MinLengthValidator} for any `formControlName`,
* `formControl`, or control with `ngModel` that also has a `minlength` attribute.
*
* @stable
*/
var MinLengthValidator = (function () {
function MinLengthValidator() {
}
MinLengthValidator.prototype.ngOnChanges = function (changes) {
if ('minlength' in changes) {
this._createValidator();
if (this._onChange)
this._onChange();
}
};
MinLengthValidator.prototype.validate = function (c) {
return this.minlength == null ? null : this._validator(c);
};
MinLengthValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; };
MinLengthValidator.prototype._createValidator = function () {
this._validator = Validators.minLength(parseInt(this.minlength, 10));
};
MinLengthValidator.decorators = [
{ type: _angular_core.Directive, args: [{
selector: '[minlength][formControlName],[minlength][formControl],[minlength][ngModel]',
providers: [MIN_LENGTH_VALIDATOR],
host: { '[attr.minlength]': 'minlength ? minlength : null' }
},] },
];
/** @nocollapse */
MinLengthValidator.ctorParameters = [];
MinLengthValidator.propDecorators = {
'minlength': [{ type: _angular_core.Input },],
};
return MinLengthValidator;
}());
/**
* Provider which adds {@link MaxLengthValidator} to {@link NG_VALIDATORS}.
*
* ## Example:
*
* {@example common/forms/ts/validators/validators.ts region='max'}
*/
var MAX_LENGTH_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: _angular_core.forwardRef(function () { return MaxLengthValidator; }),
multi: true
};
/**
* A directive which installs the {@link MaxLengthValidator} for any `formControlName,
* `formControl`,
* or control with `ngModel` that also has a `maxlength` attribute.
*
* @stable
*/
var MaxLengthValidator = (function () {
function MaxLengthValidator() {
}
MaxLengthValidator.prototype.ngOnChanges = function (changes) {
if ('maxlength' in changes) {
this._createValidator();
if (this._onChange)
this._onChange();
}
};
MaxLengthValidator.prototype.validate = function (c) {
return this.maxlength != null ? this._validator(c) : null;
};
MaxLengthValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; };
MaxLengthValidator.prototype._createValidator = function () {
this._validator = Validators.maxLength(parseInt(this.maxlength, 10));
};
MaxLengthValidator.decorators = [
{ type: _angular_core.Directive, args: [{
selector: '[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]',
providers: [MAX_LENGTH_VALIDATOR],
host: { '[attr.maxlength]': 'maxlength ? maxlength : null' }
},] },
];
/** @nocollapse */
MaxLengthValidator.ctorParameters = [];
MaxLengthValidator.propDecorators = {
'maxlength': [{ type: _angular_core.Input },],
};
return MaxLengthValidator;
}());
var PATTERN_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: _angular_core.forwardRef(function () { return PatternValidator; }),
multi: true
};
/**
* A Directive that adds the `pattern` validator to any controls marked with the
* `pattern` attribute, via the {@link NG_VALIDATORS} binding. Uses attribute value
* as the regex to validate Control value against. Follows pattern attribute
* semantics; i.e. regex must match entire Control value.
*
* ### Example
*
* ```
* <input [name]="fullName" pattern="[a-zA-Z ]*" ngModel>
* ```
* @stable
*/
var PatternValidator = (function () {
function PatternValidator() {
}
PatternValidator.prototype.ngOnChanges = function (changes) {
if ('pattern' in changes) {
this._createValidator();
if (this._onChange)
this._onChange();
}
};
PatternValidator.prototype.validate = function (c) { return this._validator(c); };
PatternValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; };
PatternValidator.prototype._createValidator = function () { this._validator = Validators.pattern(this.pattern); };
PatternValidator.decorators = [
{ type: _angular_core.Directive, args: [{
selector: '[pattern][formControlName],[pattern][formControl],[pattern][ngModel]',
providers: [PATTERN_VALIDATOR],
host: { '[attr.pattern]': 'pattern ? pattern : null' }
},] },
];
/** @nocollapse */
PatternValidator.ctorParameters = [];
PatternValidator.propDecorators = {
'pattern': [{ type: _angular_core.Input },],
};
return PatternValidator;
}());
/**
* @whatItDoes Creates an {@link AbstractControl} from a user-specified configuration.
*
* It is essentially syntactic sugar that shortens the `new FormGroup()`,
* `new FormControl()`, and `new FormArray()` boilerplate that can build up in larger
* forms.
*
* @howToUse
*
* To use, inject `FormBuilder` into your component class. You can then call its methods
* directly.
*
* {@example forms/ts/formBuilder/form_builder_example.ts region='Component'}
*
* * **npm package**: `@angular/forms`
*
* * **NgModule**: {@link ReactiveFormsModule}
*
* @stable
*/
var FormBuilder = (function () {
function FormBuilder() {
}
/**
* Construct a new {@link FormGroup} with the given map of configuration.
* Valid keys for the `extra` parameter map are `validator` and `asyncValidator`.
*
* See the {@link FormGroup} constructor for more details.
*/
FormBuilder.prototype.group = function (controlsConfig, extra) {
if (extra === void 0) { extra = null; }
var controls = this._reduceControls(controlsConfig);
var validator = isPresent(extra) ? extra['validator'] : null;
var asyncValidator = isPresent(extra) ? extra['asyncValidator'] : null;
return new FormGroup(controls, validator, asyncValidator);
};
/**
* Construct a new {@link FormControl} with the given `formState`,`validator`, and
* `asyncValidator`.
*
* `formState` can either be a standalone value for the form control or an object
* that contains both a value and a disabled status.
*
*/
FormBuilder.prototype.control = function (formState, validator, asyncValidator) {
if (validator === void 0) { validator = null; }
if (asyncValidator === void 0) { asyncValidator = null; }
return new FormControl(formState, validator, asyncValidator);
};
/**
* Construct a {@link FormArray} from the given `controlsConfig` array of
* configuration, with the given optional `validator` and `asyncValidator`.
*/
FormBuilder.prototype.array = function (controlsConfig, validator, asyncValidator) {
var _this = this;
if (validator === void 0) { validator = null; }
if (asyncValidator === void 0) { asyncValidator = null; }
var controls = controlsConfig.map(function (c) { return _this._createControl(c); });
return new FormArray(controls, validator, asyncValidator);
};
/** @internal */
FormBuilder.prototype._reduceControls = function (controlsConfig) {
var _this = this;
var controls = {};
Object.keys(controlsConfig).forEach(function (controlName) {
controls[controlName] = _this._createControl(controlsConfig[controlName]);
});
return controls;
};
/** @internal */
FormBuilder.prototype._createControl = function (controlConfig) {
if (controlConfig instanceof FormControl || controlConfig instanceof FormGroup ||
controlConfig instanceof FormArray) {
return controlConfig;
}
else if (Array.isArray(controlConfig)) {
var value = controlConfig[0];
var validator = controlConfig.length > 1 ? controlConfig[1] : null;
var asyncValidator = controlConfig.length > 2 ? controlConfig[2] : null;
return this.control(value, validator, asyncValidator);
}
else {
return this.control(controlConfig);
}
};
FormBuilder.decorators = [
{ type: _angular_core.Injectable },
];
/** @nocollapse */
FormBuilder.ctorParameters = [];
return FormBuilder;
}());
var SHARED_FORM_DIRECTIVES = [
NgSelectOption, NgSelectMultipleOption, DefaultValueAccessor, NumberValueAccessor,
RangeValueAccessor, CheckboxControlValueAccessor, SelectControlValueAccessor,
SelectMultipleControlValueAccessor, RadioControlValueAccessor, NgControlStatus,
NgControlStatusGroup, RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator
];
var TEMPLATE_DRIVEN_DIRECTIVES = [NgModel, NgModelGroup, NgForm];
var REACTIVE_DRIVEN_DIRECTIVES = [FormControlDirective, FormGroupDirective, FormControlName, FormGroupName, FormArrayName];
/**
* Internal module used for sharing directives between FormsModule and ReactiveFormsModule
*/
var InternalFormsSharedModule = (function () {
function InternalFormsSharedModule() {
}
InternalFormsSharedModule.decorators = [
{ type: _angular_core.NgModule, args: [{
declarations: SHARED_FORM_DIRECTIVES,
exports: SHARED_FORM_DIRECTIVES,
},] },
];
/** @nocollapse */
InternalFormsSharedModule.ctorParameters = [];
return InternalFormsSharedModule;
}());
/**
* The ng module for forms.
* @stable
*/
var FormsModule = (function () {
function FormsModule() {
}
FormsModule.decorators = [
{ type: _angular_core.NgModule, args: [{
declarations: TEMPLATE_DRIVEN_DIRECTIVES,
providers: [RadioControlRegistry],
exports: [InternalFormsSharedModule, TEMPLATE_DRIVEN_DIRECTIVES]
},] },
];
/** @nocollapse */
FormsModule.ctorParameters = [];
return FormsModule;
}());
/**
* The ng module for reactive forms.
* @stable
*/
var ReactiveFormsModule = (function () {
function ReactiveFormsModule() {
}
ReactiveFormsModule.decorators = [
{ type: _angular_core.NgModule, args: [{
declarations: [REACTIVE_DRIVEN_DIRECTIVES],
providers: [FormBuilder, RadioControlRegistry],
exports: [InternalFormsSharedModule, REACTIVE_DRIVEN_DIRECTIVES]
},] },
];
/** @nocollapse */
ReactiveFormsModule.ctorParameters = [];
return ReactiveFormsModule;
}());
exports.AbstractControlDirective = AbstractControlDirective;
exports.AbstractFormGroupDirective = AbstractFormGroupDirective;
exports.CheckboxControlValueAccessor = CheckboxControlValueAccessor;
exports.ControlContainer = ControlContainer;
exports.NG_VALUE_ACCESSOR = NG_VALUE_ACCESSOR;
exports.DefaultValueAccessor = DefaultValueAccessor;
exports.NgControl = NgControl;
exports.NgControlStatus = NgControlStatus;
exports.NgControlStatusGroup = NgControlStatusGroup;
exports.NgForm = NgForm;
exports.NgModel = NgModel;
exports.NgModelGroup = NgModelGroup;
exports.RadioControlValueAccessor = RadioControlValueAccessor;
exports.FormControlDirective = FormControlDirective;
exports.FormControlName = FormControlName;
exports.FormGroupDirective = FormGroupDirective;
exports.FormArrayName = FormArrayName;
exports.FormGroupName = FormGroupName;
exports.NgSelectOption = NgSelectOption;
exports.SelectControlValueAccessor = SelectControlValueAccessor;
exports.SelectMultipleControlValueAccessor = SelectMultipleControlValueAccessor;
exports.MaxLengthValidator = MaxLengthValidator;
exports.MinLengthValidator = MinLengthValidator;
exports.PatternValidator = PatternValidator;
exports.RequiredValidator = RequiredValidator;
exports.FormBuilder = FormBuilder;
exports.AbstractControl = AbstractControl;
exports.FormArray = FormArray;
exports.FormControl = FormControl;
exports.FormGroup = FormGroup;
exports.NG_ASYNC_VALIDATORS = NG_ASYNC_VALIDATORS;
exports.NG_VALIDATORS = NG_VALIDATORS;
exports.Validators = Validators;
exports.FormsModule = FormsModule;
exports.ReactiveFormsModule = ReactiveFormsModule;
})); |
/*
* @flow
* @lint-ignore-every LINEWRAP1
*/
import {suite, test} from 'flow-dev-tools/src/test/Tester';
export default suite(({addFile, addFiles, addCode}) => [
test('Requiring a .css file', [
addFile('foo.css')
.addCode("import './foo.css'")
.noNewErrors(),
]),
test('.css extension cannot be omitted', [
addFile('foo.css')
.addCode("import './foo'")
.newErrors(
`
test.js:3
3: import './foo'
^^^^^^^ Cannot resolve module \`./foo\`.
`,
),
]),
test('By default, .css files export the Object type', [
addFile('foo.css')
.addCode("const css = require('./foo.css');")
.addCode("(css: string)")
.newErrors(
`
test.js:5
5: (css: string)
^^^ Cannot cast \`css\` to string because object type [1] is incompatible with string [2].
References:
3: const css = require('./foo.css');
^^^^^^^^^^^ [1]
5: (css: string)
^^^^^^ [2]
`,
),
]),
test('Typical use of a .css file', [
addFile('foo.css')
.addCode("import { active, hovered } from './foo.css';")
.addCode("(active: string);")
.addCode("(hovered: number);")
.noNewErrors()
.because("active and hovered have the type any"),
]),
test('Requiring a .png file', [
addFile('bar.png')
.addCode("import './bar.png'")
.noNewErrors(),
]),
test('.png extension cannot be omitted', [
addFile('bar.png')
.addCode("import './bar'")
.newErrors(
`
test.js:3
3: import './bar'
^^^^^^^ Cannot resolve module \`./bar\`.
`,
),
]),
test('By default, .png files export the string type', [
addFile('bar.png')
.addCode("const png = require('./bar.png');")
.addCode("(png: number)")
.newErrors(
`
test.js:5
5: (png: number)
^^^ Cannot cast \`png\` to number because string [1] is incompatible with number [2].
References:
3: const png = require('./bar.png');
^^^^^^^^^^^ [1]
5: (png: number)
^^^^^^ [2]
`,
),
]),
test('module.name_mapper should still work', [
addFiles('foo.css', 'cssMock.js')
.addCode('const css = require("./foo.css");')
.addCode('(css: string)')
.newErrors(
`
test.js:5
5: (css: string)
^^^ Cannot cast \`css\` to string because boolean [1] is incompatible with string [2].
References:
2: declare module.exports: boolean;
^^^^^^^ [1]. See: cssMock.js:2
5: (css: string)
^^^^^^ [2]
`,
),
]).flowConfig('_flowconfig_with_module_name_mapper'),
]);
|
application.setInterface({
process : function(input, code, cb) {
var result = {
output: null,
error: null
};
try {
eval('method = '+code);
eval('data = '+ input);
result.output = method(data);
} catch(e) {
result.error = e.message;
}
cb(result);
}
});
|
/* global define */
define([
'can/util/library',
'can/component',
'../models/Todo',
'can/route'
], function (can, Component, Todo, route) {
'use strict';
var ESCAPE_KEY = 27;
return Component.extend({
// Create this component on a tag like `<todo-app>`
tag: 'todo-app',
scope: {
// Store the Todo model in the scope
Todo: Todo,
// A list of all Todos retrieved from LocalStorage
todos: new Todo.List({}),
// Edit a Todo
edit: function (todo, el) {
todo.attr('editing', true);
el.parents('.todo').find('.edit').focus();
},
cancelEditing: function (todo, el, e) {
if (e.which === ESCAPE_KEY) {
el.val(todo.attr('text'));
todo.attr('editing', false);
}
},
// Returns a list of Todos filtered based on the route
displayList: function () {
var filter = route.attr('filter');
return this.todos.filter(function (todo) {
if (filter === 'completed') {
return todo.attr('complete');
}
if (filter === 'active') {
return !todo.attr('complete');
}
return true;
});
},
updateTodo: function (todo, el) {
var value = can.trim(el.val());
if (value === '') {
todo.destroy();
} else {
todo.attr({
editing: false,
text: value
});
}
},
createTodo: function (context, el) {
var value = can.trim(el.val());
var TodoModel = this.Todo;
if (value !== '') {
new TodoModel({
text: value,
complete: false
}).save();
route.removeAttr('filter');
el.val('');
}
},
toggleAll: function (scope, el) {
var toggle = el.prop('checked');
this.attr('todos').each(function (todo) {
todo.attr('complete', toggle);
});
},
clearCompleted: function () {
this.attr('todos').completed().forEach(function (todo) {
todo.destroy();
});
}
},
events: {
// When a new Todo has been created, add it to the todo list
'{Todo} created': function (Construct, ev, todo) {
this.scope.attr('todos').push(todo);
}
},
helpers: {
link: function (name, filter) {
var data = filter ? { filter: filter } : {};
return route.link(name, data, {
className: route.attr('filter') === filter ? 'selected' : ''
});
},
plural: function (singular, num) {
return num() === 1 ? singular : singular + 's';
}
}
});
});
|
(function(punymce) {
punymce.plugins.TextColor = function(ed) {
var colors = '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,008000,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF';
var DOM = punymce.DOM, Event = punymce.Event, each = punymce.each, extend = punymce.extend, s;
if (!ed.settings.textcolor || ed.settings.textcolor.skip_css)
DOM.loadCSS(punymce.baseURL + '/plugins/textcolor/css/editor.css');
s = extend({
colors : colors
}, ed.settings.textcolor);
extend(ed.commands, {
mceColor : function(u, v, e) {
var n, t = this, id = ed.settings.id, p = DOM.getPos(e.target), co, cb;
if (ed.hideMenu)
return ed.hideMenu();
function hide(e) {
ed.hideMenu = null;
Event.remove(document, 'click', hide);
Event.remove(ed.getDoc(), 'click', hide);
DOM.get(id + '_mcolor').style.display = 'none';
return 1;
};
n = DOM.get(id + '_mcolor');
if (!n) {
n = DOM.get(id + '_t');
n = DOM.add(document.body, 'div', {id : id + '_mcolor', 'class' : 'punymce_color punymce'});
n = DOM.add(n, 'table', {'class' : 'punymce'});
n = DOM.add(n, 'tbody');
co = 8;
each(s.colors.split(','), function(c) {
if (co == 8) {
r = DOM.add(n, 'tr');
co = 0;
}
co++;
Event.add(DOM.add(DOM.add(r, 'td'), 'a', {href : '#', style : 'background:#' + c}), 'mousedown', function(e) {
hide.call(t);
ed.execCommand('forecolor', 0, '#' + c);
return Event.cancel(e);
});
});
}
Event.add(document, 'click', hide, t);
Event.add(ed.getDoc(), 'click', hide, t);
ed.hideMenu = hide;
s = DOM.get(id + '_mcolor').style;
s.left = p.x + 'px';
s.top = (p.y + e.target.clientHeight + 2) + 'px';
s.display = 'block';
}
});
extend(ed.tools, {
textcolor : {cmd : 'mceColor', title : punymce.I18n.textcolor}
});
};
// English i18n strings
punymce.extend(punymce.I18n, {
textcolor : 'Text color'
});
})(punymce);
|
// This file is part of Indico.
// Copyright (C) 2002 - 2021 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.
import fetchConfigURL from 'indico-url:rb.config';
import {indicoAxios} from 'indico/utils/axios';
import {ajaxAction} from 'indico/utils/redux';
export const FETCH_REQUEST = 'config/FETCH_REQUEST';
export const FETCH_SUCCESS = 'config/FETCH_SUCCESS';
export const FETCH_ERROR = 'config/FETCH_ERROR';
export const CONFIG_RECEIVED = 'config/CONFIG_RECEIVED';
export const SET_ROOMS_SPRITE_TOKEN = 'config/SET_ROOMS_SPRITE_TOKEN';
export function fetchConfig() {
return ajaxAction(
() => indicoAxios.get(fetchConfigURL()),
FETCH_REQUEST,
[CONFIG_RECEIVED, FETCH_SUCCESS],
[FETCH_ERROR]
);
}
export function setRoomsSpriteToken(token) {
return {
type: SET_ROOMS_SPRITE_TOKEN,
token,
};
}
|
/*
Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
|
module.exports = function(app) {
app.factory('Resource', ['$http', 'handleError', function($http, handleError) {
var Resource = function(resourceArr, errArr, baseUrl, options) {
if (!this instanceof Resource) {
return new Resource.apply(null, arguments); // eslint-disable-line
}
this.data = resourceArr;
this.url = baseUrl;
this.errors = errArr;
this.options = options || {};
this.options.errMessages = this.options.errMessages || {};
};
Resource.prototype.getAll = function() {
return $http.get(this.url)
.then((res) => {
this.data.splice(0);
for (var i = 0; i < res.data.length; i++) {
this.data.push(res.data[i]);
}
}, handleError(this.errors, this.options.errMessages.getAll || 'could not GET resource'));
};
Resource.prototype.create = function(resource) {
return $http.post(this.url, resource)
.then((res) => {
this.data.push(res.data);
}, handleError(this.errors, this.options.errMessages.create || 'could not POST resource'));
};
Resource.prototype.update = function(resource) {
return $http.put(this.url + '/' + resource._id, resource)
.catch(handleError(this.errors, this.options.errMessages.update ||
'could not UPDATE resource'));
};
Resource.prototype.remove = function(resource) {
return $http.delete(this.url + '/' + resource._id)
.then(() => {
this.data.splice(this.data.indexOf(resource), 1);
}, handleError(this.errors, this.options.errMessages.remove ||
'could not DELETE resource'));
};
return Resource;
}]);
};
|
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.modalClasses = void 0;
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _unstyled = require("@material-ui/unstyled");
var _utils = require("@material-ui/utils");
var _ModalUnstyled = _interopRequireWildcard(require("@material-ui/unstyled/ModalUnstyled"));
var _experimentalStyled = _interopRequireDefault(require("../styles/experimentalStyled"));
var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps"));
var _Backdrop = _interopRequireDefault(require("../Backdrop"));
var _jsxRuntime = require("react/jsx-runtime");
const modalClasses = _ModalUnstyled.modalUnstyledClasses;
exports.modalClasses = modalClasses;
const overridesResolver = (props, styles) => {
const {
styleProps
} = props;
return (0, _utils.deepmerge)((0, _extends2.default)({}, !styleProps.open && styleProps.exited && styles.hidden), styles.root || {});
};
const extendUtilityClasses = styleProps => {
return styleProps.classes;
};
const ModalRoot = (0, _experimentalStyled.default)('div', {}, {
name: 'MuiModal',
slot: 'Root',
overridesResolver
})(({
theme,
styleProps
}) => (0, _extends2.default)({
/* Styles applied to the root element. */
position: 'fixed',
zIndex: theme.zIndex.modal,
right: 0,
bottom: 0,
top: 0,
left: 0
}, !styleProps.open && styleProps.exited && {
visibility: 'hidden'
}));
/**
* Modal is a lower-level construct that is leveraged by the following components:
*
* - [Dialog](/api/dialog/)
* - [Drawer](/api/drawer/)
* - [Menu](/api/menu/)
* - [Popover](/api/popover/)
*
* If you are creating a modal dialog, you probably want to use the [Dialog](/api/dialog/) component
* rather than directly using Modal.
*
* This component shares many concepts with [react-overlays](https://react-bootstrap.github.io/react-overlays/#modals).
*/
const Modal = /*#__PURE__*/React.forwardRef(function Modal(inProps, ref) {
var _componentsProps$root;
const props = (0, _useThemeProps.default)({
name: 'MuiModal',
props: inProps
});
const {
BackdropComponent = _Backdrop.default,
closeAfterTransition = false,
children,
components = {},
componentsProps = {},
disableAutoFocus = false,
disableEnforceFocus = false,
disableEscapeKeyDown = false,
disablePortal = false,
disableRestoreFocus = false,
disableScrollLock = false,
hideBackdrop = false,
keepMounted = false
} = props,
other = (0, _objectWithoutPropertiesLoose2.default)(props, ["BackdropComponent", "closeAfterTransition", "children", "components", "componentsProps", "disableAutoFocus", "disableEnforceFocus", "disableEscapeKeyDown", "disablePortal", "disableRestoreFocus", "disableScrollLock", "hideBackdrop", "keepMounted"]);
const [exited, setExited] = React.useState(true);
const commonProps = {
closeAfterTransition,
disableAutoFocus,
disableEnforceFocus,
disableEscapeKeyDown,
disablePortal,
disableRestoreFocus,
disableScrollLock,
hideBackdrop,
keepMounted
};
const styleProps = (0, _extends2.default)({}, props, commonProps, {
exited
});
const classes = extendUtilityClasses(styleProps);
return /*#__PURE__*/(0, _jsxRuntime.jsx)(_ModalUnstyled.default, (0, _extends2.default)({
components: (0, _extends2.default)({
Root: ModalRoot
}, components),
componentsProps: {
root: (0, _extends2.default)({}, componentsProps.root, (!components.Root || !(0, _unstyled.isHostComponent)(components.Root)) && {
styleProps: (0, _extends2.default)({}, (_componentsProps$root = componentsProps.root) === null || _componentsProps$root === void 0 ? void 0 : _componentsProps$root.styleProps)
})
},
BackdropComponent: BackdropComponent,
onTransitionEnter: () => setExited(false),
onTransitionExited: () => setExited(true),
ref: ref
}, other, {
classes: classes
}, commonProps, {
children: children
}));
});
process.env.NODE_ENV !== "production" ? Modal.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* A backdrop component. This prop enables custom backdrop rendering.
* @default Backdrop
*/
BackdropComponent: _propTypes.default.elementType,
/**
* Props applied to the [`Backdrop`](/api/backdrop/) element.
*/
BackdropProps: _propTypes.default.object,
/**
* A single child content element.
*/
children: _utils.elementAcceptingRef.isRequired,
/**
* Override or extend the styles applied to the component.
*/
classes: _propTypes.default.object,
/**
* When set to true the Modal waits until a nested Transition is completed before closing.
* @default false
*/
closeAfterTransition: _propTypes.default.bool,
/**
* The components used for each slot inside the Modal.
* Either a string to use a HTML element or a component.
* @default {}
*/
components: _propTypes.default.shape({
Root: _propTypes.default.elementType
}),
/**
* The props used for each slot inside the Modal.
* @default {}
*/
componentsProps: _propTypes.default.object,
/**
* An HTML element or function that returns one.
* The `container` will have the portal children appended to it.
*
* By default, it uses the body of the top-level document object,
* so it's simply `document.body` most of the time.
*/
container: _propTypes.default
/* @typescript-to-proptypes-ignore */
.oneOfType([_utils.HTMLElementType, _propTypes.default.func]),
/**
* If `true`, the modal will not automatically shift focus to itself when it opens, and
* replace it to the last focused element when it closes.
* This also works correctly with any modal children that have the `disableAutoFocus` prop.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
* @default false
*/
disableAutoFocus: _propTypes.default.bool,
/**
* If `true`, the modal will not prevent focus from leaving the modal while open.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
* @default false
*/
disableEnforceFocus: _propTypes.default.bool,
/**
* If `true`, hitting escape will not fire the `onClose` callback.
* @default false
*/
disableEscapeKeyDown: _propTypes.default.bool,
/**
* The `children` will be under the DOM hierarchy of the parent component.
* @default false
*/
disablePortal: _propTypes.default.bool,
/**
* If `true`, the modal will not restore focus to previously focused element once
* modal is hidden.
* @default false
*/
disableRestoreFocus: _propTypes.default.bool,
/**
* Disable the scroll lock behavior.
* @default false
*/
disableScrollLock: _propTypes.default.bool,
/**
* If `true`, the backdrop is not rendered.
* @default false
*/
hideBackdrop: _propTypes.default.bool,
/**
* Always keep the children in the DOM.
* This prop can be useful in SEO situation or
* when you want to maximize the responsiveness of the Modal.
* @default false
*/
keepMounted: _propTypes.default.bool,
/**
* Callback fired when the backdrop is clicked.
*/
onBackdropClick: _propTypes.default.func,
/**
* Callback fired when the component requests to be closed.
* The `reason` parameter can optionally be used to control the response to `onClose`.
*
* @param {object} event The event source of the callback.
* @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
*/
onClose: _propTypes.default.func,
/**
* If `true`, the component is shown.
*/
open: _propTypes.default.bool.isRequired,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: _propTypes.default.object
} : void 0;
var _default = Modal;
exports.default = _default; |
var settingsCache = require('../../server/services/settings/cache'),
_ = require('lodash');
function getContextObject(data, context) {
/**
* If the data object does not contain the requested context, we return the fallback object.
*/
const blog = {
cover_image: settingsCache.get('cover_image'),
twitter: settingsCache.get('twitter'),
facebook: settingsCache.get('facebook')
};
let chosenContext;
// @TODO: meta layer is very broken, it's really hard to understand what it's doing
// The problem is that handlebars root object is structured differently. Sometimes the object is flat on data
// and sometimes the object is part of a key e.g. data.post. This needs to be prepared at the very first stage and not in each helper.
if ((_.includes(context, 'page') || _.includes(context, 'amp')) && data.post) {
chosenContext = data.post;
} else if (_.includes(context, 'post') && data.post) {
chosenContext = data.post;
} else if (_.includes(context, 'page') && data.page) {
chosenContext = data.page;
} else if (_.includes(context, 'tag') && data.tag) {
chosenContext = data.tag;
} else if (_.includes(context, 'author') && data.author) {
chosenContext = data.author;
} else if (data[context]) {
// @NOTE: This is confusing as hell. It tries to get data[['author']], which works, but coincidence?
chosenContext = data[context];
}
// Super fallback.
if (!chosenContext) {
chosenContext = blog;
}
return chosenContext;
}
module.exports = getContextObject;
|
/*
YUI 3.7.2 (build 5639)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('history-html5', function (Y, NAME) {
/**
* Provides browser history management using the HTML5 history API.
*
* @module history
* @submodule history-html5
* @since 3.2.0
*/
/**
* <p>
* Provides browser history management using the HTML5 history API.
* </p>
*
* <p>
* When calling the <code>add()</code>, <code>addValue()</code>,
* <code>replace()</code>, or <code>replaceValue()</code> methods on
* <code>HistoryHTML5</code>, the following additional options are supported:
* </p>
*
* <dl>
* <dt><strong>title (String)</strong></dt>
* <dd>
* Title to use for the new history entry. Browsers will typically display
* this title to the user in the detailed history window or in a dropdown
* menu attached to the back/forward buttons. If not specified, the title
* of the current document will be used.
* </dd>
*
* <dt><strong>url (String)</strong></dt>
* <dd>
* URL to display to the user for the new history entry. This URL will be
* visible in the browser's address bar and will be the bookmarked URL if
* the user bookmarks the page. It may be a relative path ("foo/bar"), an
* absolute path ("/foo/bar"), or a full URL ("http://example.com/foo/bar").
* If you specify a full URL, the origin <i>must</i> be the same as the
* origin of the current page, or an error will occur. If no URL is
* specified, the current URL will not be changed.
* </dd>
* </dl>
*
* @class HistoryHTML5
* @extends HistoryBase
* @constructor
* @param {Object} config (optional) Configuration object.
*/
var HistoryBase = Y.HistoryBase,
Lang = Y.Lang,
win = Y.config.win,
useHistoryHTML5 = Y.config.useHistoryHTML5,
SRC_POPSTATE = 'popstate',
SRC_REPLACE = HistoryBase.SRC_REPLACE;
function HistoryHTML5() {
HistoryHTML5.superclass.constructor.apply(this, arguments);
}
Y.extend(HistoryHTML5, HistoryBase, {
// -- Initialization -------------------------------------------------------
_init: function (config) {
var bookmarkedState = win.history.state;
// Treat empty state objects as `null` so they're not processed further.
if (Y.Object.isEmpty(bookmarkedState)) {
bookmarkedState = null;
}
config || (config = {});
// If both the initial state and the bookmarked state are objects, merge
// them (bookmarked state wins).
if (config.initialState
&& Lang.type(config.initialState) === 'object'
&& Lang.type(bookmarkedState) === 'object') {
this._initialState = Y.merge(config.initialState, bookmarkedState);
} else {
// Otherwise, the bookmarked state always wins if there is one. If
// there isn't a bookmarked state, history-base will take care of
// falling back to config.initialState or null.
this._initialState = bookmarkedState;
}
Y.on('popstate', this._onPopState, win, this);
HistoryHTML5.superclass._init.apply(this, arguments);
},
// -- Protected Methods ----------------------------------------------------
/**
* Overrides HistoryBase's <code>_storeState()</code> and pushes or replaces
* a history entry using the HTML5 history API when necessary.
*
* @method _storeState
* @param {String} src Source of the changes.
* @param {Object} newState New state to store.
* @param {Object} options Zero or more options.
* @protected
*/
_storeState: function (src, newState, options) {
if (src !== SRC_POPSTATE) {
win.history[src === SRC_REPLACE ? 'replaceState' : 'pushState'](
newState,
options.title || Y.config.doc.title || '',
options.url || null
);
}
HistoryHTML5.superclass._storeState.apply(this, arguments);
},
// -- Protected Event Handlers ---------------------------------------------
/**
* Handler for popstate events.
*
* @method _onPopState
* @param {Event} e
* @protected
*/
_onPopState: function (e) {
this._resolveChanges(SRC_POPSTATE, e._event.state || null);
}
}, {
// -- Public Static Properties ---------------------------------------------
NAME: 'historyhtml5',
/**
* Constant used to identify state changes originating from
* <code>popstate</code> events.
*
* @property SRC_POPSTATE
* @type String
* @static
* @final
*/
SRC_POPSTATE: SRC_POPSTATE
});
if (!Y.Node.DOM_EVENTS.popstate) {
Y.Node.DOM_EVENTS.popstate = 1;
}
Y.HistoryHTML5 = HistoryHTML5;
/**
* <p>
* If <code>true</code>, the <code>Y.History</code> alias will always point to
* <code>Y.HistoryHTML5</code> when the history-html5 module is loaded, even if
* the current browser doesn't support HTML5 history.
* </p>
*
* <p>
* If <code>false</code>, the <code>Y.History</code> alias will always point to
* <code>Y.HistoryHash</code> when the history-hash module is loaded, even if
* the current browser supports HTML5 history.
* </p>
*
* <p>
* If neither <code>true</code> nor <code>false</code>, the
* <code>Y.History</code> alias will point to the best available history adapter
* that the browser supports. This is the default behavior.
* </p>
*
* @property useHistoryHTML5
* @type boolean
* @for config
* @since 3.2.0
*/
// HistoryHTML5 will always win over HistoryHash unless useHistoryHTML5 is false
// or HTML5 history is not supported.
if (useHistoryHTML5 === true || (useHistoryHTML5 !== false &&
HistoryBase.html5)) {
Y.History = HistoryHTML5;
}
}, '3.7.2', {"optional": ["json"], "requires": ["event-base", "history-base", "node-base"]});
|
const path = require('path');
const deepMerge = require('deepmerge');
const { BannerPlugin } = require('webpack');
const baseConfig = require('./webpack.config.base');
const { name, version, author, homepage } = require('./package.json');
const arrayMerge = (target, source) => [...source, ...target];
const prodConfig = deepMerge(
baseConfig,
{
mode: 'production',
output: {
path: path.join(__dirname, '/public/assets/scripts'),
publicPath: '/public/assets/scripts/',
},
plugins: [
new BannerPlugin(
`${name} v${version} | © ${new Date().getFullYear()} ${author} | ${homepage}`,
),
],
},
{
arrayMerge,
},
);
module.exports = [
deepMerge(
prodConfig,
{
output: { filename: 'choices.js', libraryTarget: 'umd' },
optimization: { minimize: false },
},
{
arrayMerge,
},
),
deepMerge(
prodConfig,
{ output: { filename: 'choices.min.js' } },
{
arrayMerge,
},
),
];
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: If x is -Infinity, Math.ceil(x) is -Infinity
es5id: 15.8.2.6_A5
description: Checking if Math.ceil(x) is -Infinity, where x is -Infinity
---*/
// CHECK#1
var x = -Infinity;
if (Math.ceil(x) !== -Infinity)
{
$ERROR("#1: 'var x = -Infinity; Math.ceil(x) !== -Infinity'");
}
|
/******************************************************
* jQuery plug-in
* Easy Pinned Footer
* Developed by J.P. Given (http://johnpatrickgiven.com)
* Useage: anyone so long as credit is left alone
******************************************************/
(function($) {
// plugin definition
$.fn.pinFooter = function(options) {
// Get the height of the footer and window + window width
var wH = getWindowHeight();
wW = getWindowWidth();
var fH = $("#navbar-footer").outerHeight(true);
var bH = $("body").outerHeight(true);
var mB = parseInt($("body").css("margin-bottom"));
if (options == 'relative') {
if (bH > getWindowHeight()) {
$("#navbar-footer").css("position","absolute");
$("#navbar-footer").css("width","100%");
$("#navbar-footer").css("top",bH + fH + "px");
$("body").css("overflow-x","hidden");
$("#navbar-footer").css("z-index","100");
$('.left-nav').css('height', bH-113 +'px');
$('.docs .left-nav').css('height', bH-8 +'px'); //sgdocs section only
} else {
$("#navbar-footer").css("position","fixed");
$("#navbar-footer").css("z-index","100");
$("#navbar-footer").css("width",wW + "px");
$("#navbar-footer").css("top",wH - fH + "px");
//left nav adjustment
var leftnavHeight = wH-155;
$('.left-nav').css('height', leftnavHeight+'px');
$('.docs .left-nav').css('height', leftnavHeight+33 +'px'); //sgdocs section only
}
} else { // Pinned option
// Set CSS attributes for positioning footer
$("#navbar-footer").css("position","fixed");
$("#navbar-footer").css("width",wW + "px");
$("#navbar-footer").css("top",wH - fH + "px");
$("body").css("height",(bH + mB) + "px");
}
};
// private function for debugging
function debug($obj) {
if (window.console && window.console.log) {
window.console.log('Window Width: ' + $(window).width());
window.console.log('Window Height: ' + $(window).height());
}
};
// Dependable function to get Window Height
function getWindowHeight() {
var windowHeight = 0;
if (typeof(window.innerHeight) == 'number') {
windowHeight = window.innerHeight;
}
else {
if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
}
else {
if (document.body && document.body.clientHeight) {
windowHeight = document.body.clientHeight;
}
}
}
return windowHeight;
};
// Dependable function to get Window Width
function getWindowWidth() {
var windowWidth = 0;
if (typeof(window.innerWidth) == 'number') {
windowWidth = window.innerWidth;
}
else {
if (document.documentElement && document.documentElement.clientWidth) {
windowWidth = document.documentElement.clientWidth;
}
else {
if (document.body && document.body.clientWidth) {
windowWidth = document.body.clientWidth;
}
}
}
return windowWidth;
};
})(jQuery); |
Clazz.declarePackage ("J.modelset");
Clazz.load (["JU.M3", "$.P3"], "J.modelset.Orientation", ["J.util.Escape"], function () {
c$ = Clazz.decorateAsClass (function () {
this.saveName = null;
this.rotationMatrix = null;
this.xTrans = 0;
this.yTrans = 0;
this.zoom = 0;
this.rotationRadius = 0;
this.center = null;
this.navCenter = null;
this.xNav = NaN;
this.yNav = NaN;
this.navDepth = NaN;
this.cameraDepth = NaN;
this.cameraX = NaN;
this.cameraY = NaN;
this.windowCenteredFlag = false;
this.navigationMode = false;
this.moveToText = null;
this.pymolView = null;
this.viewer = null;
Clazz.instantialize (this, arguments);
}, J.modelset, "Orientation");
Clazz.prepareFields (c$, function () {
this.rotationMatrix = new JU.M3 ();
this.center = new JU.P3 ();
this.navCenter = new JU.P3 ();
});
Clazz.makeConstructor (c$,
function (viewer, asDefault, pymolView) {
this.viewer = viewer;
if (pymolView != null) {
this.pymolView = pymolView;
this.moveToText = "moveTo -1.0 PyMOL " + J.util.Escape.eAF (pymolView);
return;
}viewer.finalizeTransformParameters ();
if (asDefault) {
var rotationMatrix = viewer.getModelSetAuxiliaryInfoValue ("defaultOrientationMatrix");
if (rotationMatrix == null) this.rotationMatrix.setIdentity ();
else this.rotationMatrix.setM (rotationMatrix);
} else {
viewer.getRotation (this.rotationMatrix);
}this.xTrans = viewer.getTranslationXPercent ();
this.yTrans = viewer.getTranslationYPercent ();
this.zoom = viewer.getZoomSetting ();
this.center.setT (viewer.getRotationCenter ());
this.windowCenteredFlag = viewer.isWindowCentered ();
this.rotationRadius = viewer.getFloat (570425388);
this.navigationMode = viewer.getBoolean (603979887);
this.moveToText = viewer.getMoveToText (-1);
if (this.navigationMode) {
this.xNav = viewer.getNavigationOffsetPercent ('X');
this.yNav = viewer.getNavigationOffsetPercent ('Y');
this.navDepth = viewer.getNavigationDepthPercent ();
this.navCenter = JU.P3.newP (viewer.getNavigationCenter ());
}if (viewer.getCamera ().z != 0) {
this.cameraDepth = viewer.getCameraDepth ();
this.cameraX = viewer.getCamera ().x;
this.cameraY = viewer.getCamera ().y;
}}, "J.viewer.Viewer,~B,~A");
$_M(c$, "getMoveToText",
function (asCommand) {
return (asCommand ? " " + this.moveToText + "\n save orientation " + J.util.Escape.eS (this.saveName.substring (12)) + ";\n" : this.moveToText);
}, "~B");
$_M(c$, "restore",
function (timeSeconds, isAll) {
if (isAll) {
this.viewer.setBooleanProperty ("windowCentered", this.windowCenteredFlag);
this.viewer.setBooleanProperty ("navigationMode", this.navigationMode);
if (this.pymolView == null) this.viewer.moveTo (this.viewer.eval, timeSeconds, this.center, null, NaN, this.rotationMatrix, this.zoom, this.xTrans, this.yTrans, this.rotationRadius, this.navCenter, this.xNav, this.yNav, this.navDepth, this.cameraDepth, this.cameraX, this.cameraY);
else this.viewer.movePyMOL (this.viewer.eval, timeSeconds, this.pymolView);
} else {
this.viewer.setRotationMatrix (this.rotationMatrix);
}return true;
}, "~N,~B");
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:327bd8f9945a74a79458afe4625c642d692e2a5d4e114179b3a8ca2039c1dcf5
size 733
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.