code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
define([ 'dojo/_base/declare', 'JBrowse/Component' ], function( declare, Component ) { return declare( Component, { constructor: function( args ) { this.name = args.name; this.cssLoaded = args.cssLoaded; this._finalizeConfig( args.config ); }, _defaultConfig: function() { return { baseUrl: '/plugins/'+this.name }; } }); });
wurmlab/afra
www/JBrowse/Plugin.js
JavaScript
apache-2.0
430
import moment from 'moment'; function rdTimer() { return { restrict: 'E', scope: { timestamp: '=' }, template: '{{currentTime}}', controller($scope) { $scope.currentTime = '00:00:00'; // We're using setInterval directly instead of $timeout, to avoid using $apply, to // prevent the digest loop being run every second. let currentTimer = setInterval(() => { $scope.currentTime = moment(moment() - moment($scope.timestamp)).utc().format('HH:mm:ss'); $scope.$digest(); }, 1000); $scope.$on('$destroy', () => { if (currentTimer) { clearInterval(currentTimer); currentTimer = null; } }); }, }; } export default function (ngModule) { ngModule.directive('rdTimer', rdTimer); }
imsally/redash
client/app/components/rd-timer.js
JavaScript
bsd-2-clause
794
// Copyright 2005 Google Inc. // All Rights Reserved // // An XPath parser and evaluator written in JavaScript. The // implementation is complete except for functions handling // namespaces. // // Reference: [XPATH] XPath Specification // <http://www.w3.org/TR/1999/REC-xpath-19991116>. // // // The API of the parser has several parts: // // 1. The parser function xpathParse() that takes a string and returns // an expession object. // // 2. The expression object that has an evaluate() method to evaluate the // XPath expression it represents. (It is actually a hierarchy of // objects that resembles the parse tree, but an application will call // evaluate() only on the top node of this hierarchy.) // // 3. The context object that is passed as an argument to the evaluate() // method, which represents the DOM context in which the expression is // evaluated. // // 4. The value object that is returned from evaluate() and represents // values of the different types that are defined by XPath (number, // string, boolean, and node-set), and allows to convert between them. // // These parts are near the top of the file, the functions and data // that are used internally follow after them. // // // Author: Steffen Meschkat <mesch@google.com> // The entry point for the parser. // // @param expr a string that contains an XPath expression. // @return an expression object that can be evaluated with an // expression context. function xpathParse(expr) { xpathLog('parse ' + expr); xpathParseInit(); var cached = xpathCacheLookup(expr); if (cached) { xpathLog(' ... cached'); return cached; } // Optimize for a few common cases: simple attribute node tests // (@id), simple element node tests (page), variable references // ($address), numbers (4), multi-step path expressions where each // step is a plain element node test // (page/overlay/locations/location). if (expr.match(/^(\$|@)?\w+$/i)) { var ret = makeSimpleExpr(expr); xpathParseCache[expr] = ret; xpathLog(' ... simple'); return ret; } if (expr.match(/^\w+(\/\w+)*$/i)) { var ret = makeSimpleExpr2(expr); xpathParseCache[expr] = ret; xpathLog(' ... simple 2'); return ret; } var cachekey = expr; // expr is modified during parse var stack = []; var ahead = null; var previous = null; var done = false; var parse_count = 0; var lexer_count = 0; var reduce_count = 0; while (!done) { parse_count++; expr = expr.replace(/^\s*/, ''); previous = ahead; ahead = null; var rule = null; var match = ''; for (var i = 0; i < xpathTokenRules.length; ++i) { var result = xpathTokenRules[i].re.exec(expr); lexer_count++; if (result && result.length > 0 && result[0].length > match.length) { rule = xpathTokenRules[i]; match = result[0]; break; } } // Special case: allow operator keywords to be element and // variable names. // NOTE(mesch): The parser resolves conflicts by looking ahead, // and this is the only case where we look back to // disambiguate. So this is indeed something different, and // looking back is usually done in the lexer (via states in the // general case, called "start conditions" in flex(1)). Also,the // conflict resolution in the parser is not as robust as it could // be, so I'd like to keep as much off the parser as possible (all // these precedence values should be computed from the grammar // rules and possibly associativity declarations, as in bison(1), // and not explicitly set. if (rule && (rule == TOK_DIV || rule == TOK_MOD || rule == TOK_AND || rule == TOK_OR) && (!previous || previous.tag == TOK_AT || previous.tag == TOK_DSLASH || previous.tag == TOK_SLASH || previous.tag == TOK_AXIS || previous.tag == TOK_DOLLAR)) { rule = TOK_QNAME; } if (rule) { expr = expr.substr(match.length); xpathLog('token: ' + match + ' -- ' + rule.label); ahead = { tag: rule, match: match, prec: rule.prec ? rule.prec : 0, // || 0 is removed by the compiler expr: makeTokenExpr(match) }; } else { xpathLog('DONE'); done = true; } while (xpathReduce(stack, ahead)) { reduce_count++; xpathLog('stack: ' + stackToString(stack)); } } xpathLog('stack: ' + stackToString(stack)); // DGF any valid XPath should "reduce" to a single Expr token if (stack.length != 1) { throw 'XPath parse error ' + cachekey + ':\n' + stackToString(stack); } var result = stack[0].expr; xpathParseCache[cachekey] = result; xpathLog('XPath parse: ' + parse_count + ' / ' + lexer_count + ' / ' + reduce_count); return result; } var xpathParseCache = {}; function xpathCacheLookup(expr) { return xpathParseCache[expr]; } /*DGF xpathReduce is where the magic happens in this parser. Skim down to the bottom of this file to find the table of grammatical rules and precedence numbers, "The productions of the grammar". The idea here is that we want to take a stack of tokens and apply grammatical rules to them, "reducing" them to higher-level tokens. Ultimately, any valid XPath should reduce to exactly one "Expr" token. Reduce too early or too late and you'll have two tokens that can't reduce to single Expr. For example, you may hastily reduce a qname that should name a function, incorrectly treating it as a tag name. Or you may reduce too late, accidentally reducing the last part of the XPath into a top-level "Expr" that won't reduce with earlier parts of the XPath. A "cand" is a grammatical rule candidate, with a given precedence number. "ahead" is the upcoming token, which also has a precedence number. If the token has a higher precedence number than the rule candidate, we'll "shift" the token onto the token stack, instead of immediately applying the rule candidate. Some tokens have left associativity, in which case we shift when they have LOWER precedence than the candidate. */ function xpathReduce(stack, ahead) { var cand = null; if (stack.length > 0) { var top = stack[stack.length-1]; var ruleset = xpathRules[top.tag.key]; if (ruleset) { for (var i = 0; i < ruleset.length; ++i) { var rule = ruleset[i]; var match = xpathMatchStack(stack, rule[1]); if (match.length) { cand = { tag: rule[0], rule: rule, match: match }; cand.prec = xpathGrammarPrecedence(cand); break; } } } } var ret; if (cand && (!ahead || cand.prec > ahead.prec || (ahead.tag.left && cand.prec >= ahead.prec))) { for (var i = 0; i < cand.match.matchlength; ++i) { stack.pop(); } xpathLog('reduce ' + cand.tag.label + ' ' + cand.prec + ' ahead ' + (ahead ? ahead.tag.label + ' ' + ahead.prec + (ahead.tag.left ? ' left' : '') : ' none ')); var matchexpr = mapExpr(cand.match, function(m) { return m.expr; }); xpathLog('going to apply ' + cand.rule[3].toString()); cand.expr = cand.rule[3].apply(null, matchexpr); stack.push(cand); ret = true; } else { if (ahead) { xpathLog('shift ' + ahead.tag.label + ' ' + ahead.prec + (ahead.tag.left ? ' left' : '') + ' over ' + (cand ? cand.tag.label + ' ' + cand.prec : ' none')); stack.push(ahead); } ret = false; } return ret; } function xpathMatchStack(stack, pattern) { // NOTE(mesch): The stack matches for variable cardinality are // greedy but don't do backtracking. This would be an issue only // with rules of the form A* A, i.e. with an element with variable // cardinality followed by the same element. Since that doesn't // occur in the grammar at hand, all matches on the stack are // unambiguous. var S = stack.length; var P = pattern.length; var p, s; var match = []; match.matchlength = 0; var ds = 0; for (p = P - 1, s = S - 1; p >= 0 && s >= 0; --p, s -= ds) { ds = 0; var qmatch = []; if (pattern[p] == Q_MM) { p -= 1; match.push(qmatch); while (s - ds >= 0 && stack[s - ds].tag == pattern[p]) { qmatch.push(stack[s - ds]); ds += 1; match.matchlength += 1; } } else if (pattern[p] == Q_01) { p -= 1; match.push(qmatch); while (s - ds >= 0 && ds < 2 && stack[s - ds].tag == pattern[p]) { qmatch.push(stack[s - ds]); ds += 1; match.matchlength += 1; } } else if (pattern[p] == Q_1M) { p -= 1; match.push(qmatch); if (stack[s].tag == pattern[p]) { while (s - ds >= 0 && stack[s - ds].tag == pattern[p]) { qmatch.push(stack[s - ds]); ds += 1; match.matchlength += 1; } } else { return []; } } else if (stack[s].tag == pattern[p]) { match.push(stack[s]); ds += 1; match.matchlength += 1; } else { return []; } reverseInplace(qmatch); qmatch.expr = mapExpr(qmatch, function(m) { return m.expr; }); } reverseInplace(match); if (p == -1) { return match; } else { return []; } } function xpathTokenPrecedence(tag) { return tag.prec || 2; } function xpathGrammarPrecedence(frame) { var ret = 0; if (frame.rule) { /* normal reduce */ if (frame.rule.length >= 3 && frame.rule[2] >= 0) { ret = frame.rule[2]; } else { for (var i = 0; i < frame.rule[1].length; ++i) { var p = xpathTokenPrecedence(frame.rule[1][i]); ret = Math.max(ret, p); } } } else if (frame.tag) { /* TOKEN match */ ret = xpathTokenPrecedence(frame.tag); } else if (frame.length) { /* Q_ match */ for (var j = 0; j < frame.length; ++j) { var p = xpathGrammarPrecedence(frame[j]); ret = Math.max(ret, p); } } return ret; } function stackToString(stack) { var ret = ''; for (var i = 0; i < stack.length; ++i) { if (ret) { ret += '\n'; } ret += stack[i].tag.label; } return ret; } // XPath expression evaluation context. An XPath context consists of a // DOM node, a list of DOM nodes that contains this node, a number // that represents the position of the single node in the list, and a // current set of variable bindings. (See XPath spec.) // // The interface of the expression context: // // Constructor -- gets the node, its position, the node set it // belongs to, and a parent context as arguments. The parent context // is used to implement scoping rules for variables: if a variable // is not found in the current context, it is looked for in the // parent context, recursively. Except for node, all arguments have // default values: default position is 0, default node set is the // set that contains only the node, and the default parent is null. // // Notice that position starts at 0 at the outside interface; // inside XPath expressions this shows up as position()=1. // // clone() -- creates a new context with the current context as // parent. If passed as argument to clone(), the new context has a // different node, position, or node set. What is not passed is // inherited from the cloned context. // // setVariable(name, expr) -- binds given XPath expression to the // name. // // getVariable(name) -- what the name says. // // setNode(position) -- sets the context to the node at the given // position. Needed to implement scoping rules for variables in // XPath. (A variable is visible to all subsequent siblings, not // only to its children.) // // set/isCaseInsensitive -- specifies whether node name tests should // be case sensitive. If you're executing xpaths against a regular // HTML DOM, you probably don't want case-sensitivity, because // browsers tend to disagree about whether elements & attributes // should be upper/lower case. If you're running xpaths in an // XSLT instance, you probably DO want case sensitivity, as per the // XSL spec. // // set/isReturnOnFirstMatch -- whether XPath evaluation should quit as soon // as a result is found. This is an optimization that might make sense if you // only care about the first result. // // set/isIgnoreNonElementNodesForNTA -- whether to ignore non-element nodes // when evaluating the "node()" any node test. While technically this is // contrary to the XPath spec, practically it can enhance performance // significantly, and makes sense if you a) use "node()" when you mean "*", // and b) use "//" when you mean "/descendant::*/". function ExprContext(node, opt_position, opt_nodelist, opt_parent, opt_caseInsensitive, opt_ignoreAttributesWithoutValue, opt_returnOnFirstMatch, opt_ignoreNonElementNodesForNTA) { this.node = node; this.position = opt_position || 0; this.nodelist = opt_nodelist || [ node ]; this.variables = {}; this.parent = opt_parent || null; this.caseInsensitive = opt_caseInsensitive || false; this.ignoreAttributesWithoutValue = opt_ignoreAttributesWithoutValue || false; this.returnOnFirstMatch = opt_returnOnFirstMatch || false; this.ignoreNonElementNodesForNTA = opt_ignoreNonElementNodesForNTA || false; if (opt_parent) { this.root = opt_parent.root; } else if (this.node.nodeType == DOM_DOCUMENT_NODE) { // NOTE(mesch): DOM Spec stipulates that the ownerDocument of a // document is null. Our root, however is the document that we are // processing, so the initial context is created from its document // node, which case we must handle here explcitly. this.root = node; } else { this.root = node.ownerDocument; } } ExprContext.prototype.clone = function(opt_node, opt_position, opt_nodelist) { return new ExprContext( opt_node || this.node, typeof opt_position != 'undefined' ? opt_position : this.position, opt_nodelist || this.nodelist, this, this.caseInsensitive, this.ignoreAttributesWithoutValue, this.returnOnFirstMatch, this.ignoreNonElementNodesForNTA); }; ExprContext.prototype.setVariable = function(name, value) { if (value instanceof StringValue || value instanceof BooleanValue || value instanceof NumberValue || value instanceof NodeSetValue) { this.variables[name] = value; return; } if ('true' === value) { this.variables[name] = new BooleanValue(true); } else if ('false' === value) { this.variables[name] = new BooleanValue(false); } else if (TOK_NUMBER.re.test(value)) { this.variables[name] = new NumberValue(value); } else { // DGF What if it's null? this.variables[name] = new StringValue(value); } }; ExprContext.prototype.getVariable = function(name) { if (typeof this.variables[name] != 'undefined') { return this.variables[name]; } else if (this.parent) { return this.parent.getVariable(name); } else { return null; } }; ExprContext.prototype.setNode = function(position) { this.node = this.nodelist[position]; this.position = position; }; ExprContext.prototype.contextSize = function() { return this.nodelist.length; }; ExprContext.prototype.isCaseInsensitive = function() { return this.caseInsensitive; }; ExprContext.prototype.setCaseInsensitive = function(caseInsensitive) { return this.caseInsensitive = caseInsensitive; }; ExprContext.prototype.isIgnoreAttributesWithoutValue = function() { return this.ignoreAttributesWithoutValue; }; ExprContext.prototype.setIgnoreAttributesWithoutValue = function(ignore) { return this.ignoreAttributesWithoutValue = ignore; }; ExprContext.prototype.isReturnOnFirstMatch = function() { return this.returnOnFirstMatch; }; ExprContext.prototype.setReturnOnFirstMatch = function(returnOnFirstMatch) { return this.returnOnFirstMatch = returnOnFirstMatch; }; ExprContext.prototype.isIgnoreNonElementNodesForNTA = function() { return this.ignoreNonElementNodesForNTA; }; ExprContext.prototype.setIgnoreNonElementNodesForNTA = function(ignoreNonElementNodesForNTA) { return this.ignoreNonElementNodesForNTA = ignoreNonElementNodesForNTA; }; // XPath expression values. They are what XPath expressions evaluate // to. Strangely, the different value types are not specified in the // XPath syntax, but only in the semantics, so they don't show up as // nonterminals in the grammar. Yet, some expressions are required to // evaluate to particular types, and not every type can be coerced // into every other type. Although the types of XPath values are // similar to the types present in JavaScript, the type coercion rules // are a bit peculiar, so we explicitly model XPath types instead of // mapping them onto JavaScript types. (See XPath spec.) // // The four types are: // // StringValue // // NumberValue // // BooleanValue // // NodeSetValue // // The common interface of the value classes consists of methods that // implement the XPath type coercion rules: // // stringValue() -- returns the value as a JavaScript String, // // numberValue() -- returns the value as a JavaScript Number, // // booleanValue() -- returns the value as a JavaScript Boolean, // // nodeSetValue() -- returns the value as a JavaScript Array of DOM // Node objects. // function StringValue(value) { this.value = value; this.type = 'string'; } StringValue.prototype.stringValue = function() { return this.value; } StringValue.prototype.booleanValue = function() { return this.value.length > 0; } StringValue.prototype.numberValue = function() { return this.value - 0; } StringValue.prototype.nodeSetValue = function() { throw this; } function BooleanValue(value) { this.value = value; this.type = 'boolean'; } BooleanValue.prototype.stringValue = function() { return '' + this.value; } BooleanValue.prototype.booleanValue = function() { return this.value; } BooleanValue.prototype.numberValue = function() { return this.value ? 1 : 0; } BooleanValue.prototype.nodeSetValue = function() { throw this; } function NumberValue(value) { this.value = value; this.type = 'number'; } NumberValue.prototype.stringValue = function() { return '' + this.value; } NumberValue.prototype.booleanValue = function() { return !!this.value; } NumberValue.prototype.numberValue = function() { return this.value - 0; } NumberValue.prototype.nodeSetValue = function() { throw this; } function NodeSetValue(value) { this.value = value; this.type = 'node-set'; } NodeSetValue.prototype.stringValue = function() { if (this.value.length == 0) { return ''; } else { return xmlValue(this.value[0]); } } NodeSetValue.prototype.booleanValue = function() { return this.value.length > 0; } NodeSetValue.prototype.numberValue = function() { return this.stringValue() - 0; } NodeSetValue.prototype.nodeSetValue = function() { return this.value; }; // XPath expressions. They are used as nodes in the parse tree and // possess an evaluate() method to compute an XPath value given an XPath // context. Expressions are returned from the parser. Teh set of // expression classes closely mirrors the set of non terminal symbols // in the grammar. Every non trivial nonterminal symbol has a // corresponding expression class. // // The common expression interface consists of the following methods: // // evaluate(context) -- evaluates the expression, returns a value. // // toString() -- returns the XPath text representation of the // expression (defined in xsltdebug.js). // // parseTree(indent) -- returns a parse tree representation of the // expression (defined in xsltdebug.js). function TokenExpr(m) { this.value = m; } TokenExpr.prototype.evaluate = function() { return new StringValue(this.value); }; function LocationExpr() { this.absolute = false; this.steps = []; } LocationExpr.prototype.appendStep = function(s) { var combinedStep = this._combineSteps(this.steps[this.steps.length-1], s); if (combinedStep) { this.steps[this.steps.length-1] = combinedStep; } else { this.steps.push(s); } } LocationExpr.prototype.prependStep = function(s) { var combinedStep = this._combineSteps(s, this.steps[0]); if (combinedStep) { this.steps[0] = combinedStep; } else { this.steps.unshift(s); } }; // DGF try to combine two steps into one step (perf enhancement) LocationExpr.prototype._combineSteps = function(prevStep, nextStep) { if (!prevStep) return null; if (!nextStep) return null; var hasPredicates = (prevStep.predicates && prevStep.predicates.length > 0); if (prevStep.nodetest instanceof NodeTestAny && !hasPredicates) { // maybe suitable to be combined if (prevStep.axis == xpathAxis.DESCENDANT_OR_SELF) { if (nextStep.axis == xpathAxis.CHILD) { // HBC - commenting out, because this is not a valid reduction //nextStep.axis = xpathAxis.DESCENDANT; //return nextStep; } else if (nextStep.axis == xpathAxis.SELF) { nextStep.axis = xpathAxis.DESCENDANT_OR_SELF; return nextStep; } } else if (prevStep.axis == xpathAxis.DESCENDANT) { if (nextStep.axis == xpathAxis.SELF) { nextStep.axis = xpathAxis.DESCENDANT; return nextStep; } } } return null; } LocationExpr.prototype.evaluate = function(ctx) { var start; if (this.absolute) { start = ctx.root; } else { start = ctx.node; } var nodes = []; xPathStep(nodes, this.steps, 0, start, ctx); return new NodeSetValue(nodes); }; function xPathStep(nodes, steps, step, input, ctx) { var s = steps[step]; var ctx2 = ctx.clone(input); if (ctx.returnOnFirstMatch && !s.hasPositionalPredicate) { var nodelist = s.evaluate(ctx2).nodeSetValue(); // the predicates were not processed in the last evaluate(), so that we can // process them here with the returnOnFirstMatch optimization. We do a // depth-first grab at any nodes that pass the predicate tests. There is no // way to optimize when predicates contain positional selectors, including // indexes or uses of the last() or position() functions, because they // typically require the entire nodelist for context. Process without // optimization if we encounter such selectors. var nLength = nodelist.length; var pLength = s.predicate.length; nodelistLoop: for (var i = 0; i < nLength; ++i) { var n = nodelist[i]; for (var j = 0; j < pLength; ++j) { if (!s.predicate[j].evaluate(ctx.clone(n, i, nodelist)).booleanValue()) { continue nodelistLoop; } } // n survived the predicate tests! if (step == steps.length - 1) { nodes.push(n); } else { xPathStep(nodes, steps, step + 1, n, ctx); } if (nodes.length > 0) { break; } } } else { // set returnOnFirstMatch to false for the cloned ExprContext, because // behavior in StepExpr.prototype.evaluate is driven off its value. Note // that the original context may still have true for this value. ctx2.returnOnFirstMatch = false; var nodelist = s.evaluate(ctx2).nodeSetValue(); for (var i = 0; i < nodelist.length; ++i) { if (step == steps.length - 1) { nodes.push(nodelist[i]); } else { xPathStep(nodes, steps, step + 1, nodelist[i], ctx); } } } } function StepExpr(axis, nodetest, opt_predicate) { this.axis = axis; this.nodetest = nodetest; this.predicate = opt_predicate || []; this.hasPositionalPredicate = false; for (var i = 0; i < this.predicate.length; ++i) { if (predicateExprHasPositionalSelector(this.predicate[i].expr)) { this.hasPositionalPredicate = true; break; } } } StepExpr.prototype.appendPredicate = function(p) { this.predicate.push(p); if (!this.hasPositionalPredicate) { this.hasPositionalPredicate = predicateExprHasPositionalSelector(p.expr); } } StepExpr.prototype.evaluate = function(ctx) { var input = ctx.node; var nodelist = []; var skipNodeTest = false; if (this.nodetest instanceof NodeTestAny) { skipNodeTest = true; } // NOTE(mesch): When this was a switch() statement, it didn't work // in Safari/2.0. Not sure why though; it resulted in the JavaScript // console output "undefined" (without any line number or so). if (this.axis == xpathAxis.ANCESTOR_OR_SELF) { nodelist.push(input); for (var n = input.parentNode; n; n = n.parentNode) { nodelist.push(n); } } else if (this.axis == xpathAxis.ANCESTOR) { for (var n = input.parentNode; n; n = n.parentNode) { nodelist.push(n); } } else if (this.axis == xpathAxis.ATTRIBUTE) { if (this.nodetest.name != undefined) { // single-attribute step if (input.attributes) { if (input.attributes instanceof Array) { // probably evaluating on document created by xmlParse() copyArray(nodelist, input.attributes); } else { if (this.nodetest.name == 'style') { var value = input.getAttribute('style'); if (value && typeof(value) != 'string') { // this is the case where indexing into the attributes array // doesn't give us the attribute node in IE - we create our own // node instead nodelist.push(XNode.create(DOM_ATTRIBUTE_NODE, 'style', value.cssText, document)); } else { nodelist.push(input.attributes[this.nodetest.name]); } } else { nodelist.push(input.attributes[this.nodetest.name]); } } } } else { // all-attributes step if (ctx.ignoreAttributesWithoutValue) { copyArrayIgnoringAttributesWithoutValue(nodelist, input.attributes); } else { copyArray(nodelist, input.attributes); } } } else if (this.axis == xpathAxis.CHILD) { copyArray(nodelist, input.childNodes); } else if (this.axis == xpathAxis.DESCENDANT_OR_SELF) { if (this.nodetest.evaluate(ctx).booleanValue()) { nodelist.push(input); } var tagName = xpathExtractTagNameFromNodeTest(this.nodetest, ctx.ignoreNonElementNodesForNTA); xpathCollectDescendants(nodelist, input, tagName); if (tagName) skipNodeTest = true; } else if (this.axis == xpathAxis.DESCENDANT) { var tagName = xpathExtractTagNameFromNodeTest(this.nodetest, ctx.ignoreNonElementNodesForNTA); xpathCollectDescendants(nodelist, input, tagName); if (tagName) skipNodeTest = true; } else if (this.axis == xpathAxis.FOLLOWING) { for (var n = input; n; n = n.parentNode) { for (var nn = n.nextSibling; nn; nn = nn.nextSibling) { nodelist.push(nn); xpathCollectDescendants(nodelist, nn); } } } else if (this.axis == xpathAxis.FOLLOWING_SIBLING) { for (var n = input.nextSibling; n; n = n.nextSibling) { nodelist.push(n); } } else if (this.axis == xpathAxis.NAMESPACE) { alert('not implemented: axis namespace'); } else if (this.axis == xpathAxis.PARENT) { if (input.parentNode) { nodelist.push(input.parentNode); } } else if (this.axis == xpathAxis.PRECEDING) { for (var n = input; n; n = n.parentNode) { for (var nn = n.previousSibling; nn; nn = nn.previousSibling) { nodelist.push(nn); xpathCollectDescendantsReverse(nodelist, nn); } } } else if (this.axis == xpathAxis.PRECEDING_SIBLING) { for (var n = input.previousSibling; n; n = n.previousSibling) { nodelist.push(n); } } else if (this.axis == xpathAxis.SELF) { nodelist.push(input); } else { throw 'ERROR -- NO SUCH AXIS: ' + this.axis; } if (!skipNodeTest) { // process node test var nodelist0 = nodelist; nodelist = []; for (var i = 0; i < nodelist0.length; ++i) { var n = nodelist0[i]; if (this.nodetest.evaluate(ctx.clone(n, i, nodelist0)).booleanValue()) { nodelist.push(n); } } } // process predicates if (!ctx.returnOnFirstMatch) { for (var i = 0; i < this.predicate.length; ++i) { var nodelist0 = nodelist; nodelist = []; for (var ii = 0; ii < nodelist0.length; ++ii) { var n = nodelist0[ii]; if (this.predicate[i].evaluate(ctx.clone(n, ii, nodelist0)).booleanValue()) { nodelist.push(n); } } } } return new NodeSetValue(nodelist); }; function NodeTestAny() { this.value = new BooleanValue(true); } NodeTestAny.prototype.evaluate = function(ctx) { return this.value; }; function NodeTestElementOrAttribute() {} NodeTestElementOrAttribute.prototype.evaluate = function(ctx) { return new BooleanValue( ctx.node.nodeType == DOM_ELEMENT_NODE || ctx.node.nodeType == DOM_ATTRIBUTE_NODE); } function NodeTestText() {} NodeTestText.prototype.evaluate = function(ctx) { return new BooleanValue(ctx.node.nodeType == DOM_TEXT_NODE); } function NodeTestComment() {} NodeTestComment.prototype.evaluate = function(ctx) { return new BooleanValue(ctx.node.nodeType == DOM_COMMENT_NODE); } function NodeTestPI(target) { this.target = target; } NodeTestPI.prototype.evaluate = function(ctx) { return new BooleanValue(ctx.node.nodeType == DOM_PROCESSING_INSTRUCTION_NODE && (!this.target || ctx.node.nodeName == this.target)); } function NodeTestNC(nsprefix) { this.regex = new RegExp("^" + nsprefix + ":"); this.nsprefix = nsprefix; } NodeTestNC.prototype.evaluate = function(ctx) { var n = ctx.node; return new BooleanValue(this.regex.match(n.nodeName)); } function NodeTestName(name) { this.name = name; this.re = new RegExp('^' + name + '$', "i"); } NodeTestName.prototype.evaluate = function(ctx) { var n = ctx.node; if (ctx.caseInsensitive) { if (n.nodeName.length != this.name.length) return new BooleanValue(false); return new BooleanValue(this.re.test(n.nodeName)); } else { return new BooleanValue(n.nodeName == this.name); } } function PredicateExpr(expr) { this.expr = expr; } PredicateExpr.prototype.evaluate = function(ctx) { var v = this.expr.evaluate(ctx); if (v.type == 'number') { // NOTE(mesch): Internally, position is represented starting with // 0, however in XPath position starts with 1. See functions // position() and last(). return new BooleanValue(ctx.position == v.numberValue() - 1); } else { return new BooleanValue(v.booleanValue()); } }; function FunctionCallExpr(name) { this.name = name; this.args = []; } FunctionCallExpr.prototype.appendArg = function(arg) { this.args.push(arg); }; FunctionCallExpr.prototype.evaluate = function(ctx) { var fn = '' + this.name.value; var f = this.xpathfunctions[fn]; if (f) { return f.call(this, ctx); } else { xpathLog('XPath NO SUCH FUNCTION ' + fn); return new BooleanValue(false); } }; FunctionCallExpr.prototype.xpathfunctions = { 'last': function(ctx) { assert(this.args.length == 0); // NOTE(mesch): XPath position starts at 1. return new NumberValue(ctx.contextSize()); }, 'position': function(ctx) { assert(this.args.length == 0); // NOTE(mesch): XPath position starts at 1. return new NumberValue(ctx.position + 1); }, 'count': function(ctx) { assert(this.args.length == 1); var v = this.args[0].evaluate(ctx); return new NumberValue(v.nodeSetValue().length); }, 'id': function(ctx) { assert(this.args.length == 1); var e = this.args[0].evaluate(ctx); var ret = []; var ids; if (e.type == 'node-set') { ids = []; var en = e.nodeSetValue(); for (var i = 0; i < en.length; ++i) { var v = xmlValue(en[i]).split(/\s+/); for (var ii = 0; ii < v.length; ++ii) { ids.push(v[ii]); } } } else { ids = e.stringValue().split(/\s+/); } var d = ctx.root; for (var i = 0; i < ids.length; ++i) { var n = d.getElementById(ids[i]); if (n) { ret.push(n); } } return new NodeSetValue(ret); }, 'local-name': function(ctx) { alert('not implmented yet: XPath function local-name()'); }, 'namespace-uri': function(ctx) { alert('not implmented yet: XPath function namespace-uri()'); }, 'name': function(ctx) { assert(this.args.length == 1 || this.args.length == 0); var n; if (this.args.length == 0) { n = [ ctx.node ]; } else { n = this.args[0].evaluate(ctx).nodeSetValue(); } if (n.length == 0) { return new StringValue(''); } else { return new StringValue(n[0].nodeName); } }, 'string': function(ctx) { assert(this.args.length == 1 || this.args.length == 0); if (this.args.length == 0) { return new StringValue(new NodeSetValue([ ctx.node ]).stringValue()); } else { return new StringValue(this.args[0].evaluate(ctx).stringValue()); } }, 'concat': function(ctx) { var ret = ''; for (var i = 0; i < this.args.length; ++i) { ret += this.args[i].evaluate(ctx).stringValue(); } return new StringValue(ret); }, 'starts-with': function(ctx) { assert(this.args.length == 2); var s0 = this.args[0].evaluate(ctx).stringValue(); var s1 = this.args[1].evaluate(ctx).stringValue(); return new BooleanValue(s0.indexOf(s1) == 0); }, 'ends-with': function(ctx) { assert(this.args.length == 2); var s0 = this.args[0].evaluate(ctx).stringValue(); var s1 = this.args[1].evaluate(ctx).stringValue(); var re = new RegExp(RegExp.escape(s1) + '$'); return new BooleanValue(re.test(s0)); }, 'contains': function(ctx) { assert(this.args.length == 2); var s0 = this.args[0].evaluate(ctx).stringValue(); var s1 = this.args[1].evaluate(ctx).stringValue(); return new BooleanValue(s0.indexOf(s1) != -1); }, 'substring-before': function(ctx) { assert(this.args.length == 2); var s0 = this.args[0].evaluate(ctx).stringValue(); var s1 = this.args[1].evaluate(ctx).stringValue(); var i = s0.indexOf(s1); var ret; if (i == -1) { ret = ''; } else { ret = s0.substr(0,i); } return new StringValue(ret); }, 'substring-after': function(ctx) { assert(this.args.length == 2); var s0 = this.args[0].evaluate(ctx).stringValue(); var s1 = this.args[1].evaluate(ctx).stringValue(); var i = s0.indexOf(s1); var ret; if (i == -1) { ret = ''; } else { ret = s0.substr(i + s1.length); } return new StringValue(ret); }, 'substring': function(ctx) { // NOTE: XPath defines the position of the first character in a // string to be 1, in JavaScript this is 0 ([XPATH] Section 4.2). assert(this.args.length == 2 || this.args.length == 3); var s0 = this.args[0].evaluate(ctx).stringValue(); var s1 = this.args[1].evaluate(ctx).numberValue(); var ret; if (this.args.length == 2) { var i1 = Math.max(0, Math.round(s1) - 1); ret = s0.substr(i1); } else { var s2 = this.args[2].evaluate(ctx).numberValue(); var i0 = Math.round(s1) - 1; var i1 = Math.max(0, i0); var i2 = Math.round(s2) - Math.max(0, -i0); ret = s0.substr(i1, i2); } return new StringValue(ret); }, 'string-length': function(ctx) { var s; if (this.args.length > 0) { s = this.args[0].evaluate(ctx).stringValue(); } else { s = new NodeSetValue([ ctx.node ]).stringValue(); } return new NumberValue(s.length); }, 'normalize-space': function(ctx) { var s; if (this.args.length > 0) { s = this.args[0].evaluate(ctx).stringValue(); } else { s = new NodeSetValue([ ctx.node ]).stringValue(); } s = s.replace(/^\s*/,'').replace(/\s*$/,'').replace(/\s+/g, ' '); return new StringValue(s); }, 'translate': function(ctx) { assert(this.args.length == 3); var s0 = this.args[0].evaluate(ctx).stringValue(); var s1 = this.args[1].evaluate(ctx).stringValue(); var s2 = this.args[2].evaluate(ctx).stringValue(); for (var i = 0; i < s1.length; ++i) { s0 = s0.replace(new RegExp(s1.charAt(i), 'g'), s2.charAt(i)); } return new StringValue(s0); }, 'matches': function(ctx) { assert(this.args.length >= 2); var s0 = this.args[0].evaluate(ctx).stringValue(); var s1 = this.args[1].evaluate(ctx).stringValue(); if (this.args.length > 2) { var s2 = this.args[2].evaluate(ctx).stringValue(); if (/[^mi]/.test(s2)) { throw 'Invalid regular expression syntax: ' + s2; } } try { var re = new RegExp(s1, s2); } catch (e) { throw 'Invalid matches argument: ' + s1; } return new BooleanValue(re.test(s0)); }, 'boolean': function(ctx) { assert(this.args.length == 1); return new BooleanValue(this.args[0].evaluate(ctx).booleanValue()); }, 'not': function(ctx) { assert(this.args.length == 1); var ret = !this.args[0].evaluate(ctx).booleanValue(); return new BooleanValue(ret); }, 'true': function(ctx) { assert(this.args.length == 0); return new BooleanValue(true); }, 'false': function(ctx) { assert(this.args.length == 0); return new BooleanValue(false); }, 'lang': function(ctx) { assert(this.args.length == 1); var lang = this.args[0].evaluate(ctx).stringValue(); var xmllang; var n = ctx.node; while (n && n != n.parentNode /* just in case ... */) { xmllang = n.getAttribute('xml:lang'); if (xmllang) { break; } n = n.parentNode; } if (!xmllang) { return new BooleanValue(false); } else { var re = new RegExp('^' + lang + '$', 'i'); return new BooleanValue(xmllang.match(re) || xmllang.replace(/_.*$/,'').match(re)); } }, 'number': function(ctx) { assert(this.args.length == 1 || this.args.length == 0); if (this.args.length == 1) { return new NumberValue(this.args[0].evaluate(ctx).numberValue()); } else { return new NumberValue(new NodeSetValue([ ctx.node ]).numberValue()); } }, 'sum': function(ctx) { assert(this.args.length == 1); var n = this.args[0].evaluate(ctx).nodeSetValue(); var sum = 0; for (var i = 0; i < n.length; ++i) { sum += xmlValue(n[i]) - 0; } return new NumberValue(sum); }, 'floor': function(ctx) { assert(this.args.length == 1); var num = this.args[0].evaluate(ctx).numberValue(); return new NumberValue(Math.floor(num)); }, 'ceiling': function(ctx) { assert(this.args.length == 1); var num = this.args[0].evaluate(ctx).numberValue(); return new NumberValue(Math.ceil(num)); }, 'round': function(ctx) { assert(this.args.length == 1); var num = this.args[0].evaluate(ctx).numberValue(); return new NumberValue(Math.round(num)); }, // TODO(mesch): The following functions are custom. There is a // standard that defines how to add functions, which should be // applied here. 'ext-join': function(ctx) { assert(this.args.length == 2); var nodes = this.args[0].evaluate(ctx).nodeSetValue(); var delim = this.args[1].evaluate(ctx).stringValue(); var ret = ''; for (var i = 0; i < nodes.length; ++i) { if (ret) { ret += delim; } ret += xmlValue(nodes[i]); } return new StringValue(ret); }, // ext-if() evaluates and returns its second argument, if the // boolean value of its first argument is true, otherwise it // evaluates and returns its third argument. 'ext-if': function(ctx) { assert(this.args.length == 3); if (this.args[0].evaluate(ctx).booleanValue()) { return this.args[1].evaluate(ctx); } else { return this.args[2].evaluate(ctx); } }, // ext-cardinal() evaluates its single argument as a number, and // returns the current node that many times. It can be used in the // select attribute to iterate over an integer range. 'ext-cardinal': function(ctx) { assert(this.args.length >= 1); var c = this.args[0].evaluate(ctx).numberValue(); var ret = []; for (var i = 0; i < c; ++i) { ret.push(ctx.node); } return new NodeSetValue(ret); } }; function UnionExpr(expr1, expr2) { this.expr1 = expr1; this.expr2 = expr2; } UnionExpr.prototype.evaluate = function(ctx) { var nodes1 = this.expr1.evaluate(ctx).nodeSetValue(); var nodes2 = this.expr2.evaluate(ctx).nodeSetValue(); var I1 = nodes1.length; for (var i2 = 0; i2 < nodes2.length; ++i2) { var n = nodes2[i2]; var inBoth = false; for (var i1 = 0; i1 < I1; ++i1) { if (nodes1[i1] == n) { inBoth = true; i1 = I1; // break inner loop } } if (!inBoth) { nodes1.push(n); } } return new NodeSetValue(nodes1); }; function PathExpr(filter, rel) { this.filter = filter; this.rel = rel; } PathExpr.prototype.evaluate = function(ctx) { var nodes = this.filter.evaluate(ctx).nodeSetValue(); var nodes1 = []; if (ctx.returnOnFirstMatch) { for (var i = 0; i < nodes.length; ++i) { nodes1 = this.rel.evaluate(ctx.clone(nodes[i], i, nodes)).nodeSetValue(); if (nodes1.length > 0) { break; } } return new NodeSetValue(nodes1); } else { for (var i = 0; i < nodes.length; ++i) { var nodes0 = this.rel.evaluate(ctx.clone(nodes[i], i, nodes)).nodeSetValue(); for (var ii = 0; ii < nodes0.length; ++ii) { nodes1.push(nodes0[ii]); } } return new NodeSetValue(nodes1); } }; function FilterExpr(expr, predicate) { this.expr = expr; this.predicate = predicate; } FilterExpr.prototype.evaluate = function(ctx) { // the filter expression should be evaluated in its entirety with no // optimization, as we can't backtrack to it after having moved on to // evaluating the relative location path. See the testReturnOnFirstMatch // unit test. var flag = ctx.returnOnFirstMatch; ctx.setReturnOnFirstMatch(false); var nodes = this.expr.evaluate(ctx).nodeSetValue(); ctx.setReturnOnFirstMatch(flag); for (var i = 0; i < this.predicate.length; ++i) { var nodes0 = nodes; nodes = []; for (var j = 0; j < nodes0.length; ++j) { var n = nodes0[j]; if (this.predicate[i].evaluate(ctx.clone(n, j, nodes0)).booleanValue()) { nodes.push(n); } } } return new NodeSetValue(nodes); } function UnaryMinusExpr(expr) { this.expr = expr; } UnaryMinusExpr.prototype.evaluate = function(ctx) { return new NumberValue(-this.expr.evaluate(ctx).numberValue()); }; function BinaryExpr(expr1, op, expr2) { this.expr1 = expr1; this.expr2 = expr2; this.op = op; } BinaryExpr.prototype.evaluate = function(ctx) { var ret; switch (this.op.value) { case 'or': ret = new BooleanValue(this.expr1.evaluate(ctx).booleanValue() || this.expr2.evaluate(ctx).booleanValue()); break; case 'and': ret = new BooleanValue(this.expr1.evaluate(ctx).booleanValue() && this.expr2.evaluate(ctx).booleanValue()); break; case '+': ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() + this.expr2.evaluate(ctx).numberValue()); break; case '-': ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() - this.expr2.evaluate(ctx).numberValue()); break; case '*': ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() * this.expr2.evaluate(ctx).numberValue()); break; case 'mod': ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() % this.expr2.evaluate(ctx).numberValue()); break; case 'div': ret = new NumberValue(this.expr1.evaluate(ctx).numberValue() / this.expr2.evaluate(ctx).numberValue()); break; case '=': ret = this.compare(ctx, function(x1, x2) { return x1 == x2; }); break; case '!=': ret = this.compare(ctx, function(x1, x2) { return x1 != x2; }); break; case '<': ret = this.compare(ctx, function(x1, x2) { return x1 < x2; }); break; case '<=': ret = this.compare(ctx, function(x1, x2) { return x1 <= x2; }); break; case '>': ret = this.compare(ctx, function(x1, x2) { return x1 > x2; }); break; case '>=': ret = this.compare(ctx, function(x1, x2) { return x1 >= x2; }); break; default: alert('BinaryExpr.evaluate: ' + this.op.value); } return ret; }; BinaryExpr.prototype.compare = function(ctx, cmp) { var v1 = this.expr1.evaluate(ctx); var v2 = this.expr2.evaluate(ctx); var ret; if (v1.type == 'node-set' && v2.type == 'node-set') { var n1 = v1.nodeSetValue(); var n2 = v2.nodeSetValue(); ret = false; for (var i1 = 0; i1 < n1.length; ++i1) { for (var i2 = 0; i2 < n2.length; ++i2) { if (cmp(xmlValue(n1[i1]), xmlValue(n2[i2]))) { ret = true; // Break outer loop. Labels confuse the jscompiler and we // don't use them. i2 = n2.length; i1 = n1.length; } } } } else if (v1.type == 'node-set' || v2.type == 'node-set') { if (v1.type == 'number') { var s = v1.numberValue(); var n = v2.nodeSetValue(); ret = false; for (var i = 0; i < n.length; ++i) { var nn = xmlValue(n[i]) - 0; if (cmp(s, nn)) { ret = true; break; } } } else if (v2.type == 'number') { var n = v1.nodeSetValue(); var s = v2.numberValue(); ret = false; for (var i = 0; i < n.length; ++i) { var nn = xmlValue(n[i]) - 0; if (cmp(nn, s)) { ret = true; break; } } } else if (v1.type == 'string') { var s = v1.stringValue(); var n = v2.nodeSetValue(); ret = false; for (var i = 0; i < n.length; ++i) { var nn = xmlValue(n[i]); if (cmp(s, nn)) { ret = true; break; } } } else if (v2.type == 'string') { var n = v1.nodeSetValue(); var s = v2.stringValue(); ret = false; for (var i = 0; i < n.length; ++i) { var nn = xmlValue(n[i]); if (cmp(nn, s)) { ret = true; break; } } } else { ret = cmp(v1.booleanValue(), v2.booleanValue()); } } else if (v1.type == 'boolean' || v2.type == 'boolean') { ret = cmp(v1.booleanValue(), v2.booleanValue()); } else if (v1.type == 'number' || v2.type == 'number') { ret = cmp(v1.numberValue(), v2.numberValue()); } else { ret = cmp(v1.stringValue(), v2.stringValue()); } return new BooleanValue(ret); } function LiteralExpr(value) { this.value = value; } LiteralExpr.prototype.evaluate = function(ctx) { return new StringValue(this.value); }; function NumberExpr(value) { this.value = value; } NumberExpr.prototype.evaluate = function(ctx) { return new NumberValue(this.value); }; function VariableExpr(name) { this.name = name; } VariableExpr.prototype.evaluate = function(ctx) { return ctx.getVariable(this.name); } // Factory functions for semantic values (i.e. Expressions) of the // productions in the grammar. When a production is matched to reduce // the current parse state stack, the function is called with the // semantic values of the matched elements as arguments, and returns // another semantic value. The semantic value is a node of the parse // tree, an expression object with an evaluate() method that evaluates the // expression in an actual context. These factory functions are used // in the specification of the grammar rules, below. function makeTokenExpr(m) { return new TokenExpr(m); } function passExpr(e) { return e; } function makeLocationExpr1(slash, rel) { rel.absolute = true; return rel; } function makeLocationExpr2(dslash, rel) { rel.absolute = true; rel.prependStep(makeAbbrevStep(dslash.value)); return rel; } function makeLocationExpr3(slash) { var ret = new LocationExpr(); ret.appendStep(makeAbbrevStep('.')); ret.absolute = true; return ret; } function makeLocationExpr4(dslash) { var ret = new LocationExpr(); ret.absolute = true; ret.appendStep(makeAbbrevStep(dslash.value)); return ret; } function makeLocationExpr5(step) { var ret = new LocationExpr(); ret.appendStep(step); return ret; } function makeLocationExpr6(rel, slash, step) { rel.appendStep(step); return rel; } function makeLocationExpr7(rel, dslash, step) { rel.appendStep(makeAbbrevStep(dslash.value)); rel.appendStep(step); return rel; } function makeStepExpr1(dot) { return makeAbbrevStep(dot.value); } function makeStepExpr2(ddot) { return makeAbbrevStep(ddot.value); } function makeStepExpr3(axisname, axis, nodetest) { return new StepExpr(axisname.value, nodetest); } function makeStepExpr4(at, nodetest) { return new StepExpr('attribute', nodetest); } function makeStepExpr5(nodetest) { return new StepExpr('child', nodetest); } function makeStepExpr6(step, predicate) { step.appendPredicate(predicate); return step; } function makeAbbrevStep(abbrev) { switch (abbrev) { case '//': return new StepExpr('descendant-or-self', new NodeTestAny); case '.': return new StepExpr('self', new NodeTestAny); case '..': return new StepExpr('parent', new NodeTestAny); } } function makeNodeTestExpr1(asterisk) { return new NodeTestElementOrAttribute; } function makeNodeTestExpr2(ncname, colon, asterisk) { return new NodeTestNC(ncname.value); } function makeNodeTestExpr3(qname) { return new NodeTestName(qname.value); } function makeNodeTestExpr4(typeo, parenc) { var type = typeo.value.replace(/\s*\($/, ''); switch(type) { case 'node': return new NodeTestAny; case 'text': return new NodeTestText; case 'comment': return new NodeTestComment; case 'processing-instruction': return new NodeTestPI(''); } } function makeNodeTestExpr5(typeo, target, parenc) { var type = typeo.replace(/\s*\($/, ''); if (type != 'processing-instruction') { throw type; } return new NodeTestPI(target.value); } function makePredicateExpr(pareno, expr, parenc) { return new PredicateExpr(expr); } function makePrimaryExpr(pareno, expr, parenc) { return expr; } function makeFunctionCallExpr1(name, pareno, parenc) { return new FunctionCallExpr(name); } function makeFunctionCallExpr2(name, pareno, arg1, args, parenc) { var ret = new FunctionCallExpr(name); ret.appendArg(arg1); for (var i = 0; i < args.length; ++i) { ret.appendArg(args[i]); } return ret; } function makeArgumentExpr(comma, expr) { return expr; } function makeUnionExpr(expr1, pipe, expr2) { return new UnionExpr(expr1, expr2); } function makePathExpr1(filter, slash, rel) { return new PathExpr(filter, rel); } function makePathExpr2(filter, dslash, rel) { rel.prependStep(makeAbbrevStep(dslash.value)); return new PathExpr(filter, rel); } function makeFilterExpr(expr, predicates) { if (predicates.length > 0) { return new FilterExpr(expr, predicates); } else { return expr; } } function makeUnaryMinusExpr(minus, expr) { return new UnaryMinusExpr(expr); } function makeBinaryExpr(expr1, op, expr2) { return new BinaryExpr(expr1, op, expr2); } function makeLiteralExpr(token) { // remove quotes from the parsed value: var value = token.value.substring(1, token.value.length - 1); return new LiteralExpr(value); } function makeNumberExpr(token) { return new NumberExpr(token.value); } function makeVariableReference(dollar, name) { return new VariableExpr(name.value); } // Used before parsing for optimization of common simple cases. See // the begin of xpathParse() for which they are. function makeSimpleExpr(expr) { if (expr.charAt(0) == '$') { return new VariableExpr(expr.substr(1)); } else if (expr.charAt(0) == '@') { var a = new NodeTestName(expr.substr(1)); var b = new StepExpr('attribute', a); var c = new LocationExpr(); c.appendStep(b); return c; } else if (expr.match(/^[0-9]+$/)) { return new NumberExpr(expr); } else { var a = new NodeTestName(expr); var b = new StepExpr('child', a); var c = new LocationExpr(); c.appendStep(b); return c; } } function makeSimpleExpr2(expr) { var steps = stringSplit(expr, '/'); var c = new LocationExpr(); for (var i = 0; i < steps.length; ++i) { var a = new NodeTestName(steps[i]); var b = new StepExpr('child', a); c.appendStep(b); } return c; } // The axes of XPath expressions. var xpathAxis = { ANCESTOR_OR_SELF: 'ancestor-or-self', ANCESTOR: 'ancestor', ATTRIBUTE: 'attribute', CHILD: 'child', DESCENDANT_OR_SELF: 'descendant-or-self', DESCENDANT: 'descendant', FOLLOWING_SIBLING: 'following-sibling', FOLLOWING: 'following', NAMESPACE: 'namespace', PARENT: 'parent', PRECEDING_SIBLING: 'preceding-sibling', PRECEDING: 'preceding', SELF: 'self' }; var xpathAxesRe = [ xpathAxis.ANCESTOR_OR_SELF, xpathAxis.ANCESTOR, xpathAxis.ATTRIBUTE, xpathAxis.CHILD, xpathAxis.DESCENDANT_OR_SELF, xpathAxis.DESCENDANT, xpathAxis.FOLLOWING_SIBLING, xpathAxis.FOLLOWING, xpathAxis.NAMESPACE, xpathAxis.PARENT, xpathAxis.PRECEDING_SIBLING, xpathAxis.PRECEDING, xpathAxis.SELF ].join('|'); // The tokens of the language. The label property is just used for // generating debug output. The prec property is the precedence used // for shift/reduce resolution. Default precedence is 0 as a lookahead // token and 2 on the stack. TODO(mesch): this is certainly not // necessary and too complicated. Simplify this! // NOTE: tabular formatting is the big exception, but here it should // be OK. var TOK_PIPE = { label: "|", prec: 17, re: new RegExp("^\\|") }; var TOK_DSLASH = { label: "//", prec: 19, re: new RegExp("^//") }; var TOK_SLASH = { label: "/", prec: 30, re: new RegExp("^/") }; var TOK_AXIS = { label: "::", prec: 20, re: new RegExp("^::") }; var TOK_COLON = { label: ":", prec: 1000, re: new RegExp("^:") }; var TOK_AXISNAME = { label: "[axis]", re: new RegExp('^(' + xpathAxesRe + ')') }; var TOK_PARENO = { label: "(", prec: 34, re: new RegExp("^\\(") }; var TOK_PARENC = { label: ")", re: new RegExp("^\\)") }; var TOK_DDOT = { label: "..", prec: 34, re: new RegExp("^\\.\\.") }; var TOK_DOT = { label: ".", prec: 34, re: new RegExp("^\\.") }; var TOK_AT = { label: "@", prec: 34, re: new RegExp("^@") }; var TOK_COMMA = { label: ",", re: new RegExp("^,") }; var TOK_OR = { label: "or", prec: 10, re: new RegExp("^or\\b") }; var TOK_AND = { label: "and", prec: 11, re: new RegExp("^and\\b") }; var TOK_EQ = { label: "=", prec: 12, re: new RegExp("^=") }; var TOK_NEQ = { label: "!=", prec: 12, re: new RegExp("^!=") }; var TOK_GE = { label: ">=", prec: 13, re: new RegExp("^>=") }; var TOK_GT = { label: ">", prec: 13, re: new RegExp("^>") }; var TOK_LE = { label: "<=", prec: 13, re: new RegExp("^<=") }; var TOK_LT = { label: "<", prec: 13, re: new RegExp("^<") }; var TOK_PLUS = { label: "+", prec: 14, re: new RegExp("^\\+"), left: true }; var TOK_MINUS = { label: "-", prec: 14, re: new RegExp("^\\-"), left: true }; var TOK_DIV = { label: "div", prec: 15, re: new RegExp("^div\\b"), left: true }; var TOK_MOD = { label: "mod", prec: 15, re: new RegExp("^mod\\b"), left: true }; var TOK_BRACKO = { label: "[", prec: 32, re: new RegExp("^\\[") }; var TOK_BRACKC = { label: "]", re: new RegExp("^\\]") }; var TOK_DOLLAR = { label: "$", re: new RegExp("^\\$") }; var TOK_NCNAME = { label: "[ncname]", re: new RegExp('^' + XML_NC_NAME) }; var TOK_ASTERISK = { label: "*", prec: 15, re: new RegExp("^\\*"), left: true }; var TOK_LITERALQ = { label: "[litq]", prec: 20, re: new RegExp("^'[^\\']*'") }; var TOK_LITERALQQ = { label: "[litqq]", prec: 20, re: new RegExp('^"[^\\"]*"') }; var TOK_NUMBER = { label: "[number]", prec: 35, re: new RegExp('^\\d+(\\.\\d*)?') }; var TOK_QNAME = { label: "[qname]", re: new RegExp('^(' + XML_NC_NAME + ':)?' + XML_NC_NAME) }; var TOK_NODEO = { label: "[nodetest-start]", re: new RegExp('^(processing-instruction|comment|text|node)\\(') }; // The table of the tokens of our grammar, used by the lexer: first // column the tag, second column a regexp to recognize it in the // input, third column the precedence of the token, fourth column a // factory function for the semantic value of the token. // // NOTE: order of this list is important, because the first match // counts. Cf. DDOT and DOT, and AXIS and COLON. var xpathTokenRules = [ TOK_DSLASH, TOK_SLASH, TOK_DDOT, TOK_DOT, TOK_AXIS, TOK_COLON, TOK_AXISNAME, TOK_NODEO, TOK_PARENO, TOK_PARENC, TOK_BRACKO, TOK_BRACKC, TOK_AT, TOK_COMMA, TOK_OR, TOK_AND, TOK_NEQ, TOK_EQ, TOK_GE, TOK_GT, TOK_LE, TOK_LT, TOK_PLUS, TOK_MINUS, TOK_ASTERISK, TOK_PIPE, TOK_MOD, TOK_DIV, TOK_LITERALQ, TOK_LITERALQQ, TOK_NUMBER, TOK_QNAME, TOK_NCNAME, TOK_DOLLAR ]; // All the nonterminals of the grammar. The nonterminal objects are // identified by object identity; the labels are used in the debug // output only. var XPathLocationPath = { label: "LocationPath" }; var XPathRelativeLocationPath = { label: "RelativeLocationPath" }; var XPathAbsoluteLocationPath = { label: "AbsoluteLocationPath" }; var XPathStep = { label: "Step" }; var XPathNodeTest = { label: "NodeTest" }; var XPathPredicate = { label: "Predicate" }; var XPathLiteral = { label: "Literal" }; var XPathExpr = { label: "Expr" }; var XPathPrimaryExpr = { label: "PrimaryExpr" }; var XPathVariableReference = { label: "Variablereference" }; var XPathNumber = { label: "Number" }; var XPathFunctionCall = { label: "FunctionCall" }; var XPathArgumentRemainder = { label: "ArgumentRemainder" }; var XPathPathExpr = { label: "PathExpr" }; var XPathUnionExpr = { label: "UnionExpr" }; var XPathFilterExpr = { label: "FilterExpr" }; var XPathDigits = { label: "Digits" }; var xpathNonTerminals = [ XPathLocationPath, XPathRelativeLocationPath, XPathAbsoluteLocationPath, XPathStep, XPathNodeTest, XPathPredicate, XPathLiteral, XPathExpr, XPathPrimaryExpr, XPathVariableReference, XPathNumber, XPathFunctionCall, XPathArgumentRemainder, XPathPathExpr, XPathUnionExpr, XPathFilterExpr, XPathDigits ]; // Quantifiers that are used in the productions of the grammar. var Q_01 = { label: "?" }; var Q_MM = { label: "*" }; var Q_1M = { label: "+" }; // Tag for left associativity (right assoc is implied by undefined). var ASSOC_LEFT = true; // The productions of the grammar. Columns of the table: // // - target nonterminal, // - pattern, // - precedence, // - semantic value factory // // The semantic value factory is a function that receives parse tree // nodes from the stack frames of the matched symbols as arguments and // returns an a node of the parse tree. The node is stored in the top // stack frame along with the target object of the rule. The node in // the parse tree is an expression object that has an evaluate() method // and thus evaluates XPath expressions. // // The precedence is used to decide between reducing and shifting by // comparing the precendence of the rule that is candidate for // reducing with the precedence of the look ahead token. Precedence of // -1 means that the precedence of the tokens in the pattern is used // instead. TODO: It shouldn't be necessary to explicitly assign // precedences to rules. // DGF As it stands, these precedences are purely empirical; we're // not sure they can be made to be consistent at all. var xpathGrammarRules = [ [ XPathLocationPath, [ XPathRelativeLocationPath ], 18, passExpr ], [ XPathLocationPath, [ XPathAbsoluteLocationPath ], 18, passExpr ], [ XPathAbsoluteLocationPath, [ TOK_SLASH, XPathRelativeLocationPath ], 18, makeLocationExpr1 ], [ XPathAbsoluteLocationPath, [ TOK_DSLASH, XPathRelativeLocationPath ], 18, makeLocationExpr2 ], [ XPathAbsoluteLocationPath, [ TOK_SLASH ], 0, makeLocationExpr3 ], [ XPathAbsoluteLocationPath, [ TOK_DSLASH ], 0, makeLocationExpr4 ], [ XPathRelativeLocationPath, [ XPathStep ], 31, makeLocationExpr5 ], [ XPathRelativeLocationPath, [ XPathRelativeLocationPath, TOK_SLASH, XPathStep ], 31, makeLocationExpr6 ], [ XPathRelativeLocationPath, [ XPathRelativeLocationPath, TOK_DSLASH, XPathStep ], 31, makeLocationExpr7 ], [ XPathStep, [ TOK_DOT ], 33, makeStepExpr1 ], [ XPathStep, [ TOK_DDOT ], 33, makeStepExpr2 ], [ XPathStep, [ TOK_AXISNAME, TOK_AXIS, XPathNodeTest ], 33, makeStepExpr3 ], [ XPathStep, [ TOK_AT, XPathNodeTest ], 33, makeStepExpr4 ], [ XPathStep, [ XPathNodeTest ], 33, makeStepExpr5 ], [ XPathStep, [ XPathStep, XPathPredicate ], 33, makeStepExpr6 ], [ XPathNodeTest, [ TOK_ASTERISK ], 33, makeNodeTestExpr1 ], [ XPathNodeTest, [ TOK_NCNAME, TOK_COLON, TOK_ASTERISK ], 33, makeNodeTestExpr2 ], [ XPathNodeTest, [ TOK_QNAME ], 33, makeNodeTestExpr3 ], [ XPathNodeTest, [ TOK_NODEO, TOK_PARENC ], 33, makeNodeTestExpr4 ], [ XPathNodeTest, [ TOK_NODEO, XPathLiteral, TOK_PARENC ], 33, makeNodeTestExpr5 ], [ XPathPredicate, [ TOK_BRACKO, XPathExpr, TOK_BRACKC ], 33, makePredicateExpr ], [ XPathPrimaryExpr, [ XPathVariableReference ], 33, passExpr ], [ XPathPrimaryExpr, [ TOK_PARENO, XPathExpr, TOK_PARENC ], 33, makePrimaryExpr ], [ XPathPrimaryExpr, [ XPathLiteral ], 30, passExpr ], [ XPathPrimaryExpr, [ XPathNumber ], 30, passExpr ], [ XPathPrimaryExpr, [ XPathFunctionCall ], 31, passExpr ], [ XPathFunctionCall, [ TOK_QNAME, TOK_PARENO, TOK_PARENC ], -1, makeFunctionCallExpr1 ], [ XPathFunctionCall, [ TOK_QNAME, TOK_PARENO, XPathExpr, XPathArgumentRemainder, Q_MM, TOK_PARENC ], -1, makeFunctionCallExpr2 ], [ XPathArgumentRemainder, [ TOK_COMMA, XPathExpr ], -1, makeArgumentExpr ], [ XPathUnionExpr, [ XPathPathExpr ], 20, passExpr ], [ XPathUnionExpr, [ XPathUnionExpr, TOK_PIPE, XPathPathExpr ], 20, makeUnionExpr ], [ XPathPathExpr, [ XPathLocationPath ], 20, passExpr ], [ XPathPathExpr, [ XPathFilterExpr ], 19, passExpr ], [ XPathPathExpr, [ XPathFilterExpr, TOK_SLASH, XPathRelativeLocationPath ], 19, makePathExpr1 ], [ XPathPathExpr, [ XPathFilterExpr, TOK_DSLASH, XPathRelativeLocationPath ], 19, makePathExpr2 ], [ XPathFilterExpr, [ XPathPrimaryExpr, XPathPredicate, Q_MM ], 31, makeFilterExpr ], [ XPathExpr, [ XPathPrimaryExpr ], 16, passExpr ], [ XPathExpr, [ XPathUnionExpr ], 16, passExpr ], [ XPathExpr, [ TOK_MINUS, XPathExpr ], -1, makeUnaryMinusExpr ], [ XPathExpr, [ XPathExpr, TOK_OR, XPathExpr ], -1, makeBinaryExpr ], [ XPathExpr, [ XPathExpr, TOK_AND, XPathExpr ], -1, makeBinaryExpr ], [ XPathExpr, [ XPathExpr, TOK_EQ, XPathExpr ], -1, makeBinaryExpr ], [ XPathExpr, [ XPathExpr, TOK_NEQ, XPathExpr ], -1, makeBinaryExpr ], [ XPathExpr, [ XPathExpr, TOK_LT, XPathExpr ], -1, makeBinaryExpr ], [ XPathExpr, [ XPathExpr, TOK_LE, XPathExpr ], -1, makeBinaryExpr ], [ XPathExpr, [ XPathExpr, TOK_GT, XPathExpr ], -1, makeBinaryExpr ], [ XPathExpr, [ XPathExpr, TOK_GE, XPathExpr ], -1, makeBinaryExpr ], [ XPathExpr, [ XPathExpr, TOK_PLUS, XPathExpr ], -1, makeBinaryExpr, ASSOC_LEFT ], [ XPathExpr, [ XPathExpr, TOK_MINUS, XPathExpr ], -1, makeBinaryExpr, ASSOC_LEFT ], [ XPathExpr, [ XPathExpr, TOK_ASTERISK, XPathExpr ], -1, makeBinaryExpr, ASSOC_LEFT ], [ XPathExpr, [ XPathExpr, TOK_DIV, XPathExpr ], -1, makeBinaryExpr, ASSOC_LEFT ], [ XPathExpr, [ XPathExpr, TOK_MOD, XPathExpr ], -1, makeBinaryExpr, ASSOC_LEFT ], [ XPathLiteral, [ TOK_LITERALQ ], -1, makeLiteralExpr ], [ XPathLiteral, [ TOK_LITERALQQ ], -1, makeLiteralExpr ], [ XPathNumber, [ TOK_NUMBER ], -1, makeNumberExpr ], [ XPathVariableReference, [ TOK_DOLLAR, TOK_QNAME ], 200, makeVariableReference ] ]; // That function computes some optimizations of the above data // structures and will be called right here. It merely takes the // counter variables out of the global scope. var xpathRules = []; function xpathParseInit() { if (xpathRules.length) { return; } // Some simple optimizations for the xpath expression parser: sort // grammar rules descending by length, so that the longest match is // first found. xpathGrammarRules.sort(function(a,b) { var la = a[1].length; var lb = b[1].length; if (la < lb) { return 1; } else if (la > lb) { return -1; } else { return 0; } }); var k = 1; for (var i = 0; i < xpathNonTerminals.length; ++i) { xpathNonTerminals[i].key = k++; } for (i = 0; i < xpathTokenRules.length; ++i) { xpathTokenRules[i].key = k++; } xpathLog('XPath parse INIT: ' + k + ' rules'); // Another slight optimization: sort the rules into bins according // to the last element (observing quantifiers), so we can restrict // the match against the stack to the subest of rules that match the // top of the stack. // // TODO(mesch): What we actually want is to compute states as in // bison, so that we don't have to do any explicit and iterated // match against the stack. function push_(array, position, element) { if (!array[position]) { array[position] = []; } array[position].push(element); } for (i = 0; i < xpathGrammarRules.length; ++i) { var rule = xpathGrammarRules[i]; var pattern = rule[1]; for (var j = pattern.length - 1; j >= 0; --j) { if (pattern[j] == Q_1M) { push_(xpathRules, pattern[j-1].key, rule); break; } else if (pattern[j] == Q_MM || pattern[j] == Q_01) { push_(xpathRules, pattern[j-1].key, rule); --j; } else { push_(xpathRules, pattern[j].key, rule); break; } } } xpathLog('XPath parse INIT: ' + xpathRules.length + ' rule bins'); var sum = 0; mapExec(xpathRules, function(i) { if (i) { sum += i.length; } }); xpathLog('XPath parse INIT: ' + (sum / xpathRules.length) + ' average bin size'); } // Local utility functions that are used by the lexer or parser. function xpathCollectDescendants(nodelist, node, opt_tagName) { if (opt_tagName && node.getElementsByTagName) { copyArray(nodelist, node.getElementsByTagName(opt_tagName)); return; } for (var n = node.firstChild; n; n = n.nextSibling) { nodelist.push(n); xpathCollectDescendants(nodelist, n); } } /** * DGF - extract a tag name suitable for getElementsByTagName * * @param nodetest the node test * @param ignoreNonElementNodesForNTA if true, the node list returned when * evaluating "node()" will not contain * non-element nodes. This can boost * performance. This is false by default. */ function xpathExtractTagNameFromNodeTest(nodetest, ignoreNonElementNodesForNTA) { if (nodetest instanceof NodeTestName) { return nodetest.name; } if ((ignoreNonElementNodesForNTA && nodetest instanceof NodeTestAny) || nodetest instanceof NodeTestElementOrAttribute) { return "*"; } } function xpathCollectDescendantsReverse(nodelist, node) { for (var n = node.lastChild; n; n = n.previousSibling) { nodelist.push(n); xpathCollectDescendantsReverse(nodelist, n); } } // The entry point for the library: match an expression against a DOM // node. Returns an XPath value. function xpathDomEval(expr, node) { var expr1 = xpathParse(expr); var ret = expr1.evaluate(new ExprContext(node)); return ret; } // Utility function to sort a list of nodes. Used by xsltSort() and // nxslSelect(). function xpathSort(input, sort) { if (sort.length == 0) { return; } var sortlist = []; for (var i = 0; i < input.contextSize(); ++i) { var node = input.nodelist[i]; var sortitem = { node: node, key: [] }; var context = input.clone(node, 0, [ node ]); for (var j = 0; j < sort.length; ++j) { var s = sort[j]; var value = s.expr.evaluate(context); var evalue; if (s.type == 'text') { evalue = value.stringValue(); } else if (s.type == 'number') { evalue = value.numberValue(); } sortitem.key.push({ value: evalue, order: s.order }); } // Make the sort stable by adding a lowest priority sort by // id. This is very convenient and furthermore required by the // spec ([XSLT] - Section 10 Sorting). sortitem.key.push({ value: i, order: 'ascending' }); sortlist.push(sortitem); } sortlist.sort(xpathSortByKey); var nodes = []; for (var i = 0; i < sortlist.length; ++i) { nodes.push(sortlist[i].node); } input.nodelist = nodes; input.setNode(0); } // Sorts by all order criteria defined. According to the JavaScript // spec ([ECMA] Section 11.8.5), the compare operators compare strings // as strings and numbers as numbers. // // NOTE: In browsers which do not follow the spec, this breaks only in // the case that numbers should be sorted as strings, which is very // uncommon. function xpathSortByKey(v1, v2) { // NOTE: Sort key vectors of different length never occur in // xsltSort. for (var i = 0; i < v1.key.length; ++i) { var o = v1.key[i].order == 'descending' ? -1 : 1; if (v1.key[i].value > v2.key[i].value) { return +1 * o; } else if (v1.key[i].value < v2.key[i].value) { return -1 * o; } } return 0; } // Parses and then evaluates the given XPath expression in the given // input context. Notice that parsed xpath expressions are cached. function xpathEval(select, context) { var expr = xpathParse(select); var ret = expr.evaluate(context); return ret; }
generaltso/ajaxslt
xpath.js
JavaScript
bsd-3-clause
70,892
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. (async function() { TestRunner.addResult(`Tests that InspectorCSSAgent API methods work as expected.\n`); await TestRunner.loadLegacyModule('elements'); await TestRunner.loadTestModule('elements_test_runner'); await TestRunner.showPanel('elements'); await TestRunner.loadHTML(` <head> <link rel="stylesheet" href="resources/styles-new-API.css"> <style> /* An inline stylesheet */ body.mainpage { text-decoration: none; /* at least one valid property is necessary for WebCore to match a rule */ ;badproperty: 1badvalue1; } body.mainpage { prop1: val1; prop2: val2; } body:hover { color: #CDE; } #target:target { background: #bada55; outline: 5px solid lime; } </style> </head> <body id="mainBody" class="main1 main2 mainpage" style="font-weight: normal; width: 85%; background-image: url(bar.png)"> <table width="50%" id="thetable"> </table> <h1 id="toggle">H1</h1> <p id="target">:target</p> </body> `); await (() => { // TODO(crbug.com/1046354): This is a workaround for loadHTML() resolving // before parsing is finished. In this case the link stylesheet is blocking // html parsing with BlockHTMLParsingOnStyleSheets enabled and mainBody is // not found by selectNodeWithId below. let resolve; const promise = new Promise(r => resolve = r); TestRunner.waitForPageLoad(() => resolve()); return promise; })(); var bodyId; TestRunner.runTestSuite([ function test_styles(next) { function callback(styles) { TestRunner.addResult(''); TestRunner.addResult('=== Computed style property count for body ==='); var propCount = styles.computedStyle.length; TestRunner.addResult(propCount > 200 ? 'OK' : 'FAIL (' + propCount + ')'); TestRunner.addResult(''); TestRunner.addResult('=== Matched rules for body ==='); ElementsTestRunner.dumpRuleMatchesArray(styles.matchedCSSRules); TestRunner.addResult(''); TestRunner.addResult('=== Pseudo rules for body ==='); for (var i = 0; i < styles.pseudoElements.length; ++i) { TestRunner.addResult('PseudoType=' + styles.pseudoElements[i].pseudoType); ElementsTestRunner.dumpRuleMatchesArray(styles.pseudoElements[i].matches); } TestRunner.addResult(''); TestRunner.addResult('=== Inherited styles for body ==='); for (var i = 0; i < styles.inherited.length; ++i) { TestRunner.addResult('Level=' + (i + 1)); ElementsTestRunner.dumpStyle(styles.inherited[i].inlineStyle); ElementsTestRunner.dumpRuleMatchesArray(styles.inherited[i].matchedCSSRules); } TestRunner.addResult(''); TestRunner.addResult('=== Inline style for body ==='); ElementsTestRunner.dumpStyle(styles.inlineStyle); next(); } var resultStyles = {}; function computedCallback(computedStyle) { if (!computedStyle) { TestRunner.addResult('Error'); TestRunner.completeTest(); return; } resultStyles.computedStyle = computedStyle; } function matchedCallback(response) { if (response.getError()) { TestRunner.addResult('error: ' + response.getError()); TestRunner.completeTest(); return; } resultStyles.inlineStyle = response.inlineStyle; resultStyles.matchedCSSRules = response.matchedCSSRules; resultStyles.pseudoElements = response.pseudoElements; resultStyles.inherited = response.inherited; } function nodeCallback(node) { bodyId = node.id; var promises = [ TestRunner.CSSAgent.getComputedStyleForNode(node.id).then(computedCallback), TestRunner.CSSAgent.invoke_getMatchedStylesForNode({nodeId: node.id}).then(matchedCallback) ]; Promise.all(promises).then(callback.bind(null, resultStyles)); } ElementsTestRunner.selectNodeWithId('mainBody', nodeCallback); }, async function test_forcedStateHover(next) { await TestRunner.CSSAgent.forcePseudoState(bodyId, ['hover']); const response = await TestRunner.CSSAgent.invoke_getMatchedStylesForNode({nodeId: bodyId}); TestRunner.addResult('=== BODY with forced :hover ==='); ElementsTestRunner.dumpRuleMatchesArray(response.matchedCSSRules); // Note: the forced :hover state persists for now, but is removed // as part of the next test. next(); }, async function test_forcedStateTarget(next) { await TestRunner.CSSAgent.forcePseudoState(bodyId, ['target']); ElementsTestRunner.nodeWithId('target', nodeCallback); async function nodeCallback(node) { const nodeId = node.id; await TestRunner.CSSAgent.forcePseudoState(nodeId, ['target']); const response = await TestRunner.CSSAgent.invoke_getMatchedStylesForNode({nodeId: nodeId}); TestRunner.addResult('=== #target with forced :target ==='); ElementsTestRunner.dumpRuleMatchesArray(response.matchedCSSRules); // Reset all forced pseudo states for the next tests. await TestRunner.CSSAgent.forcePseudoState(nodeId, []); next(); } }, function test_textNodeComputedStyles(next) { ElementsTestRunner.nodeWithId('toggle', nodeCallback); async function nodeCallback(node) { var textNode = node.children()[0]; if (textNode.nodeType() !== Node.TEXT_NODE) { TestRunner.addResult('Failed to retrieve TextNode.'); TestRunner.completeTest(); return; } var computedStyle = await TestRunner.CSSAgent.getComputedStyleForNode(textNode.id); if (!computedStyle) { TestRunner.addResult('Error'); return; } TestRunner.addResult(''); TestRunner.addResult('=== Computed style property count for TextNode ==='); var propCount = computedStyle.length; TestRunner.addResult(propCount > 200 ? 'OK' : 'FAIL (' + propCount + ')'); next(); } }, function test_tableStyles(next) { async function nodeCallback(node) { var response = await TestRunner.CSSAgent.invoke_getInlineStylesForNode({nodeId: node.id}); if (response.getError()) { TestRunner.addResult('error: ' + response.getError()); next(); return; } TestRunner.addResult(''); TestRunner.addResult('=== Attributes style for table ==='); ElementsTestRunner.dumpStyle(response.attributesStyle); var result = await TestRunner.CSSAgent.getStyleSheetText(response.inlineStyle.styleSheetId); TestRunner.addResult(''); TestRunner.addResult('=== Stylesheet-for-inline-style text ==='); TestRunner.addResult(result || ''); await TestRunner.CSSAgent.setStyleSheetText(response.inlineStyle.styleSheetId, ''); TestRunner.addResult(''); TestRunner.addResult('=== Stylesheet-for-inline-style modification result ==='); TestRunner.addResult(null); next(); } ElementsTestRunner.nodeWithId('thetable', nodeCallback); }, async function test_addRule(next) { var frameId = TestRunner.resourceTreeModel.mainFrame.id; var styleSheetId = await TestRunner.CSSAgent.createStyleSheet(frameId); if (!styleSheetId) { TestRunner.addResult('Error in CSS.createStyleSheet'); next(); return; } var range = {startLine: 0, startColumn: 0, endLine: 0, endColumn: 0}; var rule = await TestRunner.CSSAgent.addRule(styleSheetId, 'body {}', range); if (!rule) { TestRunner.addResult('Error in CSS.addRule'); next(); return; } var style = await TestRunner.CSSAgent.setStyleTexts([{ styleSheetId: rule.style.styleSheetId, range: { startLine: rule.style.range.startLine, startColumn: rule.style.range.startColumn, endLine: rule.style.range.startLine, endColumn: rule.style.range.startColumn }, text: 'font-family: serif;' }]); if (!style) { TestRunner.addResult('Error in CSS.setStyleTexts'); next(); return; } var response = await TestRunner.CSSAgent.invoke_getMatchedStylesForNode({nodeId: bodyId}); if (response.getError()) { TestRunner.addResult('error: ' + response.getError()); next(); return; } TestRunner.addResult(''); TestRunner.addResult('=== Matched rules after rule added ==='); ElementsTestRunner.dumpRuleMatchesArray(response.matchedCSSRules); next(); }, ]); })();
chromium/chromium
third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-new-API.js
JavaScript
bsd-3-clause
8,869
// Norwegian $.extend( $.fn.pickadate.defaults, { monthsFull: [ 'janaur', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ], monthsShort: [ 'jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des' ], weekdaysFull: [ 'søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag' ], weekdaysShort: [ 'søn','man','tir', 'ons', 'tor', 'fre', 'lør' ], today: 'i dag', clear: 'slette', firstDay: 1, format: 'dd. mmm. yyyy', formatSubmit: 'yyyy/mm/dd' })
FronterAS/pickadate.js
v2-(deprecated)/pickadate.js/translations/pickadate.no_NO.js
JavaScript
mit
583
/*! * Module dependencies. */ var async = require('async'); var ValidationError = require('../error/validation.js'); var ObjectId = require('../types/objectid'); /** * Applies validators and defaults to update and findOneAndUpdate operations, * specifically passing a null doc as `this` to validators and defaults * * @param {Query} query * @param {Schema} schema * @param {Object} castedDoc * @param {Object} options * @method runValidatorsOnUpdate * @api private */ module.exports = function(query, schema, castedDoc, options) { var keys = Object.keys(castedDoc || {}); var updatedKeys = {}; var updatedValues = {}; var numKeys = keys.length; var hasDollarUpdate = false; var modified = {}; for (var i = 0; i < numKeys; ++i) { if (keys[i].charAt(0) === '$') { modifiedPaths(castedDoc[keys[i]], '', modified); var flat = flatten(castedDoc[keys[i]]); var paths = Object.keys(flat); var numPaths = paths.length; for (var j = 0; j < numPaths; ++j) { var updatedPath = paths[j].replace('.$.', '.0.'); updatedPath = updatedPath.replace(/\.\$$/, '.0'); if (keys[i] === '$set' || keys[i] === '$setOnInsert') { updatedValues[updatedPath] = flat[paths[j]]; } else if (keys[i] === '$unset') { updatedValues[updatedPath] = undefined; } updatedKeys[updatedPath] = true; } hasDollarUpdate = true; } } if (!hasDollarUpdate) { modifiedPaths(castedDoc, '', modified); updatedValues = flatten(castedDoc); updatedKeys = Object.keys(updatedValues); } if (options && options.upsert) { paths = Object.keys(query._conditions); numPaths = keys.length; for (i = 0; i < numPaths; ++i) { var path = paths[i]; var condition = query._conditions[path]; if (condition && typeof condition === 'object') { var conditionKeys = Object.keys(condition); var numConditionKeys = conditionKeys.length; var hasDollarKey = false; for (j = 0; j < numConditionKeys; ++j) { if (conditionKeys[j].charAt(0) === '$') { hasDollarKey = true; break; } } if (hasDollarKey) { continue; } } updatedKeys[path] = true; modified[path] = true; } if (options.setDefaultsOnInsert) { schema.eachPath(function(path, schemaType) { if (path === '_id') { // Ignore _id for now because it causes bugs in 2.4 return; } if (schemaType.$isSingleNested) { // Only handle nested schemas 1-level deep to avoid infinite // recursion re: https://github.com/mongodb-js/mongoose-autopopulate/issues/11 schemaType.schema.eachPath(function(_path, _schemaType) { if (path === '_id') { // Ignore _id for now because it causes bugs in 2.4 return; } var def = _schemaType.getDefault(null, true); if (!modified[path + '.' + _path] && typeof def !== 'undefined') { castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; castedDoc.$setOnInsert[path + '.' + _path] = def; updatedValues[path + '.' + _path] = def; } }); } else { var def = schemaType.getDefault(null, true); if (!modified[path] && typeof def !== 'undefined') { castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; castedDoc.$setOnInsert[path] = def; updatedValues[path] = def; } } }); } } var updates = Object.keys(updatedValues); var numUpdates = updates.length; var validatorsToExecute = []; var validationErrors = []; for (i = 0; i < numUpdates; ++i) { (function(i) { var schemaPath = schema._getSchema(updates[i]); if (schemaPath) { validatorsToExecute.push(function(callback) { schemaPath.doValidate( updatedValues[updates[i]], function(err) { if (err) { err.path = updates[i]; validationErrors.push(err); } callback(null); }, options && options.context === 'query' ? query : null); }); } })(i); } return function(callback) { async.parallel(validatorsToExecute, function() { if (validationErrors.length) { var err = new ValidationError(null); for (var i = 0; i < validationErrors.length; ++i) { err.errors[validationErrors[i].path] = validationErrors[i]; } return callback(err); } callback(null); }); }; }; function modifiedPaths(update, path, result) { var keys = Object.keys(update); var numKeys = keys.length; result = result || {}; path = path ? path + '.' : ''; for (var i = 0; i < numKeys; ++i) { var key = keys[i]; var val = update[key]; result[path + key] = true; if (shouldFlatten(val)) { modifiedPaths(val, path + key, result); } } return result; } function flatten(update, path) { var keys = Object.keys(update); var numKeys = keys.length; var result = {}; path = path ? path + '.' : ''; for (var i = 0; i < numKeys; ++i) { var key = keys[i]; var val = update[key]; if (shouldFlatten(val)) { var flat = flatten(val, path + key); for (var k in flat) { result[k] = flat[k]; } } else { result[path + key] = val; } } return result; } function shouldFlatten(val) { return val && typeof val === 'object' && !(val instanceof Date) && !(val instanceof ObjectId) && (!Array.isArray(val) || val.length > 0); }
merlox/thetoptenweb-blog
node_modules/mongoose/lib/services/updateValidators.js
JavaScript
mit
5,743
module.exports={A:{A:{"2":"J C G E B A VB"},B:{"1":"D Y g H L"},C:{"1":"0 1 3 4 5 6 l m n o p q r s x y u t","2":"TB z F I J C G E B A D Y g H L RB QB","129":"f K h i j k","420":"M N O P Q R S T U V W X v Z a b c d e"},D:{"1":"0 1 4 5 6 u t FB AB CB UB DB","2":"F I J C G E B A D Y g H L M N O P","420":"3 Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s x y"},E:{"1":"A LB","2":"9 F I J C G E B EB GB HB IB JB KB"},F:{"1":"j k l m n o p q r s","2":"7 8 E A H L M MB NB OB PB SB","420":"D N O P Q R S T U V W X v Z a b c d e f K h i w"},G:{"1":"A","2":"2 9 G BB WB XB YB ZB aB bB cB dB"},H:{"2":"eB"},I:{"1":"t","2":"2 z F fB gB hB iB jB kB"},J:{"2":"C","420":"B"},K:{"1":"K","2":"7 8 B A","420":"D w"},L:{"1":"AB"},M:{"1":"u"},N:{"2":"B A"},O:{"420":"lB"},P:{"420":"F I"},Q:{"420":"mB"},R:{"420":"nB"}},B:4,C:"getUserMedia/Stream API"};
hellokidder/js-studying
微信小程序/wxtest/node_modules/caniuse-lite/data/features/stream.js
JavaScript
mit
847
import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('paper-content', 'PaperContentComponent', { // specify the other units that are required for this test // needs: ['component:foo', 'helper:bar'] unit: true }); test('it renders', function(assert) { assert.expect(2); // creates the component instance var component = this.subject(); assert.equal(component._state, 'preRender'); // appends the component to the page this.render(); assert.equal(component._state, 'inDOM'); });
elwayman02/ember-paper
tests/unit/components/paper-content-test.js
JavaScript
mit
527
// Generated by CoffeeScript 1.9.0 (function() { var key, ref, val; ref = require('./coffee-script'); for (key in ref) { val = ref[key]; exports[key] = val; } }).call(this);
nlhuykhang/atom-config
packages/linter-coffeelint/node_modules/coffeelint/lib/lib/coffee-script/index.js
JavaScript
mit
192
// Copyright Joyent, Inc. and other Node contributors. // // 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. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var tls = require('tls'); var path = require('path'); // https://github.com/joyent/node/issues/1218 // uncatchable exception on TLS connection error (function() { var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); var errorEmitted = false; process.on('exit', function() { assert.ok(errorEmitted); }); var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { assert.ok(false); // callback should never be executed }); conn.on('error', function() { errorEmitted = true; }); })(); // SSL_accept/SSL_connect error handling (function() { var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); var errorEmitted = false; process.on('exit', function() { assert.ok(errorEmitted); }); var conn = tls.connect({ cert: cert, key: key, port: common.PORT, ciphers: 'rick-128-roll' }, function() { assert.ok(false); // callback should never be executed }); conn.on('error', function() { errorEmitted = true; }); })();
teeple/pns_server
work/install/node-v0.10.25/test/simple/test-tls-connect.js
JavaScript
gpl-2.0
2,554
import Reaction from "./core"; import * as Accounts from "./core/accounts"; import Router from "./router"; import { GeoCoder } from "./geocoder"; import Hooks from "./hooks"; import Logger from "./logger"; import { MethodHooks } from "./method-hooks"; // Legacy globals // TODO: add deprecation warnings ReactionCore = Reaction; ReactionRouter = Router; ReactionRegistry = { assignOwnerRoles: Reaction.assignOwnerRoles, createDefaultAdminUser: Reaction.createDefaultAdminUser, getRegistryDomain: Reaction.getRegistryDomain, loadPackages: Reaction.loadPackages, loadSettings: Reaction.loadSettings, Packages: Reaction.Packages, setDomain: Reaction.setDomain, setShopName: Reaction.setShopName }; export { Reaction, Accounts, Router, GeoCoder, Hooks, Logger, MethodHooks };
NahomAgidew/eCommerce
server/api/index.js
JavaScript
gpl-3.0
804
// Generated by CoffeeScript 1.6.1 (function() { this.Conditional = (function() { function Conditional(element, callerElId) { var dependencies; this.el = $(element).find('.conditional-wrapper'); this.callerElId = callerElId; if (callerElId !== void 0) { dependencies = this.el.data('depends'); if ((typeof dependencies === 'string') && (dependencies.length > 0) && (dependencies.indexOf(callerElId) === -1)) { return; } } this.url = this.el.data('url'); this.render(element); } Conditional.prototype.render = function(element) { var _this = this; return $.postWithPrefix("" + this.url + "/conditional_get", function(response) { var i, parentEl, parentId, _i, _len, _ref; _this.el.html(''); _ref = response.html; for (_i = 0, _len = _ref.length; _i < _len; _i++) { i = _ref[_i]; _this.el.append(i); } parentEl = $(element).parent(); parentId = parentEl.attr('id'); if (response.message === false) { if (parentEl.hasClass('vert')) { parentEl.hide(); } else { $(element).hide(); } } else { if (parentEl.hasClass('vert')) { parentEl.show(); } else { $(element).show(); } } return XBlock.initializeBlocks(_this.el); }); }; return Conditional; })(); }).call(this);
Emergya/icm-openedx-educamadrid-platform-basic
common/static/xmodule/modules/js/002-671868a7e1fc0cd56c25e708428edc7b.js
JavaScript
agpl-3.0
1,499
//// [tests/cases/compiler/exportStarForValues10.ts] //// //// [file0.ts] export var v = 1; //// [file1.ts] export interface Foo { x } //// [file2.ts] export * from "file0"; export * from "file1"; var x = 1; //// [file0.js] System.register([], function(exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; var v; return { setters:[], execute: function() { exports_1("v", v = 1); } } }); //// [file1.js] System.register([], function(exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; return { setters:[], execute: function() { } } }); //// [file2.js] System.register(["file0"], function(exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; var x; function exportStar_1(m) { var exports = {}; for(var n in m) { if (n !== "default") exports[n] = m[n]; } exports_1(exports); } return { setters:[ function (file0_1_1) { exportStar_1(file0_1_1); }], execute: function() { x = 1; } } });
AbubakerB/TypeScript
tests/baselines/reference/exportStarForValues10.js
JavaScript
apache-2.0
1,278
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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'; const fs = require('fs'); // Fire me up! /** * Module with server-side configuration. */ module.exports = { implements: 'settings', inject: ['nconf'], factory(nconf) { /** * Normalize a port into a number, string, or false. */ const _normalizePort = function(val) { const port = parseInt(val, 10); // named pipe if (isNaN(port)) return val; // port number if (port >= 0) return port; return false; }; const mail = nconf.get('mail') || {}; const packaged = __dirname.startsWith('/snapshot/') || __dirname.startsWith('C:\\snapshot\\'); const dfltAgentDists = packaged ? 'libs/agent_dists' : 'agent_dists'; const dfltHost = packaged ? '0.0.0.0' : '127.0.0.1'; const dfltPort = packaged ? 80 : 3000; return { agent: { dists: nconf.get('agent:dists') || dfltAgentDists }, packaged, server: { host: nconf.get('server:host') || dfltHost, port: _normalizePort(nconf.get('server:port') || dfltPort), SSLOptions: nconf.get('server:ssl') && { enable301Redirects: true, trustXFPHeader: true, key: fs.readFileSync(nconf.get('server:key')), cert: fs.readFileSync(nconf.get('server:cert')), passphrase: nconf.get('server:keyPassphrase') } }, mail, mongoUrl: nconf.get('mongodb:url') || 'mongodb://127.0.0.1/console', cookieTTL: 3600000 * 24 * 30, sessionSecret: nconf.get('server:sessionSecret') || 'keyboard cat', tokenLength: 20 }; } };
psadusumilli/ignite
modules/web-console/backend/app/settings.js
JavaScript
apache-2.0
2,672
/** * Copyright 2018 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ import {PageConfig} from '../../../../third_party/subscriptions-project/config'; import {ServiceAdapter} from '../service-adapter'; import {SubscriptionService} from '../amp-subscriptions'; describes.realWin( 'service adapter', { amp: true, }, env => { let win; let ampdoc; let subscriptionService; let serviceAdapter; let pageConfig; const serviceConfig = { services: [ { authorizationUrl: 'https://lipsum.com/authorize', actions: { subscribe: 'https://lipsum.com/subscribe', login: 'https://lipsum.com/login', }, }, ], }; beforeEach(() => { pageConfig = new PageConfig('example.org:basic', true); ampdoc = env.ampdoc; win = env.win; ampdoc = env.ampdoc; const element = win.document.createElement('script'); element.id = 'amp-subscriptions'; element.setAttribute('type', 'json'); element.innerHTML = JSON.stringify(serviceConfig); win.document.body.appendChild(element); subscriptionService = new SubscriptionService(ampdoc); serviceAdapter = new ServiceAdapter(subscriptionService); }); describe('getEncryptedDocumentKey', () => { it('should call getEncryptedDocumentKey of subscription service', () => { const stub = sandbox.stub( subscriptionService, 'getEncryptedDocumentKey' ); serviceAdapter.getEncryptedDocumentKey('serviceId'); expect(stub).to.be.calledOnce; expect(stub).to.be.calledWith('serviceId'); }); }); describe('getPageConfig', () => { it('should call getPageConfig of subscription service', () => { const stub = sandbox .stub(subscriptionService, 'getPageConfig') .callsFake(() => pageConfig); serviceAdapter.getPageConfig(); expect(stub).to.be.calledOnce; }); }); describe('delegateAction', () => { it('should call delegateActionToLocal of subscription service', () => { const p = Promise.resolve(); const stub = sandbox .stub(serviceAdapter, 'delegateActionToService') .callsFake(() => p); const action = 'action'; const result = serviceAdapter.delegateActionToLocal(action); expect(stub).to.be.calledWith(action, 'local'); expect(result).to.equal(p); }); it('should call delegateActionToService of subscription service', () => { const p = Promise.resolve(); const stub = sandbox .stub(subscriptionService, 'delegateActionToService') .callsFake(() => p); const action = 'action'; const result = serviceAdapter.delegateActionToLocal(action); expect(stub).to.be.calledWith(action); expect(result).to.equal(p); }); }); describe('resetPlatforms', () => { it('should call initializePlatformStore_', () => { const stub = sandbox.stub(subscriptionService, 'resetPlatforms'); serviceAdapter.resetPlatforms(); expect(stub).to.be.calledOnce; }); }); describe('getDialog', () => { it('should call getDialog of subscription service', () => { const stub = sandbox.stub(subscriptionService, 'getDialog'); serviceAdapter.getDialog(); expect(stub).to.be.calledOnce; }); }); describe('decorateServiceAction', () => { it('should call decorateServiceAction of subscription service', () => { const element = win.document.createElement('div'); const serviceId = 'local'; const stub = sandbox.stub(subscriptionService, 'decorateServiceAction'); serviceAdapter.decorateServiceAction(element, serviceId, 'action'); expect(stub).to.be.calledWith(element, serviceId, 'action'); }); }); describe('getReaderId', () => { it('should delegate call to getReaderId', () => { const readerIdPromise = Promise.resolve(); const stub = sandbox .stub(subscriptionService, 'getReaderId') .returns(readerIdPromise); const promise = serviceAdapter.getReaderId('service1'); expect(stub).to.be.calledOnce.calledWith('service1'); expect(promise).to.equal(readerIdPromise); }); }); } );
dotandads/amphtml
extensions/amp-subscriptions/0.1/test/test-service-adapter.js
JavaScript
apache-2.0
4,939
// (C) Copyright 2015 Martin Dougiamas // // 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. angular.module('mm.addons.mod_resource') /** * Mod resource handlers. * * @module mm.addons.mod_resource * @ngdoc service * @name $mmaModResourceHandlers */ .factory('$mmaModResourceHandlers', function($mmCourse, $mmaModResource, $mmEvents, $state, $mmSite, $mmCourseHelper, $mmCoursePrefetchDelegate, $mmFilepool, $mmFS, mmCoreDownloading, mmCoreNotDownloaded, mmCoreOutdated, mmCoreEventPackageStatusChanged, mmaModResourceComponent, $q, $mmContentLinksHelper, $mmaModResourcePrefetchHandler) { var self = {}; /** * Course content handler. * * @module mm.addons.mod_resource * @ngdoc method * @name $mmaModResourceHandlers#courseContent */ self.courseContent = function() { var self = {}; /** * Whether or not the module is enabled for the site. * * @return {Boolean} */ self.isEnabled = function() { return $mmaModResource.isPluginEnabled(); }; /** * Get the controller. * * @param {Object} module The module info. * @param {Number} courseid The course ID. * @return {Function} */ self.getController = function(module, courseid) { return function($scope) { var downloadBtn, refreshBtn, revision = $mmFilepool.getRevisionFromFileList(module.contents), timemodified = $mmFilepool.getTimemodifiedFromFileList(module.contents); downloadBtn = { hidden: true, icon: 'ion-ios-cloud-download-outline', label: 'mm.core.download', action: function(e) { e.preventDefault(); e.stopPropagation(); var size = $mmaModResourcePrefetchHandler.getDownloadSize(module); $mmCourseHelper.prefetchModule($scope, $mmaModResource, module, size, false); } }; refreshBtn = { icon: 'ion-android-refresh', label: 'mm.core.refresh', hidden: true, action: function(e) { e.preventDefault(); e.stopPropagation(); var size = $mmaModResourcePrefetchHandler.getDownloadSize(module); $mmCourseHelper.prefetchModule($scope, $mmaModResource, module, size, true); } }; $scope.title = module.name; if (module.contents.length) { var filename = module.contents[0].filename, extension = $mmFS.getFileExtension(filename); if (module.contents.length == 1 || (extension != "html" && extension != "htm")) { $scope.icon = $mmFS.getFileIcon(filename); } else { $scope.icon = $mmCourse.getModuleIconSrc('resource'); } } else { $scope.icon = $mmCourse.getModuleIconSrc('resource'); } $scope.class = 'mma-mod_resource-handler'; $scope.buttons = [downloadBtn, refreshBtn]; $scope.spinner = true; // Show spinner while calculating status. $scope.action = function(e) { if (e) { e.preventDefault(); e.stopPropagation(); } $state.go('site.mod_resource', {module: module, courseid: courseid}); }; // Show buttons according to module status. function showStatus(status) { if (status) { $scope.spinner = status === mmCoreDownloading; downloadBtn.hidden = status !== mmCoreNotDownloaded; refreshBtn.hidden = status !== mmCoreOutdated; } } // Listen for changes on this module status. var statusObserver = $mmEvents.on(mmCoreEventPackageStatusChanged, function(data) { if (data.siteid === $mmSite.getId() && data.componentId === module.id && data.component === mmaModResourceComponent) { showStatus(data.status); } }); // Get current status to decide which icon should be shown. $mmCoursePrefetchDelegate.getModuleStatus(module, courseid, revision, timemodified).then(showStatus); $scope.$on('$destroy', function() { statusObserver && statusObserver.off && statusObserver.off(); }); }; }; return self; }; /** * Content links handler. * * @module mm.addons.mod_resource * @ngdoc method * @name $mmaModResourceHandlers#linksHandler */ self.linksHandler = function() { var self = {}; /** * Whether or not the handler is enabled for a certain site. * * @param {String} siteId Site ID. * @param {Number} [courseId] Course ID related to the URL. * @return {Promise} Promise resolved with true if enabled. */ function isEnabled(siteId, courseId) { return $mmaModResource.isPluginEnabled(siteId).then(function(enabled) { if (!enabled) { return false; } return courseId || $mmCourse.canGetModuleWithoutCourseId(siteId); }); } /** * Get actions to perform with the link. * * @param {String[]} siteIds Site IDs the URL belongs to. * @param {String} url URL to treat. * @param {Number} [courseId] Course ID related to the URL. * @return {Promise} Promise resolved with the list of actions. * See {@link $mmContentLinksDelegate#registerLinkHandler}. */ self.getActions = function(siteIds, url, courseId) { // Check it's a resource URL. if (typeof self.handles(url) != 'undefined') { return $mmContentLinksHelper.treatModuleIndexUrl(siteIds, url, isEnabled, courseId); } return $q.when([]); }; /** * Check if the URL is handled by this handler. If so, returns the URL of the site. * * @param {String} url URL to check. * @return {String} Site URL. Undefined if the URL doesn't belong to this handler. */ self.handles = function(url) { var position = url.indexOf('/mod/resource/view.php'); if (position > -1) { return url.substr(0, position); } }; return self; }; return self; });
Nithis111/AIT
www/addons/mod/resource/services/handlers.js
JavaScript
apache-2.0
7,714
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ var gadgets = gadgets || {}; gadgets.i18n = gadgets.i18n || {}; gadgets.i18n.NumberFormatConstants = { DECIMAL_SEP:".", GROUP_SEP:",", PERCENT:"%", ZERO_DIGIT:"0", PLUS_SIGN:"+", MINUS_SIGN:"-", EXP_SYMBOL:"E", PERMILL:"\u2030", INFINITY:"\u221E", NAN:"NaN", DECIMAL_PATTERN:"#,##,##0.###", SCIENTIFIC_PATTERN:"#E0", PERCENT_PATTERN:"#,##,##0%", CURRENCY_PATTERN:"\u00A4#,##,##0.00;(\u00A4#,##,##0.00)", DEF_CURRENCY_CODE:"LKR" }; gadgets.i18n.NumberFormatConstants.MONETARY_SEP = gadgets.i18n.NumberFormatConstants.DECIMAL_SEP; gadgets.i18n.NumberFormatConstants.MONETARY_GROUP_SEP = gadgets.i18n.NumberFormatConstants.GROUP_SEP;
ShinichiU/OpenPNE3_with_webInstaller
plugins/opOpenSocialPlugin/lib/vendor/Shindig/features/i18n/data/NumberFormatConstants__si_LK.js
JavaScript
apache-2.0
1,468
/* global createHttpBackend: false, createMockXhr: false, MockXhr: false */ 'use strict'; describe('$httpBackend', function() { var $backend, $browser, callbacks, xhr, fakeDocument, callback; beforeEach(inject(function($injector) { callbacks = {counter: 0}; $browser = $injector.get('$browser'); fakeDocument = { $$scripts: [], createElement: jasmine.createSpy('createElement').and.callFake(function() { // Return a proper script element... return document.createElement(arguments[0]); }), body: { appendChild: jasmine.createSpy('body.appendChild').and.callFake(function(script) { fakeDocument.$$scripts.push(script); }), removeChild: jasmine.createSpy('body.removeChild').and.callFake(function(script) { var index = fakeDocument.$$scripts.indexOf(script); if (index != -1) { fakeDocument.$$scripts.splice(index, 1); } }) } }; $backend = createHttpBackend($browser, createMockXhr, $browser.defer, callbacks, fakeDocument); callback = jasmine.createSpy('done'); })); it('should do basics - open async xhr and send data', function() { $backend('GET', '/some-url', 'some-data', noop); xhr = MockXhr.$$lastInstance; expect(xhr.$$method).toBe('GET'); expect(xhr.$$url).toBe('/some-url'); expect(xhr.$$data).toBe('some-data'); expect(xhr.$$async).toBe(true); }); it('should pass null to send if no body is set', function() { $backend('GET', '/some-url', undefined, noop); xhr = MockXhr.$$lastInstance; expect(xhr.$$data).toBe(null); }); it('should pass the correct falsy value to send if falsy body is set (excluding undefined, NaN)', function() { var values = [false, 0, "", null]; angular.forEach(values, function(value) { $backend('GET', '/some-url', value, noop); xhr = MockXhr.$$lastInstance; expect(xhr.$$data).toBe(value); }); } ); it('should pass NaN to send if NaN body is set', function() { $backend('GET', '/some-url', NaN, noop); xhr = MockXhr.$$lastInstance; expect(isNaN(xhr.$$data)).toEqual(true); }); it('should call completion function with xhr.statusText if present', function() { callback.and.callFake(function(status, response, headers, statusText) { expect(statusText).toBe('OK'); }); $backend('GET', '/some-url', null, callback); xhr = MockXhr.$$lastInstance; xhr.statusText = 'OK'; xhr.onload(); expect(callback).toHaveBeenCalledOnce(); }); it('should call completion function with empty string if not present', function() { callback.and.callFake(function(status, response, headers, statusText) { expect(statusText).toBe(''); }); $backend('GET', '/some-url', null, callback); xhr = MockXhr.$$lastInstance; xhr.onload(); expect(callback).toHaveBeenCalledOnce(); }); it('should normalize IE\'s 1223 status code into 204', function() { callback.and.callFake(function(status) { expect(status).toBe(204); }); $backend('GET', 'URL', null, callback); xhr = MockXhr.$$lastInstance; xhr.status = 1223; xhr.onload(); expect(callback).toHaveBeenCalledOnce(); }); it('should set only the requested headers', function() { $backend('POST', 'URL', null, noop, {'X-header1': 'value1', 'X-header2': 'value2'}); xhr = MockXhr.$$lastInstance; expect(xhr.$$reqHeaders).toEqual({ 'X-header1': 'value1', 'X-header2': 'value2' }); }); it('should set requested headers even if they have falsy values', function() { $backend('POST', 'URL', null, noop, { 'X-header1': 0, 'X-header2': '', 'X-header3': false, 'X-header4': undefined }); xhr = MockXhr.$$lastInstance; expect(xhr.$$reqHeaders).toEqual({ 'X-header1': 0, 'X-header2': '', 'X-header3': false }); }); it('should not try to read response data when request is aborted', function() { callback.and.callFake(function(status, response, headers) { expect(status).toBe(-1); expect(response).toBe(null); expect(headers).toBe(null); }); $backend('GET', '/url', null, callback, {}, 2000); xhr = MockXhr.$$lastInstance; spyOn(xhr, 'abort'); $browser.defer.flush(); expect(xhr.abort).toHaveBeenCalledOnce(); xhr.status = 0; xhr.onabort(); expect(callback).toHaveBeenCalledOnce(); }); it('should abort request on timeout', function() { callback.and.callFake(function(status, response) { expect(status).toBe(-1); }); $backend('GET', '/url', null, callback, {}, 2000); xhr = MockXhr.$$lastInstance; spyOn(xhr, 'abort'); expect($browser.deferredFns[0].time).toBe(2000); $browser.defer.flush(); expect(xhr.abort).toHaveBeenCalledOnce(); xhr.status = 0; xhr.onabort(); expect(callback).toHaveBeenCalledOnce(); }); it('should abort request on timeout promise resolution', inject(function($timeout) { callback.and.callFake(function(status, response) { expect(status).toBe(-1); }); $backend('GET', '/url', null, callback, {}, $timeout(noop, 2000)); xhr = MockXhr.$$lastInstance; spyOn(xhr, 'abort'); $timeout.flush(); expect(xhr.abort).toHaveBeenCalledOnce(); xhr.status = 0; xhr.onabort(); expect(callback).toHaveBeenCalledOnce(); })); it('should not abort resolved request on timeout promise resolution', inject(function($timeout) { callback.and.callFake(function(status, response) { expect(status).toBe(200); }); $backend('GET', '/url', null, callback, {}, $timeout(noop, 2000)); xhr = MockXhr.$$lastInstance; spyOn(xhr, 'abort'); xhr.status = 200; xhr.onload(); expect(callback).toHaveBeenCalledOnce(); $timeout.flush(); expect(xhr.abort).not.toHaveBeenCalled(); })); it('should cancel timeout on completion', function() { callback.and.callFake(function(status, response) { expect(status).toBe(200); }); $backend('GET', '/url', null, callback, {}, 2000); xhr = MockXhr.$$lastInstance; spyOn(xhr, 'abort'); expect($browser.deferredFns[0].time).toBe(2000); xhr.status = 200; xhr.onload(); expect(callback).toHaveBeenCalledOnce(); expect($browser.deferredFns.length).toBe(0); expect(xhr.abort).not.toHaveBeenCalled(); }); it('should set withCredentials', function() { $backend('GET', '/some.url', null, callback, {}, null, true); expect(MockXhr.$$lastInstance.withCredentials).toBe(true); }); it('should call $xhrFactory with method and url', function() { var mockXhrFactory = jasmine.createSpy('mockXhrFactory').and.callFake(createMockXhr); $backend = createHttpBackend($browser, mockXhrFactory, $browser.defer, callbacks, fakeDocument); $backend('GET', '/some-url', 'some-data', noop); expect(mockXhrFactory).toHaveBeenCalledWith('GET', '/some-url'); }); it('should set up event listeners', function() { var progressFn = function() {}; var uploadProgressFn = function() {}; $backend('GET', '/url', null, callback, {}, null, null, null, {progress: progressFn}, {progress: uploadProgressFn}); xhr = MockXhr.$$lastInstance; expect(xhr.$$events.progress[0]).toBe(progressFn); expect(xhr.upload.$$events.progress[0]).toBe(uploadProgressFn); }); describe('responseType', function() { it('should set responseType and return xhr.response', function() { $backend('GET', '/whatever', null, callback, {}, null, null, 'blob'); var xhrInstance = MockXhr.$$lastInstance; expect(xhrInstance.responseType).toBe('blob'); callback.and.callFake(function(status, response) { expect(response).toBe(xhrInstance.response); }); xhrInstance.response = {some: 'object'}; xhrInstance.onload(); expect(callback).toHaveBeenCalledOnce(); }); it('should read responseText if response was not defined', function() { // old browsers like IE9, don't support responseType, so they always respond with responseText $backend('GET', '/whatever', null, callback, {}, null, null, 'blob'); var xhrInstance = MockXhr.$$lastInstance; var responseText = '{"some": "object"}'; expect(xhrInstance.responseType).toBe('blob'); callback.and.callFake(function(status, response) { expect(response).toBe(responseText); }); xhrInstance.responseText = responseText; xhrInstance.onload(); expect(callback).toHaveBeenCalledOnce(); }); }); describe('JSONP', function() { var SCRIPT_URL = /([^\?]*)\?cb=angular\.callbacks\.(.*)/; it('should add script tag for JSONP request', function() { callback.and.callFake(function(status, response) { expect(status).toBe(200); expect(response).toBe('some-data'); }); $backend('JSONP', 'http://example.org/path?cb=JSON_CALLBACK', null, callback); expect(fakeDocument.$$scripts.length).toBe(1); var script = fakeDocument.$$scripts.shift(), url = script.src.match(SCRIPT_URL); expect(url[1]).toBe('http://example.org/path'); callbacks[url[2]]('some-data'); browserTrigger(script, "load"); expect(callback).toHaveBeenCalledOnce(); }); it('should clean up the callback and remove the script', function() { $backend('JSONP', 'http://example.org/path?cb=JSON_CALLBACK', null, callback); expect(fakeDocument.$$scripts.length).toBe(1); var script = fakeDocument.$$scripts.shift(), callbackId = script.src.match(SCRIPT_URL)[2]; callbacks[callbackId]('some-data'); browserTrigger(script, "load"); expect(callbacks[callbackId]).toBe(angular.noop); expect(fakeDocument.body.removeChild).toHaveBeenCalledOnceWith(script); }); it('should set url to current location if not specified or empty string', function() { $backend('JSONP', undefined, null, callback); expect(fakeDocument.$$scripts[0].src).toBe($browser.url()); fakeDocument.$$scripts.shift(); $backend('JSONP', '', null, callback); expect(fakeDocument.$$scripts[0].src).toBe($browser.url()); }); it('should abort request on timeout and replace callback with noop', function() { callback.and.callFake(function(status, response) { expect(status).toBe(-1); }); $backend('JSONP', 'http://example.org/path?cb=JSON_CALLBACK', null, callback, null, 2000); expect(fakeDocument.$$scripts.length).toBe(1); expect($browser.deferredFns[0].time).toBe(2000); var script = fakeDocument.$$scripts.shift(), callbackId = script.src.match(SCRIPT_URL)[2]; $browser.defer.flush(); expect(fakeDocument.$$scripts.length).toBe(0); expect(callback).toHaveBeenCalledOnce(); expect(callbacks[callbackId]).toBe(angular.noop); }); // TODO(vojta): test whether it fires "async-start" // TODO(vojta): test whether it fires "async-end" on both success and error }); describe('protocols that return 0 status code', function() { function respond(status, content) { xhr = MockXhr.$$lastInstance; xhr.status = status; xhr.responseText = content; xhr.onload(); } it('should convert 0 to 200 if content and file protocol', function() { $backend = createHttpBackend($browser, createMockXhr); $backend('GET', 'file:///whatever/index.html', null, callback); respond(0, 'SOME CONTENT'); expect(callback).toHaveBeenCalled(); expect(callback.calls.mostRecent().args[0]).toBe(200); }); it('should convert 0 to 200 if content for protocols other than file', function() { $backend = createHttpBackend($browser, createMockXhr); $backend('GET', 'someProtocol:///whatever/index.html', null, callback); respond(0, 'SOME CONTENT'); expect(callback).toHaveBeenCalled(); expect(callback.calls.mostRecent().args[0]).toBe(200); }); it('should convert 0 to 404 if no content and file protocol', function() { $backend = createHttpBackend($browser, createMockXhr); $backend('GET', 'file:///whatever/index.html', null, callback); respond(0, ''); expect(callback).toHaveBeenCalled(); expect(callback.calls.mostRecent().args[0]).toBe(404); }); it('should not convert 0 to 404 if no content for protocols other than file', function() { $backend = createHttpBackend($browser, createMockXhr); $backend('GET', 'someProtocol:///whatever/index.html', null, callback); respond(0, ''); expect(callback).toHaveBeenCalled(); expect(callback.calls.mostRecent().args[0]).toBe(0); }); it('should convert 0 to 404 if no content - relative url', function() { /* global urlParsingNode: true */ var originalUrlParsingNode = urlParsingNode; //temporarily overriding the DOM element to pretend that the test runs origin with file:// protocol urlParsingNode = { hash: "#/C:/", host: "", hostname: "", href: "file:///C:/base#!/C:/foo", pathname: "/C:/foo", port: "", protocol: "file:", search: "", setAttribute: angular.noop }; try { $backend = createHttpBackend($browser, createMockXhr); $backend('GET', '/whatever/index.html', null, callback); respond(0, ''); expect(callback).toHaveBeenCalled(); expect(callback.calls.mostRecent().args[0]).toBe(404); } finally { urlParsingNode = originalUrlParsingNode; } }); it('should return original backend status code if different from 0', function() { $backend = createHttpBackend($browser, createMockXhr); // request to http:// $backend('POST', 'http://rest_api/create_whatever', null, callback); respond(201, ''); expect(callback).toHaveBeenCalled(); expect(callback.calls.mostRecent().args[0]).toBe(201); // request to file:// $backend('POST', 'file://rest_api/create_whatever', null, callback); respond(201, ''); expect(callback).toHaveBeenCalled(); expect(callback.calls.mostRecent().args[0]).toBe(201); // request to file:// with HTTP status >= 300 $backend('POST', 'file://rest_api/create_whatever', null, callback); respond(503, ''); expect(callback).toHaveBeenCalled(); expect(callback.calls.mostRecent().args[0]).toBe(503); }); }); });
aakoch/angular.js
test/ng/httpBackendSpec.js
JavaScript
mit
14,615
import Ember from "ember-metal/core"; import { get } from "ember-metal/property_get"; import run from "ember-metal/run_loop"; import { computed } from "ember-metal/computed"; import EmberView from "ember-views/views/view"; var originalLookup = Ember.lookup; var lookup, view; QUnit.module("EmberView.create", { setup: function() { Ember.lookup = lookup = {}; }, teardown: function() { run(function() { view.destroy(); }); Ember.lookup = originalLookup; } }); test("registers view in the global views hash using layerId for event targeted", function() { view = EmberView.create(); run(function() { view.appendTo('#qunit-fixture'); }); equal(EmberView.views[get(view, 'elementId')], view, 'registers view'); }); QUnit.module("EmberView.createWithMixins"); test("should warn if a non-array is used for classNames", function() { expectAssertion(function() { EmberView.createWithMixins({ elementId: 'test', classNames: computed(function() { return ['className']; }).volatile() }); }, /Only arrays are allowed/i); }); test("should warn if a non-array is used for classNamesBindings", function() { expectAssertion(function() { EmberView.createWithMixins({ elementId: 'test', classNameBindings: computed(function() { return ['className']; }).volatile() }); }, /Only arrays are allowed/i); });
vitch/ember.js
packages/ember-views/tests/views/view/init_test.js
JavaScript
mit
1,410
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ gTestfile = 'short-001.js'; /** Template for LiveConnect Tests File Name: number-004.js Description: When setting the value of a Java field with a JavaScript number or when passing a JavaScript number to a Java method as an argument, LiveConnect should be able to convert the number to any one of the following types: byte short int long float double char java.lang.Double Note that the value of the Java field may not be as precise as the JavaScript value's number, if for example, you pass a large number to a short or byte, or a float to integer. JavaScript numbers cannot be converted to instances of java.lang.Float or java.lang.Integer. This test does not cover the cases in which a Java method returns one of the above primitive Java types. Currently split up into numerous tests, since rhino live connect fails to translate numbers into the correct types. test for creating java.lang.Short objects. @author christine@netscape.com @version 1.00 */ var SECTION = "LiveConnect"; var VERSION = "1_3"; var TITLE = "LiveConnect JavaScript to Java Data Type Conversion"; startTest(); writeHeaderToLog( SECTION + " "+ TITLE); // typeof all resulting objects is "object"; var E_TYPE = "object"; // JS class of all resulting objects is "JavaObject"; var E_JSCLASS = "[object JavaObject]"; var a = new Array(); var i = 0; a[i++] = new TestObject( "new java.lang.Short(\"0\")", new java.lang.Short("0"), 0 ); a[i++] = new TestObject( "new java.lang.Short( 5 )", new java.lang.Short(5), 5 ); a[i++] = new TestObject( "new java.lang.Short( 5.5 )", new java.lang.Short(5.5), 5 ); a[i++] = new TestObject( "new java.lang.Short( Number(5) )", new java.lang.Short(Number(5)), 5 ); a[i++] = new TestObject( "new java.lang.Short( Number(5.5) )", new java.lang.Short(Number(5.5)), 5 ); for ( var i = 0; i < a.length; i++ ) { // check typeof new TestCase( SECTION, "typeof (" + a[i].description +")", a[i].type, typeof a[i].javavalue ); /* // check the js class new TestCase( SECTION, "("+ a[i].description +").getJSClass()", E_JSCLASS, a[i].jsclass ); */ // check the number value of the object new TestCase( SECTION, "Number(" + a[i].description +")", a[i].jsvalue, Number( a[i].javavalue ) ); } test(); function TestObject( description, javavalue, jsvalue ) { this.description = description; this.javavalue = javavalue; this.jsvalue = jsvalue; this.type = E_TYPE; // LC2 does not support the __proto__ property in Java objects. // this.javavalue.__proto__.getJSClass = Object.prototype.toString; // this.jsclass = this.javavalue.getJSClass(); return this; }
sam/htmlunit-rhino-fork
testsrc/tests/lc2/JSToJava/short-001.js
JavaScript
mpl-2.0
3,033
horizon.addInitFunction(function() { var allPanelGroupBodies = $('.nav_accordion > dd > div > ul'); allPanelGroupBodies.each(function(index, value) { var activePanels = $(this).find('li > a.active'); if(activePanels.length === 0) { $(this).slideUp(0); } }); // mark the active panel group var activePanel = $('.nav_accordion > dd > div > ul > li > a.active'); activePanel.closest('div').find('h4').addClass('active'); // dashboard click $('.nav_accordion > dt').click(function() { var myDashHeader = $(this); var myDashWasActive = myDashHeader.hasClass("active"); // mark the active dashboard var allDashboardHeaders = $('.nav_accordion > dt'); allDashboardHeaders.removeClass("active"); // collapse all dashboard contents var allDashboardBodies = $('.nav_accordion > dd'); allDashboardBodies.slideUp(); // if the current dashboard was active, leave it collapsed if(!myDashWasActive) { myDashHeader.addClass("active"); // expand the active dashboard body var myDashBody = myDashHeader.next(); myDashBody.slideDown(); var activeDashPanel = myDashBody.find("div > ul > li > a.active"); // if the active panel is not in the expanded dashboard if (activeDashPanel.length === 0) { // expand the active panel group var activePanel = myDashBody.find("div:first > ul"); activePanel.slideDown(); activePanel.closest('div').find("h4").addClass("active"); // collapse the inactive panel groups var nonActivePanels = myDashBody.find("div:not(:first) > ul"); nonActivePanels.slideUp(); } // the expanded dashboard contains the active panel else { // collapse the inactive panel groups activeDashPanel.closest('div').find("h4").addClass("active"); allPanelGroupBodies.each(function(index, value) { var activePanels = value.find('li > a.active'); if(activePanels.length === 0) { $(this).slideUp(); } }); } } return false; }); // panel group click $('.nav_accordion > dd > div > h4').click(function() { var myPanelGroupHeader = $(this); myPanelGroupWasActive = myPanelGroupHeader.hasClass("active"); // collapse all panel groups var allPanelGroupHeaders = $('.nav_accordion > dd > div > h4'); allPanelGroupHeaders.removeClass("active"); allPanelGroupBodies.slideUp(); // expand the selected panel group if not already active if(!myPanelGroupWasActive) { myPanelGroupHeader.addClass("active"); myPanelGroupHeader.closest('div').find('ul').slideDown(); } }); // panel selection $('.nav_accordion > dd > ul > li > a').click(function() { horizon.modals.modal_spinner(gettext("Loading")); }); });
spandanb/horizon
horizon/static/horizon/js/horizon.accordion_nav.js
JavaScript
apache-2.0
2,840
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Igor Bukanov * Ethan Hugg * Milen Nankov * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ START("13.5.1 - XMLList Constructor as Function"); x = XMLList(); TEST(1, "xml", typeof(x)); TEST(2, true, x instanceof XMLList); // Make sure it's not copied if it's an XMLList x = <> <alpha>one</alpha> <bravo>two</bravo> </>; y = XMLList(x); TEST(3, x === y, true); x += <charlie>three</charlie>; TEST(4, x === y, false); // Load from one XML type x = XMLList(<alpha>one</alpha>); TEST_XML(5, "<alpha>one</alpha>", x); // Load from Anonymous x = XMLList(<><alpha>one</alpha><bravo>two</bravo></>); correct = new XMLList(); correct += <alpha>one</alpha>; correct += <bravo>two</bravo>; TEST_XML(6, correct.toString(), x); // Load from Anonymous as string x = XMLList(<><alpha>one</alpha><bravo>two</bravo></>); correct = new XMLList(); correct += <alpha>one</alpha>; correct += <bravo>two</bravo>; TEST_XML(7, correct.toString(), x); // Load from single textnode x = XMLList("foobar"); TEST_XML(8, "foobar", x); x = XMLList(7); TEST_XML(9, "7", x); // Undefined and null should behave like "" x = XMLList(null); TEST_XML(10, "", x); x = XMLList(undefined); TEST_XML(11, "", x); END();
darkrsw/safe
tests/browser_extensions/e4x/XMLList/13.5.1.js
JavaScript
bsd-3-clause
2,967
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. 'use strict'; /** * @fileoverview Provides a mechanism for drawing massive numbers of * colored rectangles into a canvas in an efficient manner, provided * they are drawn left to right with fixed y and height throughout. * * The basic idea used here is to fuse subpixel rectangles together so that * we never issue a canvas fillRect for them. It turns out Javascript can * do this quite efficiently, compared to asking Canvas2D to do the same. * * A few extra things are done by this class in the name of speed: * - Viewport culling: off-viewport rectangles are discarded. * * - The actual discarding operation is done in world space, * e.g. pre-transform. * * - Rather than expending compute cycles trying to figure out an average * color for fused rectangles from css strings, you instead draw using * palletized colors. The fused rect is the max pallete index encountered. * * Make sure to flush the trackRenderer before finishing drawing in order * to commit any queued drawing operations. */ base.exportTo('tracing', function() { /** * Creates a fast rect renderer with a specific set of culling rules * and color pallette. * @param {GraphicsContext2D} ctx Canvas2D drawing context. * @param {number} minRectSize Only rectangles with width < minRectSize are * considered for merging. * @param {number} maxMergeDist Controls how many successive small rectangles * can be merged together before issuing a rectangle. * @param {Array} pallette The color pallete for drawing. Pallette slots * should map to valid Canvas fillStyle strings. * * @constructor */ function FastRectRenderer(ctx, minRectSize, maxMergeDist, pallette) { this.ctx_ = ctx; this.minRectSize_ = minRectSize; this.maxMergeDist_ = maxMergeDist; this.pallette_ = pallette; } FastRectRenderer.prototype = { y_: 0, h_: 0, merging_: false, mergeStartX_: 0, mergeCurRight_: 0, /** * Changes the y position and height for subsequent fillRect * calls. x and width are specifieid on the fillRect calls. */ setYandH: function(y, h) { this.flush(); this.y_ = y; this.h_ = h; }, /** * Fills rectangle at the specified location, if visible. If the * rectangle is subpixel, it will be merged with adjacent rectangles. * The drawing operation may not take effect until flush is called. * @param {number} colorId The color of this rectangle, as an index * in the renderer's color pallete. */ fillRect: function(x, w, colorId) { var r = x + w; if (w < this.minRectSize_) { if (r - this.mergeStartX_ > this.maxMergeDist_) this.flush(); if (!this.merging_) { this.merging_ = true; this.mergeStartX_ = x; this.mergeCurRight_ = r; this.mergedColorId = colorId; } else { this.mergeCurRight_ = r; this.mergedColorId = Math.max(this.mergedColorId, colorId); } } else { if (this.merging_) this.flush(); this.ctx_.fillStyle = this.pallette_[colorId]; this.ctx_.fillRect(x, this.y_, w, this.h_); } }, /** * Commits any pending fillRect operations to the underlying graphics * context. */ flush: function() { if (this.merging_) { this.ctx_.fillStyle = this.pallette_[this.mergedColorId]; this.ctx_.fillRect(this.mergeStartX_, this.y_, this.mergeCurRight_ - this.mergeStartX_, this.h_); this.merging_ = false; } } }; return { FastRectRenderer: FastRectRenderer }; });
xin3liang/platform_external_chromium-trace
trace-viewer/src/tracing/fast_rect_renderer.js
JavaScript
bsd-3-clause
3,854
Package.describe({ name: 'rocketchat:videobridge', version: '0.2.0', summary: 'jitsi integration', git: '' }); Package.onUse(function(api) { api.versionsFrom('1.0'); api.use([ 'ecmascript', 'underscore', 'less@2.5.0', 'rocketchat:lib' ]); api.use('templating', 'client'); api.addAssets('client/public/external_api.js', 'client'); api.addFiles('client/stylesheets/video.less', 'client'); api.addFiles('client/views/videoFlexTab.html', 'client'); api.addFiles('client/views/videoFlexTab.js', 'client'); api.addFiles('client/tabBar.js', 'client'); api.addFiles('client/actionLink.js', 'client'); api.addFiles('client/messageType.js', 'client'); api.addFiles('server/settings.js', 'server'); api.addFiles('server/models/Rooms.js', 'server'); api.addFiles('server/methods/jitsiSetTimeout.js', 'server'); api.addFiles('server/actionLink.js', 'server'); });
BorntraegerMarc/Rocket.Chat
packages/rocketchat-videobridge/package.js
JavaScript
mit
884
Package.describe({ name: 'rocketchat:favico', version: '0.0.1', summary: 'Favico.js for Rocket.Chat' }); Package.onUse(function(api) { api.addFiles('favico.js', 'client'); });
xasx/Rocket.Chat
packages/rocketchat-favico/package.js
JavaScript
mit
181
/** * @fileOverview Surface */ import React, { Component, PropTypes } from 'react'; import classNames from 'classnames'; import { getPresentationAttributes } from '../util/ReactUtils'; const propTypes = { width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, viewBox: PropTypes.shape({ x: PropTypes.number, y: PropTypes.number, width: PropTypes.number, height: PropTypes.number, }), className: PropTypes.string, style: PropTypes.object, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]), }; function Surface(props) { const { children, width, height, viewBox, className, style, ...others } = props; const svgView = viewBox || { width, height, x: 0, y: 0 }; const layerClass = classNames('recharts-surface', className); const attrs = getPresentationAttributes(others); return ( <svg {...attrs} className={layerClass} width={width} height={height} style={style} viewBox={`${svgView.x} ${svgView.y} ${svgView.width} ${svgView.height}`} version="1.1" > {children} </svg> ); } Surface.propTypes = propTypes; export default Surface;
happyboy171/Feeding-Fish-View-
src/vendor/recharts/src/container/Surface.js
JavaScript
mit
1,199
… consts: [[__AttributeMarker.Bindings__, "click", "change"]], template: function MyComponent_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "div", 0); $r3$.ɵɵlistener("click", function MyComponent_Template_div_click_0_listener() { return ctx.click(); })("change", function MyComponent_Template_div_change_0_listener() { return ctx.change(); }); $r3$.ɵɵelementEnd(); } }
ocombe/angular
packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_listener/same_element_chained_listeners_template.js
JavaScript
mit
425
// when the dom is ready... $(function() { var i = 0; $("colgroup").each(function() { i++; $(this).attr("id", "col"+i); }); var totalCols = i; i = 1; $("td").each(function() { $(this).attr("rel", "col"+i); i++; if (i > totalCols) { i = 1; } }); $("td").hover(function() { $(this).parent().addClass("hover"); var curCol = $(this).attr("rel"); $("#"+curCol).addClass("hover"); }, function() { $(this).parent().removeClass("hover"); var curCol = $(this).attr("rel"); $("#"+curCol).removeClass("hover"); }); });
EduSec/EduSec
js/example-one.js
JavaScript
gpl-3.0
725
var searchData= [ ['glm_20core',['GLM Core',['../a00155.html',1,'']]], ['geometric_20functions',['Geometric functions',['../a00147.html',1,'']]], ['gtc_20extensions_20_28stable_29',['GTC Extensions (Stable)',['../a00153.html',1,'']]], ['glm_5fgtc_5fbitfield',['GLM_GTC_bitfield',['../a00159.html',1,'']]], ['glm_5fgtc_5fcolor_5fencoding',['GLM_GTC_color_encoding',['../a00160.html',1,'']]], ['glm_5fgtc_5fcolor_5fspace',['GLM_GTC_color_space',['../a00161.html',1,'']]], ['glm_5fgtc_5fconstants',['GLM_GTC_constants',['../a00162.html',1,'']]], ['glm_5fgtc_5fepsilon',['GLM_GTC_epsilon',['../a00163.html',1,'']]], ['glm_5fgtc_5ffunctions',['GLM_GTC_functions',['../a00164.html',1,'']]], ['glm_5fgtc_5finteger',['GLM_GTC_integer',['../a00165.html',1,'']]], ['glm_5fgtc_5fmatrix_5faccess',['GLM_GTC_matrix_access',['../a00166.html',1,'']]], ['glm_5fgtc_5fmatrix_5finteger',['GLM_GTC_matrix_integer',['../a00167.html',1,'']]], ['glm_5fgtc_5fmatrix_5finverse',['GLM_GTC_matrix_inverse',['../a00168.html',1,'']]], ['glm_5fgtc_5fmatrix_5ftransform',['GLM_GTC_matrix_transform',['../a00169.html',1,'']]], ['glm_5fgtc_5fnoise',['GLM_GTC_noise',['../a00170.html',1,'']]], ['glm_5fgtc_5fpacking',['GLM_GTC_packing',['../a00171.html',1,'']]], ['glm_5fgtc_5fquaternion',['GLM_GTC_quaternion',['../a00172.html',1,'']]], ['glm_5fgtc_5frandom',['GLM_GTC_random',['../a00173.html',1,'']]], ['glm_5fgtc_5freciprocal',['GLM_GTC_reciprocal',['../a00174.html',1,'']]], ['glm_5fgtc_5fround',['GLM_GTC_round',['../a00175.html',1,'']]], ['glm_5fgtc_5ftype_5faligned',['GLM_GTC_type_aligned',['../a00176.html',1,'']]], ['glm_5fgtc_5ftype_5fprecision',['GLM_GTC_type_precision',['../a00177.html',1,'']]], ['glm_5fgtc_5ftype_5fptr',['GLM_GTC_type_ptr',['../a00178.html',1,'']]], ['glm_5fgtc_5fulp',['GLM_GTC_ulp',['../a00179.html',1,'']]], ['glm_5fgtc_5fvec1',['GLM_GTC_vec1',['../a00180.html',1,'']]], ['gtx_20extensions_20_28experimental_29',['GTX Extensions (Experimental)',['../a00154.html',1,'']]], ['glm_5fgtx_5fassociated_5fmin_5fmax',['GLM_GTX_associated_min_max',['../a00181.html',1,'']]], ['glm_5fgtx_5fbit',['GLM_GTX_bit',['../a00182.html',1,'']]], ['glm_5fgtx_5fclosest_5fpoint',['GLM_GTX_closest_point',['../a00183.html',1,'']]], ['glm_5fgtx_5fcolor_5fspace',['GLM_GTX_color_space',['../a00184.html',1,'']]], ['glm_5fgtx_5fcolor_5fspace_5fycocg',['GLM_GTX_color_space_YCoCg',['../a00185.html',1,'']]], ['glm_5fgtx_5fcommon',['GLM_GTX_common',['../a00186.html',1,'']]], ['glm_5fgtx_5fcompatibility',['GLM_GTX_compatibility',['../a00187.html',1,'']]], ['glm_5fgtx_5fcomponent_5fwise',['GLM_GTX_component_wise',['../a00188.html',1,'']]], ['glm_5fgtx_5fdual_5fquaternion',['GLM_GTX_dual_quaternion',['../a00189.html',1,'']]], ['glm_5fgtx_5feuler_5fangles',['GLM_GTX_euler_angles',['../a00190.html',1,'']]], ['glm_5fgtx_5fextend',['GLM_GTX_extend',['../a00191.html',1,'']]], ['glm_5fgtx_5fextented_5fmin_5fmax',['GLM_GTX_extented_min_max',['../a00192.html',1,'']]], ['glm_5fgtx_5ffast_5fexponential',['GLM_GTX_fast_exponential',['../a00193.html',1,'']]], ['glm_5fgtx_5ffast_5fsquare_5froot',['GLM_GTX_fast_square_root',['../a00194.html',1,'']]], ['glm_5fgtx_5ffast_5ftrigonometry',['GLM_GTX_fast_trigonometry',['../a00195.html',1,'']]], ['glm_5fgtx_5fgradient_5fpaint',['GLM_GTX_gradient_paint',['../a00196.html',1,'']]], ['glm_5fgtx_5fhanded_5fcoordinate_5fspace',['GLM_GTX_handed_coordinate_space',['../a00197.html',1,'']]], ['glm_5fgtx_5fhash',['GLM_GTX_hash',['../a00198.html',1,'']]], ['glm_5fgtx_5finteger',['GLM_GTX_integer',['../a00199.html',1,'']]], ['glm_5fgtx_5fintersect',['GLM_GTX_intersect',['../a00200.html',1,'']]], ['glm_5fgtx_5fio',['GLM_GTX_io',['../a00201.html',1,'']]], ['glm_5fgtx_5flog_5fbase',['GLM_GTX_log_base',['../a00202.html',1,'']]], ['glm_5fgtx_5fmatrix_5fcross_5fproduct',['GLM_GTX_matrix_cross_product',['../a00203.html',1,'']]], ['glm_5fgtx_5fmatrix_5fdecompose',['GLM_GTX_matrix_decompose',['../a00204.html',1,'']]], ['glm_5fgtx_5fmatrix_5finterpolation',['GLM_GTX_matrix_interpolation',['../a00205.html',1,'']]], ['glm_5fgtx_5fmatrix_5fmajor_5fstorage',['GLM_GTX_matrix_major_storage',['../a00206.html',1,'']]], ['glm_5fgtx_5fmatrix_5foperation',['GLM_GTX_matrix_operation',['../a00207.html',1,'']]], ['glm_5fgtx_5fmatrix_5fquery',['GLM_GTX_matrix_query',['../a00208.html',1,'']]], ['glm_5fgtx_5fmatrix_5ftransform_5f2d',['GLM_GTX_matrix_transform_2d',['../a00209.html',1,'']]], ['glm_5fgtx_5fmixed_5fproducte',['GLM_GTX_mixed_producte',['../a00210.html',1,'']]], ['glm_5fgtx_5fnorm',['GLM_GTX_norm',['../a00211.html',1,'']]], ['glm_5fgtx_5fnormal',['GLM_GTX_normal',['../a00212.html',1,'']]], ['glm_5fgtx_5fnormalize_5fdot',['GLM_GTX_normalize_dot',['../a00213.html',1,'']]], ['glm_5fgtx_5fnumber_5fprecision',['GLM_GTX_number_precision',['../a00214.html',1,'']]], ['glm_5fgtx_5foptimum_5fpow',['GLM_GTX_optimum_pow',['../a00215.html',1,'']]], ['glm_5fgtx_5forthonormalize',['GLM_GTX_orthonormalize',['../a00216.html',1,'']]], ['glm_5fgtx_5fperpendicular',['GLM_GTX_perpendicular',['../a00217.html',1,'']]], ['glm_5fgtx_5fpolar_5fcoordinates',['GLM_GTX_polar_coordinates',['../a00218.html',1,'']]], ['glm_5fgtx_5fprojection',['GLM_GTX_projection',['../a00219.html',1,'']]], ['glm_5fgtx_5fquaternion',['GLM_GTX_quaternion',['../a00220.html',1,'']]], ['glm_5fgtx_5frange',['GLM_GTX_range',['../a00221.html',1,'']]], ['glm_5fgtx_5fraw_5fdata',['GLM_GTX_raw_data',['../a00222.html',1,'']]], ['glm_5fgtx_5frotate_5fnormalized_5faxis',['GLM_GTX_rotate_normalized_axis',['../a00223.html',1,'']]], ['glm_5fgtx_5frotate_5fvector',['GLM_GTX_rotate_vector',['../a00224.html',1,'']]], ['glm_5fgtx_5fscalar_5frelational',['GLM_GTX_scalar_relational',['../a00225.html',1,'']]], ['glm_5fgtx_5fspline',['GLM_GTX_spline',['../a00226.html',1,'']]], ['glm_5fgtx_5fstd_5fbased_5ftype',['GLM_GTX_std_based_type',['../a00227.html',1,'']]], ['glm_5fgtx_5fstring_5fcast',['GLM_GTX_string_cast',['../a00228.html',1,'']]], ['glm_5fgtx_5ftransform',['GLM_GTX_transform',['../a00229.html',1,'']]], ['glm_5fgtx_5ftransform2',['GLM_GTX_transform2',['../a00230.html',1,'']]], ['glm_5fgtx_5ftype_5faligned',['GLM_GTX_type_aligned',['../a00231.html',1,'']]], ['glm_5fgtx_5ftype_5ftrait',['GLM_GTX_type_trait',['../a00232.html',1,'']]], ['glm_5fgtx_5fvec_5fswizzle',['GLM_GTX_vec_swizzle',['../a00233.html',1,'']]], ['glm_5fgtx_5fvector_5fangle',['GLM_GTX_vector_angle',['../a00234.html',1,'']]], ['glm_5fgtx_5fvector_5fquery',['GLM_GTX_vector_query',['../a00235.html',1,'']]], ['glm_5fgtx_5fwrap',['GLM_GTX_wrap',['../a00236.html',1,'']]] ];
sTorro/CViewGL
extern/glm-0.9.7.1/doc/api/search/groups_4.js
JavaScript
gpl-3.0
6,690
/** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. * * @category Shopware * @package Customer * @subpackage CustomerStream * @version $Id$ * @author shopware AG */ // {namespace name=backend/customer/view/main} // {block name="backend/customer/view/customer_stream/conditions/has_canceled_orders_condition"} Ext.define('Shopware.apps.Customer.view.customer_stream.conditions.HasCanceledOrdersCondition', { getLabel: function() { return '{s name="has_canceled_orders_condition"}{/s}'; }, supports: function(conditionClass) { return (conditionClass == 'Shopware\\Bundle\\CustomerSearchBundle\\Condition\\HasCanceledOrdersCondition'); }, create: function(callback) { callback(this._create()); }, load: function(conditionClass, items, callback) { callback(this._create()); }, _create: function() { return { title: this.getLabel(), conditionClass: 'Shopware\\Bundle\\CustomerSearchBundle\\Condition\\HasCanceledOrdersCondition', items: [{ xtype: 'component', padding: 10, html: '{s name="has_canceled_orders_condition_text"}{/s}' }] }; } }); // {/block}
wlwwt/shopware
themes/Backend/ExtJs/backend/customer/view/customer_stream/conditions/has_canceled_orders_condition.js
JavaScript
agpl-3.0
2,130
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Flags: --allow-natives-syntax (function TestNewlineInCPPComment() { function Module() { "use asm" // Crash by comment! function f() {} return f } Module(); assertTrue(%IsAsmWasmCode(Module)); })(); (function TestNewlineInCComment() { function Module() { "use asm" /* Crash by comment! */ function f() {} return f } Module(); assertTrue(%IsAsmWasmCode(Module)); })();
weolar/miniblink49
v8_7_5/test/mjsunit/asm/regress-913822.js
JavaScript
apache-2.0
580
"use strict"; 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 __()); }; var core_1 = require('@angular/core'); var dom_adapter_1 = require('../dom_adapter'); var event_manager_1 = require('./event_manager'); var DomEventsPlugin = (function (_super) { __extends(DomEventsPlugin, _super); function DomEventsPlugin() { _super.apply(this, arguments); } // This plugin should come last in the list of plugins, because it accepts all // events. DomEventsPlugin.prototype.supports = function (eventName) { return true; }; DomEventsPlugin.prototype.addEventListener = function (element, eventName, handler) { var zone = this.manager.getZone(); var outsideHandler = function (event /** TODO #9100 */) { return zone.runGuarded(function () { return handler(event); }); }; return this.manager.getZone().runOutsideAngular(function () { return dom_adapter_1.getDOM().onAndCancel(element, eventName, outsideHandler); }); }; DomEventsPlugin.prototype.addGlobalEventListener = function (target, eventName, handler) { var element = dom_adapter_1.getDOM().getGlobalEventTarget(target); var zone = this.manager.getZone(); var outsideHandler = function (event /** TODO #9100 */) { return zone.runGuarded(function () { return handler(event); }); }; return this.manager.getZone().runOutsideAngular(function () { return dom_adapter_1.getDOM().onAndCancel(element, eventName, outsideHandler); }); }; /** @nocollapse */ DomEventsPlugin.decorators = [ { type: core_1.Injectable }, ]; return DomEventsPlugin; }(event_manager_1.EventManagerPlugin)); exports.DomEventsPlugin = DomEventsPlugin; //# sourceMappingURL=dom_events.js.map
evandor/skysail-webconsole
webconsole.client/client/dist/lib/@angular/platform-browser/src/dom/events/dom_events.js
JavaScript
apache-2.0
1,930
// (C) Copyright 2015 Martin Dougiamas // // 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. angular.module('mm.addons.mod_quiz', ['mm.core']) .constant('mmaModQuizComponent', 'mmaModQuiz') .constant('mmaModQuizCheckChangesInterval', 5000) .constant('mmaModQuizComponent', 'mmaModQuiz') .constant('mmaModQuizEventAttemptFinished', 'mma_mod_quiz_attempt_finished') .constant('mmaModQuizEventAutomSynced', 'mma_mod_quiz_autom_synced') .constant('mmaModQuizSyncTime', 300000) // In milliseconds. .config(function($stateProvider) { $stateProvider .state('site.mod_quiz', { url: '/mod_quiz', params: { module: null, courseid: null }, views: { 'site': { controller: 'mmaModQuizIndexCtrl', templateUrl: 'addons/mod/quiz/templates/index.html' } } }) .state('site.mod_quiz-attempt', { url: '/mod_quiz-attempt', params: { courseid: null, quizid: null, attemptid: null }, views: { 'site': { controller: 'mmaModQuizAttemptCtrl', templateUrl: 'addons/mod/quiz/templates/attempt.html' } } }) .state('site.mod_quiz-player', { url: '/mod_quiz-player', params: { courseid: null, quizid: null, moduleurl: null // Module URL to open it in browser. }, views: { 'site': { controller: 'mmaModQuizPlayerCtrl', templateUrl: 'addons/mod/quiz/templates/player.html' } } }) .state('site.mod_quiz-review', { url: '/mod_quiz-review', params: { courseid: null, quizid: null, attemptid: null, page: -1 }, views: { 'site': { controller: 'mmaModQuizReviewCtrl', templateUrl: 'addons/mod/quiz/templates/review.html' } } }); }) .config(function($mmCourseDelegateProvider, $mmContentLinksDelegateProvider, $mmCoursePrefetchDelegateProvider) { $mmCourseDelegateProvider.registerContentHandler('mmaModQuiz', 'quiz', '$mmaModQuizHandlers.courseContentHandler'); $mmCoursePrefetchDelegateProvider.registerPrefetchHandler('mmaModQuiz', 'quiz', '$mmaModQuizPrefetchHandler'); $mmContentLinksDelegateProvider.registerLinkHandler('mmaModQuiz:index', '$mmaModQuizHandlers.indexLinksHandler'); $mmContentLinksDelegateProvider.registerLinkHandler('mmaModQuiz:grade', '$mmaModQuizHandlers.gradeLinksHandler'); $mmContentLinksDelegateProvider.registerLinkHandler('mmaModQuiz:review', '$mmaModQuizHandlers.reviewLinksHandler'); }) .run(function($mmCronDelegate) { $mmCronDelegate.register('mmaModQuiz', '$mmaModQuizHandlers.syncHandler'); });
VieiraAkA/Aplicacao
www/addons/mod/quiz/main.js
JavaScript
apache-2.0
3,228
try { eval("bosh"); } catch (e) { bosh = {}; }
jaxl/ebosh
bosh.js/src/bosh.xmpp.js
JavaScript
isc
48
/*! * resanitize - Regular expression-based HTML sanitizer and ad remover, geared toward RSS feed descriptions * Copyright(c) 2012 Dan MacTough <danmactough@gmail.com> * All rights reserved. */ /** * Dependencies */ var validator = require('validator'); /** * Remove unsafe parts and ads from HTML * * Example: * * var resanitize = require('resanitize'); * resanitize('<div style="border: 400px solid pink;">Headline</div>'); * // => '<div>Headline</div>' * * References: * - http://en.wikipedia.org/wiki/C0_and_C1_control_codes * - http://en.wikipedia.org/wiki/Unicode_control_characters * - http://www.utf8-chartable.de/unicode-utf8-table.pl * * @param {String|Buffer} HTML string to sanitize * @return {String} sanitized HTML * @api public */ function resanitize (str) { if ('string' !== typeof str) { if (Buffer.isBuffer(str)) { str = str.toString(); } else { throw new TypeError('Invalid argument: must be String or Buffer'); } } str = stripAsciiCtrlChars(str); str = stripExtendedCtrlChars(str); str = fixSpace(str); str = stripComments(str); str = stripAds(str); // It's important that this comes before the remainder // because it matches on certain attribute values that // get stripped below. str = validator.sanitize(str).xss().replace(/\[removed\]/g, '') str = fixImages(str); str = stripUnsafeTags(str); str = stripUnsafeAttrs(str); return str; } module.exports = resanitize; /** * Replace UTF-8 non-breaking space with a regular space and strip null bytes */ function fixSpace (str) { return str.replace(/\u00A0/g, ' ') // Unicode non-breaking space .replace(/[\u2028\u2029]/g, '') // UCS newline characters .replace(/\0/g, ''); } module.exports.fixSpace = fixSpace; /** * Strip superfluous whitespace */ function stripHtmlExtraSpace (str) { return str.replace(/<(div|p)[^>]*?>\s*?(?:<br[^>]*?>)*?\s*?<\/\1>/gi, '') .replace(/<(div|span)[^>]*?>\s*?<\/\1>/gi, ''); } module.exports.stripHtmlExtraSpace = stripHtmlExtraSpace; /** * Strip ASCII control characters */ function stripAsciiCtrlChars (str) { return str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/g, ''); } module.exports.stripAsciiCtrlChars = stripAsciiCtrlChars; /** * Strip ISO 6429 control characters */ function stripExtendedCtrlChars (str) { return str.replace(/[\u0080-\u009F]+/g, ''); } module.exports.stripExtendedCtrlChars = stripExtendedCtrlChars; /** * Strip HTML comments */ function stripComments (str) { return str.replace(/<!--[^>]*?-->/g, ''); } module.exports.stripComments = stripComments; /** * Permit only the provided attributes to remain in the tag */ function filterAttrs () { var allowed = []; if (Array.isArray(arguments[0])) { allowed = arguments[0]; } else { allowed = Array.prototype.slice.call(arguments); } return function (attr, name) { if ( ~allowed.indexOf(name && name.toLowerCase()) ) { return attr; } else { return ''; } }; } module.exports.filterAttrs = filterAttrs; /** * Strip the provided attributes from the tag */ function stripAttrs () { var banned = [] , regexes = []; if (Array.isArray(arguments[0])) { banned = arguments[0].filter(function (attr) { if ('string' === typeof attr) { return true; } else if (attr.constructor && 'RegExp' === attr.constructor.name) { regexes.push(attr); } }); } else { banned = Array.prototype.slice.call(arguments).filter(function (attr) { if ('string' === typeof attr) { return true; } else if (attr.constructor && 'RegExp' === attr.constructor.name) { regexes.push(attr); } }); } return function (attr, name) { if ( ~banned.indexOf(name && name.toLowerCase()) || regexes.some(function (re) { return re.test(name); }) ) { return ''; } else { return attr; } }; } module.exports.stripAttrs = stripAttrs; /** * Filter an HTML opening or self-closing tag */ function filterTag (nextFilter) { return function (rematch) { if ('function' === typeof nextFilter) { rematch = rematch.replace(/([^\s"']+?)=("|')[^>]+?\2/g, nextFilter); } // Cleanup extra whitespace return rematch.replace(/\s+/g, ' ') .replace(/ (\/)?>/, '$1>'); }; } module.exports.filterTag = filterTag; function fixImages (str) { return str.replace(/(<img[^>]*?>)/g, filterTag(filterAttrs('src', 'alt', 'title', 'height', 'width')) ); } module.exports.fixImages = fixImages; function stripUnsafeAttrs (str) { var unsafe = [ 'id' , 'class' , 'style' , 'accesskey' , 'action' , 'autocomplete' , 'autofocus' , 'clear' , 'contextmenu' , 'contenteditable' , 'draggable' , 'dropzone' , 'method' , 'tabindex' , 'target' , /on\w+/i , /data-\w+/i ]; return str.replace(/<([^ >]+?) [^>]*?>/g, filterTag(stripAttrs(unsafe))); } module.exports.stripUnsafeAttrs = stripUnsafeAttrs; function stripUnsafeTags (str) { var el = /<(?:form|input|font|blink|script|style|comment|plaintext|xmp|link|listing|meta|body|frame|frameset)\b/; var ct = 0, max = 2; // We'll repeatedly try to strip any maliciously nested elements up to [max] times while (el.test(str) && ct++ < max) { str = str.replace(/<form[^>]*?>[\s\S]*?<\/form>/gi, '') .replace(/<input[^>]*?>[\s\S]*?<\/input>/gi, '') .replace(/<\/?(?:form|input|font|blink)[^>]*?>/gi, '') // These are XSS/security risks .replace(/<script[^>]*?>[\s\S]*?<\/script>/gi, '') .replace(/<style[^>]*?>[\s\S]*?<\/style>/gi, '') // shouldn't work anyway... .replace(/<comment[^>]*?>[\s\S]*?<\/comment>/gi, '') .replace(/<plaintext[^>]*?>[\s\S]*?<\/plaintext>/gi, '') .replace(/<xmp[^>]*?>[\s\S]*?<\/xmp>/gi, '') .replace(/<\/?(?:link|listing|meta|body|frame|frameset)[^>]*?>/gi, '') // Delete iframes, except those inserted by Google in lieu of video embeds .replace(/<iframe(?![^>]*?src=("|')\S+?reader.googleusercontent.com\/reader\/embediframe.+?\1)[^>]*?>[\s\S]*?<\/iframe>/gi, '') ; } if (el.test(str)) { // We couldn't safely strip the HTML, so we return an empty string return ''; } return str; } module.exports.stripUnsafeTags = stripUnsafeTags; function stripAds (str) { return str.replace(/<div[^>]*?class=("|')snap_preview\1[^>]*?>(?:<br[^>]*?>)?([\s\S]*?)<\/div>/gi, '$2') .replace(/<div[^>]*?class=("|')(?:feedflare|zemanta-pixie)\1[^>]*?>[\s\S]*?<\/div>/gi, '') .replace(/<!--AD BEGIN-->[\s\S]*?<!--AD END-->\s*/gi, '') .replace(/<table[^>]*?>[\s\S]*?<\/table>\s*?<div[^>]*?>[\s\S]*?Ads by Pheedo[\s\S]*?<\/div>/gi, '') .replace(/<table[^>]*?>.*?<img[^>]*?src=("|')[^>]*?advertisement[^>]*?\1.*?>.*?<\/table>/gi, '') .replace(/<br[^>]*?>\s*?<br[^>]*?>\s*?<span[^>]*?class=("|')advertisement\1[^>]*?>[\s\S]*?<\/span>[\s\S]*<div[^>]*?>[\s\S]*?Ads by Pheedo[\s\S]*?<\/div>/gi, '') .replace(/<br[^>]*?>\s*?<br[^>]*?>\s*?(?:<[^>]+>\s*)*?<hr[^>]*?>\s*?<div[^>]*?>(?:Featured Advertiser|Presented By:)<\/div>[\s\S]*<div[^>]*?>[\s\S]*?(?:Ads by Pheedo|ads\.pheedo\.com)[\s\S]*?<\/div>/gi, '') .replace(/<br[^>]*?>\s*?<br[^>]*?>\s*?<a[^>]*?href=("|')http:\/\/[^>]*?\.?(?:pheedo|pheedcontent)\.com\/[^>]*?\1[\s\S]*?<\/a>[\s\S]*$/gim, '') .replace(/<div[^>]*?class=("|')cbw snap_nopreview\1[^>]*?>[\s\S]*$/gim, '') .replace(/<div><a href=(?:"|')http:\/\/d\.techcrunch\.com\/ck\.php[\s\S]*?<\/div> */gi, '') .replace(/<(p|div)[^>]*?>\s*?<a[^>]*?href=("|')[^>]+?\2[^>]*?><img[^>]*?src=("|')http:\/\/(?:feedads\.googleadservices|feedproxy\.google|feeds2?\.feedburner)\.com\/(?:~|%7e)[^>]*?\/[^>]+?\3[^>]*?>[\s\S]*?<\/\1>/gi, '') .replace(/<(p|div)[^>]*?>\s*?<a[^>]*?href=("|')[^>]+?\2[^>]*?><img[^>]*?src=("|')http:\/\/feeds\.[^>]+?\.[^>]+?\/(?:~|%7e)[^>]\/[^>]+?\3[^>]*?>[\s\S]*?<\/\1>/gi, '') .replace(/<a[^>]*?href=("|')http:\/\/feeds\.[^>]+?\.[^>]+?\/(?:~|%7e)[a-qs-z]\/[^>]+?\1[\s\S]*?<\/a>/gi, '') .replace(/<a[^>]*?href=("|')http:\/\/[^>]*?\.?addtoany\.com\/[^>]*?\1[\s\S]*?<\/a>/gi, '') .replace(/<a[^>]*?href=("|')http:\/\/feeds\.wordpress\.com\/[\.\d]+?\/(?:comments|go[\s\S]*)\/[^>]+?\1[\s\S]*?<\/a> ?/gi, '') .replace(/<a[^>]*?href=("|')http:\/\/[^>]*?\.?doubleclick\.net\/[^>]*?\1[\s\S]*?<\/a>/gi, '') .replace(/<a[^>]*?href=("|')http:\/\/[^>]*?\.?fmpub\.net\/adserver\/[^>]*?\1[\s\S]*?<\/a>/gi, '') .replace(/<a[^>]*?href=("|')http:\/\/[^>]*?\.?eyewonderlabs\.com\/[^>]*?\1[\s\S]*?<\/a>/gi, '') .replace(/<a[^>]*?href=("|')http:\/\/[^>]*?\.?pheedo\.com\/[^>]*?\1[\s\S]*?<\/a>/gi, '') .replace(/<a[^>]*?href=("|')http:\/\/api\.tweetmeme\.com\/share\?[^>]*?\1[\s\S]*?<\/a>/gi, '') .replace(/<p><a[^>]*?href=("|')http:\/\/rss\.cnn\.com\/+?(?:~|%7e)a\/[^>]*?\1[\s\S]*?<\/p>/gi, '') .replace(/<img[^>]*?src=("|')http:\/\/feeds\.[^>]+?\.[^>]+?\/(?:~|%7e)r\/[^>]+?\1[\s\S]*?>/gi, '') .replace(/<img[^>]*?src=("|')http:\/\/rss\.nytimes\.com\/c\/[^>]*?\1.*?>.*$/gim, '') .replace(/<img[^>]*?src=("|')http:\/\/feeds\.washingtonpost\.com\/c\/[^>]*?\1.*?>.*$/gim, '') .replace(/<img[^>]*?src=("|')http:\/\/[^>]*?\.?feedsportal\.com\/c\/[^>]*?\1.*?>.*$/gim, '') .replace(/<img[^>]*?src=("|')http:\/\/(?:feedads\.googleadservices|feedproxy\.google|feeds2\.feedburner)\.com\/(?:~|%7e)r\/[^>]+?\1[\s\S]*?>/gi, '') .replace(/<img[^>]*?src=("|')http:\/\/rss\.cnn\.com\/~r\/[^>]*?\1[\s\S]*?>/gi, '') .replace(/<img[^>]*?src=("|')http:\/\/[^>]*?\.?fmpub\.net\/adserver\/[^>]*?\1[\s\S]*?>/gi, '') .replace(/<img[^>]*?src=("|')http:\/\/[^>]*?\.?pheedo\.com\/[^>]*?\1[\s\S]*?>/gi, '') .replace(/<img[^>]*?src=("|')http:\/\/stats\.wordpress\.com\/[\w]\.gif\?[^>]*?\1[\s\S]*?>/gi, '') .replace(/<img[^>]*?src=("|')http:\/\/feeds\.wired\.com\/c\/[^>]*?\1.*?>.*$/gim, '') .replace(/<p><strong><em>Crunch Network[\s\S]*?<\/p>/gi, '') .replace(/<embed[^>]*?castfire_player[\s\S]*?> *?(<\/embed>)?/gi, '') .replace(/<embed[^>]*?src=("|')[^>]*?castfire\.com[^>]+?\1[\s\S]*?> *?(<\/embed>)?/gi, '') .replace(/<p align=("|')right\1><em>Sponsor<\/em>[\s\S]*?<\/p>/gi, '') .replace(/<div [\s\S]*?<img [^>]*?src=(?:"|')[^>]*?\/share-buttons\/[\s\S]*?<\/div>[\s]*/gi, '') // This is that annoying footer in every delicious item .replace(/<span[^>]*?>\s*?<a[^>]*?href=("|')[^\1]+?src=feed_newsgator\1[^>]*?>[\s\S]*<\/span>/gi, '') // This is the annoying footer from ATL .replace(/<p[^>]*?><strong><a[^>]*?href=("|')[^>]*?abovethelaw\.com\/[\s\S]+?\1[^>]*?>Continue reading[\s\S]*<\/p>/gi, '') // This is the annoying link at the end of WaPo articles .replace(/<a[^>]*?>Read full article[\s\S]*?<\/a>/gi, '') // These ads go... .replace(/<div[^>]*?><a[^>]*?href=("|')[^>]*?crunchbase\.com\/company\/[\s\S]+?\1[^>]*?>[\s\S]*?<div[\s\S]*?>Loading information about[\s\S]*?<\/div>/gi, '') .replace(/<div[^>]*?class=("|')cb_widget_[^>]+?\1[\s\S]*?><\/div>/gi, '') .replace(/<div[^>]*?class=("|')cb_widget_[^>]+?\1[\s\S]*?>[\s\S]*?<\/div>/gi, '') // Before these .replace(/<a[^>]*?href=("|')[^>]*?crunchbase\.com\/\1[\s\S]*?<\/a>\s*/gi, '') .replace(/<div[^>]*?class=("|')cb_widget\1[^>]*?>[\s\S]*?<\/div>/gi, '') // Clean up some empty things //.replace(/<(div|p|span)[^>]*?>(\s|<br *?\/?>|(?R))*?<\/\1>/gi, '') .replace(/(\s|<br[^>]*?\/?>)*$/gim, '') ; } module.exports.stripAds = stripAds; /** * Dumbly strip angle brackets */ function stripHtml (str) { return str.replace(/<.*?>/g, ''); } module.exports.stripHtml = stripHtml;
danmactough/node-resanitize
resanitize.js
JavaScript
mit
12,345
/* * /MathJax/jax/output/CommonHTML/config.js * * Copyright (c) 2009-2018 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ MathJax.OutputJax.CommonHTML=MathJax.OutputJax({id:"CommonHTML",version:"2.7.3",directory:MathJax.OutputJax.directory+"/CommonHTML",extensionDir:MathJax.OutputJax.extensionDir+"/CommonHTML",autoloadDir:MathJax.OutputJax.directory+"/CommonHTML/autoload",fontDir:MathJax.OutputJax.directory+"/CommonHTML/fonts",webfontDir:MathJax.OutputJax.fontDir+"/HTML-CSS",config:{matchFontHeight:true,scale:100,minScaleAdjust:50,mtextFontInherit:false,undefinedFamily:"STIXGeneral,'Cambria Math','Arial Unicode MS',serif",EqnChunk:(MathJax.Hub.Browser.isMobile?20:100),EqnChunkFactor:1.5,EqnChunkDelay:100,linebreaks:{automatic:false,width:"container"}}});if(!MathJax.Hub.config.delayJaxRegistration){MathJax.OutputJax.CommonHTML.Register("jax/mml")}MathJax.OutputJax.CommonHTML.loadComplete("config.js");
davidsiaw/weaver
data/weaver/js/MathJax/jax/output/CommonHTML/config.js
JavaScript
mit
1,466
var satisfy = require('satisfy') , Satisfaction = satisfy.Satisfaction; var _fill = Satisfaction.prototype.fill; Satisfaction.prototype.fill = function () { if (arguments.length === 1) { var namesToVals = arguments[0]; for (var name in namesToVals) { _fill.call(this, 'input[name="' + name + '"]', namesToVals[name]); } return this; } if (arguments.length === 2) { if ('string' === typeof arguments[1]) { return _fill.apply(this, arguments); } var formSelector = this._currFormSelector = arguments[0] , namesToVals = arguments[1]; for (var name in namesToVals) { this.fill(formSelector + ' input[name="' + name + '"]', namesToVals[name]); } return this; } throw new Error("Unsupported function signature for Satisfaction.prototype.fill"); }; Satisfaction.prototype.submit = function submit () { var submitSelector = '' , currFormSelector = this._currFormSelector; if (currFormSelector) { submitSelector += currFormSelector + ' '; } submitSelector += 'input[type=submit]'; return this.click(submitSelector); } var _expect = Satisfaction.prototype.expect; Satisfaction.prototype.expect = function (selector) { return new Assertion(selector, this); }; var flags = { not: ['to', 'have'] , to: ['not', 'have'] , have: [] }; function Assertion (selector, satisfaction, flag, parent) { this.selector = selector; this.satisfaction = satisfaction; if (flag == 'not') { this.onComplete = function () { this.selector = ':not(' + this.selector + ')'; } } this.flags = {}; if (undefined != parent) { this.flags[flag] = true; for (var i in parent.flags) if (parent.flags.hasOwnProperty(i)) { this.flags[i] = true; } if (parent.onComplete) this.onComplete = parent.onComplete; } var $flags = flag ? flags[flag] : Object.keys(flags) , self = this; for (var i = $flags.length; i--; ) { // avoid recursion if (this.flags[$flags[i]]) continue; var name = $flags[i] , assertion = new Assertion(this.selector, this.satisfaction, name, this); this[name] = assertion; } } Assertion.prototype.text = function (str) { this.selector += ':contains(' + str + ')' return this }; // Delegate any methods with satisfaction method names back to satisfaction var satisfyMethodNames = ['run', 'fill', 'expect', 'click', 'submit']; for (var i = satisfyMethodNames.length; i--; ) { var name = satisfyMethodNames[i]; (function (name) { Assertion.prototype[name] = function () { if (this.onComplete) this.onComplete(); console.log(this.selector); _expect.call(this.satisfaction, this.selector); return this.satisfaction[name].apply(this.satisfaction, arguments); }; })(name); } module.exports = satisfy;
fjytzh/pomeframe
web-server/node_modules/everyauth/test/util/satisfy.js
JavaScript
mit
2,810
t = db.index_arr1 t.drop() t.insert( { _id : 1 , a : 5 , b : [ { x : 1 } ] } ) t.insert( { _id : 2 , a : 5 , b : [] } ) t.insert( { _id : 3 , a : 5 } ) assert.eq( 3 , t.find( { a : 5 } ).itcount() , "A1" ) t.ensureIndex( { a : 1 , "b.x" : 1 } ) //t.find().sort( { a : 1 } )._addSpecial( "$returnKey" , 1 ).forEach( printjson ) //t.find( { a : 5 } ).forEach( printjson ) assert.eq( 3 , t.find( { a : 5 } ).itcount() , "A2" ); // SERVER-1082 assert.eq( 2 , t.getIndexes().length , "B1" ) t.insert( { _id : 4 , a : 5 , b : [] } ) t.ensureIndex( { a : 1 , "b.a" : 1 , "b.c" : 1 } ) assert.eq( 3 , t.getIndexes().length , "B2" )
barakav/robomongo
src/third-party/mongodb/jstests/index_arr1.js
JavaScript
gpl-3.0
634
var namespace_mix_e_r_p_1_1_net_1_1_core_1_1_modules_1_1_back_office_1_1_hubs = [ [ "DbHub", "class_mix_e_r_p_1_1_net_1_1_core_1_1_modules_1_1_back_office_1_1_hubs_1_1_db_hub.html", "class_mix_e_r_p_1_1_net_1_1_core_1_1_modules_1_1_back_office_1_1_hubs_1_1_db_hub" ] ];
mixerp/mixerp
docs/api/namespace_mix_e_r_p_1_1_net_1_1_core_1_1_modules_1_1_back_office_1_1_hubs.js
JavaScript
gpl-3.0
273
/* * jQuery UI @VERSION * * Copyright (c) 2008 AUTHORS.txt (http://ui.jquery.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI */ ;(function($) { /** jQuery core modifications and additions **/ $.keyCode = { BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38 }; var _remove = $.fn.remove, isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9); //Helper functions and ui object $.ui = { version: "@VERSION", // $.ui.plugin is deprecated. Use the proxy pattern instead. plugin: { add: function(module, option, set) { var proto = $.ui[module].prototype; for(var i in set) { proto.plugins[i] = proto.plugins[i] || []; proto.plugins[i].push([option, set[i]]); } }, call: function(instance, name, args) { var set = instance.plugins[name]; if(!set) { return; } for (var i = 0; i < set.length; i++) { if (instance.options[set[i][0]]) { set[i][1].apply(instance.element, args); } } } }, contains: function(a, b) { var safari2 = $.browser.safari && $.browser.version < 522; if (a.contains && !safari2) { return a.contains(b); } if (a.compareDocumentPosition) return !!(a.compareDocumentPosition(b) & 16); while (b = b.parentNode) if (b == a) return true; return false; }, cssCache: {}, css: function(name) { if ($.ui.cssCache[name]) { return $.ui.cssCache[name]; } var tmp = $('<div class="ui-gen">').addClass(name).css({position:'absolute', top:'-5000px', left:'-5000px', display:'block'}).appendTo('body'); //if (!$.browser.safari) //tmp.appendTo('body'); //Opera and Safari set width and height to 0px instead of auto //Safari returns rgba(0,0,0,0) when bgcolor is not set $.ui.cssCache[name] = !!( (!(/auto|default/).test(tmp.css('cursor')) || (/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) || !(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor'))) ); try { $('body').get(0).removeChild(tmp.get(0)); } catch(e){} return $.ui.cssCache[name]; }, hasScroll: function(el, a) { //If overflow is hidden, the element might have extra content, but the user wants to hide it if ($(el).css('overflow') == 'hidden') { return false; } var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop', has = false; if (el[scroll] > 0) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[scroll] = 1; has = (el[scroll] > 0); el[scroll] = 0; return has; }, isOverAxis: function(x, reference, size) { //Determines when x coordinate is over "b" element axis return (x > reference) && (x < (reference + size)); }, isOver: function(y, x, top, left, height, width) { //Determines when x, y coordinates is over "b" element return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width); } }; // WAI-ARIA normalization if (isFF2) { var attr = $.attr, removeAttr = $.fn.removeAttr, ariaNS = "http://www.w3.org/2005/07/aaa", ariaState = /^aria-/, ariaRole = /^wairole:/; $.attr = function(elem, name, value) { var set = value !== undefined; return (name == 'role' ? (set ? attr.call(this, elem, name, "wairole:" + value) : (attr.apply(this, arguments) || "").replace(ariaRole, "")) : (ariaState.test(name) ? (set ? elem.setAttributeNS(ariaNS, name.replace(ariaState, "aaa:"), value) : attr.call(this, elem, name.replace(ariaState, "aaa:"))) : attr.apply(this, arguments))); }; $.fn.removeAttr = function(name) { return (ariaState.test(name) ? this.each(function() { this.removeAttributeNS(ariaNS, name.replace(ariaState, "")); }) : removeAttr.call(this, name)); }; } //jQuery plugins $.fn.extend({ remove: function() { // Safari has a native remove event which actually removes DOM elements, // so we have to use triggerHandler instead of trigger (#3037). $("*", this).add(this).each(function() { $(this).triggerHandler("remove"); }); return _remove.apply(this, arguments ); }, enableSelection: function() { return this .attr('unselectable', 'off') .css('MozUserSelect', '') .unbind('selectstart.ui'); }, disableSelection: function() { return this .attr('unselectable', 'on') .css('MozUserSelect', 'none') .bind('selectstart.ui', function() { return false; }); }, scrollParent: function() { var scrollParent; if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); }).eq(0); } return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent; } }); //Additional selectors $.extend($.expr[':'], { data: function(a, i, m) { return $.data(a, m[3]); }, // TODO: add support for object, area tabbable: function(a, i, m) { var nodeName = a.nodeName.toLowerCase(); function isVisible(element) { return !($(element).is(':hidden') || $(element).parents(':hidden').length); } return ( // in tab order a.tabIndex >= 0 && ( // filter node types that participate in the tab order // anchor tag ('a' == nodeName && a.href) || // enabled form element (/input|select|textarea|button/.test(nodeName) && 'hidden' != a.type && !a.disabled) ) && // visible on page isVisible(a) ); } }); // $.widget is a factory to create jQuery plugins // taking some boilerplate code out of the plugin code function getter(namespace, plugin, method, args) { function getMethods(type) { var methods = $[namespace][plugin][type] || []; return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods); } var methods = getMethods('getter'); if (args.length == 1 && typeof args[0] == 'string') { methods = methods.concat(getMethods('getterSetter')); } return ($.inArray(method, methods) != -1); } $.widget = function(name, prototype) { var namespace = name.split(".")[0]; name = name.split(".")[1]; // create plugin method $.fn[name] = function(options) { var isMethodCall = (typeof options == 'string'), args = Array.prototype.slice.call(arguments, 1); // prevent calls to internal methods if (isMethodCall && options.substring(0, 1) == '_') { return this; } // handle getter methods if (isMethodCall && getter(namespace, name, options, args)) { var instance = $.data(this[0], name); return (instance ? instance[options].apply(instance, args) : undefined); } // handle initialization and non-getter methods return this.each(function() { var instance = $.data(this, name); // constructor (!instance && !isMethodCall && $.data(this, name, new $[namespace][name](this, options))); // method call (instance && isMethodCall && $.isFunction(instance[options]) && instance[options].apply(instance, args)); }); }; // create widget constructor $[namespace] = $[namespace] || {}; $[namespace][name] = function(element, options) { var self = this; this.namespace = namespace; this.widgetName = name; this.widgetEventPrefix = $[namespace][name].eventPrefix || name; this.widgetBaseClass = namespace + '-' + name; this.options = $.extend({}, $.widget.defaults, $[namespace][name].defaults, $.metadata && $.metadata.get(element)[name], options); this.element = $(element) .bind('setData.' + name, function(event, key, value) { return self._setData(key, value); }) .bind('getData.' + name, function(event, key) { return self._getData(key); }) .bind('remove', function() { return self.destroy(); }); this._init(); }; // add widget prototype $[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype); // TODO: merge getter and getterSetter properties from widget prototype // and plugin prototype $[namespace][name].getterSetter = 'option'; }; $.widget.prototype = { _init: function() {}, destroy: function() { this.element.removeData(this.widgetName) .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .removeAttr('aria-disabled'); }, option: function(key, value) { var options = key, self = this; if (typeof key == "string") { if (value === undefined) { return this._getData(key); } options = {}; options[key] = value; } $.each(options, function(key, value) { self._setData(key, value); }); }, _getData: function(key) { return this.options[key]; }, _setData: function(key, value) { this.options[key] = value; if (key == 'disabled') { this.element[value ? 'addClass' : 'removeClass']( this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .attr("aria-disabled", value); } }, enable: function() { this._setData('disabled', false); }, disable: function() { this._setData('disabled', true); }, _trigger: function(type, event, data) { var eventName = (type == this.widgetEventPrefix ? type : this.widgetEventPrefix + type); event = event || $.event.fix({ type: eventName, target: this.element[0] }); return this.element.triggerHandler(eventName, [event, data], this.options[type]); } }; $.widget.defaults = { disabled: false }; /** Mouse Interaction Plugin **/ $.ui.mouse = { _mouseInit: function() { var self = this; this.element .bind('mousedown.'+this.widgetName, function(event) { return self._mouseDown(event); }) .bind('click.'+this.widgetName, function(event) { if(self._preventClickEvent) { self._preventClickEvent = false; return false; } }); // Prevent text selection in IE if ($.browser.msie) { this._mouseUnselectable = this.element.attr('unselectable'); this.element.attr('unselectable', 'on'); } this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind('.'+this.widgetName); // Restore text selection in IE ($.browser.msie && this.element.attr('unselectable', this._mouseUnselectable)); }, _mouseDown: function(event) { // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var self = this, btnIsLeft = (event.which == 1), elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { self.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return self._mouseMove(event); }; this._mouseUpDelegate = function(event) { return self._mouseUp(event); }; $(document) .bind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .bind('mouseup.'+this.widgetName, this._mouseUpDelegate); // preventDefault() is used to prevent the selection of text here - // however, in Safari, this causes select boxes not to be selectable // anymore, so this fix is needed if(!$.browser.safari) event.preventDefault(); return true; }, _mouseMove: function(event) { // IE mouseup check - mouseup happened when mouse was out of window if ($.browser.msie && !event.button) { return this._mouseUp(event); } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { $(document) .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); if (this._mouseStarted) { this._mouseStarted = false; this._preventClickEvent = true; this._mouseStop(event); } return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(event) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(event) {}, _mouseDrag: function(event) {}, _mouseStop: function(event) {}, _mouseCapture: function(event) { return true; } }; $.ui.mouse.defaults = { cancel: null, distance: 1, delay: 0 }; })(jQuery);
damilare/opencore
opencore/views/static/jquery-ui/grid/ui/ui.core.js
JavaScript
gpl-2.0
13,924
/* * This file is part of Cockpit. * * Copyright (C) 2014 Red Hat, Inc. * * Cockpit is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * Cockpit is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Cockpit; If not, see <http://www.gnu.org/licenses/>. */ var $ = require("jquery"); /* Construct a simple image editor inside 'element'. It can only crop * an image to a square region. * * - editor = image_editor(element, width, height) * * - editor.load_data(data).done(...).fail(...) * * - editor.select_file().done(...).fail(...) * * - editor.get_data(width, height) * * - editor.changed * * - editor.start_crop() */ function image_editor(element, width, height) { var self = { load_data: load_data, get_data: get_data, start_cropping: start_cropping, stop_cropping: stop_cropping, select_file: select_file, changed: false }; var square_size = Math.min (width, height); var initial_crop_size = square_size; var crop_handle_width = 20; var $image_canvas, $overlay_canvas, $file_input; var image_canvas, overlay_canvas; var image_2d, overlay_2d; function setup() { element.empty(). css('width', width). css('height', height). css('position', 'relative'). append( $image_canvas = $('<canvas>'), $overlay_canvas = $('<canvas>'). css('position', 'absolute'). css('top', 0). css('left', 0). css('z-index', 10)); $('body').append( $file_input = $('<input data-role="none" type="file">').hide()); image_canvas = $image_canvas[0]; image_2d = image_canvas.getContext("2d"); overlay_canvas = $overlay_canvas[0]; overlay_2d = overlay_canvas.getContext("2d"); image_canvas.width = overlay_canvas.width = width; image_canvas.height = overlay_canvas.height = height; $file_input.on('change', load_file); } var cropping = false; var crop_x, crop_y, crop_s; function start_cropping() { cropping = true; set_crop ((width - initial_crop_size) / 2, (height - initial_crop_size) / 2, initial_crop_size, true); $overlay_canvas.on('mousedown', mousedown); } function stop_cropping() { cropping = false; overlay_2d.clearRect(0, 0, width, height); $overlay_canvas.off('mousedown', mousedown); } function set_crop(x, y, s, fix) { function clamp (low, val, high) { if (val < low) return low; if (val > high) return high; return val; } x = Math.floor(x); y = Math.floor(y); s = Math.floor(s); var min_s = 2 * crop_handle_width; if (fix) { // move it until it fits s = clamp (min_s, s, square_size); x = clamp (0, x, width - s); y = clamp (0, y, height - s); } else if (x < 0 || y < 0 || x + s > width || y + s > height || s < min_s) return; crop_x = x; crop_y = y; crop_s = s; draw_crop (x, y, x+s, y+s); } function draw_crop(x1,y1,x2,y2) { var ctxt = overlay_2d; function draw_box (x1, y1, x2, y2) { ctxt.strokeStyle = 'black'; ctxt.strokeRect(x1+0.5, y1+0.5, x2-x1-1, y2-y1-1); ctxt.strokeStyle = 'white'; ctxt.strokeRect(x1+1.5, y1+1.5, x2-x1-3, y2-y1-3); } ctxt.clearRect(0, 0, width, height); ctxt.fillStyle = 'rgba(0,0,0,0.8)'; ctxt.fillRect(0, 0, width, height); ctxt.clearRect(x1, y1, x2 - x1, y2 - y1); var h_w = crop_handle_width; draw_box (x1, y1, x1+h_w, y1+h_w); draw_box (x2-h_w, y1, x2, y1+h_w); draw_box (x1, y2-h_w, x1+h_w, y2); draw_box (x2-h_w, y2-h_w, x2, y2); draw_box (x1, y1, x2, y2); } function mousedown(ev) { var offset = $overlay_canvas.offset(); var xoff = ev.pageX - offset.left - crop_x; var yoff = ev.pageY - offset.top - crop_y; var orig_x = crop_x; var orig_y = crop_y; var orig_s = crop_s; var proj_sign, dx_sign, dy_sign, ds_sign; var h_w = crop_handle_width; function mousemove(ev) { var x = ev.pageX - offset.left - xoff; var y = ev.pageY - offset.top - yoff; if (proj_sign === 0) set_crop (x, y, orig_s, true); else { var d = Math.floor((x - orig_x + proj_sign * (y - orig_y)) / 2); set_crop (orig_x + dx_sign*d, orig_y + dy_sign*d, orig_s + ds_sign*d, false); } self.changed = true; } function mouseup(ev) { $('body').off('mousemove', mousemove); $('body').off('mouseup', mouseup); } if (xoff > 0 && yoff > 0 && xoff < crop_s && yoff < crop_s) { if (xoff < h_w && yoff < h_w) { // top left proj_sign = 1; dx_sign = 1; dy_sign = 1; ds_sign = -1; } else if (xoff > crop_s - h_w && yoff < h_w) { // top right proj_sign = -1; dx_sign = 0; dy_sign = -1; ds_sign = 1; } else if (xoff < h_w && yoff > crop_s - h_w) { // bottom left proj_sign = -1; dx_sign = 1; dy_sign = 0; ds_sign = -1; } else if (xoff > crop_s - h_w && yoff > crop_s - h_w) { // bottom right proj_sign = 1; dx_sign = 0; dy_sign = 0; ds_sign = 1; } else { // center proj_sign = 0; } $('body').on('mousemove', mousemove); $('body').on('mouseup', mouseup); } } function load_data(data) { var dfd = $.Deferred(); var img = new window.Image(); img.onerror = function () { dfd.reject(); }; img.onload = function () { var dest_w, dest_h; if (img.width > img.height) { dest_w = width; dest_h = dest_w * (img.height/img.width); } else { dest_h = height; dest_w = dest_h * (img.width/img.height); } image_2d.fillStyle = 'rgb(255,255,255)'; image_2d.fillRect(0, 0, width, height); image_2d.drawImage(img, (width - dest_w) / 2, (height - dest_h) / 2, dest_w, dest_h); initial_crop_size = Math.min(dest_h, dest_w); dfd.resolve(); }; img.src = data; return dfd.promise(); } function get_data(width, height, format) { var dest = $('<canvas/>')[0]; dest.width = width; dest.height = height; var ctxt = dest.getContext("2d"); if (cropping) { ctxt.drawImage (image_canvas, crop_x, crop_y, crop_s, crop_s, 0, 0, width, height); } else { ctxt.drawImage (image_canvas, 0, 0, square_size, square_size, 0, 0, width, height); } return dest.toDataURL(format); } var select_dfd; function load_file() { var files, file, reader; files = $file_input[0].files; if (files.length != 1) { select_dfd.reject(); return; } file = files[0]; if (!file.type.match("image.*")) { select_dfd.reject(); return; } reader = new window.FileReader(); reader.onerror = function () { select_dfd.reject(); }; reader.onload = function () { load_data(reader.result). done(function () { select_dfd.resolve(); }). fail(function () { select_dfd.reject(); }); }; reader.readAsDataURL(file); } function select_file() { select_dfd = $.Deferred(); if (window.File && window.FileReader) $file_input.trigger('click'); else select_dfd.reject(); return select_dfd.promise(); } setup(); return self; } module.exports = image_editor;
SotolitoLabs/cockpit
pkg/dashboard/image-editor.js
JavaScript
lgpl-2.1
9,115
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * Check For Statement for automatic semicolon insertion * * @path ch07/7.9/S7.9_A6.4_T1.js * @description Three semicolons. For header is (false semicolon false semicolon false semicolon) * @negative */ //CHECK#1 for(false;false;false;) { break; }
hippich/typescript
tests/Fidelity/test262/suite/ch07/7.9/S7.9_A6.4_T1.js
JavaScript
apache-2.0
395
define(function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var HaxeHighlightRules = require("./haxe_highlight_rules").HaxeHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = HaxeHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.$id = "ace/mode/haxe"; }).call(Mode.prototype); exports.Mode = Mode; });
steveworley/tornado
web/scripts/lib/ace/mode/haxe.js
JavaScript
mit
1,666
var fs = require('fs'); function File() { this.promise = Promise.resolve(); } // Static method for File.prototype.read File.read = function (filePath) { var file = new File(); return file.read(filePath); }; File.prototype.then = function (onFulfilled, onRejected) { this.promise = this.promise.then(onFulfilled, onRejected); return this; }; File.prototype['catch'] = function (onRejected) { this.promise = this.promise.catch(onRejected); return this; }; File.prototype.read = function (filePath) { return this.then(function () { return fs.readFileSync(filePath, 'utf-8'); }); }; File.prototype.transform = function (fn) { return this.then(fn); }; File.prototype.write = function (filePath) { return this.then(function (data) { return fs.writeFileSync(filePath, data); }); };
purepennons/promises-book
Ch4_AdvancedPromises/embed/embed-fs-promise-chain.js
JavaScript
mit
838
/* Copyright (c) 2012 Barnesandnoble.com, llc, Donavon West, and Domenic Denicola 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. */ (function (global, undefined) { "use strict"; var tasks = (function () { function Task(handler, args) { this.handler = handler; this.args = args; } Task.prototype.run = function () { // See steps in section 5 of the spec. if (typeof this.handler === "function") { // Choice of `thisArg` is not in the setImmediate spec; `undefined` is in the setTimeout spec though: // http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html this.handler.apply(undefined, this.args); } else { var scriptSource = "" + this.handler; /*jshint evil: true */ eval(scriptSource); } }; var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; return { addFromSetImmediateArguments: function (args) { var handler = args[0]; var argsToHandle = Array.prototype.slice.call(args, 1); var task = new Task(handler, argsToHandle); var thisHandle = nextHandle++; tasksByHandle[thisHandle] = task; return thisHandle; }, runIfPresent: function (handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (!currentlyRunningATask) { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { task.run(); } finally { delete tasksByHandle[handle]; currentlyRunningATask = false; } } } else { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. global.setTimeout(function () { tasks.runIfPresent(handle); }, 0); } }, remove: function (handle) { delete tasksByHandle[handle]; } }; }()); function canUseNextTick() { // Don't get fooled by e.g. browserify environments. return typeof process === "object" && Object.prototype.toString.call(process) === "[object process]"; } function canUseMessageChannel() { return !!global.MessageChannel; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (!global.postMessage || global.importScripts) { return false; } var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function () { postMessageIsAsynchronous = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } function canUseReadyStateChange() { return "document" in global && "onreadystatechange" in global.document.createElement("script"); } function installNextTickImplementation(attachTo) { attachTo.setImmediate = function () { var handle = tasks.addFromSetImmediateArguments(arguments); process.nextTick(function () { tasks.runIfPresent(handle); }); return handle; }; } function installMessageChannelImplementation(attachTo) { var channel = new global.MessageChannel(); channel.port1.onmessage = function (event) { var handle = event.data; tasks.runIfPresent(handle); }; attachTo.setImmediate = function () { var handle = tasks.addFromSetImmediateArguments(arguments); channel.port2.postMessage(handle); return handle; }; } function installPostMessageImplementation(attachTo) { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var MESSAGE_PREFIX = "com.bn.NobleJS.setImmediate" + Math.random(); function isStringAndStartsWith(string, putativeStart) { return typeof string === "string" && string.substring(0, putativeStart.length) === putativeStart; } function onGlobalMessage(event) { // This will catch all incoming messages (even from other windows!), so we need to try reasonably hard to // avoid letting anyone else trick us into firing off. We test the origin is still this window, and that a // (randomly generated) unpredictable identifying prefix is present. if (event.source === global && isStringAndStartsWith(event.data, MESSAGE_PREFIX)) { var handle = event.data.substring(MESSAGE_PREFIX.length); tasks.runIfPresent(handle); } } if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } attachTo.setImmediate = function () { var handle = tasks.addFromSetImmediateArguments(arguments); // Make `global` post a message to itself with the handle and identifying prefix, thus asynchronously // invoking our onGlobalMessage listener above. global.postMessage(MESSAGE_PREFIX + handle, "*"); return handle; }; } function installReadyStateChangeImplementation(attachTo) { attachTo.setImmediate = function () { var handle = tasks.addFromSetImmediateArguments(arguments); // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var scriptEl = global.document.createElement("script"); scriptEl.onreadystatechange = function () { tasks.runIfPresent(handle); scriptEl.onreadystatechange = null; scriptEl.parentNode.removeChild(scriptEl); scriptEl = null; }; global.document.documentElement.appendChild(scriptEl); return handle; }; } function installSetTimeoutImplementation(attachTo) { attachTo.setImmediate = function () { var handle = tasks.addFromSetImmediateArguments(arguments); global.setTimeout(function () { tasks.runIfPresent(handle); }, 0); return handle; }; } if (!global.setImmediate) { // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live. var attachTo = typeof Object.getPrototypeOf === "function" && "setTimeout" in Object.getPrototypeOf(global) ? Object.getPrototypeOf(global) : global; if (canUseNextTick()) { // For Node.js before 0.9 installNextTickImplementation(attachTo); } else if (canUsePostMessage()) { // For non-IE10 modern browsers installPostMessageImplementation(attachTo); } else if (canUseMessageChannel()) { // For web workers, where supported installMessageChannelImplementation(attachTo); } else if (canUseReadyStateChange()) { // For IE 6–8 installReadyStateChangeImplementation(attachTo); } else { // For older browsers installSetTimeoutImplementation(attachTo); } attachTo.clearImmediate = tasks.remove; } }(typeof global === "object" && global ? global : this));
digitalbazaar/credentials-io
tests/setImmediate.js
JavaScript
bsd-3-clause
9,641
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. 'use strict'; /** @suppress {duplicate} */ var remoting = remoting || {}; /** * @param {Array<remoting.HostSetupFlow.State>} sequence Sequence of * steps for the flow. * @constructor */ remoting.HostSetupFlow = function(sequence) { this.sequence_ = sequence; this.currentStep_ = 0; this.state_ = sequence[0]; this.pin = ''; this.consent = false; }; /** @enum {number} */ remoting.HostSetupFlow.State = { NONE: 0, // Dialog states. ASK_PIN: 1, // Prompts the user to install the host package. INSTALL_HOST: 2, // Processing states. STARTING_HOST: 3, UPDATING_PIN: 4, STOPPING_HOST: 5, // Done states. HOST_STARTED: 6, UPDATED_PIN: 7, HOST_STOPPED: 8, // Failure states. REGISTRATION_FAILED: 9, START_HOST_FAILED: 10, UPDATE_PIN_FAILED: 11, STOP_HOST_FAILED: 12 }; /** @return {remoting.HostSetupFlow.State} Current state of the flow. */ remoting.HostSetupFlow.prototype.getState = function() { return this.state_; }; remoting.HostSetupFlow.prototype.switchToNextStep = function() { if (this.state_ == remoting.HostSetupFlow.State.NONE) { return; } if (this.currentStep_ < this.sequence_.length - 1) { this.currentStep_ += 1; this.state_ = this.sequence_[this.currentStep_]; } else { this.state_ = remoting.HostSetupFlow.State.NONE; } }; /** * @param {!remoting.Error} error */ remoting.HostSetupFlow.prototype.switchToErrorState = function(error) { if (error.hasTag(remoting.Error.Tag.CANCELLED)) { // Stop the setup flow if user rejected one of the actions. this.state_ = remoting.HostSetupFlow.State.NONE; } else { // Current step failed, so switch to corresponding error state. if (this.state_ == remoting.HostSetupFlow.State.STARTING_HOST) { if (error.hasTag(remoting.Error.Tag.REGISTRATION_FAILED)) { this.state_ = remoting.HostSetupFlow.State.REGISTRATION_FAILED; } else { this.state_ = remoting.HostSetupFlow.State.START_HOST_FAILED; } } else if (this.state_ == remoting.HostSetupFlow.State.UPDATING_PIN) { this.state_ = remoting.HostSetupFlow.State.UPDATE_PIN_FAILED; } else if (this.state_ == remoting.HostSetupFlow.State.STOPPING_HOST) { this.state_ = remoting.HostSetupFlow.State.STOP_HOST_FAILED; } else { // TODO(sergeyu): Add other error states and use them here. this.state_ = remoting.HostSetupFlow.State.START_HOST_FAILED; } } }; /** * @param {remoting.HostController} hostController The HostController * responsible for the host daemon. * @param {function(!remoting.Error)} onError Function to call when an error * occurs. * @constructor */ remoting.HostSetupDialog = function(hostController, onError) { this.hostController_ = hostController; this.onError_ = onError; this.pinEntry_ = document.getElementById('daemon-pin-entry'); this.pinConfirm_ = document.getElementById('daemon-pin-confirm'); this.pinErrorDiv_ = document.getElementById('daemon-pin-error-div'); this.pinErrorMessage_ = document.getElementById('daemon-pin-error-message'); /** @type {remoting.HostSetupFlow} */ this.flow_ = new remoting.HostSetupFlow([remoting.HostSetupFlow.State.NONE]); /** @type {remoting.HostSetupDialog} */ var that = this; /** @param {Event} event The event. */ var onPinSubmit = function(event) { event.preventDefault(); that.onPinSubmit_(); }; var onPinConfirmFocus = function() { that.validatePin_(); }; var form = document.getElementById('ask-pin-form'); form.addEventListener('submit', onPinSubmit, false); /** @param {Event} event The event. */ var onDaemonPinEntryKeyPress = function(event) { if (event.which == 13) { document.getElementById('daemon-pin-confirm').focus(); event.preventDefault(); } }; /** @param {Event} event A keypress event. */ var noDigitsInPin = function(event) { if (event.which == 13) { return; // Otherwise the "submit" action can't be triggered by Enter. } if ((event.which >= 48) && (event.which <= 57)) { return; } event.preventDefault(); }; this.pinEntry_.addEventListener('keypress', onDaemonPinEntryKeyPress, false); this.pinEntry_.addEventListener('keypress', noDigitsInPin, false); this.pinConfirm_.addEventListener('focus', onPinConfirmFocus, false); this.pinConfirm_.addEventListener('keypress', noDigitsInPin, false); this.usageStats_ = document.getElementById('usagestats-consent'); this.usageStatsCheckbox_ = /** @type {HTMLInputElement} */ (document.getElementById('usagestats-consent-checkbox')); }; /** * Show the dialog in order to get a PIN prior to starting the daemon. When the * user clicks OK, the dialog shows a spinner until the daemon has started. * * @return {void} Nothing. */ remoting.HostSetupDialog.prototype.showForStart = function() { /** @type {remoting.HostSetupDialog} */ var that = this; /** * @param {remoting.HostController.State} state */ var onState = function(state) { // Although we don't need an access token in order to start the host, // using callWithToken here ensures consistent error handling in the // case where the refresh token is invalid. remoting.identity.getToken().then( that.showForStartWithToken_.bind(that, state), remoting.Error.handler(that.onError_)); }; this.hostController_.getLocalHostState(onState); }; /** * @param {remoting.HostController.State} state The current state of the local * host. * @param {string} token The OAuth2 token. * @private */ remoting.HostSetupDialog.prototype.showForStartWithToken_ = function(state, token) { /** @type {remoting.HostSetupDialog} */ var that = this; /** * @param {remoting.UsageStatsConsent} consent */ function onGetConsent(consent) { // Hide the usage stats check box if it is not supported or the policy // doesn't allow usage stats collection. var checkBoxLabel = that.usageStats_.querySelector('.checkbox-label'); that.usageStats_.hidden = !consent.supported || (consent.setByPolicy && !consent.allowed); that.usageStatsCheckbox_.checked = consent.allowed; that.usageStatsCheckbox_.disabled = consent.setByPolicy; checkBoxLabel.classList.toggle('disabled', consent.setByPolicy); if (consent.setByPolicy) { that.usageStats_.title = l10n.getTranslationOrError( /*i18n-content*/ 'SETTING_MANAGED_BY_POLICY'); } else { that.usageStats_.title = ''; } } /** @param {!remoting.Error} error */ function onError(error) { console.error('Error getting consent status: ' + error.toString()); } this.usageStats_.hidden = true; this.usageStatsCheckbox_.checked = false; // Prevent user from ticking the box until the current consent status is // known. this.usageStatsCheckbox_.disabled = true; this.hostController_.getConsent().then( onGetConsent, remoting.Error.handler(onError)); var flow = [ remoting.HostSetupFlow.State.INSTALL_HOST, remoting.HostSetupFlow.State.ASK_PIN, remoting.HostSetupFlow.State.STARTING_HOST, remoting.HostSetupFlow.State.HOST_STARTED]; var installed = state != remoting.HostController.State.NOT_INSTALLED && state != remoting.HostController.State.UNKNOWN; // Skip the installation step when the host is already installed. if (installed) { flow.shift(); } this.startNewFlow_(flow); }; /** * Show the dialog in order to change the PIN associated with a running daemon. * * @return {void} Nothing. */ remoting.HostSetupDialog.prototype.showForPin = function() { this.usageStats_.hidden = true; this.startNewFlow_( [remoting.HostSetupFlow.State.ASK_PIN, remoting.HostSetupFlow.State.UPDATING_PIN, remoting.HostSetupFlow.State.UPDATED_PIN]); }; /** * Show the dialog in order to stop the daemon. * * @return {void} Nothing. */ remoting.HostSetupDialog.prototype.showForStop = function() { // TODO(sergeyu): Add another step to unregister the host, crubg.com/121146 . this.startNewFlow_( [remoting.HostSetupFlow.State.STOPPING_HOST, remoting.HostSetupFlow.State.HOST_STOPPED]); }; /** * @return {void} Nothing. */ remoting.HostSetupDialog.prototype.hide = function() { remoting.setMode(remoting.AppMode.HOME); }; /** * Starts new flow with the specified sequence of steps. * @param {Array<remoting.HostSetupFlow.State>} sequence Sequence of steps. * @private */ remoting.HostSetupDialog.prototype.startNewFlow_ = function(sequence) { this.flow_ = new remoting.HostSetupFlow(sequence); this.pinEntry_.value = ''; this.pinConfirm_.value = ''; this.pinErrorDiv_.hidden = true; this.updateState_(); }; /** * Updates current UI mode according to the current state of the setup * flow and start the action corresponding to the current step (if * any). * @private */ remoting.HostSetupDialog.prototype.updateState_ = function() { remoting.updateLocalHostState(); /** @param {string} tag1 * @param {string=} opt_tag2 */ function showDoneMessage(tag1, opt_tag2) { var messageDiv = document.getElementById('host-setup-done-message'); l10n.localizeElementFromTag(messageDiv, tag1); messageDiv = document.getElementById('host-setup-done-message-2'); if (opt_tag2) { l10n.localizeElementFromTag(messageDiv, opt_tag2); } else { messageDiv.innerText = ''; } remoting.setMode(remoting.AppMode.HOST_SETUP_DONE); } /** @param {string} tag */ function showErrorMessage(tag) { var errorDiv = document.getElementById('host-setup-error-message'); l10n.localizeElementFromTag(errorDiv, tag); remoting.setMode(remoting.AppMode.HOST_SETUP_ERROR); } var state = this.flow_.getState(); if (state == remoting.HostSetupFlow.State.NONE) { this.hide(); } else if (state == remoting.HostSetupFlow.State.ASK_PIN) { remoting.setMode(remoting.AppMode.HOST_SETUP_ASK_PIN); } else if (state == remoting.HostSetupFlow.State.INSTALL_HOST) { this.installHost_(); } else if (state == remoting.HostSetupFlow.State.STARTING_HOST) { remoting.showSetupProcessingMessage(/*i18n-content*/'HOST_SETUP_STARTING'); this.startHost_(); } else if (state == remoting.HostSetupFlow.State.UPDATING_PIN) { remoting.showSetupProcessingMessage( /*i18n-content*/'HOST_SETUP_UPDATING_PIN'); this.updatePin_(); } else if (state == remoting.HostSetupFlow.State.STOPPING_HOST) { remoting.showSetupProcessingMessage(/*i18n-content*/'HOST_SETUP_STOPPING'); this.stopHost_(); } else if (state == remoting.HostSetupFlow.State.HOST_STARTED) { // TODO(jamiewalch): Only display the second string if the computer's power // management settings indicate that it's necessary. showDoneMessage(/*i18n-content*/'HOST_SETUP_STARTED', /*i18n-content*/'HOST_SETUP_STARTED_DISABLE_SLEEP'); } else if (state == remoting.HostSetupFlow.State.UPDATED_PIN) { showDoneMessage(/*i18n-content*/'HOST_SETUP_UPDATED_PIN'); } else if (state == remoting.HostSetupFlow.State.HOST_STOPPED) { showDoneMessage(/*i18n-content*/'HOST_SETUP_STOPPED'); } else if (state == remoting.HostSetupFlow.State.REGISTRATION_FAILED) { showErrorMessage(/*i18n-content*/'ERROR_HOST_REGISTRATION_FAILED'); } else if (state == remoting.HostSetupFlow.State.START_HOST_FAILED) { showErrorMessage(/*i18n-content*/'HOST_SETUP_HOST_FAILED'); } else if (state == remoting.HostSetupFlow.State.UPDATE_PIN_FAILED) { showErrorMessage(/*i18n-content*/'HOST_SETUP_UPDATE_PIN_FAILED'); } else if (state == remoting.HostSetupFlow.State.STOP_HOST_FAILED) { showErrorMessage(/*i18n-content*/'HOST_SETUP_STOP_FAILED'); } }; /** * Shows the prompt that asks the user to install the host. */ remoting.HostSetupDialog.prototype.installHost_ = function() { /** @type {remoting.HostSetupDialog} */ var that = this; /** @type {remoting.HostSetupFlow} */ var flow = this.flow_; /** @param {!remoting.Error} error */ var onError = function(error) { flow.switchToErrorState(error); that.updateState_(); }; var onDone = function() { that.hostController_.getLocalHostState(onHostState); }; /** @param {remoting.HostController.State} state */ var onHostState = function(state) { var installed = state != remoting.HostController.State.NOT_INSTALLED && state != remoting.HostController.State.UNKNOWN; if (installed) { that.flow_.switchToNextStep(); that.updateState_(); } else { // Prompt the user again if the host is not installed. hostInstallDialog.tryAgain(); } }; /** @type {remoting.HostInstallDialog} */ var hostInstallDialog = new remoting.HostInstallDialog(); hostInstallDialog.show(onDone, onError); } /** * Registers and starts the host. */ remoting.HostSetupDialog.prototype.startHost_ = function() { /** @type {remoting.HostSetupDialog} */ var that = this; /** @type {remoting.HostSetupFlow} */ var flow = this.flow_; /** @return {boolean} */ function isFlowActive() { if (flow !== that.flow_ || flow.getState() != remoting.HostSetupFlow.State.STARTING_HOST) { console.error('Host setup was interrupted when starting the host'); return false; } return true; } function onHostStarted() { if (isFlowActive()) { flow.switchToNextStep(); that.updateState_(); } } /** @param {!remoting.Error} error */ function onError(error) { if (isFlowActive()) { flow.switchToErrorState(error); that.updateState_(); } } this.hostController_.start(this.flow_.pin, this.flow_.consent).then( onHostStarted ).catch( remoting.Error.handler(onError) ); }; remoting.HostSetupDialog.prototype.updatePin_ = function() { /** @type {remoting.HostSetupDialog} */ var that = this; /** @type {remoting.HostSetupFlow} */ var flow = this.flow_; /** @return {boolean} */ function isFlowActive() { if (flow !== that.flow_ || flow.getState() != remoting.HostSetupFlow.State.UPDATING_PIN) { console.error('Host setup was interrupted when updating PIN'); return false; } return true; } function onPinUpdated() { if (isFlowActive()) { flow.switchToNextStep(); that.updateState_(); } } /** @param {!remoting.Error} error */ function onError(error) { if (isFlowActive()) { flow.switchToErrorState(error); that.updateState_(); } } this.hostController_.updatePin(flow.pin, onPinUpdated, onError); }; /** * Stops the host. */ remoting.HostSetupDialog.prototype.stopHost_ = function() { /** @type {remoting.HostSetupDialog} */ var that = this; /** @type {remoting.HostSetupFlow} */ var flow = this.flow_; /** @return {boolean} */ function isFlowActive() { if (flow !== that.flow_ || flow.getState() != remoting.HostSetupFlow.State.STOPPING_HOST) { console.error('Host setup was interrupted when stopping the host'); return false; } return true; } function onHostStopped() { if (isFlowActive()) { flow.switchToNextStep(); that.updateState_(); } } /** @param {!remoting.Error} error */ function onError(error) { if (isFlowActive()) { flow.switchToErrorState(error); that.updateState_(); } } this.hostController_.stop(onHostStopped, onError); }; /** * Validates the PIN and shows an error message if it's invalid. * @return {boolean} true if the PIN is valid, false otherwise. * @private */ remoting.HostSetupDialog.prototype.validatePin_ = function() { var pin = this.pinEntry_.value; var pinIsValid = remoting.HostSetupDialog.validPin_(pin); if (!pinIsValid) { l10n.localizeElementFromTag( this.pinErrorMessage_, /*i18n-content*/'INVALID_PIN'); } this.pinErrorDiv_.hidden = pinIsValid; return pinIsValid; }; /** @private */ remoting.HostSetupDialog.prototype.onPinSubmit_ = function() { if (this.flow_.getState() != remoting.HostSetupFlow.State.ASK_PIN) { console.error('PIN submitted in an invalid state', this.flow_.getState()); return; } var pin1 = this.pinEntry_.value; var pin2 = this.pinConfirm_.value; if (pin1 != pin2) { l10n.localizeElementFromTag( this.pinErrorMessage_, /*i18n-content*/'PINS_NOT_EQUAL'); this.pinErrorDiv_.hidden = false; this.prepareForPinEntry_(); return; } if (!this.validatePin_()) { this.prepareForPinEntry_(); return; } this.flow_.pin = pin1; this.flow_.consent = !this.usageStats_.hidden && this.usageStatsCheckbox_.checked; this.flow_.switchToNextStep(); this.updateState_(); }; /** @private */ remoting.HostSetupDialog.prototype.prepareForPinEntry_ = function() { this.pinEntry_.value = ''; this.pinConfirm_.value = ''; this.pinEntry_.focus(); }; /** * Returns whether a PIN is valid. * * @private * @param {string} pin A PIN. * @return {boolean} Whether the PIN is valid. */ remoting.HostSetupDialog.validPin_ = function(pin) { if (pin.length < 6) { return false; } for (var i = 0; i < pin.length; i++) { var c = pin.charAt(i); if ((c < '0') || (c > '9')) { return false; } } return true; }; /** @type {remoting.HostSetupDialog} */ remoting.hostSetupDialog = null;
Pluto-tv/chromium-crosswalk
remoting/webapp/crd/js/host_setup_dialog.js
JavaScript
bsd-3-clause
17,508
/* Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ define(["dojo"],function(_1){ dijit=_1._dijit||{}; return dijit; });
skobbler/AddressHunter
web-app/public/js/dijit/lib/main.js
JavaScript
bsd-3-clause
266
import React, {Component} from 'react'; import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import FlatButton from 'material-ui/FlatButton'; import Toggle from 'material-ui/Toggle'; import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; import NavigationClose from 'material-ui/svg-icons/navigation/close'; class Login extends Component { static muiName = 'FlatButton'; render() { return ( <FlatButton {...this.props} label="Login" /> ); } } const Logged = (props) => ( <IconMenu {...props} iconButtonElement={ <IconButton><MoreVertIcon /></IconButton> } targetOrigin={{horizontal: 'right', vertical: 'top'}} anchorOrigin={{horizontal: 'right', vertical: 'top'}} > <MenuItem primaryText="Refresh" /> <MenuItem primaryText="Help" /> <MenuItem primaryText="Sign out" /> </IconMenu> ); Logged.muiName = 'IconMenu'; /** * This example is taking advantage of the composability of the `AppBar` * to render different components depending on the application state. */ class AppBarExampleComposition extends Component { state = { logged: true, }; handleChange = (event, logged) => { this.setState({logged: logged}); }; render() { return ( <div> <Toggle label="Logged" defaultToggled={true} onToggle={this.handleChange} labelPosition="right" style={{margin: 20}} /> <AppBar title="Title" iconElementLeft={<IconButton><NavigationClose /></IconButton>} iconElementRight={this.state.logged ? <Logged /> : <Login />} /> </div> ); } } export default AppBarExampleComposition;
pbogdan/react-flux-mui
react-flux-mui/js/material-ui/docs/src/app/components/pages/components/AppBar/ExampleComposition.js
JavaScript
bsd-3-clause
1,832
/* YUI 3.15.0 (build 834026e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('uploader-html5', function (Y, NAME) { /** * This module provides a UI for file selection and multiple file upload capability using * HTML5 XMLHTTPRequest Level 2 as a transport engine. * The supported features include: automatic upload queue management, upload progress * tracking, drag-and-drop support, server response retrieval and error reporting. * * @module uploader-html5 */ // Shorthands for the external modules var substitute = Y.Lang.sub, UploaderQueue = Y.Uploader.Queue; /** * This module provides a UI for file selection and multiple file upload capability using * HTML5 XMLHTTPRequest Level 2 as a transport engine. * @class UploaderHTML5 * @extends Widget * @constructor */ function UploaderHTML5() { UploaderHTML5.superclass.constructor.apply ( this, arguments ); } Y.UploaderHTML5 = Y.extend( UploaderHTML5, Y.Widget, { /** * Stored reference to the instance of the file input field used to * initiate the file selection dialog. * * @property _fileInputField * @type {Node} * @protected */ _fileInputField: null, /** * Stored reference to the click event binding of the `Select Files` * button. * * @property _buttonBinding * @type {EventHandle} * @protected */ _buttonBinding: null, /** * Stored reference to the instance of Uploader.Queue used to manage * the upload process. This is a read-only property that only exists * during an active upload process. Only one queue can be active at * a time; if an upload start is attempted while a queue is active, * it will be ignored. * * @property queue * @type {Uploader.Queue} */ queue: null, // Y.UploaderHTML5 prototype /** * Construction logic executed during UploaderHTML5 instantiation. * * @method initializer * @protected */ initializer : function () { this._fileInputField = null; this.queue = null; this._buttonBinding = null; this._fileList = []; // Publish available events /** * Signals that files have been selected. * * @event fileselect * @param event {Event} The event object for the `fileselect` with the * following payload: * <dl> * <dt>fileList</dt> * <dd>An `Array` of files selected by the user, encapsulated * in Y.FileHTML5 objects.</dd> * </dl> */ this.publish("fileselect"); /** * Signals that an upload of multiple files has been started. * * @event uploadstart * @param event {Event} The event object for the `uploadstart`. */ this.publish("uploadstart"); /** * Signals that an upload of a specific file has started. * * @event fileuploadstart * @param event {Event} The event object for the `fileuploadstart` with the * following payload: * <dl> * <dt>file</dt> * <dd>A reference to the Y.File that dispatched the event.</dd> * <dt>originEvent</dt> * <dd>The original event dispatched by Y.File.</dd> * </dl> */ this.publish("fileuploadstart"); /** * Reports on upload progress of a specific file. * * @event uploadprogress * @param event {Event} The event object for the `uploadprogress` with the * following payload: * <dl> * <dt>file</dt> * <dd>The pointer to the instance of `Y.File` that dispatched the event.</dd> * <dt>bytesLoaded</dt> * <dd>The number of bytes of the file that has been uploaded</dd> * <dt>bytesTotal</dt> * <dd>The total number of bytes in the file</dd> * <dt>percentLoaded</dt> * <dd>The fraction of the file that has been uploaded, out of 100</dd> * <dt>originEvent</dt> * <dd>The original event dispatched by the HTML5 uploader</dd> * </dl> */ this.publish("uploadprogress"); /** * Reports on the total upload progress of the file list. * * @event totaluploadprogress * @param event {Event} The event object for the `totaluploadprogress` with the * following payload: * <dl> * <dt>bytesLoaded</dt> * <dd>The number of bytes of the file list that has been uploaded</dd> * <dt>bytesTotal</dt> * <dd>The total number of bytes in the file list</dd> * <dt>percentLoaded</dt> * <dd>The fraction of the file list that has been uploaded, out of 100</dd> * </dl> */ this.publish("totaluploadprogress"); /** * Signals that a single file upload has been completed. * * @event uploadcomplete * @param event {Event} The event object for the `uploadcomplete` with the * following payload: * <dl> * <dt>file</dt> * <dd>The pointer to the instance of `Y.File` whose upload has been completed.</dd> * <dt>originEvent</dt> * <dd>The original event fired by the SWF Uploader</dd> * <dt>data</dt> * <dd>Data returned by the server.</dd> * </dl> */ this.publish("uploadcomplete"); /** * Signals that the upload process of the entire file list has been completed. * * @event alluploadscomplete * @param event {Event} The event object for the `alluploadscomplete`. */ this.publish("alluploadscomplete"); /** * Signals that a error has occurred in a specific file's upload process. * * @event uploaderror * @param event {Event} The event object for the `uploaderror` with the * following payload: * <dl> * <dt>originEvent</dt> * <dd>The original error event fired by the HTML5 Uploader. </dd> * <dt>file</dt> * <dd>The pointer at the instance of Y.File that returned the error.</dd> * <dt>status</dt> * <dd>The status reported by the XMLHttpRequest object.</dd> * <dt>statusText</dt> * <dd>The statusText reported by the XMLHttpRequest object.</dd> * </dl> */ this.publish("uploaderror"); /** * Signals that a dragged object has entered into the uploader's associated drag-and-drop area. * * @event dragenter * @param event {Event} The event object for the `dragenter`. */ this.publish("dragenter"); /** * Signals that an object has been dragged over the uploader's associated drag-and-drop area. * * @event dragover * @param event {Event} The event object for the `dragover`. */ this.publish("dragover"); /** * Signals that an object has been dragged off of the uploader's associated drag-and-drop area. * * @event dragleave * @param event {Event} The event object for the `dragleave`. */ this.publish("dragleave"); /** * Signals that an object has been dropped over the uploader's associated drag-and-drop area. * * @event drop * @param event {Event} The event object for the `drop` with the * following payload: * <dl> * <dt>fileList</dt> * <dd>An `Array` of files dropped by the user, encapsulated * in Y.FileHTML5 objects.</dd> * </dl> */ this.publish("drop"); }, /** * Create the DOM structure for the UploaderHTML5. * UploaderHTML5's DOM structure consists of a "Select Files" button that can * be replaced by the developer's widget of choice; and a hidden file input field * that is used to instantiate the File Select dialog. * * @method renderUI * @protected */ renderUI : function () { var contentBox = this.get('contentBox'), selButton = this.get("selectFilesButton"); selButton.setStyles({width:"100%", height:"100%"}); contentBox.append(selButton); this._fileInputField = Y.Node.create(UploaderHTML5.HTML5FILEFIELD_TEMPLATE); contentBox.append(this._fileInputField); }, /** * Binds to the UploaderHTML5 UI and subscribes to the necessary events. * * @method bindUI * @protected */ bindUI : function () { this._bindSelectButton(); this._setMultipleFiles(); this._setFileFilters(); this._bindDropArea(); this._triggerEnabled(); this.after("multipleFilesChange", this._setMultipleFiles, this); this.after("fileFiltersChange", this._setFileFilters, this); this.after("enabledChange", this._triggerEnabled, this); this.after("selectFilesButtonChange", this._bindSelectButton, this); this.after("dragAndDropAreaChange", this._bindDropArea, this); this.after("tabIndexChange", function () { this.get("selectFilesButton").set("tabIndex", this.get("tabIndex")); }, this); this._fileInputField.on("change", this._updateFileList, this); this._fileInputField.on("click", function(event) { event.stopPropagation(); }, this); this.get("selectFilesButton").set("tabIndex", this.get("tabIndex")); }, /** * Recreates the file field to null out the previous list of files and * thus allow for an identical file list selection. * * @method _rebindFileField * @protected */ _rebindFileField : function () { this._fileInputField.remove(true); this._fileInputField = Y.Node.create(UploaderHTML5.HTML5FILEFIELD_TEMPLATE); this.get("contentBox").append(this._fileInputField); this._fileInputField.on("change", this._updateFileList, this); this._setMultipleFiles(); this._setFileFilters(); }, /** * Binds the specified drop area's drag and drop events to the * uploader's custom handler. * * @method _bindDropArea * @protected */ _bindDropArea : function (event) { var ev = event || {prevVal: null}, ddArea = this.get("dragAndDropArea"); if (ev.prevVal !== null) { ev.prevVal.detach('drop', this._ddEventHandler); ev.prevVal.detach('dragenter', this._ddEventHandler); ev.prevVal.detach('dragover', this._ddEventHandler); ev.prevVal.detach('dragleave', this._ddEventHandler); } if (ddArea !== null) { ddArea.on('drop', this._ddEventHandler, this); ddArea.on('dragenter', this._ddEventHandler, this); ddArea.on('dragover', this._ddEventHandler, this); ddArea.on('dragleave', this._ddEventHandler, this); } }, /** * Binds the instantiation of the file select dialog to the current file select * control. * * @method _bindSelectButton * @protected */ _bindSelectButton : function () { this._buttonBinding = this.get("selectFilesButton").on("click", this.openFileSelectDialog, this); }, /** * Handles the drag and drop events from the uploader's specified drop * area. * * @method _ddEventHandler * @protected */ _ddEventHandler : function (event) { event.stopPropagation(); event.preventDefault(); if (Y.Array.indexOf(event._event.dataTransfer.types, 'Files') > -1) { switch (event.type) { case "dragenter": this.fire("dragenter"); break; case "dragover": this.fire("dragover"); break; case "dragleave": this.fire("dragleave"); break; case "drop": var newfiles = event._event.dataTransfer.files, parsedFiles = [], filterFunc = this.get("fileFilterFunction"), oldfiles; if (filterFunc) { Y.each(newfiles, function (value) { var newfile = new Y.FileHTML5(value); if (filterFunc(newfile)) { parsedFiles.push(newfile); } }); } else { Y.each(newfiles, function (value) { parsedFiles.push(new Y.FileHTML5(value)); }); } if (parsedFiles.length > 0) { oldfiles = this.get("fileList"); this.set("fileList", this.get("appendNewFiles") ? oldfiles.concat(parsedFiles) : parsedFiles); this.fire("fileselect", {fileList: parsedFiles}); } this.fire("drop", {fileList: parsedFiles}); break; } } }, /** * Adds or removes a specified state CSS class to the underlying uploader button. * * @method _setButtonClass * @protected * @param state {String} The name of the state enumerated in `buttonClassNames` attribute * from which to derive the needed class name. * @param add {Boolean} A Boolean indicating whether to add or remove the class. */ _setButtonClass : function (state, add) { if (add) { this.get("selectFilesButton").addClass(this.get("buttonClassNames")[state]); } else { this.get("selectFilesButton").removeClass(this.get("buttonClassNames")[state]); } }, /** * Syncs the state of the `multipleFiles` attribute between this class * and the file input field. * * @method _setMultipleFiles * @protected */ _setMultipleFiles : function () { if (this.get("multipleFiles") === true) { this._fileInputField.set("multiple", "multiple"); } else { this._fileInputField.set("multiple", ""); } }, /** * Syncs the state of the `fileFilters` attribute between this class * and the file input field. * * @method _setFileFilters * @protected */ _setFileFilters : function () { if (this.get("fileFilters").length > 0) { this._fileInputField.set("accept", this.get("fileFilters").join(",")); } else { this._fileInputField.set("accept", ""); } }, /** * Syncs the state of the `enabled` attribute between this class * and the underlying button. * * @method _triggerEnabled * @private */ _triggerEnabled : function () { if (this.get("enabled") && this._buttonBinding === null) { this._bindSelectButton(); this._setButtonClass("disabled", false); this.get("selectFilesButton").setAttribute("aria-disabled", "false"); } else if (!this.get("enabled") && this._buttonBinding) { this._buttonBinding.detach(); this._buttonBinding = null; this._setButtonClass("disabled", true); this.get("selectFilesButton").setAttribute("aria-disabled", "true"); } }, /** * Getter for the `fileList` attribute * * @method _getFileList * @private */ _getFileList : function () { return this._fileList.concat(); }, /** * Setter for the `fileList` attribute * * @method _setFileList * @private */ _setFileList : function (val) { this._fileList = val.concat(); return this._fileList.concat(); }, /** * Adjusts the content of the `fileList` based on the results of file selection * and the `appendNewFiles` attribute. If the `appendNewFiles` attribute is true, * then selected files are appended to the existing list; otherwise, the list is * cleared and populated with the newly selected files. * * @method _updateFileList * @param ev {Event} The file selection event received from the uploader. * @protected */ _updateFileList : function (ev) { var newfiles = ev.target.getDOMNode().files, parsedFiles = [], filterFunc = this.get("fileFilterFunction"), oldfiles; if (filterFunc) { Y.each(newfiles, function (value) { var newfile = new Y.FileHTML5(value); if (filterFunc(newfile)) { parsedFiles.push(newfile); } }); } else { Y.each(newfiles, function (value) { parsedFiles.push(new Y.FileHTML5(value)); }); } if (parsedFiles.length > 0) { oldfiles = this.get("fileList"); this.set("fileList", this.get("appendNewFiles") ? oldfiles.concat(parsedFiles) : parsedFiles ); this.fire("fileselect", {fileList: parsedFiles}); } this._rebindFileField(); }, /** * Handles and retransmits events fired by `Y.File` and `Y.Uploader.Queue`. * * @method _uploadEventHandler * @param event The event dispatched during the upload process. * @protected */ _uploadEventHandler : function (event) { switch (event.type) { case "file:uploadstart": this.fire("fileuploadstart", event); break; case "file:uploadprogress": this.fire("uploadprogress", event); break; case "uploaderqueue:totaluploadprogress": this.fire("totaluploadprogress", event); break; case "file:uploadcomplete": this.fire("uploadcomplete", event); break; case "uploaderqueue:alluploadscomplete": this.queue = null; this.fire("alluploadscomplete", event); break; case "file:uploaderror": // overflow intentional case "uploaderqueue:uploaderror": this.fire("uploaderror", event); break; case "file:uploadcancel": // overflow intentional case "uploaderqueue:uploadcancel": this.fire("uploadcancel", event); break; } }, /** * Opens the File Selection dialog by simulating a click on the file input field. * * @method openFileSelectDialog */ openFileSelectDialog : function () { var fileDomNode = this._fileInputField.getDOMNode(); if (fileDomNode.click) { fileDomNode.click(); } }, /** * Starts the upload of a specific file. * * @method upload * @param file {File} Reference to the instance of the file to be uploaded. * @param url {String} The URL to upload the file to. * @param postVars {Object} (optional) A set of key-value pairs to send as variables along with the file upload HTTP request. * If not specified, the values from the attribute `postVarsPerFile` are used instead. */ upload : function (file, url, postvars) { var uploadURL = url || this.get("uploadURL"), postVars = postvars || this.get("postVarsPerFile"), fileId = file.get("id"); postVars = postVars.hasOwnProperty(fileId) ? postVars[fileId] : postVars; if (file instanceof Y.FileHTML5) { file.on("uploadstart", this._uploadEventHandler, this); file.on("uploadprogress", this._uploadEventHandler, this); file.on("uploadcomplete", this._uploadEventHandler, this); file.on("uploaderror", this._uploadEventHandler, this); file.on("uploadcancel", this._uploadEventHandler, this); file.startUpload(uploadURL, postVars, this.get("fileFieldName")); } }, /** * Starts the upload of all files on the file list, using an automated queue. * * @method uploadAll * @param url {String} The URL to upload the files to. * @param [postVars] {Object} A set of key-value pairs to send as variables along with the file upload HTTP request. * If not specified, the values from the attribute `postVarsPerFile` are used instead. */ uploadAll : function (url, postvars) { this.uploadThese(this.get("fileList"), url, postvars); }, /** * Starts the upload of the files specified in the first argument, using an automated queue. * * @method uploadThese * @param files {Array} The list of files to upload. * @param url {String} The URL to upload the files to. * @param [postVars] {Object} A set of key-value pairs to send as variables along with the file upload HTTP request. * If not specified, the values from the attribute `postVarsPerFile` are used instead. */ uploadThese : function (files, url, postvars) { if (!this.queue) { var uploadURL = url || this.get("uploadURL"), postVars = postvars || this.get("postVarsPerFile"); this.queue = new UploaderQueue({ simUploads: this.get("simLimit"), errorAction: this.get("errorAction"), fileFieldName: this.get("fileFieldName"), fileList: files, uploadURL: uploadURL, perFileParameters: postVars, retryCount: this.get("retryCount"), uploadHeaders: this.get("uploadHeaders"), withCredentials: this.get("withCredentials") }); this.queue.on("uploadstart", this._uploadEventHandler, this); this.queue.on("uploadprogress", this._uploadEventHandler, this); this.queue.on("totaluploadprogress", this._uploadEventHandler, this); this.queue.on("uploadcomplete", this._uploadEventHandler, this); this.queue.on("alluploadscomplete", this._uploadEventHandler, this); this.queue.on("uploadcancel", this._uploadEventHandler, this); this.queue.on("uploaderror", this._uploadEventHandler, this); this.queue.startUpload(); this.fire("uploadstart"); } else if (this.queue._currentState === UploaderQueue.UPLOADING) { this.queue.set("perFileParameters", this.get("postVarsPerFile")); Y.each(files, function (file) { this.queue.addToQueueBottom(file); }, this); } } }, { /** * The template for the hidden file input field container. The file input field will only * accept clicks if its visibility is set to hidden (and will not if it's `display` value * is set to `none`) * * @property HTML5FILEFIELD_TEMPLATE * @type {String} * @static */ HTML5FILEFIELD_TEMPLATE: "<input type='file' style='visibility:hidden; width:0px; height: 0px;'>", /** * The template for the "Select Files" button. * * @property SELECT_FILES_BUTTON * @type {String} * @static * @default '<button type="button" class="yui3-button" role="button" aria-label="{selectButtonLabel}" * tabindex="{tabIndex}">{selectButtonLabel}</button>' */ SELECT_FILES_BUTTON: '<button type="button" class="yui3-button" role="button" aria-label="{selectButtonLabel}" ' + 'tabindex="{tabIndex}">{selectButtonLabel}</button>', /** * The static property reflecting the type of uploader that `Y.Uploader` * aliases. The UploaderHTML5 value is `"html5"`. * * @property TYPE * @type {String} * @static */ TYPE: "html5", /** * The identity of the widget. * * @property NAME * @type String * @default 'uploader' * @readOnly * @protected * @static */ NAME: "uploader", /** * Static property used to define the default attribute configuration of * the Widget. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { /** * A Boolean indicating whether newly selected files should be appended * to the existing file list, or whether they should replace it. * * @attribute appendNewFiles * @type {Boolean} * @default true */ appendNewFiles : { value: true }, /** * The names of CSS classes that correspond to different button states * of the "Select Files" control. These classes are assigned to the * "Select Files" control based on the configuration of the uploader. * Currently, the only class name used is that corresponding to the * `disabled` state of the uploader. Other button states should be managed * directly via CSS selectors. * <ul> * <li> <strong>`disabled`</strong>: the class corresponding to the disabled state * of the "Select Files" button.</li> * </ul> * @attribute buttonClassNames * @type {Object} * @default { * disabled: "yui3-button-disabled" * } */ buttonClassNames: { value: { "hover": "yui3-button-hover", "active": "yui3-button-active", "disabled": "yui3-button-disabled", "focus": "yui3-button-selected" } }, /** * The node that serves as the drop target for files. * * @attribute dragAndDropArea * @type {Node} * @default null */ dragAndDropArea: { value: null, setter: function (val) { return Y.one(val); } }, /** * A Boolean indicating whether the uploader is enabled or disabled for user input. * * @attribute enabled * @type {Boolean} * @default true */ enabled : { value: true }, /** * The action performed when an upload error occurs for a specific file being uploaded. * The possible values are: * <ul> * <li> <strong>`UploaderQueue.CONTINUE`</strong>: the error is ignored and the upload process is continued.</li> * <li> <strong>`UploaderQueue.STOP`</strong>: the upload process is stopped as soon as any other parallel file * uploads are finished.</li> * <li> <strong>`UploaderQueue.RESTART_ASAP`</strong>: the file is added back to the front of the queue.</li> * <li> <strong>`UploaderQueue.RESTART_AFTER`</strong>: the file is added to the back of the queue.</li> * </ul> * @attribute errorAction * @type {String} * @default UploaderQueue.CONTINUE */ errorAction: { value: "continue", validator: function (val) { return ( val === UploaderQueue.CONTINUE || val === UploaderQueue.STOP || val === UploaderQueue.RESTART_ASAP || val === UploaderQueue.RESTART_AFTER ); } }, /** * An array indicating what fileFilters should be applied to the file * selection dialog. Each element in the array should be a string * indicating the Media (MIME) type for the files that should be supported * for selection. The Media type strings should be properly formatted * or this parameter will be ignored. Examples of valid strings include: * "audio/*", "video/*", "application/pdf", etc. More information * on valid Media type strings is available here: * http://www.iana.org/assignments/media-types/index.html * @attribute fileFilters * @type {Array} * @default [] */ fileFilters: { value: [] }, /** * A filtering function that is applied to every file selected by the user. * The function receives the `Y.File` object and must return a Boolean value. * If a `false` value is returned, the file in question is not added to the * list of files to be uploaded. * Use this function to put limits on file sizes or check the file names for * correct extension, but make sure that a server-side check is also performed, * since any client-side restrictions are only advisory and can be circumvented. * * @attribute fileFilterFunction * @type {Function} * @default null */ fileFilterFunction: { value: null }, /** * A String specifying what should be the POST field name for the file * content in the upload request. * * @attribute fileFieldName * @type {String} * @default Filedata */ fileFieldName: { value: "Filedata" }, /** * The array of files to be uploaded. All elements in the array * must be instances of `Y.File` and be instantiated with an instance * of native JavaScript File() class. * * @attribute fileList * @type {Array} * @default [] */ fileList: { value: [], getter: "_getFileList", setter: "_setFileList" }, /** * A Boolean indicating whether multiple file selection is enabled. * * @attribute multipleFiles * @type {Boolean} * @default false */ multipleFiles: { value: false }, /** * An object, keyed by `fileId`, containing sets of key-value pairs * that should be passed as POST variables along with each corresponding * file. This attribute is only used if no POST variables are specifed * in the upload method call. * * @attribute postVarsPerFile * @type {Object} * @default {} */ postVarsPerFile: { value: {} }, /** * The label for the "Select Files" widget. This is the value that replaces the * `{selectButtonLabel}` token in the `SELECT_FILES_BUTTON` template. * * @attribute selectButtonLabel * @type {String} * @default "Select Files" */ selectButtonLabel: { value: "Select Files" }, /** * The widget that serves as the "Select Files control for the file uploader * * * @attribute selectFilesButton * @type {Node | Widget} * @default A standard HTML button with YUI CSS Button skin. */ selectFilesButton : { valueFn: function () { return Y.Node.create(substitute(Y.UploaderHTML5.SELECT_FILES_BUTTON, { selectButtonLabel: this.get("selectButtonLabel"), tabIndex: this.get("tabIndex") })); } }, /** * The number of files that can be uploaded * simultaneously if the automatic queue management * is used. This value can be in the range between 2 * and 5. * * @attribute simLimit * @type {Number} * @default 2 */ simLimit: { value: 2, validator: function (val) { return (val >= 1 && val <= 5); } }, /** * The URL to which file upload requested are POSTed. Only used if a different url is not passed to the upload method call. * * @attribute uploadURL * @type {String} * @default "" */ uploadURL: { value: "" }, /** * Additional HTTP headers that should be included * in the upload request. * * * @attribute uploadHeaders * @type {Object} * @default {} */ uploadHeaders: { value: {} }, /** * A Boolean that specifies whether the file should be * uploaded with the appropriate user credentials for the * domain. * * @attribute withCredentials * @type {Boolean} * @default true */ withCredentials: { value: true }, /** * The number of times to try re-uploading a file that failed to upload before * cancelling its upload. * * @attribute retryCount * @type {Number} * @default 3 */ retryCount: { value: 3 } } }); Y.UploaderHTML5.Queue = UploaderQueue; }, '3.15.0', {"requires": ["widget", "node-event-simulate", "file-html5", "uploader-queue"]});
sameertechworks/wpmoodle
moodle/lib/yuilib/3.15.0/uploader-html5/uploader-html5.js
JavaScript
gpl-2.0
33,726
/** * @private */ Ext.define('Ext.event.ListenerStack', { currentOrder: 'current', length: 0, constructor: function() { this.listeners = { before: [], current: [], after: [] }; this.lateBindingMap = {}; return this; }, add: function(fn, scope, options, order, observable) { var lateBindingMap = this.lateBindingMap, listeners = this.getAll(order), i = listeners.length, isMethodName = typeof fn === 'string', bindingMap, listener, id; if (isMethodName && scope && scope.isIdentifiable) { id = scope.getId(); bindingMap = lateBindingMap[id]; if (bindingMap) { if (bindingMap[fn]) { return false; } else { bindingMap[fn] = true; } } else { lateBindingMap[id] = bindingMap = {}; bindingMap[fn] = true; } } else { if (i > 0) { while (i--) { listener = listeners[i]; if (listener.fn === fn && listener.scope === scope) { listener.options = options; return false; } } } } listener = this.create(fn, scope, options, order, observable); // Allow for {foo: 'onFoo', scope: 'this/controller'} if (isMethodName && (!scope || scope === 'this' || scope === 'controller')) { listener.boundFn = this.bindDynamicScope(observable, fn, scope); listener.isLateBinding = false; } if (options && options.prepend) { delete options.prepend; listeners.unshift(listener); } else { listeners.push(listener); } this.length++; return true; }, bindDynamicScope: function (observable, funcName, passedScope) { return function () { var scope = observable.resolveListenerScope(passedScope); //<debug> if (typeof scope[funcName] !== 'function') { Ext.Error.raise('No such method ' + funcName + ' on ' + scope.$className); } //</debug> return scope[funcName].apply(scope, arguments); }; }, getAt: function (index, order) { return this.getAll(order)[index]; }, getAll: function (order) { return this.listeners[order || this.currentOrder]; }, count: function (order) { return this.getAll(order).length; }, create: function (fn, scope, options, order, observable) { options = options || {}; return { stack: this, fn: fn, firingFn: false, boundFn: false, isLateBinding: typeof fn === 'string', scope: scope, options: options, order: order, observable: observable, type: options.type }; }, remove: function (fn, scope, order) { var listeners = this.getAll(order), i = listeners.length, isRemoved = false, lateBindingMap = this.lateBindingMap, listener, id; if (i > 0) { // Start from the end index, faster than looping from the // beginning for "single" listeners, // which are normally LIFO while (i--) { listener = listeners[i]; if (listener.fn === fn && listener.scope === scope) { listeners.splice(i, 1); isRemoved = true; this.length--; if (scope && scope.isIdentifiable && typeof fn === 'string') { id = scope.getId(); if (lateBindingMap[id] && lateBindingMap[id][fn]) { delete lateBindingMap[id][fn]; } } break; } } } return isRemoved; } });
applifireAlgo/ZenClubApp
zenws/src/main/webapp/ext/packages/sencha-core/src/event/ListenerStack.js
JavaScript
gpl-3.0
4,258
/** Task to optimize polyfiller.js //grunt.loadTasks('_js/bower_components/webshim/grunt-tasks/'); //... optimizePolyfiller: { options: { src: 'js-webshim/dev/', //required features: 'forms mediaelement', //which features are used? dest: 'js-webshims/minified/polyfiller-custom.js', //should existing uglify be extended to uglify custom polyfiller? default: false (grunt-contrib-uglify has to be installed) uglify: true, //should initially loaded files inlined into polyfiller? default: false ( //depends on your pferformance strategy. in case you include polyfiller.js at bottom, this should be set true) inlineInitFiles: true, //only in case inlineInitFiles is true //which lang or langs are used on page? lang: 'fr it', //forms feature option default: false customMessages: false, //forms-ext feature option default: false replaceUI: false, //is swfobject not used on site default: true (used only with mediaelement) includeSwfmini: true } } */ module.exports = function( grunt ) { grunt.registerTask('optimizePolyfiller', 'optimizes polyfiller file.', function() { var code, polyfillerPath, dirPath, uglifyCfg; var options = this.options({ uglify: false, dest: 'polyfiller-custom.js', features: false, inlineInitFiles: false, //only in case inlineInitFiles is true lang: false, customMessages: false, replaceUI: false, includeSwfmini: true }); options.features = makeArrayOrFalse(options.features); options.lang = makeArrayOrFalse(options.lang); if(!options.src){ grunt.log.error('no src path specified'); } if(grunt.file.isFile(options.src)){ polyfillerPath = options.src; dirPath = options.src.slice(0, options.src.lastIndexOf("/") + 1); } else { polyfillerPath = options.src+'polyfiller.js'; dirPath = options.src; } code = grunt.file.read(polyfillerPath); code = removeFeatures(code, options.features, dirPath); code = inlineInitial(code, options, dirPath); grunt.file.write(options.dest, code); if(options.uglify){ uglifyCfg = grunt.config('uglify') || {}; uglifyCfg.polyfillerOptimized = { options: { beautify: { ascii_only : true }, preserveComments: 'some', compress: { global_defs: { "WSDEBUG": false }, dead_code: true } }, src: dirPath+options.dest, dest: dirPath+options.dest }; // grunt.config('uglify', uglifyCfg); grunt.task.run('uglify:polyfillerOptimized'); } }); var inlineInitial = (function(){ var initialAll = { forms: { 'form-core': true, 'dom-extend': {confirm: 'customMessages'}, 'form-message': {confirm: 'customMessages'} }, 'forms-ext': { 'dom-extend': {confirm: 'replaceUI'}, 'form-number-date-ui': {confirm: 'replaceUI'}, 'range-ui': {confirm: 'replaceUI'} }, mediaelement: { 'swfmini': {confirm: 'includeSwfmini'}, 'mediaelement-core': true }, track: { 'track-ui': true //todo remove dom-extend prefernce } }; return function inlineInitial(code, options, dirPath){ var inlined = {}; options.features.forEach(function(feature){ if(initialAll[feature]){ var file, add; var files = initialAll[feature]; for(file in files){ add = false; if(inlined[file]){ continue; } if(files[file] === true){ add = true; } else if(files[file].confirm && options[files[file].confirm]){ add = true; } if(add){ inlined[file] = true; code += "\n;"+grunt.file.read(dirPath+'shims/'+file+'.js'); grunt.log.writeln('Inlined '+file+" script code to polyfiller"); } } } }); if(options.lang && (options.customMessages || options.replaceUI)){ options.lang.forEach(function(lang){ if(grunt.file.isFile(dirPath+'shims/i18n/formcfg-'+lang+'.js')){ code += "\n;"+grunt.file.read(dirPath+'shims/i18n/formcfg-'+lang+'.js'); grunt.log.writeln('Inlined '+lang+" locale code to polyfiller"); } else { grunt.log.writeln('Could not find '+lang+" locale."); } }); } return code; }; })(); var removeFeatures = (function(){ var remove; var regStart = /\/\/<([A-Za-z]+)/; var regEnd = /\/\/>/; var getRemoveCombos = function (removeFeature, combos, featureCombos){ if(featureCombos[removeFeature]){ featureCombos[removeFeature].forEach(function(c){ if(combos.indexOf(c) == -1){ combos.push(c); } }); } }; return function removeFeatures(code, features, path){ if(features){ var result = []; var combos = []; var featureCombos = grunt.file.readJSON(path +'shims/combos/comboinfo.json').features; var data = code.replace(/\t/g, "").split(/[\n\r]/g); data.forEach(function(line){ var foundFeature; var featureCombo; if(remove){ remove = !(regEnd.exec(line)); } else if( !line || !(foundFeature = regStart.exec(line)) || features.indexOf(foundFeature[1]) !== -1 ){ if(combos.length && (/\/\/>removeCombos</).test(line)){ line = line.replace(/\/\/>removeCombos</, "removeCombos = removeCombos.concat(["+ combos.join(",") +"]);" ); grunt.log.writeln('Following combos are unsued: '+ combos.join(",")); } result.push(line); } else if(foundFeature){ remove = true; grunt.log.writeln('Remove '+foundFeature[1]+" code from polyfiller"); getRemoveCombos(foundFeature[1], combos, featureCombos); } }); return result.join("\n"); } else { grunt.log.writeln('No feature was removed from polyfiller code.'); } return code; }; })(); function makeArrayOrFalse(opt){ if(opt && typeof opt == 'string'){ opt = opt.split(' '); } else if(!Array.isArray(opt) || !opt.length){ opt = false; } return opt; } };
IsmailM/sequenceserver
public/vendor/npm/webshim@1.15.8/grunt-tasks/optimize-polyfiller.js
JavaScript
agpl-3.0
5,898
/* * JQuery zTree excheck 3.5.02 * http://zTree.me/ * * Copyright (c) 2010 Hunter.z * * Licensed same as jquery - MIT License * http://www.opensource.org/licenses/mit-license.php * * email: hunter.z@263.net * Date: 2013-01-28 */ (function($){ //default consts of excheck var _consts = { event: { CHECK: "ztree_check" }, id: { CHECK: "_check" }, checkbox: { STYLE: "checkbox", DEFAULT: "chk", DISABLED: "disable", FALSE: "false", TRUE: "true", FULL: "full", PART: "part", FOCUS: "focus" }, radio: { STYLE: "radio", TYPE_ALL: "all", TYPE_LEVEL: "level" } }, //default setting of excheck _setting = { check: { enable: false, autoCheckTrigger: false, chkStyle: _consts.checkbox.STYLE, nocheckInherit: false, chkDisabledInherit: false, radioType: _consts.radio.TYPE_LEVEL, chkboxType: { "Y": "ps", "N": "ps" } }, data: { key: { checked: "checked" } }, callback: { beforeCheck:null, onCheck:null } }, //default root of excheck _initRoot = function (setting) { var r = data.getRoot(setting); r.radioCheckedList = []; }, //default cache of excheck _initCache = function(treeId) {}, //default bind event of excheck _bindEvent = function(setting) { var o = setting.treeObj, c = consts.event; o.bind(c.CHECK, function (event, srcEvent, treeId, node) { tools.apply(setting.callback.onCheck, [!!srcEvent?srcEvent : event, treeId, node]); }); }, _unbindEvent = function(setting) { var o = setting.treeObj, c = consts.event; o.unbind(c.CHECK); }, //default event proxy of excheck _eventProxy = function(e) { var target = e.target, setting = data.getSetting(e.data.treeId), tId = "", node = null, nodeEventType = "", treeEventType = "", nodeEventCallback = null, treeEventCallback = null; if (tools.eqs(e.type, "mouseover")) { if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { tId = target.parentNode.id; nodeEventType = "mouseoverCheck"; } } else if (tools.eqs(e.type, "mouseout")) { if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { tId = target.parentNode.id; nodeEventType = "mouseoutCheck"; } } else if (tools.eqs(e.type, "click")) { if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { tId = target.parentNode.id; nodeEventType = "checkNode"; } } if (tId.length>0) { node = data.getNodeCache(setting, tId); switch (nodeEventType) { case "checkNode" : nodeEventCallback = _handler.onCheckNode; break; case "mouseoverCheck" : nodeEventCallback = _handler.onMouseoverCheck; break; case "mouseoutCheck" : nodeEventCallback = _handler.onMouseoutCheck; break; } } var proxyResult = { stop: false, node: node, nodeEventType: nodeEventType, nodeEventCallback: nodeEventCallback, treeEventType: treeEventType, treeEventCallback: treeEventCallback }; return proxyResult }, //default init node of excheck _initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { if (!n) return; var checkedKey = setting.data.key.checked; if (typeof n[checkedKey] == "string") n[checkedKey] = tools.eqs(n[checkedKey], "true"); n[checkedKey] = !!n[checkedKey]; n.checkedOld = n[checkedKey]; if (typeof n.nocheck == "string") n.nocheck = tools.eqs(n.nocheck, "true"); n.nocheck = !!n.nocheck || (setting.check.nocheckInherit && parentNode && !!parentNode.nocheck); if (typeof n.chkDisabled == "string") n.chkDisabled = tools.eqs(n.chkDisabled, "true"); n.chkDisabled = !!n.chkDisabled || (setting.check.chkDisabledInherit && parentNode && !!parentNode.chkDisabled); if (typeof n.halfCheck == "string") n.halfCheck = tools.eqs(n.halfCheck, "true"); n.halfCheck = !!n.halfCheck; n.check_Child_State = -1; n.check_Focus = false; n.getCheckStatus = function() {return data.getCheckStatus(setting, n);}; }, //add dom for check _afterA = function(setting, node, html) { var checkedKey = setting.data.key.checked; if (setting.check.enable) { data.makeChkFlag(setting, node); if (setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL && node[checkedKey] ) { var r = data.getRoot(setting); r.radioCheckedList.push(node); } html.push("<span ID='", node.tId, consts.id.CHECK, "' class='", view.makeChkClass(setting, node), "' treeNode", consts.id.CHECK, (node.nocheck === true?" style='display:none;'":""),"></span>"); } }, //update zTreeObj, add method of check _zTreeTools = function(setting, zTreeTools) { zTreeTools.checkNode = function(node, checked, checkTypeFlag, callbackFlag) { var checkedKey = this.setting.data.key.checked; if (node.chkDisabled === true) return; if (checked !== true && checked !== false) { checked = !node[checkedKey]; } callbackFlag = !!callbackFlag; if (node[checkedKey] === checked && !checkTypeFlag) { return; } else if (callbackFlag && tools.apply(this.setting.callback.beforeCheck, [this.setting.treeId, node], true) == false) { return; } if (tools.uCanDo(this.setting) && this.setting.check.enable && node.nocheck !== true) { node[checkedKey] = checked; var checkObj = $("#" + node.tId + consts.id.CHECK); if (checkTypeFlag || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); view.setChkClass(this.setting, checkObj, node); view.repairParentChkClassWithSelf(this.setting, node); if (callbackFlag) { setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); } } } zTreeTools.checkAllNodes = function(checked) { view.repairAllChk(this.setting, !!checked); } zTreeTools.getCheckedNodes = function(checked) { var childKey = this.setting.data.key.children; checked = (checked !== false); return data.getTreeCheckedNodes(this.setting, data.getRoot(setting)[childKey], checked); } zTreeTools.getChangeCheckedNodes = function() { var childKey = this.setting.data.key.children; return data.getTreeChangeCheckedNodes(this.setting, data.getRoot(setting)[childKey]); } zTreeTools.setChkDisabled = function(node, disabled, inheritParent, inheritChildren) { disabled = !!disabled; inheritParent = !!inheritParent; inheritChildren = !!inheritChildren; view.repairSonChkDisabled(this.setting, node, disabled, inheritChildren); view.repairParentChkDisabled(this.setting, node.getParentNode(), disabled, inheritParent); } var _updateNode = zTreeTools.updateNode; zTreeTools.updateNode = function(node, checkTypeFlag) { if (_updateNode) _updateNode.apply(zTreeTools, arguments); if (!node || !this.setting.check.enable) return; var nObj = $("#" + node.tId); if (nObj.get(0) && tools.uCanDo(this.setting)) { var checkObj = $("#" + node.tId + consts.id.CHECK); if (checkTypeFlag == true || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); view.setChkClass(this.setting, checkObj, node); view.repairParentChkClassWithSelf(this.setting, node); } } }, //method of operate data _data = { getRadioCheckedList: function(setting) { var checkedList = data.getRoot(setting).radioCheckedList; for (var i=0, j=checkedList.length; i<j; i++) { if(!data.getNodeCache(setting, checkedList[i].tId)) { checkedList.splice(i, 1); i--; j--; } } return checkedList; }, getCheckStatus: function(setting, node) { if (!setting.check.enable || node.nocheck || node.chkDisabled) return null; var checkedKey = setting.data.key.checked, r = { checked: node[checkedKey], half: node.halfCheck ? node.halfCheck : (setting.check.chkStyle == consts.radio.STYLE ? (node.check_Child_State === 2) : (node[checkedKey] ? (node.check_Child_State > -1 && node.check_Child_State < 2) : (node.check_Child_State > 0))) }; return r; }, getTreeCheckedNodes: function(setting, nodes, checked, results) { if (!nodes) return []; var childKey = setting.data.key.children, checkedKey = setting.data.key.checked, onlyOne = (checked && setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL); results = !results ? [] : results; for (var i = 0, l = nodes.length; i < l; i++) { if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] == checked) { results.push(nodes[i]); if(onlyOne) { break; } } data.getTreeCheckedNodes(setting, nodes[i][childKey], checked, results); if(onlyOne && results.length > 0) { break; } } return results; }, getTreeChangeCheckedNodes: function(setting, nodes, results) { if (!nodes) return []; var childKey = setting.data.key.children, checkedKey = setting.data.key.checked; results = !results ? [] : results; for (var i = 0, l = nodes.length; i < l; i++) { if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] != nodes[i].checkedOld) { results.push(nodes[i]); } data.getTreeChangeCheckedNodes(setting, nodes[i][childKey], results); } return results; }, makeChkFlag: function(setting, node) { if (!node) return; var childKey = setting.data.key.children, checkedKey = setting.data.key.checked, chkFlag = -1; if (node[childKey]) { for (var i = 0, l = node[childKey].length; i < l; i++) { var cNode = node[childKey][i]; var tmp = -1; if (setting.check.chkStyle == consts.radio.STYLE) { if (cNode.nocheck === true || cNode.chkDisabled === true) { tmp = cNode.check_Child_State; } else if (cNode.halfCheck === true) { tmp = 2; } else if (cNode[checkedKey]) { tmp = 2; } else { tmp = cNode.check_Child_State > 0 ? 2:0; } if (tmp == 2) { chkFlag = 2; break; } else if (tmp == 0){ chkFlag = 0; } } else if (setting.check.chkStyle == consts.checkbox.STYLE) { if (cNode.nocheck === true || cNode.chkDisabled === true) { tmp = cNode.check_Child_State; } else if (cNode.halfCheck === true) { tmp = 1; } else if (cNode[checkedKey] ) { tmp = (cNode.check_Child_State === -1 || cNode.check_Child_State === 2) ? 2 : 1; } else { tmp = (cNode.check_Child_State > 0) ? 1 : 0; } if (tmp === 1) { chkFlag = 1; break; } else if (tmp === 2 && chkFlag > -1 && i > 0 && tmp !== chkFlag) { chkFlag = 1; break; } else if (chkFlag === 2 && tmp > -1 && tmp < 2) { chkFlag = 1; break; } else if (tmp > -1) { chkFlag = tmp; } } } } node.check_Child_State = chkFlag; } }, //method of event proxy _event = { }, //method of event handler _handler = { onCheckNode: function (event, node) { if (node.chkDisabled === true) return false; var setting = data.getSetting(event.data.treeId), checkedKey = setting.data.key.checked; if (tools.apply(setting.callback.beforeCheck, [setting.treeId, node], true) == false) return true; node[checkedKey] = !node[checkedKey]; view.checkNodeRelation(setting, node); var checkObj = $("#" + node.tId + consts.id.CHECK); view.setChkClass(setting, checkObj, node); view.repairParentChkClassWithSelf(setting, node); setting.treeObj.trigger(consts.event.CHECK, [event, setting.treeId, node]); return true; }, onMouseoverCheck: function(event, node) { if (node.chkDisabled === true) return false; var setting = data.getSetting(event.data.treeId), checkObj = $("#" + node.tId + consts.id.CHECK); node.check_Focus = true; view.setChkClass(setting, checkObj, node); return true; }, onMouseoutCheck: function(event, node) { if (node.chkDisabled === true) return false; var setting = data.getSetting(event.data.treeId), checkObj = $("#" + node.tId + consts.id.CHECK); node.check_Focus = false; view.setChkClass(setting, checkObj, node); return true; } }, //method of tools for zTree _tools = { }, //method of operate ztree dom _view = { checkNodeRelation: function(setting, node) { var pNode, i, l, childKey = setting.data.key.children, checkedKey = setting.data.key.checked, r = consts.radio; if (setting.check.chkStyle == r.STYLE) { var checkedList = data.getRadioCheckedList(setting); if (node[checkedKey]) { if (setting.check.radioType == r.TYPE_ALL) { for (i = checkedList.length-1; i >= 0; i--) { pNode = checkedList[i]; pNode[checkedKey] = false; checkedList.splice(i, 1); view.setChkClass(setting, $("#" + pNode.tId + consts.id.CHECK), pNode); if (pNode.parentTId != node.parentTId) { view.repairParentChkClassWithSelf(setting, pNode); } } checkedList.push(node); } else { var parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); for (i = 0, l = parentNode[childKey].length; i < l; i++) { pNode = parentNode[childKey][i]; if (pNode[checkedKey] && pNode != node) { pNode[checkedKey] = false; view.setChkClass(setting, $("#" + pNode.tId + consts.id.CHECK), pNode); } } } } else if (setting.check.radioType == r.TYPE_ALL) { for (i = 0, l = checkedList.length; i < l; i++) { if (node == checkedList[i]) { checkedList.splice(i, 1); break; } } } } else { if (node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.Y.indexOf("s") > -1)) { view.setSonNodeCheckBox(setting, node, true); } if (!node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.N.indexOf("s") > -1)) { view.setSonNodeCheckBox(setting, node, false); } if (node[checkedKey] && setting.check.chkboxType.Y.indexOf("p") > -1) { view.setParentNodeCheckBox(setting, node, true); } if (!node[checkedKey] && setting.check.chkboxType.N.indexOf("p") > -1) { view.setParentNodeCheckBox(setting, node, false); } } }, makeChkClass: function(setting, node) { var checkedKey = setting.data.key.checked, c = consts.checkbox, r = consts.radio, fullStyle = ""; if (node.chkDisabled === true) { fullStyle = c.DISABLED; } else if (node.halfCheck) { fullStyle = c.PART; } else if (setting.check.chkStyle == r.STYLE) { fullStyle = (node.check_Child_State < 1)? c.FULL:c.PART; } else { fullStyle = node[checkedKey] ? ((node.check_Child_State === 2 || node.check_Child_State === -1) ? c.FULL:c.PART) : ((node.check_Child_State < 1)? c.FULL:c.PART); } var chkName = setting.check.chkStyle + "_" + (node[checkedKey] ? c.TRUE : c.FALSE) + "_" + fullStyle; chkName = (node.check_Focus && node.chkDisabled !== true) ? chkName + "_" + c.FOCUS : chkName; return "bttn " + c.DEFAULT + " " + chkName; }, repairAllChk: function(setting, checked) { if (setting.check.enable && setting.check.chkStyle === consts.checkbox.STYLE) { var checkedKey = setting.data.key.checked, childKey = setting.data.key.children, root = data.getRoot(setting); for (var i = 0, l = root[childKey].length; i<l ; i++) { var node = root[childKey][i]; if (node.nocheck !== true && node.chkDisabled !== true) { node[checkedKey] = checked; } view.setSonNodeCheckBox(setting, node, checked); } } }, repairChkClass: function(setting, node) { if (!node) return; data.makeChkFlag(setting, node); if (node.nocheck !== true) { var checkObj = $("#" + node.tId + consts.id.CHECK); view.setChkClass(setting, checkObj, node); } }, repairParentChkClass: function(setting, node) { if (!node || !node.parentTId) return; var pNode = node.getParentNode(); view.repairChkClass(setting, pNode); view.repairParentChkClass(setting, pNode); }, repairParentChkClassWithSelf: function(setting, node) { if (!node) return; var childKey = setting.data.key.children; if (node[childKey] && node[childKey].length > 0) { view.repairParentChkClass(setting, node[childKey][0]); } else { view.repairParentChkClass(setting, node); } }, repairSonChkDisabled: function(setting, node, chkDisabled, inherit) { if (!node) return; var childKey = setting.data.key.children; if (node.chkDisabled != chkDisabled) { node.chkDisabled = chkDisabled; } view.repairChkClass(setting, node); if (node[childKey] && inherit) { for (var i = 0, l = node[childKey].length; i < l; i++) { var sNode = node[childKey][i]; view.repairSonChkDisabled(setting, sNode, chkDisabled, inherit); } } }, repairParentChkDisabled: function(setting, node, chkDisabled, inherit) { if (!node) return; if (node.chkDisabled != chkDisabled && inherit) { node.chkDisabled = chkDisabled; } view.repairChkClass(setting, node); view.repairParentChkDisabled(setting, node.getParentNode(), chkDisabled, inherit); }, setChkClass: function(setting, obj, node) { if (!obj) return; if (node.nocheck === true) { obj.hide(); } else { obj.show(); } obj.removeClass(); obj.addClass(view.makeChkClass(setting, node)); }, setParentNodeCheckBox: function(setting, node, value, srcNode) { var childKey = setting.data.key.children, checkedKey = setting.data.key.checked, checkObj = $("#" + node.tId + consts.id.CHECK); if (!srcNode) srcNode = node; data.makeChkFlag(setting, node); if (node.nocheck !== true && node.chkDisabled !== true) { node[checkedKey] = value; view.setChkClass(setting, checkObj, node); if (setting.check.autoCheckTrigger && node != srcNode) { setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); } } if (node.parentTId) { var pSign = true; if (!value) { var pNodes = node.getParentNode()[childKey]; for (var i = 0, l = pNodes.length; i < l; i++) { if ((pNodes[i].nocheck !== true && pNodes[i].chkDisabled !== true && pNodes[i][checkedKey]) || ((pNodes[i].nocheck === true || pNodes[i].chkDisabled === true) && pNodes[i].check_Child_State > 0)) { pSign = false; break; } } } if (pSign) { view.setParentNodeCheckBox(setting, node.getParentNode(), value, srcNode); } } }, setSonNodeCheckBox: function(setting, node, value, srcNode) { if (!node) return; var childKey = setting.data.key.children, checkedKey = setting.data.key.checked, checkObj = $("#" + node.tId + consts.id.CHECK); if (!srcNode) srcNode = node; var hasDisable = false; if (node[childKey]) { for (var i = 0, l = node[childKey].length; i < l && node.chkDisabled !== true; i++) { var sNode = node[childKey][i]; view.setSonNodeCheckBox(setting, sNode, value, srcNode); if (sNode.chkDisabled === true) hasDisable = true; } } if (node != data.getRoot(setting) && node.chkDisabled !== true) { if (hasDisable && node.nocheck !== true) { data.makeChkFlag(setting, node); } if (node.nocheck !== true && node.chkDisabled !== true) { node[checkedKey] = value; if (!hasDisable) node.check_Child_State = (node[childKey] && node[childKey].length > 0) ? (value ? 2 : 0) : -1; } else { node.check_Child_State = -1; } view.setChkClass(setting, checkObj, node); if (setting.check.autoCheckTrigger && node != srcNode && node.nocheck !== true && node.chkDisabled !== true) { setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); } } } }, _z = { tools: _tools, view: _view, event: _event, data: _data }; $.extend(true, $.fn.zTree.consts, _consts); $.extend(true, $.fn.zTree._z, _z); var zt = $.fn.zTree, tools = zt._z.tools, consts = zt.consts, view = zt._z.view, data = zt._z.data, event = zt._z.event; data.exSetting(_setting); data.addInitBind(_bindEvent); data.addInitUnBind(_unbindEvent); data.addInitCache(_initCache); data.addInitNode(_initNode); data.addInitProxy(_eventProxy); data.addInitRoot(_initRoot); data.addAfterA(_afterA); data.addZTreeTools(_zTreeTools); var _createNodes = view.createNodes; view.createNodes = function(setting, level, nodes, parentNode) { if (_createNodes) _createNodes.apply(view, arguments); if (!nodes) return; view.repairParentChkClassWithSelf(setting, parentNode); } var _removeNode = view.removeNode; view.removeNode = function(setting, node) { var parentNode = node.getParentNode(); if (_removeNode) _removeNode.apply(view, arguments); if (!node || !parentNode) return; view.repairChkClass(setting, parentNode); view.repairParentChkClass(setting, parentNode); } var _appendNodes = view.appendNodes; view.appendNodes = function(setting, level, nodes, parentNode, initFlag, openFlag) { var html = ""; if (_appendNodes) { html = _appendNodes.apply(view, arguments); } if (parentNode) { data.makeChkFlag(setting, parentNode); } return html; } })(jQuery);
smgoller/geode
geode-pulse/src/main/webapp/scripts/lib/jquery.ztree.excheck-3.5.js
JavaScript
apache-2.0
21,302
if (self.importScripts) importScripts("/js-test-resources/js-test.js"); description("Test EventSource reconnect after end of event stream."); self.jsTestIsAsync = true; var retryTimeout; function checkReadyState(es, desiredState) { shouldBe("es.readyState", "es." + desiredState); } var errCount = 0; var es = new EventSource("/eventsource/resources/reconnect.php"); checkReadyState(es, "CONNECTING"); es.onopen = function (evt) { checkReadyState(es, "OPEN"); }; var evt; es.onmessage = function (arg) { evt = arg; if (errCount) shouldBeEqualToString("evt.data", "77"); shouldBeEqualToString("evt.lastEventId", "77"); }; es.onerror = function () { errCount++; if (errCount < 2) { checkReadyState(es, "CONNECTING"); retryTimeout = setTimeout(end, 1000); return; } clearTimeout(retryTimeout); retryTimeout = null; end(); }; function end() { es.close(); if (retryTimeout) testFailed("did not reconnect in time"); else checkReadyState(es, "CLOSED"); finishJSTest(); }
vadimtk/chrome4sdp
third_party/WebKit/LayoutTests/http/tests/eventsource/script-tests/eventsource-reconnect.js
JavaScript
bsd-3-clause
1,087
describe("groupBy", function() { ensureLaziness(function() { Lazy(people).groupBy(Person.getGender); }); it("groups the collection by a specified selector function", function() { var byGender = Lazy(people).groupBy(Person.getGender).toArray(); expect(byGender).toEqual([ ["M", [david, adam, daniel]], ["F", [mary, lauren, happy]] ]); }); it("groups the collection by a specified selector function for async sequences", function() { var byGender = {}; Lazy(people) .async() .groupBy(Person.getGender) .toObject() .onComplete(function(result) { populate(byGender, result); }); waitsFor(toBePopulated(byGender)); runs(function() { expect(byGender).toEqual({ M: [david, adam, daniel], F: [mary, lauren, happy] }); }); }); testAllSequenceTypes( "uses a 'pluck'-style callback when a string is passed instead of a function", [ { foo: 1, bar: 1 }, { foo: 2, bar: 2 }, { foo: 1, bar: 3 } ], function(sequence) { expect(sequence.groupBy('foo').toObject()).toEqual({ '1': [ { foo: 1, bar: 1 }, { foo: 1, bar: 3 } ], '2': [ { foo: 2, bar: 2 } ] }); } ); });
ellismarkf/hacked
src/vendor/lazy/spec/group_by_spec.js
JavaScript
mit
1,291
/* * Copyright 2012 the original author or authors. * Licensed under the Apache License, Version 2.0 (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. */ dc = { version: "1.5.0", constants : { CHART_CLASS: "dc-chart", DEBUG_GROUP_CLASS: "debug", STACK_CLASS: "stack", DESELECTED_CLASS: "deselected", SELECTED_CLASS: "selected", NODE_INDEX_NAME: "__index__", GROUP_INDEX_NAME: "__group_index__", DEFAULT_CHART_GROUP: "__default_chart_group__", EVENT_DELAY: 40, NEGLIGIBLE_NUMBER: 1e-10 }, _renderlet : null }; dc.chartRegistry = function() { // chartGroup:string => charts:array var _chartMap = {}; this.has = function(chart) { for (var e in _chartMap) { if (_chartMap[e].indexOf(chart) >= 0) return true; } return false; }; function initializeChartGroup(group) { if (!group) group = dc.constants.DEFAULT_CHART_GROUP; if (!_chartMap[group]) _chartMap[group] = []; return group; } this.register = function(chart, group) { group = initializeChartGroup(group); _chartMap[group].push(chart); }; this.clear = function() { _chartMap = {}; }; this.list = function(group) { group = initializeChartGroup(group); return _chartMap[group]; }; return this; }(); dc.registerChart = function(chart, group) { dc.chartRegistry.register(chart, group); }; dc.hasChart = function(chart) { return dc.chartRegistry.has(chart); }; dc.deregisterAllCharts = function() { dc.chartRegistry.clear(); }; dc.filterAll = function(group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { charts[i].filterAll(); } }; dc.renderAll = function(group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { charts[i].render(); } if(dc._renderlet !== null) dc._renderlet(group); }; dc.redrawAll = function(group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { charts[i].redraw(); } if(dc._renderlet !== null) dc._renderlet(group); }; dc.transition = function(selections, duration, callback) { if (duration <= 0 || duration === undefined) return selections; var s = selections .transition() .duration(duration); if (callback instanceof Function) { callback(s); } return s; }; dc.units = {}; dc.units.integers = function(s, e) { return Math.abs(e - s); }; dc.units.ordinal = function(s, e, domain){ return domain; }; dc.units.fp = {}; dc.units.fp.precision= function(precision){ var _f = function(s, e, domain){return Math.ceil(Math.abs((e-s)/_f.resolution));}; _f.resolution = precision; return _f; }; dc.round = {}; dc.round.floor = function(n) { return Math.floor(n); }; dc.round.ceil = function(n) { return Math.ceil(n); }; dc.round.round = function(n) { return Math.round(n); }; dc.override = function(obj, functionName, newFunction) { var existingFunction = obj[functionName]; obj["_" + functionName] = existingFunction; obj[functionName] = newFunction; }; dc.renderlet = function(_){ if(!arguments.length) return dc._renderlet; dc._renderlet = _; return dc; }; dc.instanceOfChart = function (o) { return o instanceof Object && o.__dc_flag__; }; dc.errors = {}; dc.errors.Exception = function(msg) { var _msg = msg != null ? msg : "Unexpected internal error"; this.message = _msg; this.toString = function(){ return _msg; }; }; dc.errors.InvalidStateException = function() { dc.errors.Exception.apply(this, arguments); };dc.dateFormat = d3.time.format("%m/%d/%Y"); dc.printers = {}; dc.printers.filters = function (filters) { var s = ""; for (var i = 0; i < filters.length; ++i) { if (i > 0) s += ", "; s += dc.printers.filter(filters[i]); } return s; }; dc.printers.filter = function (filter) { var s = ""; if (filter) { if (filter instanceof Array) { if (filter.length >= 2) s = "[" + dc.utils.printSingleValue(filter[0]) + " -> " + dc.utils.printSingleValue(filter[1]) + "]"; else if (filter.length >= 1) s = dc.utils.printSingleValue(filter[0]); } else { s = dc.utils.printSingleValue(filter) } } return s; }; dc.utils = {}; dc.utils.printSingleValue = function (filter) { var s = "" + filter; if (filter instanceof Date) s = dc.dateFormat(filter); else if (typeof(filter) == "string") s = filter; else if (typeof(filter) == "number") s = Math.round(filter); return s; }; dc.utils.add = function (l, r) { if (typeof r === "string") r = r.replace("%", "") if (l instanceof Date) { if (typeof r === "string") r = +r var d = new Date(); d.setTime(l.getTime()); d.setDate(l.getDate() + r); return d; } else if (typeof r === "string") { var percentage = (+r / 100); return l > 0 ? l * (1 + percentage) : l * (1 - percentage); } else { return l + r; } }; dc.utils.subtract = function (l, r) { if (typeof r === "string") r = r.replace("%", "") if (l instanceof Date) { if (typeof r === "string") r = +r var d = new Date(); d.setTime(l.getTime()); d.setDate(l.getDate() - r); return d; } else if (typeof r === "string") { var percentage = (+r / 100); return l < 0 ? l * (1 + percentage) : l * (1 - percentage); } else { return l - r; } }; dc.utils.GroupStack = function () { var _dataLayers = []; var _groups = []; var _defaultAccessor; function initializeDataLayer(i) { if (!_dataLayers[i]) _dataLayers[i] = []; } this.setDataPoint = function (layerIndex, pointIndex, data) { initializeDataLayer(layerIndex); _dataLayers[layerIndex][pointIndex] = data; }; this.getDataPoint = function (x, y) { initializeDataLayer(x); var dataPoint = _dataLayers[x][y]; if (dataPoint == undefined) dataPoint = 0; return dataPoint; }; this.addGroup = function (group, accessor) { if (!accessor) accessor = _defaultAccessor; _groups.push([group, accessor]); return _groups.length - 1; }; this.getGroupByIndex = function (index) { return _groups[index][0]; }; this.getAccessorByIndex = function (index) { return _groups[index][1]; }; this.size = function () { return _groups.length; }; this.clear = function () { _dataLayers = []; _groups = []; }; this.setDefaultAccessor = function (retriever) { _defaultAccessor = retriever; }; this.getDataLayers = function () { return _dataLayers; }; this.toLayers = function () { var layers = []; for (var i = 0; i < _dataLayers.length; ++i) { var layer = {index: i, points: []}; var dataPoints = _dataLayers[i]; for (var j = 0; j < dataPoints.length; ++j) layer.points.push(dataPoints[j]); layers.push(layer); } return layers; }; }; dc.utils.isNegligible = function (max) { return max === undefined || (max < dc.constants.NEGLIGIBLE_NUMBER && max > -dc.constants.NEGLIGIBLE_NUMBER); } dc.utils.groupMax = function (group, accessor) { var max = d3.max(group.all(), function (e) { return accessor(e); }); if (dc.utils.isNegligible(max)) max = 0; return max; }; dc.utils.groupMin = function (group, accessor) { var min = d3.min(group.all(), function (e) { return accessor(e); }); if (dc.utils.isNegligible(min)) min = 0; return min; }; dc.utils.nameToId = function (name) { return name.toLowerCase().replace(/[\s]/g, "_").replace(/[\.']/g, ""); }; dc.utils.appendOrSelect = function (parent, name) { var element = parent.select(name); if (element.empty()) element = parent.append(name); return element; }; dc.utils.createLegendable = function (chart, group, index) { var legendable = {name: group.__name__, data: group}; if (typeof chart.colors === 'function') legendable.color = chart.colors()(index); return legendable; }; dc.events = { current: null }; dc.events.trigger = function(closure, delay) { if (!delay){ closure(); return; } dc.events.current = closure; setTimeout(function() { if (closure == dc.events.current) closure(); }, delay); }; dc.cumulative = {}; dc.cumulative.Base = function() { this._keyIndex = []; this._map = {}; this.sanitizeKey = function(key) { key = key + ""; return key; }; this.clear = function() { this._keyIndex = []; this._map = {}; }; this.size = function() { return this._keyIndex.length; }; this.getValueByKey = function(key) { key = this.sanitizeKey(key); var value = this._map[key]; return value; }; this.setValueByKey = function(key, value) { key = this.sanitizeKey(key); return this._map[key] = value; }; this.indexOfKey = function(key) { key = this.sanitizeKey(key); return this._keyIndex.indexOf(key); }; this.addToIndex = function(key) { key = this.sanitizeKey(key); this._keyIndex.push(key); }; this.getKeyByIndex = function(index) { return this._keyIndex[index]; }; }; dc.cumulative.Sum = function() { dc.cumulative.Base.apply(this, arguments); this.add = function(key, value) { if (value == null) value = 0; if (this.getValueByKey(key) == null) { this.addToIndex(key); this.setValueByKey(key, value); } else { this.setValueByKey(key, this.getValueByKey(key) + value); } }; this.minus = function(key, value) { this.setValueByKey(key, this.getValueByKey(key) - value); }; this.cumulativeSum = function(key) { var keyIndex = this.indexOfKey(key); if (keyIndex < 0) return 0; var cumulativeValue = 0; for (var i = 0; i <= keyIndex; ++i) { var k = this.getKeyByIndex(i); cumulativeValue += this.getValueByKey(k); } return cumulativeValue; }; }; dc.cumulative.Sum.prototype = new dc.cumulative.Base(); dc.cumulative.CountUnique = function() { dc.cumulative.Base.apply(this, arguments); function hashSize(hash) { var size = 0, key; for (key in hash) { if (hash.hasOwnProperty(key)) size++; } return size; } this.add = function(key, e) { if (this.getValueByKey(key) == null) { this.setValueByKey(key, {}); this.addToIndex(key); } if (e != null) { if (this.getValueByKey(key)[e] == null) this.getValueByKey(key)[e] = 0; this.getValueByKey(key)[e] += 1; } }; this.minus = function(key, e) { this.getValueByKey(key)[e] -= 1; if (this.getValueByKey(key)[e] <= 0) delete this.getValueByKey(key)[e]; }; this.count = function(key) { return hashSize(this.getValueByKey(key)); }; this.cumulativeCount = function(key) { var keyIndex = this.indexOfKey(key); if (keyIndex < 0) return 0; var cumulativeCount = 0; for (var i = 0; i <= keyIndex; ++i) { var k = this.getKeyByIndex(i); cumulativeCount += this.count(k); } return cumulativeCount; }; }; dc.cumulative.CountUnique.prototype = new dc.cumulative.Base(); dc.baseChart = function (_chart) { _chart.__dc_flag__ = true; var _dimension; var _group; var _anchor; var _root; var _svg; var _width = 200, _height = 200; var _keyAccessor = function (d) { return d.key; }; var _valueAccessor = function (d) { return d.value; }; var _label = function (d) { return d.key; }; var _renderLabel = false; var _title = function (d) { return d.key + ": " + d.value; }; var _renderTitle = false; var _transitionDuration = 750; var _filterPrinter = dc.printers.filters; var _renderlets = []; var _chartGroup = dc.constants.DEFAULT_CHART_GROUP; var NULL_LISTENER = function (chart) { }; var _listeners = { preRender: NULL_LISTENER, postRender: NULL_LISTENER, preRedraw: NULL_LISTENER, postRedraw: NULL_LISTENER, filtered: NULL_LISTENER, zoomed: NULL_LISTENER }; var _legend; var _filters = []; var _filterHandler = function (dimension, filters) { dimension.filter(null); if (filters.length == 0) dimension.filter(null); else if (filters.length == 1) dimension.filter(filters[0]); else dimension.filterFunction(function (d) { return filters.indexOf(d) >= 0; }); return filters; }; _chart.width = function (w) { if (!arguments.length) return _width; _width = w; return _chart; }; _chart.height = function (h) { if (!arguments.length) return _height; _height = h; return _chart; }; _chart.dimension = function (d) { if (!arguments.length) return _dimension; _dimension = d; _chart.expireCache(); return _chart; }; _chart.group = function (g, name) { if (!arguments.length) return _group; _group = g; _chart.expireCache(); if (typeof name === 'string') _group.__name__ = name; return _chart; }; _chart.orderedGroup = function () { return _group.order(function (p) { return p.key; }); }; _chart.filterAll = function () { return _chart.filter(null); }; _chart.dataSet = function () { return _dimension != undefined && _group != undefined; }; _chart.select = function (s) { return _root.select(s); }; _chart.selectAll = function (s) { return _root ? _root.selectAll(s) : null; }; _chart.anchor = function (a, chartGroup) { if (!arguments.length) return _anchor; if (dc.instanceOfChart(a)) { _anchor = a.anchor(); _root = a.root(); } else { _anchor = a; _root = d3.select(_anchor); _root.classed(dc.constants.CHART_CLASS, true); dc.registerChart(_chart, chartGroup); } _chartGroup = chartGroup; return _chart; }; _chart.root = function (r) { if (!arguments.length) return _root; _root = r; return _chart; }; _chart.svg = function (_) { if (!arguments.length) return _svg; _svg = _; return _chart; }; _chart.resetSvg = function () { _chart.select("svg").remove(); return _chart.generateSvg(); }; _chart.generateSvg = function () { _svg = _chart.root().append("svg") .attr("width", _chart.width()) .attr("height", _chart.height()); return _svg; }; _chart.filterPrinter = function (_) { if (!arguments.length) return _filterPrinter; _filterPrinter = _; return _chart; }; _chart.turnOnControls = function () { if (_root) { _chart.selectAll(".reset").style("display", null); _chart.selectAll(".filter").text(_filterPrinter(_chart.filters())).style("display", null); } return _chart; }; _chart.turnOffControls = function () { if (_root) { _chart.selectAll(".reset").style("display", "none"); _chart.selectAll(".filter").style("display", "none").text(_chart.filter()); } return _chart; }; _chart.transitionDuration = function (d) { if (!arguments.length) return _transitionDuration; _transitionDuration = d; return _chart; }; _chart.render = function () { _listeners.preRender(_chart); if (_dimension == null) throw new dc.errors.InvalidStateException("Mandatory attribute chart.dimension is missing on chart[" + _chart.anchor() + "]"); if (_group == null) throw new dc.errors.InvalidStateException("Mandatory attribute chart.group is missing on chart[" + _chart.anchor() + "]"); var result = _chart.doRender(); if (_legend) _legend.render(); _chart.activateRenderlets("postRender"); return result; }; _chart.activateRenderlets = function (event) { if (_chart.transitionDuration() > 0 && _svg) { _svg.transition().duration(_chart.transitionDuration()) .each("end", function () { runAllRenderlets(); if (event) _listeners[event](_chart); }); } else { runAllRenderlets(); if (event) _listeners[event](_chart); } } _chart.redraw = function () { _listeners.preRedraw(_chart); var result = _chart.doRedraw(); _chart.activateRenderlets("postRedraw"); return result; }; _chart.invokeFilteredListener = function (chart, f) { if (f !== undefined) _listeners.filtered(_chart, f); }; _chart.invokeZoomedListener = function (chart) { _listeners.zoomed(_chart); }; _chart.hasFilter = function (filter) { if (!arguments.length) return _filters.length > 0; return _filters.indexOf(filter) >= 0; }; function removeFilter(_) { _filters.splice(_filters.indexOf(_), 1); applyFilters(); _chart.invokeFilteredListener(_chart, _); } function addFilter(_) { _filters.push(_); applyFilters(); _chart.invokeFilteredListener(_chart, _); } function resetFilters() { _filters = []; applyFilters(); _chart.invokeFilteredListener(_chart, null); } function applyFilters() { if (_chart.dataSet() && _chart.dimension().filter != undefined) { var fs = _filterHandler(_chart.dimension(), _filters); _filters = fs ? fs : _filters; } } _chart.filter = function (_) { if (!arguments.length) return _filters.length > 0 ? _filters[0] : null; if (_ == null) { resetFilters(); } else { if (_chart.hasFilter(_)) removeFilter(_); else addFilter(_); } if (_root != null && _chart.hasFilter()) { _chart.turnOnControls(); } else { _chart.turnOffControls(); } return _chart; }; _chart.filters = function () { return _filters; }; _chart.highlightSelected = function (e) { d3.select(e).classed(dc.constants.SELECTED_CLASS, true); d3.select(e).classed(dc.constants.DESELECTED_CLASS, false); }; _chart.fadeDeselected = function (e) { d3.select(e).classed(dc.constants.SELECTED_CLASS, false); d3.select(e).classed(dc.constants.DESELECTED_CLASS, true); }; _chart.resetHighlight = function (e) { d3.select(e).classed(dc.constants.SELECTED_CLASS, false); d3.select(e).classed(dc.constants.DESELECTED_CLASS, false); }; _chart.onClick = function (d) { var filter = _chart.keyAccessor()(d); dc.events.trigger(function () { _chart.filter(filter); dc.redrawAll(_chart.chartGroup()); }); }; _chart.filterHandler = function (_) { if (!arguments.length) return _filterHandler; _filterHandler = _; return _chart; }; // abstract function stub _chart.doRender = function () { // do nothing in base, should be overridden by sub-function return _chart; }; _chart.doRedraw = function () { // do nothing in base, should be overridden by sub-function return _chart; }; _chart.legendables = function () { // do nothing in base, should be overridden by sub-function return []; }; _chart.legendHighlight = function (d) { // do nothing in base, should be overridden by sub-function }; _chart.legendReset = function (d) { // do nothing in base, should be overridden by sub-function }; _chart.keyAccessor = function (_) { if (!arguments.length) return _keyAccessor; _keyAccessor = _; return _chart; }; _chart.valueAccessor = function (_) { if (!arguments.length) return _valueAccessor; _valueAccessor = _; return _chart; }; _chart.label = function (_) { if (!arguments.length) return _label; _label = _; _renderLabel = true; return _chart; }; _chart.renderLabel = function (_) { if (!arguments.length) return _renderLabel; _renderLabel = _; return _chart; }; _chart.title = function (_) { if (!arguments.length) return _title; _title = _; _renderTitle = true; return _chart; }; _chart.renderTitle = function (_) { if (!arguments.length) return _renderTitle; _renderTitle = _; return _chart; }; _chart.renderlet = function (_) { _renderlets.push(_); return _chart; }; function runAllRenderlets() { for (var i = 0; i < _renderlets.length; ++i) { _renderlets[i](_chart); } } _chart.chartGroup = function (_) { if (!arguments.length) return _chartGroup; _chartGroup = _; return _chart; }; _chart.on = function (event, listener) { _listeners[event] = listener; return _chart; }; _chart.expireCache = function () { // do nothing in base, should be overridden by sub-function return _chart; }; _chart.legend = function (l) { if (!arguments.length) return _legend; _legend = l; _legend.parent(_chart); return _chart; }; return _chart; }; dc.marginable = function (_chart) { var _margin = {top: 10, right: 50, bottom: 30, left: 30}; _chart.margins = function (m) { if (!arguments.length) return _margin; _margin = m; return _chart; }; _chart.effectiveWidth = function () { return _chart.width() - _chart.margins().left - _chart.margins().right; }; _chart.effectiveHeight = function () { return _chart.height() - _chart.margins().top - _chart.margins().bottom; }; return _chart; };dc.coordinateGridChart = function (_chart) { var DEFAULT_Y_AXIS_TICKS = 5; var GRID_LINE_CLASS = "grid-line"; var HORIZONTAL_CLASS = "horizontal"; var VERTICAL_CLASS = "vertical"; _chart = dc.colorChart(dc.marginable(dc.baseChart(_chart))); _chart.colors(d3.scale.category10()); var _parent; var _g; var _chartBodyG; var _x; var _xOriginalDomain; var _xAxis = d3.svg.axis(); var _xUnits = dc.units.integers; var _xAxisPadding = 0; var _xElasticity = false; var _y; var _yAxis = d3.svg.axis(); var _yAxisPadding = 0; var _yElasticity = false; var _brush = d3.svg.brush(); var _brushOn = true; var _round; var _renderHorizontalGridLine = false; var _renderVerticalGridLine = false; var _refocused = false; var _unitCount; var _rangeChart; var _focusChart; var _mouseZoomable = false; var _clipPadding = 0; _chart.title(function (d) { return d.data.key + ": " + d.data.value; }); _chart.rescale = function () { _unitCount = null; _chart.xUnitCount(); } _chart.rangeChart = function (_) { if (!arguments.length) return _rangeChart; _rangeChart = _; _rangeChart.focusChart(_chart); return _chart; } _chart.generateG = function (parent) { if (parent == null) _parent = _chart.svg(); else _parent = parent; _g = _parent.append("g"); _chartBodyG = _g.append("g").attr("class", "chart-body") .attr("transform", "translate(" + _chart.margins().left + ", " + _chart.margins().top + ")") .attr("clip-path", "url(#" + getClipPathId() + ")"); return _g; }; _chart.g = function (_) { if (!arguments.length) return _g; _g = _; return _chart; }; _chart.mouseZoomable = function (z) { if (!arguments.length) return _mouseZoomable; _mouseZoomable = z; return _chart; }; _chart.chartBodyG = function (_) { if (!arguments.length) return _chartBodyG; _chartBodyG = _; return _chart; }; _chart.x = function (_) { if (!arguments.length) return _x; _x = _; _xOriginalDomain = _x.domain(); return _chart; }; _chart.xOriginalDomain = function () { return _xOriginalDomain; }; _chart.xUnits = function (_) { if (!arguments.length) return _xUnits; _xUnits = _; return _chart; }; _chart.xAxis = function (_) { if (!arguments.length) return _xAxis; _xAxis = _; return _chart; }; _chart.elasticX = function (_) { if (!arguments.length) return _xElasticity; _xElasticity = _; return _chart; }; _chart.xAxisPadding = function (_) { if (!arguments.length) return _xAxisPadding; _xAxisPadding = _; return _chart; }; _chart.xUnitCount = function () { if (_unitCount == null) { var units = _chart.xUnits()(_chart.x().domain()[0], _chart.x().domain()[1], _chart.x().domain()); if (units instanceof Array) _unitCount = units.length; else _unitCount = units; } return _unitCount; }; _chart.isOrdinal = function () { return _chart.xUnits() === dc.units.ordinal; }; _chart.prepareOrdinalXAxis = function (count) { if (!count) count = _chart.xUnitCount(); var range = []; var currentPosition = 0; var increment = _chart.xAxisLength() / count; for (var i = 0; i < count; i++) { range[i] = currentPosition; currentPosition += increment; } _x.range(range); }; function prepareXAxis(g) { if (_chart.elasticX() && !_chart.isOrdinal()) { _x.domain([_chart.xAxisMin(), _chart.xAxisMax()]); } if (_chart.isOrdinal()) { _chart.prepareOrdinalXAxis(); } else { _x.range([0, _chart.xAxisLength()]); } _xAxis = _xAxis.scale(_chart.x()).orient("bottom"); renderVerticalGridLines(g); } _chart.renderXAxis = function (g) { var axisXG = g.selectAll("g.x"); if (axisXG.empty()) axisXG = g.append("g") .attr("class", "axis x") .attr("transform", "translate(" + _chart.margins().left + "," + _chart.xAxisY() + ")"); dc.transition(axisXG, _chart.transitionDuration()) .call(_xAxis); }; function renderVerticalGridLines(g) { var gridLineG = g.selectAll("g." + VERTICAL_CLASS); if (_renderVerticalGridLine) { if (gridLineG.empty()) gridLineG = g.insert("g", ":first-child") .attr("class", GRID_LINE_CLASS + " " + VERTICAL_CLASS) .attr("transform", "translate(" + _chart.yAxisX() + "," + _chart.margins().top + ")"); var ticks = _xAxis.tickValues() ? _xAxis.tickValues() : _x.ticks(_xAxis.ticks()[0]); var lines = gridLineG.selectAll("line") .data(ticks); // enter var linesGEnter = lines.enter() .append("line") .attr("x1", function (d) { return _x(d); }) .attr("y1", _chart.xAxisY() - _chart.margins().top) .attr("x2", function (d) { return _x(d); }) .attr("y2", 0) .attr("opacity", 0); dc.transition(linesGEnter, _chart.transitionDuration()) .attr("opacity", 1); // update dc.transition(lines, _chart.transitionDuration()) .attr("x1", function (d) { return _x(d); }) .attr("y1", _chart.xAxisY() - _chart.margins().top) .attr("x2", function (d) { return _x(d); }) .attr("y2", 0); // exit lines.exit().remove(); } else { gridLineG.selectAll("line").remove() } } _chart.xAxisY = function () { return (_chart.height() - _chart.margins().bottom); }; _chart.xAxisLength = function () { return _chart.effectiveWidth(); }; function prepareYAxis(g) { if (_y == null || _chart.elasticY()) { _y = d3.scale.linear(); _y.domain([_chart.yAxisMin(), _chart.yAxisMax()]).rangeRound([_chart.yAxisHeight(), 0]); } _y.range([_chart.yAxisHeight(), 0]); _yAxis = _yAxis.scale(_y).orient("left").ticks(DEFAULT_Y_AXIS_TICKS); renderHorizontalGridLines(g); } _chart.renderYAxis = function (g) { var axisYG = g.selectAll("g.y"); if (axisYG.empty()) axisYG = g.append("g") .attr("class", "axis y") .attr("transform", "translate(" + _chart.yAxisX() + "," + _chart.margins().top + ")"); dc.transition(axisYG, _chart.transitionDuration()) .call(_yAxis); }; function renderHorizontalGridLines(g) { var gridLineG = g.selectAll("g." + HORIZONTAL_CLASS); if (_renderHorizontalGridLine) { var ticks = _yAxis.tickValues() ? _yAxis.tickValues() : _y.ticks(_yAxis.ticks()[0]); if (gridLineG.empty()) gridLineG = g.insert("g", ":first-child") .attr("class", GRID_LINE_CLASS + " " + HORIZONTAL_CLASS) .attr("transform", "translate(" + _chart.yAxisX() + "," + _chart.margins().top + ")"); var lines = gridLineG.selectAll("line") .data(ticks); // enter var linesGEnter = lines.enter() .append("line") .attr("x1", 1) .attr("y1", function (d) { return _y(d); }) .attr("x2", _chart.xAxisLength()) .attr("y2", function (d) { return _y(d); }) .attr("opacity", 0); dc.transition(linesGEnter, _chart.transitionDuration()) .attr("opacity", 1); // update dc.transition(lines, _chart.transitionDuration()) .attr("x1", 1) .attr("y1", function (d) { return _y(d); }) .attr("x2", _chart.xAxisLength()) .attr("y2", function (d) { return _y(d); }); // exit lines.exit().remove(); } else { gridLineG.selectAll("line").remove() } } _chart.yAxisX = function () { return _chart.margins().left; }; _chart.y = function (_) { if (!arguments.length) return _y; _y = _; return _chart; }; _chart.yAxis = function (y) { if (!arguments.length) return _yAxis; _yAxis = y; return _chart; }; _chart.elasticY = function (_) { if (!arguments.length) return _yElasticity; _yElasticity = _; return _chart; }; _chart.renderHorizontalGridLines = function (_) { if (!arguments.length) return _renderHorizontalGridLine; _renderHorizontalGridLine = _; return _chart; }; _chart.renderVerticalGridLines = function (_) { if (!arguments.length) return _renderVerticalGridLine; _renderVerticalGridLine = _; return _chart; }; _chart.xAxisMin = function () { var min = d3.min(_chart.group().all(), function (e) { return _chart.keyAccessor()(e); }); return dc.utils.subtract(min, _xAxisPadding); }; _chart.xAxisMax = function () { var max = d3.max(_chart.group().all(), function (e) { return _chart.keyAccessor()(e); }); return dc.utils.add(max, _xAxisPadding); }; _chart.yAxisMin = function () { var min = d3.min(_chart.group().all(), function (e) { return _chart.valueAccessor()(e); }); min = dc.utils.subtract(min, _yAxisPadding); return min; }; _chart.yAxisMax = function () { var max = d3.max(_chart.group().all(), function (e) { return _chart.valueAccessor()(e); }); max = dc.utils.add(max, _yAxisPadding); return max; }; _chart.yAxisPadding = function (_) { if (!arguments.length) return _yAxisPadding; _yAxisPadding = _; return _chart; }; _chart.yAxisHeight = function () { return _chart.effectiveHeight(); }; _chart.round = function (_) { if (!arguments.length) return _round; _round = _; return _chart; }; dc.override(_chart, "filter", function (_) { if (!arguments.length) return _chart._filter(); _chart._filter(_); if (_) { _chart.brush().extent(_); } else { _chart.brush().clear(); } return _chart; }); _chart.brush = function (_) { if (!arguments.length) return _brush; _brush = _; return _chart; }; function brushHeight() { return _chart.xAxisY() - _chart.margins().top; } _chart.renderBrush = function (g) { if (_chart.isOrdinal()) _brushOn = false; if (_brushOn) { _brush.on("brushstart", brushStart) .on("brush", brushing) .on("brushend", brushEnd); var gBrush = g.append("g") .attr("class", "brush") .attr("transform", "translate(" + _chart.margins().left + "," + _chart.margins().top + ")") .call(_brush.x(_chart.x())); gBrush.selectAll("rect").attr("height", brushHeight()); gBrush.selectAll(".resize").append("path").attr("d", _chart.resizeHandlePath); if (_chart.hasFilter()) { _chart.redrawBrush(g); } } }; function brushStart(p) { } _chart.extendBrush = function () { var extent = _brush.extent(); if (_chart.round()) { extent[0] = extent.map(_chart.round())[0]; extent[1] = extent.map(_chart.round())[1]; _g.select(".brush") .call(_brush.extent(extent)); } return extent; }; _chart.brushIsEmpty = function (extent) { return _brush.empty() || !extent || extent[1] <= extent[0]; }; function brushing(p) { var extent = _chart.extendBrush(); _chart.redrawBrush(_g); if (_chart.brushIsEmpty(extent)) { dc.events.trigger(function () { _chart.filter(null); dc.redrawAll(_chart.chartGroup()); }); } else { dc.events.trigger(function () { _chart.filter(null); _chart.filter([extent[0], extent[1]]); dc.redrawAll(_chart.chartGroup()); }, dc.constants.EVENT_DELAY); } } function brushEnd(p) { } _chart.redrawBrush = function (g) { if (_brushOn) { if (_chart.filter() && _chart.brush().empty()) _chart.brush().extent(_chart.filter()); var gBrush = g.select("g.brush"); gBrush.call(_chart.brush().x(_chart.x())); gBrush.selectAll("rect").attr("height", brushHeight()); } _chart.fadeDeselectedArea(); }; _chart.fadeDeselectedArea = function () { // do nothing, sub-chart should override this function }; // borrowed from Crossfilter example _chart.resizeHandlePath = function (d) { var e = +(d == "e"), x = e ? 1 : -1, y = brushHeight() / 3; return "M" + (.5 * x) + "," + y + "A6,6 0 0 " + e + " " + (6.5 * x) + "," + (y + 6) + "V" + (2 * y - 6) + "A6,6 0 0 " + e + " " + (.5 * x) + "," + (2 * y) + "Z" + "M" + (2.5 * x) + "," + (y + 8) + "V" + (2 * y - 8) + "M" + (4.5 * x) + "," + (y + 8) + "V" + (2 * y - 8); }; function getClipPathId() { return _chart.anchor().replace('#', '') + "-clip"; } _chart.clipPadding = function (p) { if (!arguments.length) return _clipPadding; _clipPadding = p; return _chart; }; function generateClipPath() { var defs = dc.utils.appendOrSelect(_parent, "defs"); var chartBodyClip = dc.utils.appendOrSelect(defs, "clipPath").attr("id", getClipPathId()); var padding = _clipPadding * 2; dc.utils.appendOrSelect(chartBodyClip, "rect") .attr("width", _chart.xAxisLength() + padding) .attr("height", _chart.yAxisHeight() + padding); } _chart.doRender = function () { if (_x == null) throw new dc.errors.InvalidStateException("Mandatory attribute chart.x is missing on chart[" + _chart.anchor() + "]"); _chart.resetSvg(); if (_chart.dataSet()) { _chart.generateG(); generateClipPath(); prepareXAxis(_chart.g()); prepareYAxis(_chart.g()); _chart.plotData(); _chart.renderXAxis(_chart.g()); _chart.renderYAxis(_chart.g()); _chart.renderBrush(_chart.g()); enableMouseZoom(); } return _chart; }; function enableMouseZoom() { if (_mouseZoomable) { _chart.root().call(d3.behavior.zoom() .x(_chart.x()) .scaleExtent([1, 100]) .on("zoom", function () { _chart.focus(_chart.x().domain()); _chart.invokeZoomedListener(_chart); updateRangeSelChart(); })); } } function updateRangeSelChart() { if (_rangeChart) { var refDom = _chart.x().domain(); var origDom = _rangeChart.xOriginalDomain(); var newDom = [ refDom[0] < origDom[0] ? refDom[0] : origDom[0], refDom[1] > origDom[1] ? refDom[1] : origDom[1]]; _rangeChart.focus(newDom); _rangeChart.filter(null); _rangeChart.filter(refDom); dc.events.trigger(function () { dc.redrawAll(_chart.chartGroup()); }); } } _chart.doRedraw = function () { prepareXAxis(_chart.g()); prepareYAxis(_chart.g()); _chart.plotData(); if (_chart.elasticY()) _chart.renderYAxis(_chart.g()); if (_chart.elasticX() || _refocused) _chart.renderXAxis(_chart.g()); _chart.redrawBrush(_chart.g()); return _chart; }; _chart.subRender = function () { if (_chart.dataSet()) { _chart.plotData(); } return _chart; }; _chart.brushOn = function (_) { if (!arguments.length) return _brushOn; _brushOn = _; return _chart; }; _chart.getDataWithinXDomain = function (group) { var data = []; if (_chart.isOrdinal()) { data = group.all(); } else { group.all().forEach(function (d) { var key = _chart.keyAccessor()(d); if (key >= _chart.x().domain()[0] && key <= _chart.x().domain()[1]) data.push(d); }); } return data; }; function hasRangeSelected(range) { return range instanceof Array && range.length > 1; } _chart.focus = function (range) { _refocused = true; if (hasRangeSelected(range)) { _chart.x().domain(range); } else { _chart.x().domain(_chart.xOriginalDomain()); } _chart.rescale(); _chart.redraw(); if (!hasRangeSelected(range)) _refocused = false; }; _chart.refocused = function () { return _refocused; }; _chart.focusChart = function (c) { if (!arguments.length) return _focusChart; _focusChart = c; _chart.on("filtered", function (chart) { dc.events.trigger(function () { _focusChart.focus(chart.filter()); _focusChart.filter(chart.filter()); dc.redrawAll(chart.chartGroup()); }); }); return _chart; }; return _chart; }; dc.colorChart = function(_chart) { var _colors = d3.scale.category20c(); var _colorDomain = [0, _colors.range().length]; var _colorCalculator = function(value) { var minValue = _colorDomain[0]; var maxValue = _colorDomain[1]; if (isNaN(value)) value = 0; if(maxValue == null) return _colors(value); var colorsLength = _chart.colors().range().length; var denominator = (maxValue - minValue) / colorsLength; var colorValue = Math.abs(Math.min(colorsLength - 1, Math.round((value - minValue) / denominator))); return _chart.colors()(colorValue); }; var _colorAccessor = function(d, i){return i;}; _chart.colors = function(_) { if (!arguments.length) return _colors; if (_ instanceof Array) { _colors = d3.scale.ordinal().range(_); var domain = []; for(var i = 0; i < _.length; ++i){ domain.push(i); } _colors.domain(domain); } else { _colors = _; } _colorDomain = [0, _colors.range().length]; return _chart; }; _chart.colorCalculator = function(_){ if(!arguments.length) return _colorCalculator; _colorCalculator = _; return _chart; }; _chart.getColor = function(d, i){ return _colorCalculator(_colorAccessor(d, i)); }; _chart.colorAccessor = function(_){ if(!arguments.length) return _colorAccessor; _colorAccessor = _; return _chart; }; _chart.colorDomain = function(_){ if(!arguments.length) return _colorDomain; _colorDomain = _; return _chart; }; return _chart; }; dc.stackableChart = function (_chart) { var _groupStack = new dc.utils.GroupStack(); var _stackLayout = d3.layout.stack() .offset("zero") .order("default") .values(function (d) { return d.points; }); var _allGroups; var _allValueAccessors; var _allKeyAccessors; var _stackLayers; _chart.stack = function (group, p2, retriever) { if (typeof p2 === 'string') group.__name__ = p2; else if (typeof p2 === 'function') retriever = p2; _groupStack.setDefaultAccessor(_chart.valueAccessor()); _groupStack.addGroup(group, retriever); _chart.expireCache(); return _chart; }; _chart.expireCache = function () { _allGroups = null; _allValueAccessors = null; _allKeyAccessors = null; _stackLayers = null; return _chart; }; _chart.allGroups = function () { if (_allGroups == null) { _allGroups = []; _allGroups.push(_chart.group()); for (var i = 0; i < _groupStack.size(); ++i) _allGroups.push(_groupStack.getGroupByIndex(i)); } return _allGroups; }; _chart.allValueAccessors = function () { if (_allValueAccessors == null) { _allValueAccessors = []; _allValueAccessors.push(_chart.valueAccessor()); for (var i = 0; i < _groupStack.size(); ++i) _allValueAccessors.push(_groupStack.getAccessorByIndex(i)); } return _allValueAccessors; }; _chart.getValueAccessorByIndex = function (groupIndex) { return _chart.allValueAccessors()[groupIndex]; }; _chart.yAxisMin = function () { var min, all = flattenStack(); min = d3.min(all, function (p) { return (p.y + p.y0 < p.y0) ? (p.y + p.y0) : p.y0; }); min = dc.utils.subtract(min, _chart.yAxisPadding()); return min; }; _chart.yAxisMax = function () { var max, all = flattenStack(); max = d3.max(all, function (p) { return p.y + p.y0; }); max = dc.utils.add(max, _chart.yAxisPadding()); return max; }; function flattenStack() { var all = []; if (_chart.x()) { var xDomain = _chart.x().domain(); _chart.stackLayers().forEach(function (e) { e.points.forEach(function (p) { if (p.x >= xDomain[0] && p.x <= xDomain[1]) all.push(p); }); }); } else { _chart.stackLayers().forEach(function (e) { all = all.concat(e.points); }); } return all; } _chart.allKeyAccessors = function () { if (_allKeyAccessors == null) { _allKeyAccessors = []; _allKeyAccessors.push(_chart.keyAccessor()); for (var i = 0; i < _groupStack.size(); ++i) _allKeyAccessors.push(_chart.keyAccessor()); } return _allKeyAccessors; }; _chart.getKeyAccessorByIndex = function (groupIndex) { return _chart.allKeyAccessors()[groupIndex]; }; _chart.xAxisMin = function () { var min = null; var allGroups = _chart.allGroups(); for (var groupIndex = 0; groupIndex < allGroups.length; ++groupIndex) { var group = allGroups[groupIndex]; var m = dc.utils.groupMin(group, _chart.getKeyAccessorByIndex(groupIndex)); if (min == null || min > m) min = m; } return dc.utils.subtract(min, _chart.xAxisPadding()); }; _chart.xAxisMax = function () { var max = null; var allGroups = _chart.allGroups(); for (var groupIndex = 0; groupIndex < allGroups.length; ++groupIndex) { var group = allGroups[groupIndex]; var m = dc.utils.groupMax(group, _chart.getKeyAccessorByIndex(groupIndex)); if (max == null || max < m) max = m; } return dc.utils.add(max, _chart.xAxisPadding()); }; function getKeyFromData(groupIndex, d) { return _chart.getKeyAccessorByIndex(groupIndex)(d); } function getValueFromData(groupIndex, d) { return _chart.getValueAccessorByIndex(groupIndex)(d); } function calculateDataPointMatrix(data, groupIndex) { for (var dataIndex = 0; dataIndex < data.length; ++dataIndex) { var d = data[dataIndex]; var key = getKeyFromData(groupIndex, d); var value = getValueFromData(groupIndex, d); _groupStack.setDataPoint(groupIndex, dataIndex, {data: d, x: key, y: value}); } } _chart.calculateDataPointMatrixForAll = function () { var groups = _chart.allGroups(); for (var groupIndex = 0; groupIndex < groups.length; ++groupIndex) { var group = groups[groupIndex]; var data = group.all(); calculateDataPointMatrix(data, groupIndex); } }; _chart.getChartStack = function () { return _groupStack; }; dc.override(_chart, "valueAccessor", function (_) { if (!arguments.length) return _chart._valueAccessor(); _chart.expireCache(); return _chart._valueAccessor(_); }); dc.override(_chart, "keyAccessor", function (_) { if (!arguments.length) return _chart._keyAccessor(); _chart.expireCache(); return _chart._keyAccessor(_); }); _chart.stackLayout = function (stack) { if (!arguments.length) return _stackLayout; _stackLayout = stack; return _chart; }; _chart.stackLayers = function (_) { if (!arguments.length) { if (_stackLayers == null) { _chart.calculateDataPointMatrixForAll(); _stackLayers = _chart.stackLayout()(_groupStack.toLayers()); } return _stackLayers; } else { _stackLayers = _; } }; _chart.legendables = function () { var items = []; _allGroups.forEach(function (g, i) { items.push(dc.utils.createLegendable(_chart, g, i)); }); return items; }; return _chart; }; dc.abstractBubbleChart = function (_chart) { var _maxBubbleRelativeSize = 0.3; var _minRadiusWithLabel = 10; _chart.BUBBLE_NODE_CLASS = "node"; _chart.BUBBLE_CLASS = "bubble"; _chart.MIN_RADIUS = 10; _chart = dc.colorChart(_chart); _chart.renderLabel(true); _chart.renderTitle(false); var _r = d3.scale.linear().domain([0, 100]); var _rValueAccessor = function (d) { return d.r; }; _chart.r = function (_) { if (!arguments.length) return _r; _r = _; return _chart; }; _chart.radiusValueAccessor = function (_) { if (!arguments.length) return _rValueAccessor; _rValueAccessor = _; return _chart; }; _chart.rMin = function () { var min = d3.min(_chart.group().all(), function (e) { return _chart.radiusValueAccessor()(e); }); return min; }; _chart.rMax = function () { var max = d3.max(_chart.group().all(), function (e) { return _chart.radiusValueAccessor()(e); }); return max; }; _chart.bubbleR = function (d) { var value = _chart.radiusValueAccessor()(d); var r = _chart.r()(value); if (isNaN(r) || value <= 0) r = 0; return r; }; var labelFunction = function (d) { return _chart.label()(d); }; var labelOpacity = function (d) { return (_chart.bubbleR(d) > _minRadiusWithLabel) ? 1 : 0; }; _chart.doRenderLabel = function (bubbleGEnter) { if (_chart.renderLabel()) { var label = bubbleGEnter.select("text"); if (label.empty()) { label = bubbleGEnter.append("text") .attr("text-anchor", "middle") .attr("dy", ".3em") .on("click", _chart.onClick); } label .attr("opacity", 0) .text(labelFunction); dc.transition(label, _chart.transitionDuration()) .attr("opacity", labelOpacity); } }; _chart.doUpdateLabels = function (bubbleGEnter) { if (_chart.renderLabel()) { var labels = bubbleGEnter.selectAll("text") .text(labelFunction); dc.transition(labels, _chart.transitionDuration()) .attr("opacity", labelOpacity); } }; var titleFunction = function (d) { return _chart.title()(d); }; _chart.doRenderTitles = function (g) { if (_chart.renderTitle()) { var title = g.select("title"); if (title.empty()) g.append("title").text(titleFunction); } }; _chart.doUpdateTitles = function (g) { if (_chart.renderTitle()) { g.selectAll("title").text(titleFunction); } }; _chart.minRadiusWithLabel = function (_) { if (!arguments.length) return _minRadiusWithLabel; _minRadiusWithLabel = _; return _chart; }; _chart.maxBubbleRelativeSize = function (_) { if (!arguments.length) return _maxBubbleRelativeSize; _maxBubbleRelativeSize = _; return _chart; }; _chart.initBubbleColor = function (d, i) { this[dc.constants.NODE_INDEX_NAME] = i; return _chart.getColor(d, i); }; _chart.updateBubbleColor = function (d, i) { // a work around to get correct node index since return _chart.getColor(d, this[dc.constants.NODE_INDEX_NAME]); }; _chart.fadeDeselectedArea = function () { if (_chart.hasFilter()) { _chart.selectAll("g." + _chart.BUBBLE_NODE_CLASS).each(function (d) { if (_chart.isSelectedNode(d)) { _chart.highlightSelected(this); } else { _chart.fadeDeselected(this); } }); } else { _chart.selectAll("g." + _chart.BUBBLE_NODE_CLASS).each(function (d) { _chart.resetHighlight(this); }); } }; _chart.isSelectedNode = function (d) { return _chart.hasFilter(d.key); }; _chart.onClick = function (d) { var filter = d.key; dc.events.trigger(function () { _chart.filter(filter); dc.redrawAll(_chart.chartGroup()); }); }; return _chart; }; dc.pieChart = function (parent, chartGroup) { var DEFAULT_MIN_ANGLE_FOR_LABEL = 0.5; var _sliceCssClass = "pie-slice"; var _radius, _innerRadius = 0; var _g; var _minAngleForLabel = DEFAULT_MIN_ANGLE_FOR_LABEL; var _chart = dc.colorChart(dc.baseChart({})); var _slicesCap = Infinity; var _othersLabel = "Others"; var _othersGrouper = function (data, sum) { data.push({"key": _othersLabel, "value": sum }); }; function assemblePieData() { if (_slicesCap == Infinity) { return _chart.orderedGroup().top(_slicesCap); // ordered by keys } else { var topRows = _chart.group().top(_slicesCap); // ordered by value var topRowsSum = d3.sum(topRows, _chart.valueAccessor()); var allRows = _chart.group().all(); var allRowsSum = d3.sum(allRows, _chart.valueAccessor()); _othersGrouper(topRows, allRowsSum - topRowsSum); return topRows; } } _chart.label(function (d) { return _chart.keyAccessor()(d.data); }); _chart.renderLabel(true); _chart.title(function (d) { return _chart.keyAccessor()(d.data) + ": " + _chart.valueAccessor()(d.data); }); _chart.transitionDuration(350); _chart.doRender = function () { _chart.resetSvg(); _g = _chart.svg() .append("g") .attr("transform", "translate(" + _chart.cx() + "," + _chart.cy() + ")"); drawChart(); return _chart; }; function drawChart() { if (_chart.dataSet()) { var pie = calculateDataPie(); // set radius on basis of chart dimension if missing _radius = _radius ? _radius : d3.min([_chart.width(), _chart.height()]) /2; var arc = _chart.buildArcs(); var pieData = pie(assemblePieData()); if (_g) { var slices = _g.selectAll("g." + _sliceCssClass) .data(pieData); createElements(slices, arc, pieData); updateElements(pieData, arc); removeElements(slices); highlightFilter(); } } } function createElements(slices, arc, pieData) { var slicesEnter = createSliceNodes(slices); createSlicePath(slicesEnter, arc); createTitles(slicesEnter); createLabels(pieData, arc); } function createSliceNodes(slices) { var slicesEnter = slices .enter() .append("g") .attr("class", function (d, i) { return _sliceCssClass + " _" + i; }); return slicesEnter; } function createSlicePath(slicesEnter, arc) { var slicePath = slicesEnter.append("path") .attr("fill", function (d, i) { return _chart.getColor(d, i); }) .on("click", onClick) .attr("d", function (d, i) { return safeArc(d, i, arc); }); slicePath.transition() .duration(_chart.transitionDuration()) .attrTween("d", tweenPie); } function createTitles(slicesEnter) { if (_chart.renderTitle()) { slicesEnter.append("title").text(function (d) { return _chart.title()(d); }); } } function createLabels(pieData, arc) { if (_chart.renderLabel()) { var labels = _g.selectAll("text." + _sliceCssClass) .data(pieData); var labelsEnter = labels .enter() .append("text") .attr("class", function (d, i) { return _sliceCssClass + " _" + i; }) .on("click", onClick); dc.transition(labelsEnter, _chart.transitionDuration()) .attr("transform", function (d) { d.innerRadius = _chart.innerRadius(); d.outerRadius = _radius; var centroid = arc.centroid(d); if (isNaN(centroid[0]) || isNaN(centroid[1])) { return "translate(0,0)"; } else { return "translate(" + centroid + ")"; } }) .attr("text-anchor", "middle") .text(function (d) { var data = d.data; if (sliceHasNoData(data) || sliceTooSmall(d)) return ""; return _chart.label()(d); }); } } function updateElements(pieData, arc) { updateSlicePaths(pieData, arc); updateLabels(pieData, arc); updateTitles(pieData); } function updateSlicePaths(pieData, arc) { var slicePaths = _g.selectAll("g." + _sliceCssClass) .data(pieData) .select("path") .attr("d", function (d, i) { return safeArc(d, i, arc); }); dc.transition(slicePaths, _chart.transitionDuration(), function (s) { s.attrTween("d", tweenPie); }).attr("fill", function (d, i) { return _chart.getColor(d, i); }); } function updateLabels(pieData, arc) { if (_chart.renderLabel()) { var labels = _g.selectAll("text." + _sliceCssClass) .data(pieData); dc.transition(labels, _chart.transitionDuration()) .attr("transform", function (d) { d.innerRadius = _chart.innerRadius(); d.outerRadius = _radius; var centroid = arc.centroid(d); if (isNaN(centroid[0]) || isNaN(centroid[1])) { return "translate(0,0)"; } else { return "translate(" + centroid + ")"; } }) .attr("text-anchor", "middle") .text(function (d) { var data = d.data; if (sliceHasNoData(data) || sliceTooSmall(d)) return ""; return _chart.label()(d); }); } } function updateTitles(pieData) { if (_chart.renderTitle()) { _g.selectAll("g." + _sliceCssClass) .data(pieData) .select("title") .text(function (d) { return _chart.title()(d); }); } } function removeElements(slices) { slices.exit().remove(); } function highlightFilter() { if (_chart.hasFilter()) { _chart.selectAll("g." + _sliceCssClass).each(function (d) { if (_chart.isSelectedSlice(d)) { _chart.highlightSelected(this); } else { _chart.fadeDeselected(this); } }); } else { _chart.selectAll("g." + _sliceCssClass).each(function (d) { _chart.resetHighlight(this); }); } } _chart.innerRadius = function (r) { if (!arguments.length) return _innerRadius; _innerRadius = r; return _chart; }; _chart.radius = function (r) { if (!arguments.length) return _radius; _radius = r; return _chart; }; _chart.cx = function () { return _chart.width() / 2; }; _chart.cy = function () { return _chart.height() / 2; }; _chart.buildArcs = function () { return d3.svg.arc().outerRadius(_radius).innerRadius(_innerRadius); }; _chart.isSelectedSlice = function (d) { return _chart.hasFilter(_chart.keyAccessor()(d.data)); }; _chart.doRedraw = function () { drawChart(); return _chart; }; _chart.minAngleForLabel = function (_) { if (!arguments.length) return _minAngleForLabel; _minAngleForLabel = _; return _chart; }; _chart.slicesCap = function (_) { if (!arguments.length) return _slicesCap; _slicesCap = _; return _chart; }; _chart.othersLabel = function (_) { if (!arguments.length) return _othersLabel; _othersLabel = _; return _chart; }; _chart.othersGrouper = function (_) { if (!arguments.length) return _othersGrouper; _othersGrouper = _; return _chart; }; function calculateDataPie() { return d3.layout.pie().sort(null).value(function (d) { return _chart.valueAccessor()(d); }); } function sliceTooSmall(d) { var angle = (d.endAngle - d.startAngle); return isNaN(angle) || angle < _minAngleForLabel; } function sliceHasNoData(data) { return _chart.valueAccessor()(data) == 0; } function tweenPie(b) { b.innerRadius = _chart.innerRadius(); var current = this._current; if (isOffCanvas(current)) current = {startAngle: 0, endAngle: 0}; var i = d3.interpolate(current, b); this._current = i(0); return function (t) { return safeArc(i(t), 0, _chart.buildArcs()); }; } function isOffCanvas(current) { return current == null || isNaN(current.startAngle) || isNaN(current.endAngle); } function onClick(d) { _chart.onClick(d.data); } function safeArc(d, i, arc) { var path = arc(d, i); if (path.indexOf("NaN") >= 0) path = "M0,0"; return path; } return _chart.anchor(parent, chartGroup); }; dc.barChart = function (parent, chartGroup) { var MIN_BAR_WIDTH = 1; var DEFAULT_GAP_BETWEEN_BARS = 2; var _chart = dc.stackableChart(dc.coordinateGridChart({})); var _gap = DEFAULT_GAP_BETWEEN_BARS; var _centerBar = false; var _numberOfBars; var _barWidth; dc.override(_chart, 'rescale', function () { _chart._rescale(); _numberOfBars = null; _barWidth = null; getNumberOfBars(); }); _chart.plotData = function () { var layers = _chart.chartBodyG().selectAll("g.stack") .data(_chart.stackLayers()); calculateBarWidth(); layers .enter() .append("g") .attr("class", function (d, i) { return "stack " + "_" + i; }); layers.each(function (d, i) { var layer = d3.select(this); renderBars(layer, d, i); }); _chart.stackLayers(null); }; function barHeight(d) { return Math.abs(_chart.y()(d.y + d.y0) - _chart.y()(d.y0)); } function renderBars(layer, d, i) { var bars = layer.selectAll("rect.bar") .data(d.points); bars.enter() .append("rect") .attr("class", "bar") .attr("fill", function (d) { return _chart.colors()(i); }) .append("title").text(_chart.title()); dc.transition(bars, _chart.transitionDuration()) .attr("x", function (d) { var x = _chart.x()(d.x); if (_centerBar) x -= _barWidth / 2; return x; }) .attr("y", function (d) { var y = _chart.y()(d.y + d.y0); if (d.y < 0) y -= barHeight(d); return y; }) .attr("width", _barWidth) .attr("height", function (d) { return barHeight(d); }) .select("title").text(_chart.title()); dc.transition(bars.exit(), _chart.transitionDuration()) .attr("height", 0) .remove(); } function calculateBarWidth() { if (_barWidth == null) { var numberOfBars = _chart.isOrdinal() ? getNumberOfBars() + 1 : getNumberOfBars(); var w = Math.floor((_chart.xAxisLength() - (numberOfBars - 1) * _gap) / numberOfBars); if (w == Infinity || isNaN(w) || w < MIN_BAR_WIDTH) w = MIN_BAR_WIDTH; _barWidth = w; } } function getNumberOfBars() { if (_numberOfBars == null) { _numberOfBars = _chart.xUnitCount(); } return _numberOfBars; } _chart.fadeDeselectedArea = function () { var bars = _chart.chartBodyG().selectAll("rect.bar"); var extent = _chart.brush().extent(); if (_chart.isOrdinal()) { if (_chart.hasFilter()) { bars.classed(dc.constants.SELECTED_CLASS, function (d) { return _chart.hasFilter(_chart.keyAccessor()(d.data)); }); bars.classed(dc.constants.DESELECTED_CLASS, function (d) { return !_chart.hasFilter(_chart.keyAccessor()(d.data)); }); } else { bars.classed(dc.constants.SELECTED_CLASS, false); bars.classed(dc.constants.DESELECTED_CLASS, false); } } else { if (!_chart.brushIsEmpty(extent)) { var start = extent[0]; var end = extent[1]; bars.classed(dc.constants.DESELECTED_CLASS, function (d) { var xValue = _chart.keyAccessor()(d.data); return xValue < start || xValue >= end; }); } else { bars.classed(dc.constants.DESELECTED_CLASS, false); } } }; _chart.centerBar = function (_) { if (!arguments.length) return _centerBar; _centerBar = _; return _chart; }; _chart.gap = function (_) { if (!arguments.length) return _gap; _gap = _; return _chart; }; _chart.extendBrush = function () { var extent = _chart.brush().extent(); if (_chart.round() && !_centerBar) { extent[0] = extent.map(_chart.round())[0]; extent[1] = extent.map(_chart.round())[1]; _chart.chartBodyG().select(".brush") .call(_chart.brush().extent(extent)); } return extent; }; dc.override(_chart, "prepareOrdinalXAxis", function () { return this._prepareOrdinalXAxis(_chart.xUnitCount() + 1); }); _chart.legendHighlight = function (d) { _chart.select('.chart-body').selectAll('rect.bar').filter(function () { return d3.select(this).attr('fill') == d.color; }).classed('highlight', true); _chart.select('.chart-body').selectAll('rect.bar').filter(function () { return d3.select(this).attr('fill') != d.color; }).classed('fadeout', true); }; _chart.legendReset = function (d) { _chart.selectAll('.chart-body').selectAll('rect.bar').filter(function () { return d3.select(this).attr('fill') == d.color; }).classed('highlight', false); _chart.selectAll('.chart-body').selectAll('rect.bar').filter(function () { return d3.select(this).attr('fill') != d.color; }).classed('fadeout', false); }; return _chart.anchor(parent, chartGroup); }; dc.lineChart = function (parent, chartGroup) { var DEFAULT_DOT_RADIUS = 5; var TOOLTIP_G_CLASS = "dc-tooltip"; var DOT_CIRCLE_CLASS = "dot"; var Y_AXIS_REF_LINE_CLASS = "yRef"; var X_AXIS_REF_LINE_CLASS = "xRef"; var _chart = dc.stackableChart(dc.coordinateGridChart({})); var _renderArea = false; var _dotRadius = DEFAULT_DOT_RADIUS; _chart.transitionDuration(500); _chart.plotData = function () { var layers = _chart.chartBodyG().selectAll("g.stack") .data(_chart.stackLayers()); var layersEnter = layers .enter() .append("g") .attr("class", function (d, i) { return "stack " + "_" + i; }); drawLine(layersEnter, layers); drawArea(layersEnter, layers); drawDots(layers); _chart.stackLayers(null); }; _chart.renderArea = function (_) { if (!arguments.length) return _renderArea; _renderArea = _; return _chart; }; function drawLine(layersEnter, layers) { var line = d3.svg.line() .x(function (d) { return _chart.x()(d.x); }) .y(function (d) { return _chart.y()(d.y + d.y0); }); layersEnter.append("path") .attr("class", "line") .attr("stroke", function (d, i) { return _chart.colors()(i); }) .attr("fill", function (d, i) { return _chart.colors()(i); }); dc.transition(layers.select("path.line"), _chart.transitionDuration()) .attr("d", function (d) { return line(d.points); }); } function drawArea(layersEnter, layers) { if (_renderArea) { var area = d3.svg.area() .x(function (d) { return _chart.x()(d.x); }) .y(function (d) { return _chart.y()(d.y + d.y0); }) .y0(function (d) { return _chart.y()(d.y0); }); layersEnter.append("path") .attr("class", "area") .attr("fill", function (d, i) { return _chart.colors()(i); }) .attr("d", function (d) { return area(d.points); }); dc.transition(layers.select("path.area"), _chart.transitionDuration()) .attr("d", function (d) { return area(d.points); }); } } function drawDots(layersEnter) { if (!_chart.brushOn()) { layersEnter.each(function (d, i) { var layer = d3.select(this); var g = layer.select("g." + TOOLTIP_G_CLASS); if (g.empty()) g = layer.append("g").attr("class", TOOLTIP_G_CLASS); createRefLines(g); var dots = g.selectAll("circle." + DOT_CIRCLE_CLASS) .data(g.datum().points); dots.enter() .append("circle") .attr("class", DOT_CIRCLE_CLASS) .attr("r", _dotRadius) .attr("fill", function (d) { return _chart.colors()(i); }) .style("fill-opacity", 1e-6) .style("stroke-opacity", 1e-6) .on("mousemove", function (d) { var dot = d3.select(this); showDot(dot); showRefLines(dot, g); }) .on("mouseout", function (d) { var dot = d3.select(this); hideDot(dot); hideRefLines(g); }) .append("title").text(_chart.title()); dots.attr("cx", function (d) { return _chart.x()(d.x); }) .attr("cy", function (d) { return _chart.y()(d.y + d.y0); }) .select("title").text(_chart.title()); dots.exit().remove(); }); } } function createRefLines(g) { var yRefLine = g.select("path." + Y_AXIS_REF_LINE_CLASS).empty() ? g.append("path").attr("class", Y_AXIS_REF_LINE_CLASS) : g.select("path." + Y_AXIS_REF_LINE_CLASS); yRefLine.style("display", "none").attr("stroke-dasharray", "5,5"); var xRefLine = g.select("path." + X_AXIS_REF_LINE_CLASS).empty() ? g.append("path").attr("class", X_AXIS_REF_LINE_CLASS) : g.select("path." + X_AXIS_REF_LINE_CLASS); xRefLine.style("display", "none").attr("stroke-dasharray", "5,5"); } function showDot(dot) { dot.style("fill-opacity", .8); dot.style("stroke-opacity", .8); return dot; } function showRefLines(dot, g) { var x = dot.attr("cx"); var y = dot.attr("cy"); g.select("path." + Y_AXIS_REF_LINE_CLASS).style("display", "").attr("d", "M0 " + y + "L" + (x) + " " + (y)); g.select("path." + X_AXIS_REF_LINE_CLASS).style("display", "").attr("d", "M" + x + " " + _chart.yAxisHeight() + "L" + x + " " + y); } function hideDot(dot) { dot.style("fill-opacity", 1e-6).style("stroke-opacity", 1e-6); } function hideRefLines(g) { g.select("path." + Y_AXIS_REF_LINE_CLASS).style("display", "none"); g.select("path." + X_AXIS_REF_LINE_CLASS).style("display", "none"); } _chart.dotRadius = function (_) { if (!arguments.length) return _dotRadius; _dotRadius = _; return _chart; }; _chart.legendHighlight = function (d) { _chart.selectAll('.chart-body').selectAll('path').filter(function () { return d3.select(this).attr('fill') == d.color; }).classed('highlight', true); _chart.selectAll('.chart-body').selectAll('path').filter(function () { return d3.select(this).attr('fill') != d.color; }).classed('fadeout', true); }; _chart.legendReset = function (d) { _chart.selectAll('.chart-body').selectAll('path').filter(function () { return d3.select(this).attr('fill') == d.color; }).classed('highlight', false); _chart.selectAll('.chart-body').selectAll('path').filter(function () { return d3.select(this).attr('fill') != d.color; }).classed('fadeout', false); }; return _chart.anchor(parent, chartGroup); }; dc.dataCount = function(parent, chartGroup) { var _formatNumber = d3.format(",d"); var _chart = dc.baseChart({}); _chart.doRender = function() { _chart.selectAll(".total-count").text(_formatNumber(_chart.dimension().size())); _chart.selectAll(".filter-count").text(_formatNumber(_chart.group().value())); return _chart; }; _chart.doRedraw = function(){ return _chart.doRender(); }; return _chart.anchor(parent, chartGroup); }; dc.dataTable = function(parent, chartGroup) { var LABEL_CSS_CLASS = "dc-table-label"; var ROW_CSS_CLASS = "dc-table-row"; var COLUMN_CSS_CLASS = "dc-table-column"; var GROUP_CSS_CLASS = "dc-table-group"; var _chart = dc.baseChart({}); var _size = 25; var _columns = []; var _sortBy = function(d) { return d; }; var _order = d3.ascending; var _sort; _chart.doRender = function() { _chart.selectAll("tbody").remove(); renderRows(renderGroups()); return _chart; }; function renderGroups() { var groups = _chart.root().selectAll("tbody") .data(nestEntries(), function(d) { return _chart.keyAccessor()(d); }); var rowGroup = groups .enter() .append("tbody"); rowGroup .append("tr") .attr("class", GROUP_CSS_CLASS) .append("td") .attr("class", LABEL_CSS_CLASS) .attr("colspan", _columns.length) .html(function(d) { return _chart.keyAccessor()(d); }); groups.exit().remove(); return rowGroup; } function nestEntries() { if (!_sort) _sort = crossfilter.quicksort.by(_sortBy); var entries = _chart.dimension().top(_size); return d3.nest() .key(_chart.group()) .sortKeys(_order) .sortValues(_order) .entries(_sort(entries, 0, entries.length)); } function renderRows(groups) { var rows = groups.order() .selectAll("tr." + ROW_CSS_CLASS) .data(function(d) { return d.values; }); var rowEnter = rows.enter() .append("tr") .attr("class", ROW_CSS_CLASS); for (var i = 0; i < _columns.length; ++i) { var f = _columns[i]; rowEnter.append("td") .attr("class", COLUMN_CSS_CLASS + " _" + i) .html(function(d) { return f(d); }); } rows.exit().remove(); return rows; } _chart.doRedraw = function() { return _chart.doRender(); }; _chart.size = function(s) { if (!arguments.length) return _size; _size = s; return _chart; }; _chart.columns = function(_) { if (!arguments.length) return _columns; _columns = _; return _chart; }; _chart.sortBy = function(_) { if (!arguments.length) return _sortBy; _sortBy = _; return _chart; }; _chart.order = function(_) { if (!arguments.length) return _order; _order = _; return _chart; }; return _chart.anchor(parent, chartGroup); }; dc.bubbleChart = function(parent, chartGroup) { var _chart = dc.abstractBubbleChart(dc.coordinateGridChart({})); var _elasticRadius = false; _chart.transitionDuration(750); var bubbleLocator = function(d) { return "translate(" + (bubbleX(d)) + "," + (bubbleY(d)) + ")"; }; _chart.elasticRadius = function(_) { if (!arguments.length) return _elasticRadius; _elasticRadius = _; return _chart; }; _chart.plotData = function() { if (_elasticRadius) _chart.r().domain([_chart.rMin(), _chart.rMax()]); _chart.r().range([_chart.MIN_RADIUS, _chart.xAxisLength() * _chart.maxBubbleRelativeSize()]); var bubbleG = _chart.chartBodyG().selectAll("g." + _chart.BUBBLE_NODE_CLASS) .data(_chart.group().all()); renderNodes(bubbleG); updateNodes(bubbleG); removeNodes(bubbleG); _chart.fadeDeselectedArea(); }; function renderNodes(bubbleG) { var bubbleGEnter = bubbleG.enter().append("g"); bubbleGEnter .attr("class", _chart.BUBBLE_NODE_CLASS) .attr("transform", bubbleLocator) .append("circle").attr("class", function(d, i) { return _chart.BUBBLE_CLASS + " _" + i; }) .on("click", _chart.onClick) .attr("fill", _chart.initBubbleColor) .attr("r", 0); dc.transition(bubbleG, _chart.transitionDuration()) .attr("r", function(d) { return _chart.bubbleR(d); }) .attr("opacity", function(d) { return (_chart.bubbleR(d) > 0) ? 1 : 0; }); _chart.doRenderLabel(bubbleGEnter); _chart.doRenderTitles(bubbleGEnter); } function updateNodes(bubbleG) { dc.transition(bubbleG, _chart.transitionDuration()) .attr("transform", bubbleLocator) .selectAll("circle." + _chart.BUBBLE_CLASS) .attr("fill", _chart.updateBubbleColor) .attr("r", function(d) { return _chart.bubbleR(d); }) .attr("opacity", function(d) { return (_chart.bubbleR(d) > 0) ? 1 : 0; }); _chart.doUpdateLabels(bubbleG); _chart.doUpdateTitles(bubbleG); } function removeNodes(bubbleG) { bubbleG.exit().remove(); } function bubbleX(d) { var x = _chart.x()(_chart.keyAccessor()(d)) + _chart.margins().left; if (isNaN(x)) x = 0; return x; } function bubbleY(d) { var y = _chart.margins().top + _chart.y()(_chart.valueAccessor()(d)); if (isNaN(y)) y = 0; return y; } _chart.renderBrush = function(g) { // override default x axis brush from parent chart }; _chart.redrawBrush = function(g) { // override default x axis brush from parent chart _chart.fadeDeselectedArea(); }; return _chart.anchor(parent, chartGroup); }; dc.compositeChart = function (parent, chartGroup) { var SUB_CHART_CLASS = "sub"; var _chart = dc.coordinateGridChart({}); var _children = []; _chart.transitionDuration(500); dc.override(_chart, "generateG", function () { var g = this._generateG(); for (var i = 0; i < _children.length; ++i) { var child = _children[i]; generateChildG(child, i); if (child.dimension() == null) child.dimension(_chart.dimension()); if (child.group() == null) child.group(_chart.group()); child.chartGroup(_chart.chartGroup()); child.svg(_chart.svg()); child.xUnits(_chart.xUnits()); child.transitionDuration(_chart.transitionDuration()); child.brushOn(_chart.brushOn()); } return g; }); function generateChildG(child, i) { child.generateG(_chart.g()); child.g().attr("class", SUB_CHART_CLASS + " _" + i); } _chart.plotData = function () { for (var i = 0; i < _children.length; ++i) { var child = _children[i]; if (child.g() == null) { generateChildG(child, i); } child.x(_chart.x()); child.y(_chart.y()); child.xAxis(_chart.xAxis()); child.yAxis(_chart.yAxis()); child.plotData(); child.activateRenderlets(); } }; _chart.fadeDeselectedArea = function () { for (var i = 0; i < _children.length; ++i) { var child = _children[i]; child.brush(_chart.brush()); child.fadeDeselectedArea(); } }; _chart.compose = function (charts) { _children = charts; for (var i = 0; i < _children.length; ++i) { var child = _children[i]; child.height(_chart.height()); child.width(_chart.width()); child.margins(_chart.margins()); } return _chart; }; _chart.children = function () { return _children; }; function getAllYAxisMinFromChildCharts() { var allMins = []; for (var i = 0; i < _children.length; ++i) { allMins.push(_children[i].yAxisMin()); } return allMins; } _chart.yAxisMin = function () { return d3.min(getAllYAxisMinFromChildCharts()); }; function getAllYAxisMaxFromChildCharts() { var allMaxes = []; for (var i = 0; i < _children.length; ++i) { allMaxes.push(_children[i].yAxisMax()); } return allMaxes; } _chart.yAxisMax = function () { return dc.utils.add(d3.max(getAllYAxisMaxFromChildCharts()), _chart.yAxisPadding()); }; function getAllXAxisMinFromChildCharts() { var allMins = []; for (var i = 0; i < _children.length; ++i) { allMins.push(_children[i].xAxisMin()); } return allMins; } _chart.xAxisMin = function () { return dc.utils.subtract(d3.min(getAllXAxisMinFromChildCharts()), _chart.xAxisPadding()); }; function getAllXAxisMaxFromChildCharts() { var allMaxes = []; for (var i = 0; i < _children.length; ++i) { allMaxes.push(_children[i].xAxisMax()); } return allMaxes; } _chart.xAxisMax = function () { return dc.utils.add(d3.max(getAllXAxisMaxFromChildCharts()), _chart.xAxisPadding()); }; _chart.legendables = function () { var items = []; for (var j = 0; j < _children.length; ++j) { var childChart = _children[j]; childChart.allGroups().forEach(function (g, i) { items.push(dc.utils.createLegendable(childChart, g, i)); }); } return items; }; _chart.legendHighlight = function (d) { for (var j = 0; j < _children.length; ++j) { var child = _children[j]; child.legendHighlight(d); } }; _chart.legendReset = function (d) { for (var j = 0; j < _children.length; ++j) { var child = _children[j]; child.legendReset(d); } }; return _chart.anchor(parent, chartGroup); }; dc.geoChoroplethChart = function (parent, chartGroup) { var _chart = dc.colorChart(dc.baseChart({})); _chart.colorAccessor(function (d, i) { return d; }); var _geoPath = d3.geo.path(); var _projectionFlag; var _geoJsons = []; _chart.doRender = function () { _chart.resetSvg(); for (var layerIndex = 0; layerIndex < _geoJsons.length; ++layerIndex) { var states = _chart.svg().append("g") .attr("class", "layer" + layerIndex); var regionG = states.selectAll("g." + geoJson(layerIndex).name) .data(geoJson(layerIndex).data) .enter() .append("g") .attr("class", geoJson(layerIndex).name); regionG .append("path") .attr("fill", "white") .attr("d", _geoPath); regionG.append("title"); plotData(layerIndex); } _projectionFlag = false; }; function plotData(layerIndex) { var maxValue = dc.utils.groupMax(_chart.group(), _chart.valueAccessor()); var data = generateLayeredData(); if (isDataLayer(layerIndex)) { var regionG = renderRegionG(layerIndex); renderPaths(regionG, layerIndex, data, maxValue); renderTitle(regionG, layerIndex, data); } } function generateLayeredData() { var data = {}; var groupAll = _chart.group().all(); for (var i = 0; i < groupAll.length; ++i) { data[_chart.keyAccessor()(groupAll[i])] = _chart.valueAccessor()(groupAll[i]); } return data; } function isDataLayer(layerIndex) { return geoJson(layerIndex).keyAccessor; } function renderRegionG(layerIndex) { var regionG = _chart.svg() .selectAll(layerSelector(layerIndex)) .classed("selected", function (d) { return isSelected(layerIndex, d); }) .classed("deselected", function (d) { return isDeselected(layerIndex, d); }) .attr("class", function (d) { var layerNameClass = geoJson(layerIndex).name; var regionClass = dc.utils.nameToId(geoJson(layerIndex).keyAccessor(d)); var baseClasses = layerNameClass + " " + regionClass; if (isSelected(layerIndex, d)) baseClasses += " selected"; if (isDeselected(layerIndex, d)) baseClasses += " deselected"; return baseClasses; }); return regionG; } function layerSelector(layerIndex) { return "g.layer" + layerIndex + " g." + geoJson(layerIndex).name; } function isSelected(layerIndex, d) { return _chart.hasFilter() && _chart.hasFilter(getKey(layerIndex, d)); } function isDeselected(layerIndex, d) { return _chart.hasFilter() && !_chart.hasFilter(getKey(layerIndex, d)); } function getKey(layerIndex, d) { return geoJson(layerIndex).keyAccessor(d); } function geoJson(index) { return _geoJsons[index]; } function renderPaths(regionG, layerIndex, data, maxValue) { var paths = regionG .select("path") .attr("fill", function (d) { var currentFill = d3.select(this).attr("fill"); if (currentFill) return currentFill; return "none"; }) .on("click", function (d) { return _chart.onClick(d, layerIndex); }); dc.transition(paths, _chart.transitionDuration()).attr("fill", function (d, i) { return _chart.getColor(data[geoJson(layerIndex).keyAccessor(d)], i); }); } _chart.onClick = function (d, layerIndex) { var selectedRegion = geoJson(layerIndex).keyAccessor(d); dc.events.trigger(function () { _chart.filter(selectedRegion); dc.redrawAll(_chart.chartGroup()); }); }; function renderTitle(regionG, layerIndex, data) { if (_chart.renderTitle()) { regionG.selectAll("title").text(function (d) { var key = getKey(layerIndex, d); var value = data[key]; return _chart.title()({key: key, value: value}); }); } } _chart.doRedraw = function () { for (var layerIndex = 0; layerIndex < _geoJsons.length; ++layerIndex) { plotData(layerIndex); if(_projectionFlag) { _chart.svg().selectAll("g." + geoJson(layerIndex).name + " path").attr("d", _geoPath) }; } _projectionFlag = false }; _chart.overlayGeoJson = function (json, name, keyAccessor) { for (var i = 0; i < _geoJsons.length; ++i) { if (_geoJsons[i].name == name) { _geoJsons[i].data = json; _geoJsons[i].keyAccessor = keyAccessor; return _chart } } _geoJsons.push({name: name, data: json, keyAccessor: keyAccessor}); return _chart; }; _chart.projection = function (projection) { _geoPath.projection(projection); _projectionFlag = true; return _chart; }; _chart.geoJsons = function () { return _geoJsons; }; _chart.removeGeoJson = function (name) { var geoJsons = []; for (var i = 0; i < _geoJsons.length; ++i) { var layer = _geoJsons[i]; if (layer.name != name) { geoJsons.push(layer); } } _geoJsons = geoJsons; return _chart; }; return _chart.anchor(parent, chartGroup); }; dc.bubbleOverlay = function(root, chartGroup) { var BUBBLE_OVERLAY_CLASS = "bubble-overlay"; var BUBBLE_NODE_CLASS = "node"; var BUBBLE_CLASS = "bubble"; var _chart = dc.abstractBubbleChart(dc.baseChart({})); var _g; var _points = []; _chart.transitionDuration(750); _chart.radiusValueAccessor(function(d) { return d.value; }); _chart.point = function(name, x, y) { _points.push({name: name, x: x, y: y}); return _chart; }; _chart.doRender = function() { _g = initOverlayG(); _chart.r().range([_chart.MIN_RADIUS, _chart.width() * _chart.maxBubbleRelativeSize()]); initializeBubbles(); _chart.fadeDeselectedArea(); return _chart; }; function initOverlayG() { _g = _chart.select("g." + BUBBLE_OVERLAY_CLASS); if (_g.empty()) _g = _chart.svg().append("g").attr("class", BUBBLE_OVERLAY_CLASS); return _g; } function initializeBubbles() { var data = mapData(); _points.forEach(function(point) { var nodeG = getNodeG(point, data); var circle = nodeG.select("circle." + BUBBLE_CLASS); if (circle.empty()) circle = nodeG.append("circle") .attr("class", BUBBLE_CLASS) .attr("r", 0) .attr("fill", _chart.initBubbleColor) .on("click", _chart.onClick); dc.transition(circle, _chart.transitionDuration()) .attr("r", function(d) { return _chart.bubbleR(d); }); _chart.doRenderLabel(nodeG); _chart.doRenderTitles(nodeG); }); } function mapData() { var data = {}; _chart.group().all().forEach(function(datum) { data[_chart.keyAccessor()(datum)] = datum; }); return data; } function getNodeG(point, data) { var bubbleNodeClass = BUBBLE_NODE_CLASS + " " + dc.utils.nameToId(point.name); var nodeG = _g.select("g." + dc.utils.nameToId(point.name)); if (nodeG.empty()) { nodeG = _g.append("g") .attr("class", bubbleNodeClass) .attr("transform", "translate(" + point.x + "," + point.y + ")"); } nodeG.datum(data[point.name]); return nodeG; } _chart.doRedraw = function() { updateBubbles(); _chart.fadeDeselectedArea(); return _chart; }; function updateBubbles() { var data = mapData(); _points.forEach(function(point) { var nodeG = getNodeG(point, data); var circle = nodeG.select("circle." + BUBBLE_CLASS); dc.transition(circle, _chart.transitionDuration()) .attr("r", function(d) { return _chart.bubbleR(d); }) .attr("fill", _chart.updateBubbleColor); _chart.doUpdateLabels(nodeG); _chart.doUpdateTitles(nodeG); }); } _chart.debug = function(flag) { if(flag){ var debugG = _chart.select("g." + dc.constants.DEBUG_GROUP_CLASS); if(debugG.empty()) debugG = _chart.svg() .append("g") .attr("class", dc.constants.DEBUG_GROUP_CLASS); var debugText = debugG.append("text") .attr("x", 10) .attr("y", 20); debugG .append("rect") .attr("width", _chart.width()) .attr("height", _chart.height()) .on("mousemove", function() { var position = d3.mouse(debugG.node()); var msg = position[0] + ", " + position[1]; debugText.text(msg); }); }else{ _chart.selectAll(".debug").remove(); } return _chart; }; _chart.anchor(root, chartGroup); return _chart; };dc.rowChart = function (parent, chartGroup) { var _g; var _labelOffsetX = 10; var _labelOffsetY = 15; var _gap = 5; var _rowCssClass = "row"; var _chart = dc.marginable(dc.colorChart(dc.baseChart({}))); var _xScale; var _elasticX; var _xAxis = d3.svg.axis().orient("bottom"); function calculateAxisScale() { if (!_xScale || _elasticX) { _xScale = d3.scale.linear().domain([0, d3.max(_chart.group().all(), _chart.valueAccessor())]) .range([0, _chart.effectiveWidth()]); _xAxis.scale(_xScale); } } function drawAxis() { var axisG = _g.select("g.axis"); calculateAxisScale(); if (axisG.empty()) axisG = _g.append("g").attr("class", "axis") .attr("transform", "translate(0, " + _chart.effectiveHeight() + ")"); dc.transition(axisG, _chart.transitionDuration()) .call(_xAxis); } _chart.doRender = function () { _chart.resetSvg(); _g = _chart.svg() .append("g") .attr("transform", "translate(" + _chart.margins().left + "," + _chart.margins().top + ")"); drawAxis(); drawGridLines(); drawChart(); return _chart; }; _chart.title(function (d) { return _chart.keyAccessor()(d) + ": " + _chart.valueAccessor()(d); }); _chart.label(function (d) { return _chart.keyAccessor()(d); }); function drawGridLines() { _g.selectAll("g.tick") .select("line.grid-line") .remove(); _g.selectAll("g.tick") .append("line") .attr("class", "grid-line") .attr("x1", 0) .attr("y1", 0) .attr("x2", 0) .attr("y2", function (d) { return -_chart.effectiveHeight(); }); } function drawChart() { drawAxis(); drawGridLines(); var rows = _g.selectAll("g." + _rowCssClass) .data(_chart.group().all()); createElements(rows); removeElements(rows); updateElements(rows); } function createElements(rows) { var rowEnter = rows.enter() .append("g") .attr("class", function (d, i) { return _rowCssClass + " _" + i; }); rowEnter.append("rect").attr("width", 0); createLabels(rowEnter); updateLabels(rows); } function removeElements(rows) { rows.exit().remove(); } function updateElements(rows) { var height = rowHeight(); rows = rows.attr("transform",function (d, i) { return "translate(0," + ((i + 1) * _gap + i * height) + ")"; }).select("rect") .attr("height", height) .attr("fill", _chart.getColor) .on("click", onClick) .classed("deselected", function (d) { return (_chart.hasFilter()) ? !_chart.isSelectedRow(d) : false; }) .classed("selected", function (d) { return (_chart.hasFilter()) ? _chart.isSelectedRow(d) : false; }); dc.transition(rows, _chart.transitionDuration()) .attr("width", function (d) { return _xScale(_chart.valueAccessor()(d)); }); createTitles(rows); } function createTitles(rows) { if (_chart.renderTitle()) { rows.selectAll("title").remove(); rows.append("title").text(function (d) { return _chart.title()(d); }); } } function createLabels(rowEnter) { if (_chart.renderLabel()) { rowEnter.append("text") .on("click", onClick); } } function updateLabels(rows) { if (_chart.renderLabel()) { rows.select("text") .attr("x", _labelOffsetX) .attr("y", _labelOffsetY) .attr("class", function (d, i) { return _rowCssClass + " _" + i; }) .text(function (d) { return _chart.label()(d); }); } } function numberOfRows() { return _chart.group().all().length; } function rowHeight() { var n = numberOfRows(); return (_chart.effectiveHeight() - (n + 1) * _gap) / n; } function onClick(d) { _chart.onClick(d); } _chart.doRedraw = function () { drawChart(); return _chart; }; _chart.xAxis = function () { return _xAxis; }; _chart.gap = function (g) { if (!arguments.length) return _gap; _gap = g; return _chart; }; _chart.elasticX = function (_) { if (!arguments.length) return _elasticX; _elasticX = _; return _chart; }; _chart.labelOffsetX = function (o) { if (!arguments.length) return _labelOffsetX; _labelOffsetX = o; return _chart; }; _chart.labelOffsetY = function (o) { if (!arguments.length) return _labelOffsetY; _labelOffsetY = o; return _chart; }; _chart.isSelectedRow = function (d) { return _chart.hasFilter(_chart.keyAccessor()(d)); }; return _chart.anchor(parent, chartGroup); }; dc.legend = function () { var LABEL_GAP = 2; var _legend = {}, _parent, _x = 0, _y = 0, _itemHeight = 12, _gap = 5; var _g; _legend.parent = function (p) { if (!arguments.length) return _parent; _parent = p; return _legend; }; _legend.render = function () { _g = _parent.svg().append("g") .attr("class", "dc-legend") .attr("transform", "translate(" + _x + "," + _y + ")"); var itemEnter = _g.selectAll('g.dc-legend-item') .data(_parent.legendables()) .enter() .append("g") .attr("class", "dc-legend-item") .attr("transform", function (d, i) { return "translate(0," + i * legendItemHeight() + ")"; }) .on("mouseover", function(d){ _parent.legendHighlight(d); }) .on("mouseout", function (d) { _parent.legendReset(d); }); itemEnter .append("rect") .attr("width", _itemHeight) .attr("height", _itemHeight) .attr("fill", function(d){return d.color;}); itemEnter.append("text") .text(function(d){return d.name;}) .attr("x", _itemHeight + LABEL_GAP) .attr("y", function(){return _itemHeight / 2 + (this.clientHeight?this.clientHeight:13) / 2 - 2}); }; function legendItemHeight() { return _gap + _itemHeight; } _legend.x = function (x) { if (!arguments.length) return _x; _x = x; return _legend; }; _legend.y = function (y) { if (!arguments.length) return _y; _y = y; return _legend; }; _legend.gap = function (gap) { if (!arguments.length) return _gap; _gap = gap; return _legend; }; _legend.itemHeight = function (h) { if (!arguments.length) return _itemHeight; _itemHeight = h; return _legend; }; return _legend; };
katsuya0719/visEPlus
static/vendor/js/dc.js
JavaScript
apache-2.0
104,931
/** * @license jQuery Text Highlighter * Copyright (C) 2011 - 2013 by mirz * * 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. */ (function($, window, document, undefined) { var nodeTypes = { ELEMENT_NODE: 1, TEXT_NODE: 3 }; var plugin = { name: 'textHighlighter' }; function TextHighlighter(element, options) { this.context = element; this.$context = $(element); this.options = $.extend({}, $[plugin.name].defaults, options); this.init(); } TextHighlighter.prototype = { init: function() { this.$context.addClass(this.options.contextClass); this.bindEvents(); }, destroy: function() { this.unbindEvents(); this.$context.removeClass(this.options.contextClass); this.$context.removeData(plugin.name); }, bindEvents: function() { this.$context.bind('mouseup', {self: this}, this.highlightHandler); }, unbindEvents: function() { this.$context.unbind('mouseup', this.highlightHandler); }, highlightHandler: function(event) { var self = event.data.self; self.doHighlight(); }, /** * Highlights currently selected text. */ doHighlight: function() { var range = this.getCurrentRange(); if (!range || range.collapsed) return; var rangeText = range.toString(); if (this.options.onBeforeHighlight(range) == true) { var $wrapper = $.textHighlighter.createWrapper(this.options); var createdHighlights = this.highlightRange(range, $wrapper); var normalizedHighlights = this.normalizeHighlights(createdHighlights); this.options.onAfterHighlight(normalizedHighlights, rangeText); } this.removeAllRanges(); }, /** * Returns first range of current selection object. */ getCurrentRange: function() { var selection = this.getCurrentSelection(); var range; if (selection.rangeCount > 0) { range = selection.getRangeAt(0); } return range; }, removeAllRanges: function() { var selection = this.getCurrentSelection(); selection.removeAllRanges(); }, /** * Returns current selection object. */ getCurrentSelection: function() { var currentWindow = this.getCurrentWindow(); var selection; if (currentWindow.getSelection) { selection = currentWindow.getSelection(); } else if ($('iframe').length) { $('iframe', top.document).each(function() { if (this.contentWindow === currentWindow) { selection = rangy.getIframeSelection(this); return false; } }); } else { selection = rangy.getSelection(); } return selection; }, /** * Returns owner window of this.context. */ getCurrentWindow: function() { var currentDoc = this.getCurrentDocument(); if (currentDoc.defaultView) { return currentDoc.defaultView; // Non-IE } else { return currentDoc.parentWindow; // IE } }, /** * Returns owner document of this.context. */ getCurrentDocument: function() { // if ownerDocument is null then context is document return this.context.ownerDocument ? this.context.ownerDocument : this.context; }, /** * Wraps given range (highlights it) object in the given wrapper. */ highlightRange: function(range, $wrapper) { if (range.collapsed) return; // Don't highlight content of these tags var ignoreTags = ['SCRIPT', 'STYLE', 'SELECT', 'BUTTON', 'OBJECT', 'APPLET']; var startContainer = range.startContainer; var endContainer = range.endContainer; var ancestor = range.commonAncestorContainer; var goDeeper = true; if (range.endOffset == 0) { while (!endContainer.previousSibling && endContainer.parentNode != ancestor) { endContainer = endContainer.parentNode; } endContainer = endContainer.previousSibling; } else if (endContainer.nodeType == nodeTypes.TEXT_NODE) { if (range.endOffset < endContainer.nodeValue.length) { endContainer.splitText(range.endOffset); } } else if (range.endOffset > 0) { endContainer = endContainer.childNodes.item(range.endOffset - 1); } if (startContainer.nodeType == nodeTypes.TEXT_NODE) { if (range.startOffset == startContainer.nodeValue.length) { goDeeper = false; } else if (range.startOffset > 0) { startContainer = startContainer.splitText(range.startOffset); if (endContainer == startContainer.previousSibling) endContainer = startContainer; } } else if (range.startOffset < startContainer.childNodes.length) { startContainer = startContainer.childNodes.item(range.startOffset); } else { startContainer = startContainer.nextSibling; } var done = false; var node = startContainer; var highlights = []; do { if (goDeeper && node.nodeType == nodeTypes.TEXT_NODE) { if (/\S/.test(node.nodeValue)) { var wrapper = $wrapper.clone(true).get(0); var nodeParent = node.parentNode; // highlight if node is inside the context if ($.contains(this.context, nodeParent) || nodeParent === this.context) { var highlight = $(node).wrap(wrapper).parent().get(0); highlights.push(highlight); } } goDeeper = false; } if (node == endContainer && (!endContainer.hasChildNodes() || !goDeeper)) { done = true; } if ($.inArray(node.tagName, ignoreTags) != -1) { goDeeper = false; } if (goDeeper && node.hasChildNodes()) { node = node.firstChild; } else if (node.nextSibling != null) { node = node.nextSibling; goDeeper = true; } else { node = node.parentNode; goDeeper = false; } } while (!done); return highlights; }, /** * Normalizes highlights - nested highlights are flattened and sibling higlights are merged. */ normalizeHighlights: function(highlights) { this.flattenNestedHighlights(highlights); this.mergeSiblingHighlights(highlights); // omit removed nodes var normalizedHighlights = $.map(highlights, function(hl) { if (typeof hl.parentElement != 'undefined') { // IE return hl.parentElement != null ? hl : null; } else { return hl.parentNode != null ? hl : null; } }); return normalizedHighlights; }, flattenNestedHighlights: function(highlights) { var self = this; $.each(highlights, function(i) { var $highlight = $(this); var $parent = $highlight.parent(); var $parentPrev = $parent.prev(); var $parentNext = $parent.next(); if (self.isHighlight($parent)) { if ($parent.css('background-color') != $highlight.css('background-color')) { if (self.isHighlight($parentPrev) && !$highlight.get(0).previousSibling && $parentPrev.css('background-color') != $parent.css('background-color') && $parentPrev.css('background-color') == $highlight.css('background-color')) { $highlight.insertAfter($parentPrev); } if (self.isHighlight($parentNext) && !$highlight.get(0).nextSibling && $parentNext.css('background-color') != $parent.css('background-color') && $parentNext.css('background-color') == $highlight.css('background-color')) { $highlight.insertBefore($parentNext); } if ($parent.is(':empty')) { $parent.remove(); } } else { var newNode = document.createTextNode($parent.text()); $parent.empty(); $parent.append(newNode); $(highlights[i]).remove(); } } }); }, mergeSiblingHighlights: function(highlights) { var self = this; function shouldMerge(current, node) { return node && node.nodeType == nodeTypes.ELEMENT_NODE && $(current).css('background-color') == $(node).css('background-color') && $(node).hasClass(self.options.highlightedClass) ? true : false; } $.each(highlights, function() { var highlight = this; var prev = highlight.previousSibling; var next = highlight.nextSibling; if (shouldMerge(highlight, prev)) { var mergedTxt = $(prev).text() + $(highlight).text(); $(highlight).text(mergedTxt); $(prev).remove(); } if (shouldMerge(highlight, next)) { var mergedTxt = $(highlight).text() + $(next).text(); $(highlight).text(mergedTxt); $(next).remove(); } }); }, /** * Sets color of future highlights. */ setColor: function(color) { this.options.color = color; }, /** * Returns current highlights color. */ getColor: function() { return this.options.color; }, /** * Removes all highlights in given element or in context if no element given. */ removeHighlights: function(element) { var container = (element !== undefined ? element : this.context); var unwrapHighlight = function(highlight) { return $(highlight).contents().unwrap().get(0); }; var mergeSiblingTextNodes = function(textNode) { var prev = textNode.previousSibling; var next = textNode.nextSibling; if (prev && prev.nodeType == nodeTypes.TEXT_NODE) { textNode.nodeValue = prev.nodeValue + textNode.nodeValue; prev.parentNode.removeChild(prev); } if (next && next.nodeType == nodeTypes.TEXT_NODE) { textNode.nodeValue = textNode.nodeValue + next.nodeValue; next.parentNode.removeChild(next); } }; var self = this; var $highlights = this.getAllHighlights(container, true); $highlights.each(function() { if (self.options.onRemoveHighlight(this) == true) { var textNode = unwrapHighlight(this); mergeSiblingTextNodes(textNode); } }); }, /** * Returns all highlights in given container. If container is a highlight itself and * andSelf is true, container will be also returned */ getAllHighlights: function(container, andSelf) { var classSelectorStr = '.' + this.options.highlightedClass; var $highlights = $(container).find(classSelectorStr); if (andSelf == true && $(container).hasClass(this.options.highlightedClass)) { $highlights = $highlights.add(container); } return $highlights; }, /** * Returns true if element is highlight, ie. has proper class. */ isHighlight: function($el) { return $el.hasClass(this.options.highlightedClass); }, /** * Serializes all highlights to stringified JSON object. */ serializeHighlights: function() { var $highlights = this.getAllHighlights(this.context); var refEl = this.context; var hlDescriptors = []; var self = this; var getElementPath = function (el, refElement) { var path = []; do { var elIndex = $.inArray(el, el.parentNode.childNodes); path.unshift(elIndex); el = el.parentNode; } while (el !== refElement); return path; }; $highlights.each(function(i, highlight) { var offset = 0; // Hl offset from previous sibling within parent node. var length = highlight.firstChild.length; var hlPath = getElementPath(highlight, refEl); var wrapper = $(highlight).clone().empty().get(0).outerHTML; if (highlight.previousSibling && highlight.previousSibling.nodeType === nodeTypes.TEXT_NODE) { offset = highlight.previousSibling.length; } hlDescriptors.push([ wrapper, highlight.innerText, hlPath.join(':'), offset, length ]); }); return JSON.stringify(hlDescriptors); }, /** * Deserializes highlights from stringified JSON given as parameter. */ deserializeHighlights: function(json) { try { var hlDescriptors = JSON.parse(json); } catch (e) { throw "Can't parse serialized highlights: " + e; } var highlights = []; var self = this; var deserializationFn = function (hlDescriptor) { var wrapper = hlDescriptor[0]; var hlText = hlDescriptor[1]; var hlPath = hlDescriptor[2].split(':'); var elOffset = hlDescriptor[3]; var hlLength = hlDescriptor[4]; var elIndex = hlPath.pop(); var idx = null; var node = self.context; while ((idx = hlPath.shift()) !== undefined) { node = node.childNodes[idx]; } if (node.childNodes[elIndex-1] && node.childNodes[elIndex-1].nodeType === nodeTypes.TEXT_NODE) { elIndex -= 1; } var textNode = node.childNodes[elIndex]; var hlNode = textNode.splitText(elOffset); hlNode.splitText(hlLength); if (hlNode.nextSibling && hlNode.nextSibling.nodeValue == '') { hlNode.parentNode.removeChild(hlNode.nextSibling); } if (hlNode.previousSibling && hlNode.previousSibling.nodeValue == '') { hlNode.parentNode.removeChild(hlNode.previousSibling); } var highlight = $(hlNode).wrap(wrapper).parent().get(0); highlights.push(highlight); }; $.each(hlDescriptors, function(i, hlDescriptor) { try { deserializationFn(hlDescriptor); } catch (e) { console && console.warn && console.warn("Can't deserialize " + i + "-th descriptor. Cause: " + e); return true; } }); return highlights; } }; /** * Returns TextHighlighter instance. */ $.fn.getHighlighter = function() { return this.data(plugin.name); }; $.fn[plugin.name] = function(options) { return this.each(function() { if (!$.data(this, plugin.name)) { $.data(this, plugin.name, new TextHighlighter(this, options)); } }); }; $.textHighlighter = { /** * Returns HTML element to wrap selected text in. */ createWrapper: function(options) { return $('<span></span>') .css('backgroundColor', options.color) .addClass(options.highlightedClass); }, defaults: { color: '#ffff7b', highlightedClass: 'highlighted', contextClass: 'highlighter-context', onRemoveHighlight: function() { return true; }, onBeforeHighlight: function() { return true; }, onAfterHighlight: function() { } } }; })(jQuery, window, document);
ahocevar/cdnjs
ajax/libs/texthighlighter/0.2/jquery.textHighlighter.js
JavaScript
mit
18,913
(function() { // Load plugin specific language pack // tinymce.PluginManager.requireLangPack('wpdev_bk_quicktags'); tinymce.create('tinymce.plugins.WPDEV_BK_Quicktags', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished it's initialization so use the onInit event * of the editor instance to intercept that event. * * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed, url) { set_bk_buttons(ed,url); }, /** * Creates control instances based in the incomming name. This method is normally not * needed since the addButton method of the tinymce.Editor class is a more easy way of adding buttons * but you sometimes need to create more complex controls like listboxes, split buttons etc then this * method can be used to create those. * * @param {String} n Name of the control to create. * @param {tinymce.ControlManager} cm Control manager to use inorder to create new control. * @return {tinymce.ui.Control} New control instance or null if no control was created. */ createControl : function(n, cm) { return null; }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : "WPDevelop", author : 'WPDevelop', authorurl : 'http://www.wpdevelop.com/', infourl : 'http://plugins.wpdevelop.com/', version : "1.0" }; } }); // Register plugin tinymce.PluginManager.add('wpdev_bk_quicktags', tinymce.plugins.WPDEV_BK_Quicktags); })();
middle8media/Alpha-Accounting
wp-content/plugins/booking/js/custom_buttons/editor_plugin.js
JavaScript
gpl-2.0
1,893
// // ShellJS // Unix shell commands on top of Node's API // // Copyright (c) 2012 Artur Adib // http://github.com/arturadib/shelljs // var fs = require('fs'), path = require('path'), util = require('util'), vm = require('vm'), child = require('child_process'), os = require('os'); // Node shims for < v0.7 fs.existsSync = fs.existsSync || path.existsSync; var config = { silent: false, fatal: false }; var state = { error: null, currentCmd: 'shell.js', tempDir: null }, platform = os.type().match(/^Win/) ? 'win' : 'unix'; //@ //@ All commands run synchronously, unless otherwise stated. //@ //@ //@ ### cd('dir') //@ Changes to directory `dir` for the duration of the script function _cd(options, dir) { if (!dir) error('directory not specified'); if (!fs.existsSync(dir)) error('no such file or directory: ' + dir); if (fs.existsSync(dir) && !fs.statSync(dir).isDirectory()) error('not a directory: ' + dir); process.chdir(dir); } exports.cd = wrap('cd', _cd); //@ //@ ### pwd() //@ Returns the current directory. function _pwd(options) { var pwd = path.resolve(process.cwd()); return ShellString(pwd); } exports.pwd = wrap('pwd', _pwd); //@ //@ ### ls([options ,] path [,path ...]) //@ ### ls([options ,] path_array) //@ Available options: //@ //@ + `-R`: recursive //@ + `-A`: all files (include files beginning with `.`, except for `.` and `..`) //@ //@ Examples: //@ //@ ```javascript //@ ls('projs/*.js'); //@ ls('-R', '/users/me', '/tmp'); //@ ls('-R', ['/users/me', '/tmp']); // same as above //@ ``` //@ //@ Returns array of files in the given path, or in current directory if no path provided. function _ls(options, paths) { options = parseOptions(options, { 'R': 'recursive', 'A': 'all', 'a': 'all_deprecated' }); if (options.all_deprecated) { // We won't support the -a option as it's hard to image why it's useful // (it includes '.' and '..' in addition to '.*' files) // For backwards compatibility we'll dump a deprecated message and proceed as before log('ls: Option -a is deprecated. Use -A instead'); options.all = true; } if (!paths) paths = ['.']; else if (typeof paths === 'object') paths = paths; // assume array else if (typeof paths === 'string') paths = [].slice.call(arguments, 1); var list = []; // Conditionally pushes file to list - returns true if pushed, false otherwise // (e.g. prevents hidden files to be included unless explicitly told so) function pushFile(file, query) { // hidden file? if (path.basename(file)[0] === '.') { // not explicitly asking for hidden files? if (!options.all && !(path.basename(query)[0] === '.' && path.basename(query).length > 1)) return false; } if (platform === 'win') file = file.replace(/\\/g, '/'); list.push(file); return true; } paths.forEach(function(p) { if (fs.existsSync(p)) { // Simple file? if (fs.statSync(p).isFile()) { pushFile(p, p); return; // continue } // Simple dir? if (fs.statSync(p).isDirectory()) { // Iterate over p contents fs.readdirSync(p).forEach(function(file) { if (!pushFile(file, p)) return; // Recursive? if (options.recursive) { var oldDir = _pwd(); _cd('', p); if (fs.statSync(file).isDirectory()) list = list.concat(_ls('-R'+(options.all?'A':''), file+'/*')); _cd('', oldDir); } }); return; // continue } } // p does not exist - possible wildcard present var basename = path.basename(p); var dirname = path.dirname(p); // Wildcard present on an existing dir? (e.g. '/tmp/*.js') if (basename.search(/\*/) > -1 && fs.existsSync(dirname) && fs.statSync(dirname).isDirectory) { // Escape special regular expression chars var regexp = basename.replace(/(\^|\$|\(|\)|<|>|\[|\]|\{|\}|\.|\+|\?)/g, '\\$1'); // Translates wildcard into regex regexp = '^' + regexp.replace(/\*/g, '.*') + '$'; // Iterate over directory contents fs.readdirSync(dirname).forEach(function(file) { if (file.match(new RegExp(regexp))) { if (!pushFile(path.normalize(dirname+'/'+file), basename)) return; // Recursive? if (options.recursive) { var pp = dirname + '/' + file; if (fs.lstatSync(pp).isDirectory()) list = list.concat(_ls('-R'+(options.all?'A':''), pp+'/*')); } // recursive } // if file matches }); // forEach return; } error('no such file or directory: ' + p, true); }); return list; } exports.ls = wrap('ls', _ls); //@ //@ ### find(path [,path ...]) //@ ### find(path_array) //@ Examples: //@ //@ ```javascript //@ find('src', 'lib'); //@ find(['src', 'lib']); // same as above //@ find('.').filter(function(file) { return file.match(/\.js$/); }); //@ ``` //@ //@ Returns array of all files (however deep) in the given paths. //@ //@ The main difference from `ls('-R', path)` is that the resulting file names //@ include the base directories, e.g. `lib/resources/file1` instead of just `file1`. function _find(options, paths) { if (!paths) error('no path specified'); else if (typeof paths === 'object') paths = paths; // assume array else if (typeof paths === 'string') paths = [].slice.call(arguments, 1); var list = []; function pushFile(file) { if (platform === 'win') file = file.replace(/\\/g, '/'); list.push(file); } // why not simply do ls('-R', paths)? because the output wouldn't give the base dirs // to get the base dir in the output, we need instead ls('-R', 'dir/*') for every directory paths.forEach(function(file) { pushFile(file); if (fs.statSync(file).isDirectory()) { _ls('-RA', file+'/*').forEach(function(subfile) { pushFile(subfile); }); } }); return list; } exports.find = wrap('find', _find); //@ //@ ### cp([options ,] source [,source ...], dest) //@ ### cp([options ,] source_array, dest) //@ Available options: //@ //@ + `-f`: force //@ + `-r, -R`: recursive //@ //@ Examples: //@ //@ ```javascript //@ cp('file1', 'dir1'); //@ cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); //@ cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above //@ ``` //@ //@ Copies files. The wildcard `*` is accepted. function _cp(options, sources, dest) { options = parseOptions(options, { 'f': 'force', 'R': 'recursive', 'r': 'recursive' }); // Get sources, dest if (arguments.length < 3) { error('missing <source> and/or <dest>'); } else if (arguments.length > 3) { sources = [].slice.call(arguments, 1, arguments.length - 1); dest = arguments[arguments.length - 1]; } else if (typeof sources === 'string') { sources = [sources]; } else if ('length' in sources) { sources = sources; // no-op for array } else { error('invalid arguments'); } // Dest is not existing dir, but multiple sources given if ((!fs.existsSync(dest) || !fs.statSync(dest).isDirectory()) && sources.length > 1) error('dest is not a directory (too many sources)'); // Dest is an existing file, but no -f given if (fs.existsSync(dest) && fs.statSync(dest).isFile() && !options.force) error('dest file already exists: ' + dest); if (options.recursive) { // Recursive allows the shortcut syntax "sourcedir/" for "sourcedir/*" // (see Github issue #15) sources.forEach(function(src, i) { if (src[src.length - 1] === '/') sources[i] += '*'; }); // Create dest try { fs.mkdirSync(dest, parseInt('0777', 8)); } catch (e) { // like Unix's cp, keep going even if we can't create dest dir } } sources = expand(sources); sources.forEach(function(src) { if (!fs.existsSync(src)) { error('no such file or directory: '+src, true); return; // skip file } // If here, src exists if (fs.statSync(src).isDirectory()) { if (!options.recursive) { // Non-Recursive log(src + ' is a directory (not copied)'); } else { // Recursive // 'cp /a/source dest' should create 'source' in 'dest' var newDest = path.join(dest, path.basename(src)), checkDir = fs.statSync(src); try { fs.mkdirSync(newDest, checkDir.mode); } catch (e) { //if the directory already exists, that's okay if (e.code !== 'EEXIST') throw e; } cpdirSyncRecursive(src, newDest, {force: options.force}); } return; // done with dir } // If here, src is a file // When copying to '/path/dir': // thisDest = '/path/dir/file1' var thisDest = dest; if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) thisDest = path.normalize(dest + '/' + path.basename(src)); if (fs.existsSync(thisDest) && !options.force) { error('dest file already exists: ' + thisDest, true); return; // skip file } copyFileSync(src, thisDest); }); // forEach(src) } exports.cp = wrap('cp', _cp); //@ //@ ### rm([options ,] file [, file ...]) //@ ### rm([options ,] file_array) //@ Available options: //@ //@ + `-f`: force //@ + `-r, -R`: recursive //@ //@ Examples: //@ //@ ```javascript //@ rm('-rf', '/tmp/*'); //@ rm('some_file.txt', 'another_file.txt'); //@ rm(['some_file.txt', 'another_file.txt']); // same as above //@ ``` //@ //@ Removes files. The wildcard `*` is accepted. function _rm(options, files) { options = parseOptions(options, { 'f': 'force', 'r': 'recursive', 'R': 'recursive' }); if (!files) error('no paths given'); if (typeof files === 'string') files = [].slice.call(arguments, 1); // if it's array leave it as it is files = expand(files); files.forEach(function(file) { if (!fs.existsSync(file)) { // Path does not exist, no force flag given if (!options.force) error('no such file or directory: '+file, true); return; // skip file } // If here, path exists // Remove simple file if (fs.statSync(file).isFile()) { // Do not check for file writing permissions if (options.force) { _unlinkSync(file); return; } if (isWriteable(file)) _unlinkSync(file); else error('permission denied: '+file, true); return; } // simple file // Path is an existing directory, but no -r flag given if (fs.statSync(file).isDirectory() && !options.recursive) { error('path is a directory', true); return; // skip path } // Recursively remove existing directory if (fs.statSync(file).isDirectory() && options.recursive) { rmdirSyncRecursive(file, options.force); } }); // forEach(file) } // rm exports.rm = wrap('rm', _rm); //@ //@ ### mv(source [, source ...], dest') //@ ### mv(source_array, dest') //@ Available options: //@ //@ + `f`: force //@ //@ Examples: //@ //@ ```javascript //@ mv('-f', 'file', 'dir/'); //@ mv('file1', 'file2', 'dir/'); //@ mv(['file1', 'file2'], 'dir/'); // same as above //@ ``` //@ //@ Moves files. The wildcard `*` is accepted. function _mv(options, sources, dest) { options = parseOptions(options, { 'f': 'force' }); // Get sources, dest if (arguments.length < 3) { error('missing <source> and/or <dest>'); } else if (arguments.length > 3) { sources = [].slice.call(arguments, 1, arguments.length - 1); dest = arguments[arguments.length - 1]; } else if (typeof sources === 'string') { sources = [sources]; } else if ('length' in sources) { sources = sources; // no-op for array } else { error('invalid arguments'); } sources = expand(sources); // Dest is not existing dir, but multiple sources given if ((!fs.existsSync(dest) || !fs.statSync(dest).isDirectory()) && sources.length > 1) error('dest is not a directory (too many sources)'); // Dest is an existing file, but no -f given if (fs.existsSync(dest) && fs.statSync(dest).isFile() && !options.force) error('dest file already exists: ' + dest); sources.forEach(function(src) { if (!fs.existsSync(src)) { error('no such file or directory: '+src, true); return; // skip file } // If here, src exists // When copying to '/path/dir': // thisDest = '/path/dir/file1' var thisDest = dest; if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) thisDest = path.normalize(dest + '/' + path.basename(src)); if (fs.existsSync(thisDest) && !options.force) { error('dest file already exists: ' + thisDest, true); return; // skip file } if (path.resolve(src) === path.dirname(path.resolve(thisDest))) { error('cannot move to self: '+src, true); return; // skip file } fs.renameSync(src, thisDest); }); // forEach(src) } // mv exports.mv = wrap('mv', _mv); //@ //@ ### mkdir([options ,] dir [, dir ...]) //@ ### mkdir([options ,] dir_array) //@ Available options: //@ //@ + `p`: full path (will create intermediate dirs if necessary) //@ //@ Examples: //@ //@ ```javascript //@ mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g'); //@ mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above //@ ``` //@ //@ Creates directories. function _mkdir(options, dirs) { options = parseOptions(options, { 'p': 'fullpath' }); if (!dirs) error('no paths given'); if (typeof dirs === 'string') dirs = [].slice.call(arguments, 1); // if it's array leave it as it is dirs.forEach(function(dir) { if (fs.existsSync(dir)) { if (!options.fullpath) error('path already exists: ' + dir, true); return; // skip dir } // Base dir does not exist, and no -p option given var baseDir = path.dirname(dir); if (!fs.existsSync(baseDir) && !options.fullpath) { error('no such file or directory: ' + baseDir, true); return; // skip dir } if (options.fullpath) mkdirSyncRecursive(dir); else fs.mkdirSync(dir, parseInt('0777', 8)); }); } // mkdir exports.mkdir = wrap('mkdir', _mkdir); //@ //@ ### test(expression) //@ Available expression primaries: //@ //@ + `'-b', 'path'`: true if path is a block device //@ + `'-c', 'path'`: true if path is a character device //@ + `'-d', 'path'`: true if path is a directory //@ + `'-e', 'path'`: true if path exists //@ + `'-f', 'path'`: true if path is a regular file //@ + `'-L', 'path'`: true if path is a symboilc link //@ + `'-p', 'path'`: true if path is a pipe (FIFO) //@ + `'-S', 'path'`: true if path is a socket //@ //@ Examples: //@ //@ ```javascript //@ if (test('-d', path)) { /* do something with dir */ }; //@ if (!test('-f', path)) continue; // skip if it's a regular file //@ ``` //@ //@ Evaluates expression using the available primaries and returns corresponding value. function _test(options, path) { if (!path) error('no path given'); // hack - only works with unary primaries options = parseOptions(options, { 'b': 'block', 'c': 'character', 'd': 'directory', 'e': 'exists', 'f': 'file', 'L': 'link', 'p': 'pipe', 'S': 'socket' }); var canInterpret = false; for (var key in options) if (options[key] === true) { canInterpret = true; break; } if (!canInterpret) error('could not interpret expression'); if (options.link) { try { return fs.lstatSync(path).isSymbolicLink(); } catch(e) { return false; } } if (!fs.existsSync(path)) return false; if (options.exists) return true; var stats = fs.statSync(path); if (options.block) return stats.isBlockDevice(); if (options.character) return stats.isCharacterDevice(); if (options.directory) return stats.isDirectory(); if (options.file) return stats.isFile(); if (options.pipe) return stats.isFIFO(); if (options.socket) return stats.isSocket(); } // test exports.test = wrap('test', _test); //@ //@ ### cat(file [, file ...]) //@ ### cat(file_array) //@ //@ Examples: //@ //@ ```javascript //@ var str = cat('file*.txt'); //@ var str = cat('file1', 'file2'); //@ var str = cat(['file1', 'file2']); // same as above //@ ``` //@ //@ Returns a string containing the given file, or a concatenated string //@ containing the files if more than one file is given (a new line character is //@ introduced between each file). Wildcard `*` accepted. function _cat(options, files) { var cat = ''; if (!files) error('no paths given'); if (typeof files === 'string') files = [].slice.call(arguments, 1); // if it's array leave it as it is files = expand(files); files.forEach(function(file) { if (!fs.existsSync(file)) error('no such file or directory: ' + file); cat += fs.readFileSync(file, 'utf8') + '\n'; }); if (cat[cat.length-1] === '\n') cat = cat.substring(0, cat.length-1); return ShellString(cat); } exports.cat = wrap('cat', _cat); //@ //@ ### 'string'.to(file) //@ //@ Examples: //@ //@ ```javascript //@ cat('input.txt').to('output.txt'); //@ ``` //@ //@ Analogous to the redirection operator `>` in Unix, but works with JavaScript strings (such as //@ those returned by `cat`, `grep`, etc). _Like Unix redirections, `to()` will overwrite any existing file!_ function _to(options, file) { if (!file) error('wrong arguments'); if (!fs.existsSync( path.dirname(file) )) error('no such file or directory: ' + path.dirname(file)); try { fs.writeFileSync(file, this.toString(), 'utf8'); } catch(e) { error('could not write to file (code '+e.code+'): '+file, true); } } // In the future, when Proxies are default, we can add methods like `.to()` to primitive strings. // For now, this is a dummy function to bookmark places we need such strings function ShellString(str) { return str; } String.prototype.to = wrap('to', _to); //@ //@ ### sed([options ,] search_regex, replace_str, file) //@ Available options: //@ //@ + `-i`: Replace contents of 'file' in-place. _Note that no backups will be created!_ //@ //@ Examples: //@ //@ ```javascript //@ sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js'); //@ sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js'); //@ ``` //@ //@ Reads an input string from `file` and performs a JavaScript `replace()` on the input //@ using the given search regex and replacement string. Returns the new string after replacement. function _sed(options, regex, replacement, file) { options = parseOptions(options, { 'i': 'inplace' }); if (typeof replacement === 'string') replacement = replacement; // no-op else if (typeof replacement === 'number') replacement = replacement.toString(); // fallback else error('invalid replacement string'); if (!file) error('no file given'); if (!fs.existsSync(file)) error('no such file or directory: ' + file); var result = fs.readFileSync(file, 'utf8').replace(regex, replacement); if (options.inplace) fs.writeFileSync(file, result, 'utf8'); return ShellString(result); } exports.sed = wrap('sed', _sed); //@ //@ ### grep([options ,] regex_filter, file [, file ...]) //@ ### grep([options ,] regex_filter, file_array) //@ Available options: //@ //@ + `-v`: Inverse the sense of the regex and print the lines not matching the criteria. //@ //@ Examples: //@ //@ ```javascript //@ grep('-v', 'GLOBAL_VARIABLE', '*.js'); //@ grep('GLOBAL_VARIABLE', '*.js'); //@ ``` //@ //@ Reads input string from given files and returns a string containing all lines of the //@ file that match the given `regex_filter`. Wildcard `*` accepted. function _grep(options, regex, files) { options = parseOptions(options, { 'v': 'inverse' }); if (!files) error('no paths given'); if (typeof files === 'string') files = [].slice.call(arguments, 2); // if it's array leave it as it is files = expand(files); var grep = ''; files.forEach(function(file) { if (!fs.existsSync(file)) { error('no such file or directory: ' + file, true); return; } var contents = fs.readFileSync(file, 'utf8'), lines = contents.split(/\r*\n/); lines.forEach(function(line) { var matched = line.match(regex); if ((options.inverse && !matched) || (!options.inverse && matched)) grep += line + '\n'; }); }); return ShellString(grep); } exports.grep = wrap('grep', _grep); //@ //@ ### which(command) //@ //@ Examples: //@ //@ ```javascript //@ var nodeExec = which('node'); //@ ``` //@ //@ Searches for `command` in the system's PATH. On Windows looks for `.exe`, `.cmd`, and `.bat` extensions. //@ Returns string containing the absolute path to the command. function _which(options, cmd) { if (!cmd) error('must specify command'); var pathEnv = process.env.path || process.env.Path || process.env.PATH, pathArray = splitPath(pathEnv), where = null; // No relative/absolute paths provided? if (cmd.search(/\//) === -1) { // Search for command in PATH pathArray.forEach(function(dir) { if (where) return; // already found it var attempt = path.resolve(dir + '/' + cmd); if (fs.existsSync(attempt)) { where = attempt; return; } if (platform === 'win') { var baseAttempt = attempt; attempt = baseAttempt + '.exe'; if (fs.existsSync(attempt)) { where = attempt; return; } attempt = baseAttempt + '.cmd'; if (fs.existsSync(attempt)) { where = attempt; return; } attempt = baseAttempt + '.bat'; if (fs.existsSync(attempt)) { where = attempt; return; } } // if 'win' }); } // Command not found anywhere? if (!fs.existsSync(cmd) && !where) return null; where = where || path.resolve(cmd); return ShellString(where); } exports.which = wrap('which', _which); //@ //@ ### echo(string [,string ...]) //@ //@ Examples: //@ //@ ```javascript //@ echo('hello world'); //@ var str = echo('hello world'); //@ ``` //@ //@ Prints string to stdout, and returns string with additional utility methods //@ like `.to()`. function _echo() { var messages = [].slice.call(arguments, 0); console.log.apply(this, messages); return ShellString(messages.join(' ')); } exports.echo = _echo; // don't wrap() as it could parse '-options' // Pushd/popd/dirs internals var _dirStack = []; function _isStackIndex(index) { return (/^[\-+]\d+$/).test(index); } function _parseStackIndex(index) { if (_isStackIndex(index)) { if (Math.abs(index) < _dirStack.length + 1) { // +1 for pwd return (/^-/).test(index) ? Number(index) - 1 : Number(index); } else { error(index + ': directory stack index out of range'); } } else { error(index + ': invalid number'); } } function _actualDirStack() { return [process.cwd()].concat(_dirStack); } //@ //@ ### dirs([options | '+N' | '-N']) //@ //@ Available options: //@ //@ + `-c`: Clears the directory stack by deleting all of the elements. //@ //@ Arguments: //@ //@ + `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero. //@ + `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero. //@ //@ Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified. //@ //@ See also: pushd, popd function _dirs(options, index) { if (_isStackIndex(options)) { index = options; options = ''; } options = parseOptions(options, { 'c' : 'clear' }); if (options['clear']) { _dirStack = []; return _dirStack; } var stack = _actualDirStack(); if (index) { index = _parseStackIndex(index); if (index < 0) { index = stack.length + index; } log(stack[index]); return stack[index]; } log(stack.join(' ')); return stack; } exports.dirs = wrap("dirs", _dirs); //@ //@ ### pushd([options,] [dir | '-N' | '+N']) //@ //@ Available options: //@ //@ + `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. //@ //@ Arguments: //@ //@ + `dir`: Makes the current working directory be the top of the stack, and then executes the equivalent of `cd dir`. //@ + `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. //@ + `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. //@ //@ Examples: //@ //@ ```javascript //@ // process.cwd() === '/usr' //@ pushd('/etc'); // Returns /etc /usr //@ pushd('+1'); // Returns /usr /etc //@ ``` //@ //@ Save the current directory on the top of the directory stack and then cd to `dir`. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. function _pushd(options, dir) { if (_isStackIndex(options)) { dir = options; options = ''; } options = parseOptions(options, { 'n' : 'no-cd' }); var dirs = _actualDirStack(); if (dir === '+0') { return dirs; // +0 is a noop } else if (!dir) { if (dirs.length > 1) { dirs = dirs.splice(1, 1).concat(dirs); } else { return error('no other directory'); } } else if (_isStackIndex(dir)) { var n = _parseStackIndex(dir); dirs = dirs.slice(n).concat(dirs.slice(0, n)); } else { if (options['no-cd']) { dirs.splice(1, 0, dir); } else { dirs.unshift(dir); } } if (options['no-cd']) { dirs = dirs.slice(1); } else { dir = path.resolve(dirs.shift()); _cd('', dir); } _dirStack = dirs; return _dirs(''); } exports.pushd = wrap('pushd', _pushd); //@ //@ ### popd([options,] ['-N' | '+N']) //@ //@ Available options: //@ //@ + `-n`: Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated. //@ //@ Arguments: //@ //@ + `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. //@ + `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. //@ //@ Examples: //@ //@ ```javascript //@ echo(process.cwd()); // '/usr' //@ pushd('/etc'); // '/etc /usr' //@ echo(process.cwd()); // '/etc' //@ popd(); // '/usr' //@ echo(process.cwd()); // '/usr' //@ ``` //@ //@ When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. function _popd(options, index) { if (_isStackIndex(options)) { index = options; options = ''; } options = parseOptions(options, { 'n' : 'no-cd' }); if (!_dirStack.length) { return error('directory stack empty'); } index = _parseStackIndex(index || '+0'); if (options['no-cd'] || index > 0 || _dirStack.length + index === 0) { index = index > 0 ? index - 1 : index; _dirStack.splice(index, 1); } else { var dir = path.resolve(_dirStack.shift()); _cd('', dir); } return _dirs(''); } exports.popd = wrap("popd", _popd); //@ //@ ### exit(code) //@ Exits the current process with the given exit code. exports.exit = process.exit; //@ //@ ### env['VAR_NAME'] //@ Object containing environment variables (both getter and setter). Shortcut to process.env. exports.env = process.env; //@ //@ ### exec(command [, options] [, callback]) //@ Available options (all `false` by default): //@ //@ + `async`: Asynchronous execution. Defaults to true if a callback is provided. //@ + `silent`: Do not echo program output to console. //@ //@ Examples: //@ //@ ```javascript //@ var version = exec('node --version', {silent:true}).output; //@ //@ var child = exec('some_long_running_process', {async:true}); //@ child.stdout.on('data', function(data) { //@ /* ... do something with data ... */ //@ }); //@ //@ exec('some_long_running_process', function(code, output) { //@ console.log('Exit code:', code); //@ console.log('Program output:', output); //@ }); //@ ``` //@ //@ Executes the given `command` _synchronously_, unless otherwise specified. //@ When in synchronous mode returns the object `{ code:..., output:... }`, containing the program's //@ `output` (stdout + stderr) and its exit `code`. Otherwise returns the child process object, and //@ the `callback` gets the arguments `(code, output)`. //@ //@ **Note:** For long-lived processes, it's best to run `exec()` asynchronously as //@ the current synchronous implementation uses a lot of CPU. This should be getting //@ fixed soon. function _exec(command, options, callback) { if (!command) error('must specify command'); // Callback is defined instead of options. if (typeof options === 'function') { callback = options; options = { async: true }; } // Callback is defined with options. if (typeof options === 'object' && typeof callback === 'function') { options.async = true; } options = extend({ silent: config.silent, async: false }, options); if (options.async) return execAsync(command, options, callback); else return execSync(command, options); } exports.exec = wrap('exec', _exec, {notUnix:true}); var PERMS = (function (base) { return { OTHER_EXEC : base.EXEC, OTHER_WRITE : base.WRITE, OTHER_READ : base.READ, GROUP_EXEC : base.EXEC << 3, GROUP_WRITE : base.WRITE << 3, GROUP_READ : base.READ << 3, OWNER_EXEC : base.EXEC << 6, OWNER_WRITE : base.WRITE << 6, OWNER_READ : base.READ << 6, // Literal octal numbers are apparently not allowed in "strict" javascript. Using parseInt is // the preferred way, else a jshint warning is thrown. STICKY : parseInt('01000', 8), SETGID : parseInt('02000', 8), SETUID : parseInt('04000', 8), TYPE_MASK : parseInt('0770000', 8) }; })({ EXEC : 1, WRITE : 2, READ : 4 }); //@ //@ ### chmod(octal_mode || octal_string, file) //@ ### chmod(symbolic_mode, file) //@ //@ Available options: //@ //@ + `-v`: output a diagnostic for every file processed//@ //@ + `-c`: like verbose but report only when a change is made//@ //@ + `-R`: change files and directories recursively//@ //@ //@ Examples: //@ //@ ```javascript //@ chmod(755, '/Users/brandon'); //@ chmod('755', '/Users/brandon'); // same as above //@ chmod('u+x', '/Users/brandon'); //@ ``` //@ //@ Alters the permissions of a file or directory by either specifying the //@ absolute permissions in octal form or expressing the changes in symbols. //@ This command tries to mimic the POSIX behavior as much as possible. //@ Notable exceptions: //@ //@ + In symbolic modes, 'a-r' and '-r' are identical. No consideration is //@ given to the umask. //@ + There is no "quiet" option since default behavior is to run silent. function _chmod(options, mode, filePattern) { if (!filePattern) { if (options.length > 0 && options.charAt(0) === '-') { // Special case where the specified file permissions started with - to subtract perms, which // get picked up by the option parser as command flags. // If we are down by one argument and options starts with -, shift everything over. filePattern = mode; mode = options; options = ''; } else { error('You must specify a file.'); } } options = parseOptions(options, { 'R': 'recursive', 'c': 'changes', 'v': 'verbose' }); if (typeof filePattern === 'string') { filePattern = [ filePattern ]; } var files; if (options.recursive) { files = []; expand(filePattern).forEach(function addFile(expandedFile) { var stat = fs.lstatSync(expandedFile); if (!stat.isSymbolicLink()) { files.push(expandedFile); if (stat.isDirectory()) { // intentionally does not follow symlinks. fs.readdirSync(expandedFile).forEach(function (child) { addFile(expandedFile + '/' + child); }); } } }); } else { files = expand(filePattern); } files.forEach(function innerChmod(file) { file = path.resolve(file); if (!fs.existsSync(file)) { error('File not found: ' + file); } // When recursing, don't follow symlinks. if (options.recursive && fs.lstatSync(file).isSymbolicLink()) { return; } var perms = fs.statSync(file).mode; var type = perms & PERMS.TYPE_MASK; var newPerms = perms; if (isNaN(parseInt(mode, 8))) { // parse options mode.split(',').forEach(function (symbolicMode) { /*jshint regexdash:true */ var pattern = /([ugoa]*)([=\+-])([rwxXst]*)/i; var matches = pattern.exec(symbolicMode); if (matches) { var applyTo = matches[1]; var operator = matches[2]; var change = matches[3]; var changeOwner = applyTo.indexOf('u') != -1 || applyTo === 'a' || applyTo === ''; var changeGroup = applyTo.indexOf('g') != -1 || applyTo === 'a' || applyTo === ''; var changeOther = applyTo.indexOf('o') != -1 || applyTo === 'a' || applyTo === ''; var changeRead = change.indexOf('r') != -1; var changeWrite = change.indexOf('w') != -1; var changeExec = change.indexOf('x') != -1; var changeSticky = change.indexOf('t') != -1; var changeSetuid = change.indexOf('s') != -1; var mask = 0; if (changeOwner) { mask |= (changeRead ? PERMS.OWNER_READ : 0) + (changeWrite ? PERMS.OWNER_WRITE : 0) + (changeExec ? PERMS.OWNER_EXEC : 0) + (changeSetuid ? PERMS.SETUID : 0); } if (changeGroup) { mask |= (changeRead ? PERMS.GROUP_READ : 0) + (changeWrite ? PERMS.GROUP_WRITE : 0) + (changeExec ? PERMS.GROUP_EXEC : 0) + (changeSetuid ? PERMS.SETGID : 0); } if (changeOther) { mask |= (changeRead ? PERMS.OTHER_READ : 0) + (changeWrite ? PERMS.OTHER_WRITE : 0) + (changeExec ? PERMS.OTHER_EXEC : 0); } // Sticky bit is special - it's not tied to user, group or other. if (changeSticky) { mask |= PERMS.STICKY; } switch (operator) { case '+': newPerms |= mask; break; case '-': newPerms &= ~mask; break; case '=': newPerms = type + mask; // According to POSIX, when using = to explicitly set the permissions, setuid and setgid can never be cleared. if (fs.statSync(file).isDirectory()) { newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; } break; } if (options.verbose) { log(file + ' -> ' + newPerms.toString(8)); } if (perms != newPerms) { if (!options.verbose && options.changes) { log(file + ' -> ' + newPerms.toString(8)); } fs.chmodSync(file, newPerms); } } else { error('Invalid symbolic mode change: ' + symbolicMode); } }); } else { // they gave us a full number newPerms = type + parseInt(mode, 8); // POSIX rules are that setuid and setgid can only be added using numeric form, but not cleared. if (fs.statSync(file).isDirectory()) { newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; } fs.chmodSync(file, newPerms); } }); } exports.chmod = wrap('chmod', _chmod); //@ //@ ## Configuration //@ exports.config = config; //@ //@ ### config.silent //@ Example: //@ //@ ```javascript //@ var silentState = config.silent; // save old silent state //@ config.silent = true; //@ /* ... */ //@ config.silent = silentState; // restore old silent state //@ ``` //@ //@ Suppresses all command output if `true`, except for `echo()` calls. //@ Default is `false`. //@ //@ ### config.fatal //@ Example: //@ //@ ```javascript //@ config.fatal = true; //@ cp('this_file_does_not_exist', '/dev/null'); // dies here //@ /* more commands... */ //@ ``` //@ //@ If `true` the script will die on errors. Default is `false`. //@ //@ ## Non-Unix commands //@ //@ //@ ### tempdir() //@ Searches and returns string containing a writeable, platform-dependent temporary directory. //@ Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). exports.tempdir = wrap('tempdir', tempDir); //@ //@ ### error() //@ Tests if error occurred in the last command. Returns `null` if no error occurred, //@ otherwise returns string explaining the error exports.error = function() { return state.error; }; //////////////////////////////////////////////////////////////////////////////////////////////// // // Auxiliary functions (internal use only) // function log() { if (!config.silent) console.log.apply(this, arguments); } function deprecate(what, msg) { console.log('*** ShellJS.'+what+': This function is deprecated.', msg); } function write(msg) { if (!config.silent) process.stdout.write(msg); } // Shows error message. Throws unless _continue or config.fatal are true function error(msg, _continue) { if (state.error === null) state.error = ''; state.error += state.currentCmd + ': ' + msg + '\n'; log(state.error); if (config.fatal) process.exit(1); if (!_continue) throw ''; } // Returns {'alice': true, 'bob': false} when passed: // parseOptions('-a', {'a':'alice', 'b':'bob'}); function parseOptions(str, map) { if (!map) error('parseOptions() internal error: no map given'); // All options are false by default var options = {}; for (var letter in map) options[map[letter]] = false; if (!str) return options; // defaults if (typeof str !== 'string') error('parseOptions() internal error: wrong str'); // e.g. match[1] = 'Rf' for str = '-Rf' var match = str.match(/^\-(.+)/); if (!match) return options; // e.g. chars = ['R', 'f'] var chars = match[1].split(''); chars.forEach(function(c) { if (c in map) options[map[c]] = true; else error('option not recognized: '+c); }); return options; } // Common wrapper for all Unix-like commands function wrap(cmd, fn, options) { return function() { var retValue = null; state.currentCmd = cmd; state.error = null; try { var args = [].slice.call(arguments, 0); if (options && options.notUnix) { retValue = fn.apply(this, args); } else { if (args.length === 0 || typeof args[0] !== 'string' || args[0][0] !== '-') args.unshift(''); // only add dummy option if '-option' not already present retValue = fn.apply(this, args); } } catch (e) { if (!state.error) { // If state.error hasn't been set it's an error thrown by Node, not us - probably a bug... console.log('shell.js: internal error'); console.log(e.stack || e); process.exit(1); } if (config.fatal) throw e; } state.currentCmd = 'shell.js'; return retValue; }; } // wrap // Buffered file copy, synchronous // (Using readFileSync() + writeFileSync() could easily cause a memory overflow // with large files) function copyFileSync(srcFile, destFile) { if (!fs.existsSync(srcFile)) error('copyFileSync: no such file or directory: ' + srcFile); var BUF_LENGTH = 64*1024, buf = new Buffer(BUF_LENGTH), bytesRead = BUF_LENGTH, pos = 0, fdr = null, fdw = null; try { fdr = fs.openSync(srcFile, 'r'); } catch(e) { error('copyFileSync: could not read src file ('+srcFile+')'); } try { fdw = fs.openSync(destFile, 'w'); } catch(e) { error('copyFileSync: could not write to dest file (code='+e.code+'):'+destFile); } while (bytesRead === BUF_LENGTH) { bytesRead = fs.readSync(fdr, buf, 0, BUF_LENGTH, pos); fs.writeSync(fdw, buf, 0, bytesRead); pos += bytesRead; } fs.closeSync(fdr); fs.closeSync(fdw); } // Recursively copies 'sourceDir' into 'destDir' // Adapted from https://github.com/ryanmcgrath/wrench-js // // Copyright (c) 2010 Ryan McGrath // Copyright (c) 2012 Artur Adib // // Licensed under the MIT License // http://www.opensource.org/licenses/mit-license.php function cpdirSyncRecursive(sourceDir, destDir, opts) { if (!opts) opts = {}; /* Create the directory where all our junk is moving to; read the mode of the source directory and mirror it */ var checkDir = fs.statSync(sourceDir); try { fs.mkdirSync(destDir, checkDir.mode); } catch (e) { //if the directory already exists, that's okay if (e.code !== 'EEXIST') throw e; } var files = fs.readdirSync(sourceDir); for(var i = 0; i < files.length; i++) { var currFile = fs.lstatSync(sourceDir + "/" + files[i]); if (currFile.isDirectory()) { /* recursion this thing right on back. */ cpdirSyncRecursive(sourceDir + "/" + files[i], destDir + "/" + files[i], opts); } else if (currFile.isSymbolicLink()) { var symlinkFull = fs.readlinkSync(sourceDir + "/" + files[i]); fs.symlinkSync(symlinkFull, destDir + "/" + files[i]); } else { /* At this point, we've hit a file actually worth copying... so copy it on over. */ if (fs.existsSync(destDir + "/" + files[i]) && !opts.force) { log('skipping existing file: ' + files[i]); } else { copyFileSync(sourceDir + "/" + files[i], destDir + "/" + files[i]); } } } // for files } // cpdirSyncRecursive // Recursively removes 'dir' // Adapted from https://github.com/ryanmcgrath/wrench-js // // Copyright (c) 2010 Ryan McGrath // Copyright (c) 2012 Artur Adib // // Licensed under the MIT License // http://www.opensource.org/licenses/mit-license.php function rmdirSyncRecursive(dir, force) { var files; files = fs.readdirSync(dir); // Loop through and delete everything in the sub-tree after checking it for(var i = 0; i < files.length; i++) { var file = dir + "/" + files[i], currFile = fs.lstatSync(file); if(currFile.isDirectory()) { // Recursive function back to the beginning rmdirSyncRecursive(file, force); } else if(currFile.isSymbolicLink()) { // Unlink symlinks if (force || isWriteable(file)) { try { _unlinkSync(file); } catch (e) { error('could not remove file (code '+e.code+'): ' + file, true); } } } else // Assume it's a file - perhaps a try/catch belongs here? if (force || isWriteable(file)) { try { _unlinkSync(file); } catch (e) { error('could not remove file (code '+e.code+'): ' + file, true); } } } // Now that we know everything in the sub-tree has been deleted, we can delete the main directory. // Huzzah for the shopkeep. var result; try { result = fs.rmdirSync(dir); } catch(e) { error('could not remove directory (code '+e.code+'): ' + dir, true); } return result; } // rmdirSyncRecursive // Recursively creates 'dir' function mkdirSyncRecursive(dir) { var baseDir = path.dirname(dir); // Base dir exists, no recursion necessary if (fs.existsSync(baseDir)) { fs.mkdirSync(dir, parseInt('0777', 8)); return; } // Base dir does not exist, go recursive mkdirSyncRecursive(baseDir); // Base dir created, can create dir fs.mkdirSync(dir, parseInt('0777', 8)); } // e.g. 'shelljs_a5f185d0443ca...' function randomFileName() { function randomHash(count) { if (count === 1) return parseInt(16*Math.random(), 10).toString(16); else { var hash = ''; for (var i=0; i<count; i++) hash += randomHash(1); return hash; } } return 'shelljs_'+randomHash(20); } // Returns false if 'dir' is not a writeable directory, 'dir' otherwise function writeableDir(dir) { if (!dir || !fs.existsSync(dir)) return false; if (!fs.statSync(dir).isDirectory()) return false; var testFile = dir+'/'+randomFileName(); try { fs.writeFileSync(testFile, ' '); _unlinkSync(testFile); return dir; } catch (e) { return false; } } // Cross-platform method for getting an available temporary directory. // Follows the algorithm of Python's tempfile.tempdir // http://docs.python.org/library/tempfile.html#tempfile.tempdir function tempDir() { if (state.tempDir) return state.tempDir; // from cache state.tempDir = writeableDir(process.env['TMPDIR']) || writeableDir(process.env['TEMP']) || writeableDir(process.env['TMP']) || writeableDir(process.env['Wimp$ScrapDir']) || // RiscOS writeableDir('C:\\TEMP') || // Windows writeableDir('C:\\TMP') || // Windows writeableDir('\\TEMP') || // Windows writeableDir('\\TMP') || // Windows writeableDir('/tmp') || writeableDir('/var/tmp') || writeableDir('/usr/tmp') || writeableDir('.'); // last resort return state.tempDir; } // Wrapper around exec() to enable echoing output to console in real time function execAsync(cmd, opts, callback) { var output = ''; var options = extend({ silent: config.silent }, opts); var c = child.exec(cmd, {env: process.env}, function(err) { if (callback) callback(err ? err.code : 0, output); }); c.stdout.on('data', function(data) { output += data; if (!options.silent) process.stdout.write(data); }); c.stderr.on('data', function(data) { output += data; if (!options.silent) process.stdout.write(data); }); return c; } // Hack to run child_process.exec() synchronously (sync avoids callback hell) // Uses a custom wait loop that checks for a flag file, created when the child process is done. // (Can't do a wait loop that checks for internal Node variables/messages as // Node is single-threaded; callbacks and other internal state changes are done in the // event loop). function execSync(cmd, opts) { var stdoutFile = path.resolve(tempDir()+'/'+randomFileName()), codeFile = path.resolve(tempDir()+'/'+randomFileName()), scriptFile = path.resolve(tempDir()+'/'+randomFileName()), sleepFile = path.resolve(tempDir()+'/'+randomFileName()); var options = extend({ silent: config.silent }, opts); var previousStdoutContent = ''; // Echoes stdout changes from running process, if not silent function updateStdout() { if (options.silent || !fs.existsSync(stdoutFile)) return; var stdoutContent = fs.readFileSync(stdoutFile, 'utf8'); // No changes since last time? if (stdoutContent.length <= previousStdoutContent.length) return; process.stdout.write(stdoutContent.substr(previousStdoutContent.length)); previousStdoutContent = stdoutContent; } function escape(str) { return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0"); } cmd += ' > '+stdoutFile+' 2>&1'; // works on both win/unix var script = "var child = require('child_process')," + " fs = require('fs');" + "child.exec('"+escape(cmd)+"', {env: process.env}, function(err) {" + " fs.writeFileSync('"+escape(codeFile)+"', err ? err.code.toString() : '0');" + "});"; if (fs.existsSync(scriptFile)) _unlinkSync(scriptFile); if (fs.existsSync(stdoutFile)) _unlinkSync(stdoutFile); if (fs.existsSync(codeFile)) _unlinkSync(codeFile); fs.writeFileSync(scriptFile, script); child.exec('"'+process.execPath+'" '+scriptFile, { env: process.env, cwd: exports.pwd() }); // The wait loop // sleepFile is used as a dummy I/O op to mitigate unnecessary CPU usage // (tried many I/O sync ops, writeFileSync() seems to be only one that is effective in reducing // CPU usage, though apparently not so much on Windows) while (!fs.existsSync(codeFile)) { updateStdout(); fs.writeFileSync(sleepFile, 'a'); } while (!fs.existsSync(stdoutFile)) { updateStdout(); fs.writeFileSync(sleepFile, 'a'); } // At this point codeFile exists, but it's not necessarily flushed yet. // Keep reading it until it is. var code = parseInt('', 10); while (isNaN(code)) { code = parseInt(fs.readFileSync(codeFile, 'utf8'), 10); } var stdout = fs.readFileSync(stdoutFile, 'utf8'); // No biggie if we can't erase the files now -- they're in a temp dir anyway try { _unlinkSync(scriptFile); } catch(e) {} try { _unlinkSync(stdoutFile); } catch(e) {} try { _unlinkSync(codeFile); } catch(e) {} try { _unlinkSync(sleepFile); } catch(e) {} // True if successful, false if not var obj = { code: code, output: stdout }; return obj; } // execSync() // Expands wildcards with matching file names. For a given array of file names 'list', returns // another array containing all file names as per ls(list[i]). // For example: // expand(['file*.js']) = ['file1.js', 'file2.js', ...] // (if the files 'file1.js', 'file2.js', etc, exist in the current dir) function expand(list) { var expanded = []; list.forEach(function(listEl) { // Wildcard present? if (listEl.search(/\*/) > -1) { _ls('', listEl).forEach(function(file) { expanded.push(file); }); } else { expanded.push(listEl); } }); return expanded; } // Cross-platform method for splitting environment PATH variables function splitPath(p) { if (!p) return []; if (platform === 'win') return p.split(';'); else return p.split(':'); } // extend(target_obj, source_obj1 [, source_obj2 ...]) // Shallow extend, e.g.: // extend({A:1}, {b:2}, {c:3}) returns {A:1, b:2, c:3} function extend(target) { var sources = [].slice.call(arguments, 1); sources.forEach(function(source) { for (var key in source) target[key] = source[key]; }); return target; } // Normalizes _unlinkSync() across platforms to match Unix behavior, i.e. // file can be unlinked even if it's read-only, see joyent/node#3006 function _unlinkSync(file) { try { fs.unlinkSync(file); } catch(e) { // Try to override file permission if (e.code === 'EPERM') { fs.chmodSync(file, '0666'); fs.unlinkSync(file); } else { throw e; } } } // Hack to determine if file has write permissions for current user // Avoids having to check user, group, etc, but it's probably slow function isWriteable(file) { var writePermission = true; try { var __fd = fs.openSync(file, 'a'); fs.closeSync(__fd); } catch(e) { writePermission = false; } return writePermission; }
stephenlorenz/sproutstudy
sproutStudy_web/yo/node_modules/grunt-contrib-jshint/node_modules/jshint/node_modules/shelljs/shell.js
JavaScript
apache-2.0
51,298
module.exports = require("npm:create-hash@1.1.1/browser");
TelerikFrenchConnection/JS-Applications-Teamwork
lib/npm/create-hash@1.1.1.js
JavaScript
mit
58
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v9.0.2 * @link http://www.ag-grid.com/ * @license MIT */ "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 __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var utils_1 = require("../utils"); var componentAnnotations_1 = require("../widgets/componentAnnotations"); var baseFilter_1 = require("./baseFilter"); var NumberFilter = (function (_super) { __extends(NumberFilter, _super); function NumberFilter() { return _super !== null && _super.apply(this, arguments) || this; } NumberFilter.prototype.modelFromFloatingFilter = function (from) { return { type: this.filter, filter: Number(from), filterTo: this.filterNumberTo, filterType: 'number' }; }; NumberFilter.prototype.getApplicableFilterTypes = function () { return [baseFilter_1.BaseFilter.EQUALS, baseFilter_1.BaseFilter.NOT_EQUAL, baseFilter_1.BaseFilter.LESS_THAN, baseFilter_1.BaseFilter.LESS_THAN_OR_EQUAL, baseFilter_1.BaseFilter.GREATER_THAN, baseFilter_1.BaseFilter.GREATER_THAN_OR_EQUAL, baseFilter_1.BaseFilter.IN_RANGE]; }; NumberFilter.prototype.bodyTemplate = function () { var translate = this.translate.bind(this); return "<div class=\"ag-filter-body\">\n <div>\n <input class=\"ag-filter-filter\" id=\"filterText\" type=\"text\" placeholder=\"" + translate('filterOoo') + "\"/>\n </div>\n <div class=\"ag-filter-number-to\" id=\"filterNumberToPanel\">\n <input class=\"ag-filter-filter\" id=\"filterToText\" type=\"text\" placeholder=\"" + translate('filterOoo') + "\"/>\n </div>\n </div>"; }; NumberFilter.prototype.initialiseFilterBodyUi = function () { this.filterNumber = null; this.setFilterType(NumberFilter.EQUALS); this.eFilterTextField = this.getGui().querySelector("#filterText"); this.addDestroyableEventListener(this.eFilterTextField, "input", this.onTextFieldsChanged.bind(this)); this.addDestroyableEventListener(this.eFilterToTextField, "input", this.onTextFieldsChanged.bind(this)); }; NumberFilter.prototype.afterGuiAttached = function () { this.eFilterTextField.focus(); }; NumberFilter.prototype.comparator = function () { return function (left, right) { if (left === right) return 0; if (left < right) return 1; if (left > right) return -1; }; }; NumberFilter.prototype.onTextFieldsChanged = function () { var newFilter = this.stringToFloat(this.eFilterTextField.value); var newFilterTo = this.stringToFloat(this.eFilterToTextField.value); if (this.filterNumber !== newFilter || this.filterNumberTo !== newFilterTo) { this.filterNumber = newFilter; this.filterNumberTo = newFilterTo; this.onFilterChanged(); } }; NumberFilter.prototype.filterValues = function () { return this.filter !== baseFilter_1.BaseFilter.IN_RANGE ? this.asNumber(this.filterNumber) : [this.asNumber(this.filterNumber), this.asNumber(this.filterNumberTo)]; }; NumberFilter.prototype.asNumber = function (value) { return utils_1.Utils.isNumeric(value) ? value : null; }; NumberFilter.prototype.stringToFloat = function (value) { var filterText = utils_1.Utils.makeNull(value); if (filterText && filterText.trim() === '') { filterText = null; } var newFilter; if (filterText !== null && filterText !== undefined) { newFilter = parseFloat(filterText); } else { newFilter = null; } return newFilter; }; NumberFilter.prototype.setFilter = function (filter) { filter = utils_1.Utils.makeNull(filter); if (filter !== null && !(typeof filter === 'number')) { filter = parseFloat(filter); } this.filterNumber = filter; this.eFilterTextField.value = filter; }; NumberFilter.prototype.setFilterTo = function (filter) { filter = utils_1.Utils.makeNull(filter); if (filter !== null && !(typeof filter === 'number')) { filter = parseFloat(filter); } this.filterNumberTo = filter; this.eFilterToTextField.value = filter; }; NumberFilter.prototype.getFilter = function () { return this.filterNumber; }; NumberFilter.prototype.serialize = function () { return { type: this.filter, filter: this.filterNumber, filterTo: this.filterNumberTo, filterType: 'number' }; }; NumberFilter.prototype.parse = function (model) { this.setFilterType(model.type); this.setFilter(model.filter); this.setFilterTo(model.filterTo); }; NumberFilter.prototype.refreshFilterBodyUi = function () { var visible = this.filter === NumberFilter.IN_RANGE; utils_1.Utils.setVisible(this.eNumberToPanel, visible); }; NumberFilter.prototype.resetState = function () { this.setFilterType(baseFilter_1.BaseFilter.EQUALS); this.setFilter(null); this.setFilterTo(null); }; NumberFilter.prototype.setType = function (filterType) { this.setFilterType(filterType); }; return NumberFilter; }(baseFilter_1.ScalarBaseFilter)); NumberFilter.EQUALS = 'equals'; // 1; NumberFilter.NOT_EQUAL = 'notEqual'; //2; NumberFilter.LESS_THAN_OR_EQUAL = 'lessThanOrEqual'; //4; NumberFilter.GREATER_THAN = 'greaterThan'; //5; NumberFilter.GREATER_THAN_OR_EQUAL = 'greaterThan'; //6; NumberFilter.IN_RANGE = 'inRange'; NumberFilter.LESS_THAN = 'lessThan'; //3; __decorate([ componentAnnotations_1.QuerySelector('#filterNumberToPanel'), __metadata("design:type", HTMLElement) ], NumberFilter.prototype, "eNumberToPanel", void 0); __decorate([ componentAnnotations_1.QuerySelector('#filterToText'), __metadata("design:type", HTMLInputElement) ], NumberFilter.prototype, "eFilterToTextField", void 0); exports.NumberFilter = NumberFilter;
nolsherry/cdnjs
ajax/libs/ag-grid/9.0.2/lib/filter/numberFilter.js
JavaScript
mit
7,548
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ import {stringHash32} from '../crypto'; /** * Gets a string of concatenated element names and relative positions * of the DOM element and its parentElement's (up to 25). Relative position * is the index of nodes with this tag within the parent's children. * The order is from the inner to outer nodes in DOM hierarchy. * * If a DOM hierarchy is the following: * * <div id='id1' ...> * <div id='id2' ...> * <table ...> // table:0 * <tr> // tr:0 * <td>...</td> // td:0 * <td> // td:1 * <amp-ad ...></amp-ad> * </td> * </tr> * <tr>...</tr> // tr:1 * </table> * </div> * </div> * * With the amp-ad element passed in: * 'amp-ad.0,td.1,tr.0,table.0,div/id2.0,div/id1.0' * * Note: 25 is chosen arbitrarily. * * @param {?Element} element DOM node from which to get fingerprint. * @return {string} Concatenated element ids. */ export function domFingerprintPlain(element) { const ids = []; let level = 0; while (element && element.nodeType == /* element */ 1 && level < 25) { let id = ''; if (element.id) { id = `/${element.id}`; } const nodeName = element.nodeName.toLowerCase(); ids.push(`${nodeName}${id}${indexWithinParent(element)}`); level++; element = element.parentElement; } return ids.join(); }; /** * Calculates ad slot DOM fingerprint. This key is intended to * identify "same" ad unit across many page views. This is * based on where the ad appears within the page's DOM structure. * * @param {?Element} element The DOM element from which to collect * the DOM chain element IDs. If null, DOM chain element IDs are not * included in the hash. * @return {string} The ad unit hash key string. */ export function domFingerprint(element) { return stringHash32(domFingerprintPlain(element)); }; /** * Gets a string showing the index of an element within * the children of its parent, counting only nodes with the same tag. * Stop at 25, just to have a limit. * @param {!Element} element DOM node to get index of. * @return {string} '.<index>' or ''. */ function indexWithinParent(element) { const nodeName = element.nodeName; // Find my index within my parent's children let i = 0; let count = 0; let sibling = element.previousElementSibling; // Different browsers have different children. // So count only nodes with the same tag. // Use a limit for the tags, so that different browsers get the same // count. So 25 and higher all return no index. while (sibling && count < 25 && i < 100) { if (sibling.nodeName == nodeName) { count++; } i++; sibling = sibling.previousElementSibling; } // If we got to the end, then the count is accurate; otherwise skip count. return count < 25 && i < 100 ? `.${count}` : ''; };
jdelhommeau/amphtml
src/utils/dom-fingerprint.js
JavaScript
apache-2.0
3,490
import { ShaderMaterial } from './ShaderMaterial'; import { ShaderChunk } from '../renderers/shaders/ShaderChunk'; import { UniformsLib } from '../renderers/shaders/UniformsLib'; import { UniformsUtils } from '../renderers/shaders/UniformsUtils'; /** * @author mrdoob / http://mrdoob.com/ * * parameters = { * opacity: <float> * } */ function ShadowMaterial( parameters ) { ShaderMaterial.call( this, { uniforms: UniformsUtils.merge( [ UniformsLib.lights, { opacity: { value: 1.0 } } ] ), vertexShader: ShaderChunk[ 'shadow_vert' ], fragmentShader: ShaderChunk[ 'shadow_frag' ] } ); this.lights = true; this.transparent = true; Object.defineProperties( this, { opacity: { enumerable: true, get: function () { return this.uniforms.opacity.value; }, set: function ( value ) { this.uniforms.opacity.value = value; } } } ); this.setValues( parameters ); } ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype ); ShadowMaterial.prototype.constructor = ShadowMaterial; ShadowMaterial.prototype.isShadowMaterial = true; export { ShadowMaterial };
robcbryant/projectanka
static/three/extras/materials/ShadowMaterial.js
JavaScript
apache-2.0
1,127
IonicModule .controller('$ionicTab', [ '$scope', '$ionicViewService', '$attrs', '$location', '$state', function($scope, $ionicViewService, $attrs, $location, $state) { this.$scope = $scope; //All of these exposed for testing this.hrefMatchesState = function() { return $attrs.href && $location.path().indexOf( $attrs.href.replace(/^#/, '').replace(/\/$/, '') ) === 0; }; this.srefMatchesState = function() { return $attrs.uiSref && $state.includes( $attrs.uiSref.split('(')[0] ); }; this.navNameMatchesState = function() { return this.navViewName && $ionicViewService.isCurrentStateNavView(this.navViewName); }; this.tabMatchesState = function() { return this.hrefMatchesState() || this.srefMatchesState() || this.navNameMatchesState(); }; }]);
frangucc/gamify
www/sandbox/pals/app/bower_components/ionic/js/angular/controller/tabController.js
JavaScript
mit
803
var object1 = { get [Symbol.create]() { }, set [set()](value) { } }; var object2 = { *[generator()]() { } }; var object3 = { *[generator()]() { } }; var object4 = { [Symbol.xxx]: 'hello', [ok()]: 42 };
Khan/escodegen
test/compare-harmony/computed-property.expected.js
JavaScript
bsd-2-clause
242
(function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof module === "object" && module.exports) { var $ = require('jquery'); module.exports = factory($); } else { // Browser globals factory(jQuery); } }(function (jQuery) { /*! * jQuery.textcomplete * * Repository: https://github.com/yuku-t/jquery-textcomplete * License: MIT (https://github.com/yuku-t/jquery-textcomplete/blob/master/LICENSE) * Author: Yuku Takahashi */ if (typeof jQuery === 'undefined') { throw new Error('jQuery.textcomplete requires jQuery'); } +function ($) { 'use strict'; var warn = function (message) { if (console.warn) { console.warn(message); } }; var id = 1; $.fn.textcomplete = function (strategies, option) { var args = Array.prototype.slice.call(arguments); return this.each(function () { var $this = $(this); var completer = $this.data('textComplete'); if (!completer) { option || (option = {}); option._oid = id++; // unique object id completer = new $.fn.textcomplete.Completer(this, option); $this.data('textComplete', completer); } if (typeof strategies === 'string') { if (!completer) return; args.shift() completer[strategies].apply(completer, args); if (strategies === 'destroy') { $this.removeData('textComplete'); } } else { // For backward compatibility. // TODO: Remove at v0.4 $.each(strategies, function (obj) { $.each(['header', 'footer', 'placement', 'maxCount'], function (name) { if (obj[name]) { completer.option[name] = obj[name]; warn(name + 'as a strategy param is deprecated. Use option.'); delete obj[name]; } }); }); completer.register($.fn.textcomplete.Strategy.parse(strategies)); } }); }; }(jQuery); +function ($) { 'use strict'; // Exclusive execution control utility. // // func - The function to be locked. It is executed with a function named // `free` as the first argument. Once it is called, additional // execution are ignored until the free is invoked. Then the last // ignored execution will be replayed immediately. // // Examples // // var lockedFunc = lock(function (free) { // setTimeout(function { free(); }, 1000); // It will be free in 1 sec. // console.log('Hello, world'); // }); // lockedFunc(); // => 'Hello, world' // lockedFunc(); // none // lockedFunc(); // none // // 1 sec past then // // => 'Hello, world' // lockedFunc(); // => 'Hello, world' // lockedFunc(); // none // // Returns a wrapped function. var lock = function (func) { var locked, queuedArgsToReplay; return function () { // Convert arguments into a real array. var args = Array.prototype.slice.call(arguments); if (locked) { // Keep a copy of this argument list to replay later. // OK to overwrite a previous value because we only replay // the last one. queuedArgsToReplay = args; return; } locked = true; var self = this; args.unshift(function replayOrFree() { if (queuedArgsToReplay) { // Other request(s) arrived while we were locked. // Now that the lock is becoming available, replay // the latest such request, then call back here to // unlock (or replay another request that arrived // while this one was in flight). var replayArgs = queuedArgsToReplay; queuedArgsToReplay = undefined; replayArgs.unshift(replayOrFree); func.apply(self, replayArgs); } else { locked = false; } }); func.apply(this, args); }; }; var isString = function (obj) { return Object.prototype.toString.call(obj) === '[object String]'; }; var isFunction = function (obj) { return Object.prototype.toString.call(obj) === '[object Function]'; }; var uniqueId = 0; function Completer(element, option) { this.$el = $(element); this.id = 'textcomplete' + uniqueId++; this.strategies = []; this.views = []; this.option = $.extend({}, Completer._getDefaults(), option); if (!this.$el.is('input[type=text]') && !this.$el.is('textarea') && !element.isContentEditable && element.contentEditable != 'true') { throw new Error('textcomplete must be called on a Textarea or a ContentEditable.'); } if (element === document.activeElement) { // element has already been focused. Initialize view objects immediately. this.initialize() } else { // Initialize view objects lazily. var self = this; this.$el.one('focus.' + this.id, function () { self.initialize(); }); } } Completer._getDefaults = function () { if (!Completer.DEFAULTS) { Completer.DEFAULTS = { appendTo: $('body'), zIndex: '100' }; } return Completer.DEFAULTS; } $.extend(Completer.prototype, { // Public properties // ----------------- id: null, option: null, strategies: null, adapter: null, dropdown: null, $el: null, // Public methods // -------------- initialize: function () { var element = this.$el.get(0); // Initialize view objects. this.dropdown = new $.fn.textcomplete.Dropdown(element, this, this.option); var Adapter, viewName; if (this.option.adapter) { Adapter = this.option.adapter; } else { if (this.$el.is('textarea') || this.$el.is('input[type=text]')) { viewName = typeof element.selectionEnd === 'number' ? 'Textarea' : 'IETextarea'; } else { viewName = 'ContentEditable'; } Adapter = $.fn.textcomplete[viewName]; } this.adapter = new Adapter(element, this, this.option); }, destroy: function () { this.$el.off('.' + this.id); if (this.adapter) { this.adapter.destroy(); } if (this.dropdown) { this.dropdown.destroy(); } this.$el = this.adapter = this.dropdown = null; }, // Invoke textcomplete. trigger: function (text, skipUnchangedTerm) { if (!this.dropdown) { this.initialize(); } text != null || (text = this.adapter.getTextFromHeadToCaret()); var searchQuery = this._extractSearchQuery(text); if (searchQuery.length) { var term = searchQuery[1]; // Ignore shift-key, ctrl-key and so on. if (skipUnchangedTerm && this._term === term) { return; } this._term = term; this._search.apply(this, searchQuery); } else { this._term = null; this.dropdown.deactivate(); } }, fire: function (eventName) { var args = Array.prototype.slice.call(arguments, 1); this.$el.trigger(eventName, args); return this; }, register: function (strategies) { Array.prototype.push.apply(this.strategies, strategies); }, // Insert the value into adapter view. It is called when the dropdown is clicked // or selected. // // value - The selected element of the array callbacked from search func. // strategy - The Strategy object. // e - Click or keydown event object. select: function (value, strategy, e) { this.adapter.select(value, strategy, e); this.fire('change').fire('textComplete:select', value, strategy); this.adapter.focus(); }, // Private properties // ------------------ _clearAtNext: true, _term: null, // Private methods // --------------- // Parse the given text and extract the first matching strategy. // // Returns an array including the strategy, the query term and the match // object if the text matches an strategy; otherwise returns an empty array. _extractSearchQuery: function (text) { for (var i = 0; i < this.strategies.length; i++) { var strategy = this.strategies[i]; var context = strategy.context(text); if (context || context === '') { var matchRegexp = isFunction(strategy.match) ? strategy.match(text) : strategy.match; if (isString(context)) { text = context; } var match = text.match(matchRegexp); if (match) { return [strategy, match[strategy.index], match]; } } } return [] }, // Call the search method of selected strategy.. _search: lock(function (free, strategy, term, match) { var self = this; strategy.search(term, function (data, stillSearching) { if (!self.dropdown.shown) { self.dropdown.activate(); } if (self._clearAtNext) { // The first callback in the current lock. self.dropdown.clear(); self._clearAtNext = false; } self.dropdown.setPosition(self.adapter.getCaretPosition()); self.dropdown.render(self._zip(data, strategy, term)); if (!stillSearching) { // The last callback in the current lock. free(); self._clearAtNext = true; // Call dropdown.clear at the next time. } }, match); }), // Build a parameter for Dropdown#render. // // Examples // // this._zip(['a', 'b'], 's'); // //=> [{ value: 'a', strategy: 's' }, { value: 'b', strategy: 's' }] _zip: function (data, strategy, term) { return $.map(data, function (value) { return { value: value, strategy: strategy, term: term }; }); } }); $.fn.textcomplete.Completer = Completer; }(jQuery); +function ($) { 'use strict'; var $window = $(window); var include = function (zippedData, datum) { var i, elem; var idProperty = datum.strategy.idProperty for (i = 0; i < zippedData.length; i++) { elem = zippedData[i]; if (elem.strategy !== datum.strategy) continue; if (idProperty) { if (elem.value[idProperty] === datum.value[idProperty]) return true; } else { if (elem.value === datum.value) return true; } } return false; }; var dropdownViews = {}; $(document).on('click', function (e) { var id = e.originalEvent && e.originalEvent.keepTextCompleteDropdown; $.each(dropdownViews, function (key, view) { if (key !== id) { view.deactivate(); } }); }); var commands = { SKIP_DEFAULT: 0, KEY_UP: 1, KEY_DOWN: 2, KEY_ENTER: 3, KEY_PAGEUP: 4, KEY_PAGEDOWN: 5, KEY_ESCAPE: 6 }; // Dropdown view // ============= // Construct Dropdown object. // // element - Textarea or contenteditable element. function Dropdown(element, completer, option) { this.$el = Dropdown.createElement(option); this.completer = completer; this.id = completer.id + 'dropdown'; this._data = []; // zipped data. this.$inputEl = $(element); this.option = option; // Override setPosition method. if (option.listPosition) { this.setPosition = option.listPosition; } if (option.height) { this.$el.height(option.height); } var self = this; $.each(['maxCount', 'placement', 'footer', 'header', 'noResultsMessage', 'className'], function (_i, name) { if (option[name] != null) { self[name] = option[name]; } }); this._bindEvents(element); dropdownViews[this.id] = this; } $.extend(Dropdown, { // Class methods // ------------- createElement: function (option) { var $parent = option.appendTo; if (!($parent instanceof $)) { $parent = $($parent); } var $el = $('<ul></ul>') .addClass('dropdown-menu textcomplete-dropdown') .attr('id', 'textcomplete-dropdown-' + option._oid) .css({ display: 'none', left: 0, position: 'absolute', zIndex: option.zIndex }) .appendTo($parent); return $el; } }); $.extend(Dropdown.prototype, { // Public properties // ----------------- $el: null, // jQuery object of ul.dropdown-menu element. $inputEl: null, // jQuery object of target textarea. completer: null, footer: null, header: null, id: null, maxCount: 10, placement: '', shown: false, data: [], // Shown zipped data. className: '', // Public methods // -------------- destroy: function () { // Don't remove $el because it may be shared by several textcompletes. this.deactivate(); this.$el.off('.' + this.id); this.$inputEl.off('.' + this.id); this.clear(); this.$el = this.$inputEl = this.completer = null; delete dropdownViews[this.id] }, render: function (zippedData) { var contentsHtml = this._buildContents(zippedData); var unzippedData = $.map(this.data, function (d) { return d.value; }); if (this.data.length) { this._renderHeader(unzippedData); this._renderFooter(unzippedData); if (contentsHtml) { this._renderContents(contentsHtml); this._fitToBottom(); this._activateIndexedItem(); } this._setScroll(); } else if (this.noResultsMessage) { this._renderNoResultsMessage(unzippedData); } else if (this.shown) { this.deactivate(); } }, setPosition: function (pos) { this.$el.css(this._applyPlacement(pos)); // Make the dropdown fixed if the input is also fixed // This can't be done during init, as textcomplete may be used on multiple elements on the same page // Because the same dropdown is reused behind the scenes, we need to recheck every time the dropdown is showed var position = 'absolute'; // Check if input or one of its parents has positioning we need to care about this.$inputEl.add(this.$inputEl.parents()).each(function() { if($(this).css('position') === 'absolute') // The element has absolute positioning, so it's all OK return false; if($(this).css('position') === 'fixed') { position = 'fixed'; return false; } }); this.$el.css({ position: position }); // Update positioning return this; }, clear: function () { this.$el.html(''); this.data = []; this._index = 0; this._$header = this._$footer = this._$noResultsMessage = null; }, activate: function () { if (!this.shown) { this.clear(); this.$el.show(); if (this.className) { this.$el.addClass(this.className); } this.completer.fire('textComplete:show'); this.shown = true; } return this; }, deactivate: function () { if (this.shown) { this.$el.hide(); if (this.className) { this.$el.removeClass(this.className); } this.completer.fire('textComplete:hide'); this.shown = false; } return this; }, isUp: function (e) { return e.keyCode === 38 || (e.ctrlKey && e.keyCode === 80); // UP, Ctrl-P }, isDown: function (e) { return e.keyCode === 40 || (e.ctrlKey && e.keyCode === 78); // DOWN, Ctrl-N }, isEnter: function (e) { var modifiers = e.ctrlKey || e.altKey || e.metaKey || e.shiftKey; return !modifiers && (e.keyCode === 13 || e.keyCode === 9 || (this.option.completeOnSpace === true && e.keyCode === 32)) // ENTER, TAB }, isPageup: function (e) { return e.keyCode === 33; // PAGEUP }, isPagedown: function (e) { return e.keyCode === 34; // PAGEDOWN }, isEscape: function (e) { return e.keyCode === 27; // ESCAPE }, // Private properties // ------------------ _data: null, // Currently shown zipped data. _index: null, _$header: null, _$noResultsMessage: null, _$footer: null, // Private methods // --------------- _bindEvents: function () { this.$el.on('mousedown.' + this.id, '.textcomplete-item', $.proxy(this._onClick, this)); this.$el.on('touchstart.' + this.id, '.textcomplete-item', $.proxy(this._onClick, this)); this.$el.on('mouseover.' + this.id, '.textcomplete-item', $.proxy(this._onMouseover, this)); this.$inputEl.on('keydown.' + this.id, $.proxy(this._onKeydown, this)); }, _onClick: function (e) { var $el = $(e.target); e.preventDefault(); e.originalEvent.keepTextCompleteDropdown = this.id; if (!$el.hasClass('textcomplete-item')) { $el = $el.closest('.textcomplete-item'); } var datum = this.data[parseInt($el.data('index'), 10)]; this.completer.select(datum.value, datum.strategy, e); var self = this; // Deactive at next tick to allow other event handlers to know whether // the dropdown has been shown or not. setTimeout(function () { self.deactivate(); if (e.type === 'touchstart') { self.$inputEl.focus(); } }, 0); }, // Activate hovered item. _onMouseover: function (e) { var $el = $(e.target); e.preventDefault(); if (!$el.hasClass('textcomplete-item')) { $el = $el.closest('.textcomplete-item'); } this._index = parseInt($el.data('index'), 10); this._activateIndexedItem(); }, _onKeydown: function (e) { if (!this.shown) { return; } var command; if ($.isFunction(this.option.onKeydown)) { command = this.option.onKeydown(e, commands); } if (command == null) { command = this._defaultKeydown(e); } switch (command) { case commands.KEY_UP: e.preventDefault(); this._up(); break; case commands.KEY_DOWN: e.preventDefault(); this._down(); break; case commands.KEY_ENTER: e.preventDefault(); this._enter(e); break; case commands.KEY_PAGEUP: e.preventDefault(); this._pageup(); break; case commands.KEY_PAGEDOWN: e.preventDefault(); this._pagedown(); break; case commands.KEY_ESCAPE: e.preventDefault(); this.deactivate(); break; } }, _defaultKeydown: function (e) { if (this.isUp(e)) { return commands.KEY_UP; } else if (this.isDown(e)) { return commands.KEY_DOWN; } else if (this.isEnter(e)) { return commands.KEY_ENTER; } else if (this.isPageup(e)) { return commands.KEY_PAGEUP; } else if (this.isPagedown(e)) { return commands.KEY_PAGEDOWN; } else if (this.isEscape(e)) { return commands.KEY_ESCAPE; } }, _up: function () { if (this._index === 0) { this._index = this.data.length - 1; } else { this._index -= 1; } this._activateIndexedItem(); this._setScroll(); }, _down: function () { if (this._index === this.data.length - 1) { this._index = 0; } else { this._index += 1; } this._activateIndexedItem(); this._setScroll(); }, _enter: function (e) { var datum = this.data[parseInt(this._getActiveElement().data('index'), 10)]; this.completer.select(datum.value, datum.strategy, e); this.deactivate(); }, _pageup: function () { var target = 0; var threshold = this._getActiveElement().position().top - this.$el.innerHeight(); this.$el.children().each(function (i) { if ($(this).position().top + $(this).outerHeight() > threshold) { target = i; return false; } }); this._index = target; this._activateIndexedItem(); this._setScroll(); }, _pagedown: function () { var target = this.data.length - 1; var threshold = this._getActiveElement().position().top + this.$el.innerHeight(); this.$el.children().each(function (i) { if ($(this).position().top > threshold) { target = i; return false } }); this._index = target; this._activateIndexedItem(); this._setScroll(); }, _activateIndexedItem: function () { this.$el.find('.textcomplete-item.active').removeClass('active'); this._getActiveElement().addClass('active'); }, _getActiveElement: function () { return this.$el.children('.textcomplete-item:nth(' + this._index + ')'); }, _setScroll: function () { var $activeEl = this._getActiveElement(); var itemTop = $activeEl.position().top; var itemHeight = $activeEl.outerHeight(); var visibleHeight = this.$el.innerHeight(); var visibleTop = this.$el.scrollTop(); if (this._index === 0 || this._index == this.data.length - 1 || itemTop < 0) { this.$el.scrollTop(itemTop + visibleTop); } else if (itemTop + itemHeight > visibleHeight) { this.$el.scrollTop(itemTop + itemHeight + visibleTop - visibleHeight); } }, _buildContents: function (zippedData) { var datum, i, index; var html = ''; for (i = 0; i < zippedData.length; i++) { if (this.data.length === this.maxCount) break; datum = zippedData[i]; if (include(this.data, datum)) { continue; } index = this.data.length; this.data.push(datum); html += '<li class="textcomplete-item" data-index="' + index + '"><a>'; html += datum.strategy.template(datum.value, datum.term); html += '</a></li>'; } return html; }, _renderHeader: function (unzippedData) { if (this.header) { if (!this._$header) { this._$header = $('<li class="textcomplete-header"></li>').prependTo(this.$el); } var html = $.isFunction(this.header) ? this.header(unzippedData) : this.header; this._$header.html(html); } }, _renderFooter: function (unzippedData) { if (this.footer) { if (!this._$footer) { this._$footer = $('<li class="textcomplete-footer"></li>').appendTo(this.$el); } var html = $.isFunction(this.footer) ? this.footer(unzippedData) : this.footer; this._$footer.html(html); } }, _renderNoResultsMessage: function (unzippedData) { if (this.noResultsMessage) { if (!this._$noResultsMessage) { this._$noResultsMessage = $('<li class="textcomplete-no-results-message"></li>').appendTo(this.$el); } var html = $.isFunction(this.noResultsMessage) ? this.noResultsMessage(unzippedData) : this.noResultsMessage; this._$noResultsMessage.html(html); } }, _renderContents: function (html) { if (this._$footer) { this._$footer.before(html); } else { this.$el.append(html); } }, _fitToBottom: function() { var windowScrollBottom = $window.scrollTop() + $window.height(); var height = this.$el.height(); if ((this.$el.position().top + height) > windowScrollBottom) { this.$el.offset({top: windowScrollBottom - height}); } }, _applyPlacement: function (position) { // If the 'placement' option set to 'top', move the position above the element. if (this.placement.indexOf('top') !== -1) { // Overwrite the position object to set the 'bottom' property instead of the top. position = { top: 'auto', bottom: this.$el.parent().height() - position.top + position.lineHeight, left: position.left }; } else { position.bottom = 'auto'; delete position.lineHeight; } if (this.placement.indexOf('absleft') !== -1) { position.left = 0; } else if (this.placement.indexOf('absright') !== -1) { position.right = 0; position.left = 'auto'; } return position; } }); $.fn.textcomplete.Dropdown = Dropdown; $.extend($.fn.textcomplete, commands); }(jQuery); +function ($) { 'use strict'; // Memoize a search function. var memoize = function (func) { var memo = {}; return function (term, callback) { if (memo[term]) { callback(memo[term]); } else { func.call(this, term, function (data) { memo[term] = (memo[term] || []).concat(data); callback.apply(null, arguments); }); } }; }; function Strategy(options) { $.extend(this, options); if (this.cache) { this.search = memoize(this.search); } } Strategy.parse = function (optionsArray) { return $.map(optionsArray, function (options) { return new Strategy(options); }); }; $.extend(Strategy.prototype, { // Public properties // ----------------- // Required match: null, replace: null, search: null, // Optional cache: false, context: function () { return true; }, index: 2, template: function (obj) { return obj; }, idProperty: null }); $.fn.textcomplete.Strategy = Strategy; }(jQuery); +function ($) { 'use strict'; var now = Date.now || function () { return new Date().getTime(); }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // `wait` msec. // // This utility function was originally implemented at Underscore.js. var debounce = function (func, wait) { var timeout, args, context, timestamp, result; var later = function () { var last = now() - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; result = func.apply(context, args); context = args = null; } }; return function () { context = this; args = arguments; timestamp = now(); if (!timeout) { timeout = setTimeout(later, wait); } return result; }; }; function Adapter () {} $.extend(Adapter.prototype, { // Public properties // ----------------- id: null, // Identity. completer: null, // Completer object which creates it. el: null, // Textarea element. $el: null, // jQuery object of the textarea. option: null, // Public methods // -------------- initialize: function (element, completer, option) { this.el = element; this.$el = $(element); this.id = completer.id + this.constructor.name; this.completer = completer; this.option = option; if (this.option.debounce) { this._onKeyup = debounce(this._onKeyup, this.option.debounce); } this._bindEvents(); }, destroy: function () { this.$el.off('.' + this.id); // Remove all event handlers. this.$el = this.el = this.completer = null; }, // Update the element with the given value and strategy. // // value - The selected object. It is one of the item of the array // which was callbacked from the search function. // strategy - The Strategy associated with the selected value. select: function (/* value, strategy */) { throw new Error('Not implemented'); }, // Returns the caret's relative coordinates from body's left top corner. // // FIXME: Calculate the left top corner of `this.option.appendTo` element. getCaretPosition: function () { var position = this._getCaretRelativePosition(); var offset = this.$el.offset(); position.top += offset.top; position.left += offset.left; return position; }, // Focus on the element. focus: function () { this.$el.focus(); }, // Private methods // --------------- _bindEvents: function () { this.$el.on('keyup.' + this.id, $.proxy(this._onKeyup, this)); }, _onKeyup: function (e) { if (this._skipSearch(e)) { return; } this.completer.trigger(this.getTextFromHeadToCaret(), true); }, // Suppress searching if it returns true. _skipSearch: function (clickEvent) { switch (clickEvent.keyCode) { case 13: // ENTER case 40: // DOWN case 38: // UP return true; } if (clickEvent.ctrlKey) switch (clickEvent.keyCode) { case 78: // Ctrl-N case 80: // Ctrl-P return true; } } }); $.fn.textcomplete.Adapter = Adapter; }(jQuery); +function ($) { 'use strict'; // Textarea adapter // ================ // // Managing a textarea. It doesn't know a Dropdown. function Textarea(element, completer, option) { this.initialize(element, completer, option); } Textarea.DIV_PROPERTIES = { left: -9999, position: 'absolute', top: 0, whiteSpace: 'pre-wrap' } Textarea.COPY_PROPERTIES = [ 'border-width', 'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight', 'height', 'letter-spacing', 'word-spacing', 'line-height', 'text-decoration', 'text-align', 'width', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left', 'border-style', 'box-sizing', 'tab-size' ]; $.extend(Textarea.prototype, $.fn.textcomplete.Adapter.prototype, { // Public methods // -------------- // Update the textarea with the given value and strategy. select: function (value, strategy, e) { var pre = this.getTextFromHeadToCaret(); var post = this.el.value.substring(this.el.selectionEnd); var newSubstr = strategy.replace(value, e); if ($.isArray(newSubstr)) { post = newSubstr[1] + post; newSubstr = newSubstr[0]; } pre = pre.replace(strategy.match, newSubstr); this.$el.val(pre + post); this.el.selectionStart = this.el.selectionEnd = pre.length; }, // Private methods // --------------- // Returns the caret's relative coordinates from textarea's left top corner. // // Browser native API does not provide the way to know the position of // caret in pixels, so that here we use a kind of hack to accomplish // the aim. First of all it puts a dummy div element and completely copies // the textarea's style to the element, then it inserts the text and a // span element into the textarea. // Consequently, the span element's position is the thing what we want. _getCaretRelativePosition: function () { var dummyDiv = $('<div></div>').css(this._copyCss()) .text(this.getTextFromHeadToCaret()); var span = $('<span></span>').text('.').appendTo(dummyDiv); this.$el.before(dummyDiv); var position = span.position(); position.top += span.height() - this.$el.scrollTop(); position.lineHeight = span.height(); dummyDiv.remove(); return position; }, _copyCss: function () { return $.extend({ // Set 'scroll' if a scrollbar is being shown; otherwise 'auto'. overflow: this.el.scrollHeight > this.el.offsetHeight ? 'scroll' : 'auto' }, Textarea.DIV_PROPERTIES, this._getStyles()); }, _getStyles: (function ($) { var color = $('<div></div>').css(['color']).color; if (typeof color !== 'undefined') { return function () { return this.$el.css(Textarea.COPY_PROPERTIES); }; } else { // jQuery < 1.8 return function () { var $el = this.$el; var styles = {}; $.each(Textarea.COPY_PROPERTIES, function (i, property) { styles[property] = $el.css(property); }); return styles; }; } })($), getTextFromHeadToCaret: function () { return this.el.value.substring(0, this.el.selectionEnd); } }); $.fn.textcomplete.Textarea = Textarea; }(jQuery); +function ($) { 'use strict'; var sentinelChar = '吶'; function IETextarea(element, completer, option) { this.initialize(element, completer, option); $('<span>' + sentinelChar + '</span>').css({ position: 'absolute', top: -9999, left: -9999 }).insertBefore(element); } $.extend(IETextarea.prototype, $.fn.textcomplete.Textarea.prototype, { // Public methods // -------------- select: function (value, strategy, e) { var pre = this.getTextFromHeadToCaret(); var post = this.el.value.substring(pre.length); var newSubstr = strategy.replace(value, e); if ($.isArray(newSubstr)) { post = newSubstr[1] + post; newSubstr = newSubstr[0]; } pre = pre.replace(strategy.match, newSubstr); this.$el.val(pre + post); this.el.focus(); var range = this.el.createTextRange(); range.collapse(true); range.moveEnd('character', pre.length); range.moveStart('character', pre.length); range.select(); }, getTextFromHeadToCaret: function () { this.el.focus(); var range = document.selection.createRange(); range.moveStart('character', -this.el.value.length); var arr = range.text.split(sentinelChar) return arr.length === 1 ? arr[0] : arr[1]; } }); $.fn.textcomplete.IETextarea = IETextarea; }(jQuery); // NOTE: TextComplete plugin has contenteditable support but it does not work // fine especially on old IEs. // Any pull requests are REALLY welcome. +function ($) { 'use strict'; // ContentEditable adapter // ======================= // // Adapter for contenteditable elements. function ContentEditable (element, completer, option) { this.initialize(element, completer, option); } $.extend(ContentEditable.prototype, $.fn.textcomplete.Adapter.prototype, { // Public methods // -------------- // Update the content with the given value and strategy. // When an dropdown item is selected, it is executed. select: function (value, strategy, e) { var pre = this.getTextFromHeadToCaret(); var sel = window.getSelection() var range = sel.getRangeAt(0); var selection = range.cloneRange(); selection.selectNodeContents(range.startContainer); var content = selection.toString(); var post = content.substring(range.startOffset); var newSubstr = strategy.replace(value, e); if ($.isArray(newSubstr)) { post = newSubstr[1] + post; newSubstr = newSubstr[0]; } pre = pre.replace(strategy.match, newSubstr); range.selectNodeContents(range.startContainer); range.deleteContents(); var node = document.createTextNode(pre + post); range.insertNode(node); range.setStart(node, pre.length); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); }, // Private methods // --------------- // Returns the caret's relative position from the contenteditable's // left top corner. // // Examples // // this._getCaretRelativePosition() // //=> { top: 18, left: 200, lineHeight: 16 } // // Dropdown's position will be decided using the result. _getCaretRelativePosition: function () { var range = window.getSelection().getRangeAt(0).cloneRange(); var node = document.createElement('span'); range.insertNode(node); range.selectNodeContents(node); range.deleteContents(); var $node = $(node); var position = $node.offset(); position.left -= this.$el.offset().left; position.top += $node.height() - this.$el.offset().top; position.lineHeight = $node.height(); $node.remove(); return position; }, // Returns the string between the first character and the caret. // Completer will be triggered with the result for start autocompleting. // // Example // // // Suppose the html is '<b>hello</b> wor|ld' and | is the caret. // this.getTextFromHeadToCaret() // // => ' wor' // not '<b>hello</b> wor' getTextFromHeadToCaret: function () { var range = window.getSelection().getRangeAt(0); var selection = range.cloneRange(); selection.selectNodeContents(range.startContainer); return selection.toString().substring(0, range.startOffset); } }); $.fn.textcomplete.ContentEditable = ContentEditable; }(jQuery); return jQuery; }));
tpphu/jquery-textcomplete
dist/jquery.textcomplete.js
JavaScript
mit
36,737
/*! * * ZingTouch v1.0.5 * Author: ZingChart http://zingchart.com * License: MIT */ /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _ZingTouch = __webpack_require__(1); var _ZingTouch2 = _interopRequireDefault(_ZingTouch); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } window.ZingTouch = _ZingTouch2.default; /** * @file main.js * Main file to setup event listeners on the document, * and to expose the ZingTouch object */ /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _Region2 = __webpack_require__(2); var _Region3 = _interopRequireDefault(_Region2); var _Gesture = __webpack_require__(4); var _Gesture2 = _interopRequireDefault(_Gesture); var _Expand = __webpack_require__(10); var _Expand2 = _interopRequireDefault(_Expand); var _Pan = __webpack_require__(12); var _Pan2 = _interopRequireDefault(_Pan); var _Pinch = __webpack_require__(13); var _Pinch2 = _interopRequireDefault(_Pinch); var _Rotate = __webpack_require__(14); var _Rotate2 = _interopRequireDefault(_Rotate); var _Swipe = __webpack_require__(15); var _Swipe2 = _interopRequireDefault(_Swipe); var _Tap = __webpack_require__(16); var _Tap2 = _interopRequireDefault(_Tap); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The global API interface for ZingTouch. Contains a constructor for the * Region Object, and constructors for each predefined Gesture. * @type {Object} * @namespace ZingTouch */ /** * @file ZingTouch.js * Main object containing API methods and Gesture constructors */ var ZingTouch = { _regions: [], // Constructors Gesture: _Gesture2.default, Expand: _Expand2.default, Pan: _Pan2.default, Pinch: _Pinch2.default, Rotate: _Rotate2.default, Swipe: _Swipe2.default, Tap: _Tap2.default, Region: function Region(element, capture, preventDefault) { var id = ZingTouch._regions.length; var region = new _Region3.default(element, capture, preventDefault, id); ZingTouch._regions.push(region); return region; } }; exports.default = ZingTouch; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** * @file Region.js */ var _Binder = __webpack_require__(3); var _Binder2 = _interopRequireDefault(_Binder); var _Gesture = __webpack_require__(4); var _Gesture2 = _interopRequireDefault(_Gesture); var _arbiter = __webpack_require__(6); var _arbiter2 = _interopRequireDefault(_arbiter); var _State = __webpack_require__(9); var _State2 = _interopRequireDefault(_State); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Allows the user to specify a region to capture all events to feed ZingTouch * into. This can be as narrow as the element itself, or as big as the document * itself. The more specific an area, the better performant the overall * application will perform. Contains API methods to bind/unbind specific * elements to corresponding gestures. Also contains the ability to * register/unregister new gestures. * @class Region */ var Region = function () { /** * Constructor function for the Region class. * @param {Element} element - The element to capture all * window events in that region to feed into ZingTouch. * @param {boolean} [capture=false] - Whether the region listens for * captures or bubbles. * @param {boolean} [preventDefault=true] - Whether the default browser * functionality should be disabled; * @param {Number} id - The id of the region, assigned by the ZingTouch object */ function Region(element, capture, preventDefault, id) { var _this = this; _classCallCheck(this, Region); /** * The identifier for the Region. This is assigned by the ZingTouch object * and is used to hash gesture id for uniqueness. * @type {Number} */ this.id = id; /** * The element being bound to. * @type {Element} */ this.element = element; /** * Whether the region listens for captures or bubbles. * @type {boolean} */ this.capture = typeof capture !== 'undefined' ? capture : false; /** * Boolean to disable browser functionality such as scrolling and zooming * over the region * @type {boolean} */ this.preventDefault = typeof preventDefault !== 'undefined' ? preventDefault : true; /** * The internal state object for a Region. * Keeps track of registered gestures, inputs, and events. * @type {State} */ this.state = new _State2.default(id); var eventNames = []; if (window.PointerEvent && !window.TouchEvent) { eventNames = ['pointerdown', 'pointermove', 'pointerup']; } else { eventNames = ['mousedown', 'mousemove', 'mouseup', 'touchstart', 'touchmove', 'touchend']; } // Bind detected browser events to the region element. eventNames.map(function (name) { element.addEventListener(name, function (e) { (0, _arbiter2.default)(e, _this); }, _this.capture); }); } /** * Bind an element to a registered/unregistered gesture with * multiple function signatures. * @example * bind(element) - chainable * @example * bind(element, gesture, handler, [capture]) * @param {Element} element - The element object. * @param {String|Object} [gesture] - Gesture key, or a Gesture object. * @param {Function} [handler] - The function to execute when an event is * emitted. * @param {Boolean} [capture] - capture/bubble * @param {Boolean} [bindOnce = false] - Option to bind once and * only emit the event once. * @return {Object} - a chainable object that has the same function as bind. */ _createClass(Region, [{ key: 'bind', value: function bind(element, gesture, handler, capture, bindOnce) { if (!element || element && !element.tagName) { throw 'Bind must contain an element'; } bindOnce = typeof bindOnce !== 'undefined' ? bindOnce : false; if (!gesture) { return new _Binder2.default(element, bindOnce, this.state); } else { this.state.addBinding(element, gesture, handler, capture, bindOnce); } } /** * Bind an element and sets up actions to remove the binding once * it has been emitted for the first time. * 1. bind(element) - chainable * 2. bind(element, gesture, handler, [capture]) * @param {Element} element - The element object. * @param {String|Object} gesture - Gesture key, or a Gesture object. * @param {Function} handler - The function to execute when an * event is emitted. * @param {Boolean} capture - capture/bubble * @return {Object} - a chainable object that has the same function as bind. */ }, { key: 'bindOnce', value: function bindOnce(element, gesture, handler, capture) { this.bind(element, gesture, handler, capture, true); } /** * Unbinds an element from either the specified gesture * or all if no element is specified. * @param {Element} element -The element to remove. * @param {String | Object} [gesture] - A String representing the gesture, * or the actual object being used. * @return {Array} - An array of Bindings that were unbound to the element; */ }, { key: 'unbind', value: function unbind(element, gesture) { var _this2 = this; var bindings = this.state.retrieveBindingsByElement(element); var unbound = []; bindings.forEach(function (binding) { if (gesture) { if (typeof gesture === 'string' && _this2.state.registeredGestures[gesture]) { var registeredGesture = _this2.state.registeredGestures[gesture]; if (registeredGesture.id === binding.gesture.id) { element.removeEventListener(binding.gesture.getId(), binding.handler, binding.capture); unbound.push(binding); } } } else { element.removeEventListener(binding.gesture.getId(), binding.handler, binding.capture); unbound.push(binding); } }); return unbound; } /* unbind*/ /** * Registers a new gesture with an assigned key * @param {String} key - The key used to register an element to that gesture * @param {Gesture} gesture - A gesture object */ }, { key: 'register', value: function register(key, gesture) { if (typeof key !== 'string') { throw new Error('Parameter key is an invalid string'); } if (!gesture instanceof _Gesture2.default) { throw new Error('Parameter gesture is an invalid Gesture object'); } gesture.setType(key); this.state.registerGesture(gesture, key); } /* register*/ /** * Un-registers a gesture from the Region's state such that * it is no longer emittable. * Unbinds all events that were registered with the type. * @param {String|Object} key - Gesture key that was used to * register the object * @return {Object} - The Gesture object that was unregistered * or null if it could not be found. */ }, { key: 'unregister', value: function unregister(key) { this.state.bindings.forEach(function (binding) { if (binding.gesture.getType() === key) { binding.element.removeEventListener(binding.gesture.getId(), binding.handler, binding.capture); } }); var registeredGesture = this.state.registeredGestures[key]; delete this.state.registeredGestures[key]; return registeredGesture; } }]); return Region; }(); exports.default = Region; /***/ }, /* 3 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * @file Binder.js */ /** * A chainable object that contains a single element to be bound upon. * Called from ZingTouch.bind(), and is used to chain over gesture callbacks. * @class */ var Binder = /** * Constructor function for the Binder class. * @param {Element} element - The element to bind gestures to. * @param {Boolean} bindOnce - Option to bind once and only emit * the event once. * @param {Object} state - The state of the Region that is being bound to. * @return {Object} - Returns 'this' to be chained over and over again. */ function Binder(element, bindOnce, state) { var _this = this; _classCallCheck(this, Binder); /** * The element to bind gestures to. * @type {Element} */ this.element = element; Object.keys(state.registeredGestures).forEach(function (key) { _this[key] = function (handler, capture) { state.addBinding(_this.element, key, handler, capture, bindOnce); return _this; }; }); }; exports.default = Binder; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** * @file Gesture.js * Contains the Gesture class */ var _util = __webpack_require__(5); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * The Gesture class that all gestures inherit from. */ var Gesture = function () { /** * Constructor function for the Gesture class. * @class Gesture */ function Gesture() { _classCallCheck(this, Gesture); /** * The generic string type of gesture ('expand'|'pan'|'pinch'| * 'rotate'|'swipe'|'tap'). * @type {String} */ this.type = null; /** * The unique identifier for each gesture determined at bind time by the * state object. This allows for distinctions across instance variables of * Gestures that are created on the fly (e.g. Tap-1, Tap-2, etc). * @type {String|null} */ this.id = null; } /** * Set the type of the gesture to be called during an event * @param {String} type - The unique identifier of the gesture being created. */ _createClass(Gesture, [{ key: 'setType', value: function setType(type) { this.type = type; } /** * getType() - Returns the generic type of the gesture * @return {String} - The type of gesture */ }, { key: 'getType', value: function getType() { return this.type; } /** * Set the id of the gesture to be called during an event * @param {String} id - The unique identifier of the gesture being created. */ }, { key: 'setId', value: function setId(id) { this.id = id; } /** * Return the id of the event. If the id does not exist, return the type. * @return {String} */ }, { key: 'getId', value: function getId() { return this.id !== null ? this.id : this.type; } /** * Updates internal properties with new ones, only if the properties exist. * @param {Object} object */ }, { key: 'update', value: function update(object) { for (var key in object) { if (this[key]) { this[key] = object[key]; } } } /** * start() - Event hook for the start of a gesture * @param {Array} inputs - The array of Inputs on the screen * @param {Object} state - The state object of the current region. * @param {Element} element - The element associated to the binding. * @return {null|Object} - Default of null */ }, { key: 'start', value: function start(inputs, state, element) { return null; } /** * move() - Event hook for the move of a gesture * @param {Array} inputs - The array of Inputs on the screen * @param {Object} state - The state object of the current region. * @param {Element} element - The element associated to the binding. * @return {null|Object} - Default of null */ }, { key: 'move', value: function move(inputs, state, element) { return null; } /** * end() - Event hook for the move of a gesture * @param {Array} inputs - The array of Inputs on the screen * @return {null|Object} - Default of null */ }, { key: 'end', value: function end(inputs) { return null; } /** * isValid() - Pre-checks to ensure the invariants of a gesture are satisfied. * @param {Array} inputs - The array of Inputs on the screen * @param {Object} state - The state object of the current region. * @param {Element} element - The element associated to the binding. * @return {boolean} - If the gesture is valid */ }, { key: 'isValid', value: function isValid(inputs, state, element) { var valid = true; // Checks to see if all touches originated from within the target element. if (inputs.length > 1) { inputs.forEach(function (input) { if (!_util2.default.isInside(input.initial.x, input.initial.y, element)) { valid = false; } }); } return valid; } }]); return Gesture; }(); exports.default = Gesture; /***/ }, /* 5 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * @file util.js * Various accessor and mutator functions to handle state and validation. */ var CIRCLE_DEGREES = 360; var HALF_CIRCLE_DEGREES = 180; /** * Contains generic helper functions * @type {Object} * @namespace util */ var util = { /** * Normalizes window events to be either of type start, move, or end. * @param {String} type - The event type emitted by the browser * @return {null|String} - The normalized event, or null if it is an * event not predetermined. */ normalizeEvent: function normalizeEvent(type) { switch (type) { case 'mousedown': case 'touchstart': case 'pointerdown': return 'start'; case 'mousemove': case 'touchmove': case 'pointermove': return 'move'; case 'mouseup': case 'touchend': case 'pointerup': return 'end'; default: return null; } }, /* normalizeEvent*/ /** * Determines if the current and previous coordinates are within or * up to a certain tolerance. * @param {Number} currentX - Current event's x coordinate * @param {Number} currentY - Current event's y coordinate * @param {Number} previousX - Previous event's x coordinate * @param {Number} previousY - Previous event's y coordinate * @param {Number} tolerance - The tolerance in pixel value. * @return {boolean} - true if the current coordinates are * within the tolerance, false otherwise */ isWithin: function isWithin(currentX, currentY, previousX, previousY, tolerance) { return Math.abs(currentY - previousY) <= tolerance && Math.abs(currentX - previousX) <= tolerance; }, /* isWithin*/ /** * Calculates the distance between two points. * @param {Number} x0 * @param {Number} x1 * @param {Number} y0 * @param {Number} y1 * @return {number} The numerical value between two points */ distanceBetweenTwoPoints: function distanceBetweenTwoPoints(x0, x1, y0, y1) { var dist = Math.sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)); return Math.round(dist * 100) / 100; }, /** * Calculates the midpoint coordinates between two points. * @param {Number} x0 * @param {Number} x1 * @param {Number} y0 * @param {Number} y1 * @return {Object} The coordinates of the midpoint. */ getMidpoint: function getMidpoint(x0, x1, y0, y1) { return { x: (x0 + x1) / 2, y: (y0 + y1) / 2 }; }, /** * Calculates the angle between the projection and an origin point. * | (projectionX,projectionY) * | /° * | / * | / * | / θ * | /__________ * ° (originX, originY) * @param {number} originX * @param {number} originY * @param {number} projectionX * @param {number} projectionY * @return {number} - Degree along the unit circle where the project lies */ getAngle: function getAngle(originX, originY, projectionX, projectionY) { var angle = Math.atan2(projectionY - originY, projectionX - originX) * (HALF_CIRCLE_DEGREES / Math.PI); return CIRCLE_DEGREES - (angle < 0 ? CIRCLE_DEGREES + angle : angle); }, /** * Calculates the angular distance in degrees between two angles * along the unit circle * @param {number} start - The starting point in degrees * @param {number} end - The ending point in degrees * @return {number} The number of degrees between the * starting point and ending point. Negative degrees denote a clockwise * direction, and positive a counter-clockwise direction. */ getAngularDistance: function getAngularDistance(start, end) { var angle = (end - start) % CIRCLE_DEGREES; var sign = angle < 0 ? 1 : -1; angle = Math.abs(angle); return angle > HALF_CIRCLE_DEGREES ? sign * (CIRCLE_DEGREES - angle) : sign * angle; }, /** * Calculates the velocity of pixel/milliseconds between two points * @param {Number} startX * @param {Number} startY * @param {Number} startTime * @param {Number} endX * @param {Number} endY * @param {Number} endTime * @return {Number} velocity of px/time */ getVelocity: function getVelocity(startX, startY, startTime, endX, endY, endTime) { var distance = this.distanceBetweenTwoPoints(startX, endX, startY, endY); return distance / (endTime - startTime); }, /** * Returns the farthest right input * @param {Array} inputs * @return {Object} */ getRightMostInput: function getRightMostInput(inputs) { var rightMost = null; var distance = Number.MIN_VALUE; inputs.forEach(function (input) { if (input.initial.x > distance) { rightMost = input; } }); return rightMost; }, /** * Determines is the value is an integer and not a floating point * @param {Mixed} value * @return {boolean} */ isInteger: function isInteger(value) { return typeof value === 'number' && value % 1 === 0; }, /** * Determines if the x,y position of the input is within then target. * @param {Number} x -clientX * @param {Number} y -clientY * @param {Element} target * @return {Boolean} */ isInside: function isInside(x, y, target) { var rect = target.getBoundingClientRect(); return x > rect.left && x < rect.left + rect.width && y > rect.top && y < rect.top + rect.height; }, /** * Polyfill for event.propagationPath * @param {Event} event * @return {Array} */ getPropagationPath: function getPropagationPath(event) { if (event.path) { return event.path; } else { var path = []; var node = event.target; while (node != document) { path.push(node); node = node.parentNode; } return path; } }, /** * Retrieve the index inside the path array * @param {Array} path * @param {Element} element * @return {Element} */ getPathIndex: function getPathIndex(path, element) { var index = path.length; path.forEach(function (obj, i) { if (obj === element) { index = i; } }); return index; }, setMSPreventDefault: function setMSPreventDefault(element) { element.style['-ms-content-zooming'] = 'none'; element.style['touch-action'] = 'none'; }, removeMSPreventDefault: function removeMSPreventDefault(element) { element.style['-ms-content-zooming'] = ''; element.style['touch-action'] = ''; } }; exports.default = util; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _dispatcher = __webpack_require__(7); var _dispatcher2 = _interopRequireDefault(_dispatcher); var _interpreter = __webpack_require__(8); var _interpreter2 = _interopRequireDefault(_interpreter); var _util = __webpack_require__(5); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Function that handles event flow, negotiating with the interpreter, * and dispatcher. * 1. Receiving all touch events in the window. * 2. Determining which gestures are linked to the target element. * 3. Negotiating with the Interpreter what event should occur. * 4. Sending events to the dispatcher to emit events to the target. * @param {Event} event - The event emitted from the window object. * @param {Object} region - The region object of the current listener. */ function arbiter(event, region) { var state = region.state; /* Return if a gesture is not in progress and won't be. Also catches the case where a previous event is in a partial state (2 finger pan, waits for both inputs to reach touchend) */ if (state.inputs.length === 0 && _util2.default.normalizeEvent(event.type) !== 'start') { return; } /* Check for 'stale' or events that lost focus (e.g. a pan goes off screen/off region.) Does not affect mobile devices. */ if (typeof event.buttons !== 'undefined' && _util2.default.normalizeEvent(event.type) !== 'end' && event.buttons === 0) { state.resetInputs(); return; } // Update the state with the new events. If the event is stopped, return; if (!state.updateInputs(event, region.element)) { return; } // Retrieve the initial target from any one of the inputs var bindings = state.retrieveBindingsByInitialPos(); if (bindings.length > 0) { (function () { if (region.preventDefault) { _util2.default.setMSPreventDefault(region.element); event.preventDefault ? event.preventDefault() : event.returnValue = false; } else { _util2.default.removeMSPreventDefault(region.element); } var toBeDispatched = {}; var gestures = (0, _interpreter2.default)(bindings, event, state); /* Determine the deepest path index to emit the event from, to avoid duplicate events being fired. */ gestures.forEach(function (gesture) { var id = gesture.binding.gesture.id; if (toBeDispatched[id]) { var path = _util2.default.getPropagationPath(event); if (_util2.default.getPathIndex(path, gesture.binding.element) < _util2.default.getPathIndex(path, toBeDispatched[id].binding.element)) { toBeDispatched[id] = gesture; } } else { toBeDispatched[id] = gesture; } }); Object.keys(toBeDispatched).forEach(function (index) { var gesture = toBeDispatched[index]; (0, _dispatcher2.default)(gesture.binding, gesture.data, gesture.events); }); })(); } var endCount = 0; state.inputs.forEach(function (input) { if (input.getCurrentEventType() === 'end') { endCount++; } }); if (endCount === state.inputs.length) { state.resetInputs(); } } /** * @file arbiter.js * Contains logic for the dispatcher */ exports.default = arbiter; /***/ }, /* 7 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * @file dispatcher.js * Contains logic for the dispatcher */ /** * Emits data at the target element if available, and bubbles up from * the target to the parent until the document has been reached. * Called from the arbiter. * @param {Binding} binding - An object of type Binding * @param {Object} data - The metadata computed by the gesture being emitted. * @param {Array} events - An array of ZingEvents * corresponding to the inputs on the screen. */ function dispatcher(binding, data, events) { data.events = events; var newEvent = new CustomEvent(binding.gesture.getId(), { detail: data, bubbles: true, cancelable: true }); emitEvent(binding.element, newEvent, binding); } /** * Emits the new event. Unbinds the event if the event was registered * at bindOnce. * @param {Element} target - Element object to emit the event to. * @param {Event} event - The CustomEvent to emit. * @param {Binding} binding - An object of type Binding */ function emitEvent(target, event, binding) { target.dispatchEvent(event); if (binding.bindOnce) { ZingTouch.unbind(binding.element, binding.gesture.getType()); } } exports.default = dispatcher; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _util = __webpack_require__(5); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Receives an event and an array of Bindings (element -> gesture handler) * to determine what event will be emitted. Called from the arbiter. * @param {Array} bindings - An array containing Binding objects * that associate the element to an event handler. * @param {Object} event - The event emitted from the window. * @param {Object} state - The state object of the current listener. * @return {Object | null} - Returns an object containing a binding and * metadata, or null if a gesture will not be emitted. */ function interpreter(bindings, event, state) { var evType = _util2.default.normalizeEvent(event.type); var candidates = []; bindings.forEach(function (binding) { var result = binding.gesture[evType](state.inputs, state, binding.element); if (result) { (function () { var events = []; state.inputs.forEach(function (input) { events.push(input.current); }); candidates.push({ binding: binding, data: result, events: events }); })(); } }); return candidates; } /** * @file interpreter.js * Contains logic for the interpreter */ exports.default = interpreter; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** * @file State.js */ var _Gesture = __webpack_require__(4); var _Gesture2 = _interopRequireDefault(_Gesture); var _Expand = __webpack_require__(10); var _Expand2 = _interopRequireDefault(_Expand); var _Pan = __webpack_require__(12); var _Pan2 = _interopRequireDefault(_Pan); var _Pinch = __webpack_require__(13); var _Pinch2 = _interopRequireDefault(_Pinch); var _Rotate = __webpack_require__(14); var _Rotate2 = _interopRequireDefault(_Rotate); var _Swipe = __webpack_require__(15); var _Swipe2 = _interopRequireDefault(_Swipe); var _Tap = __webpack_require__(16); var _Tap2 = _interopRequireDefault(_Tap); var _Binding = __webpack_require__(17); var _Binding2 = _interopRequireDefault(_Binding); var _Input = __webpack_require__(18); var _Input2 = _interopRequireDefault(_Input); var _util = __webpack_require__(5); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var DEFAULT_MOUSE_ID = 0; /** * Creates an object related to a Region's state, * and contains helper methods to update and clean up different states. */ var State = function () { /** * Constructor for the State class. * @param {String} regionId - The id the region this state is bound to. */ function State(regionId) { _classCallCheck(this, State); /** * The id for the region this state is bound to. * @type {String} */ this.regionId = regionId; /** * An array of current and recently inactive * Input objects related to a gesture. * @type {Input} */ this.inputs = []; /** * An array of Binding objects; The list of relations between elements, * their gestures, and the handlers. * @type {Binding} */ this.bindings = []; /** * The number of gestures that have been registered with this state * @type {Number} */ this.numGestures = 0; /** * A key/value map all the registered gestures for the listener. * Note: Can only have one gesture registered to one key. * @type {Object} */ this.registeredGestures = {}; this.registerGesture(new _Expand2.default(), 'expand'); this.registerGesture(new _Pan2.default(), 'pan'); this.registerGesture(new _Rotate2.default(), 'rotate'); this.registerGesture(new _Pinch2.default(), 'pinch'); this.registerGesture(new _Swipe2.default(), 'swipe'); this.registerGesture(new _Tap2.default(), 'tap'); } /** * Creates a new binding with the given element and gesture object. * If the gesture object provided is unregistered, it's reference * will be saved in as a binding to be later referenced. * @param {Element} element - The element the gesture is bound to. * @param {String|Object} gesture - Either a name of a registered gesture, * or an unregistered Gesture object. * @param {Function} handler - The function handler to be called * when the event is emitted. Used to bind/unbind. * @param {Boolean} capture - Whether the gesture is to be * detected in the capture of bubble phase. Used to bind/unbind. * @param {Boolean} bindOnce - Option to bind once and * only emit the event once. */ _createClass(State, [{ key: 'addBinding', value: function addBinding(element, gesture, handler, capture, bindOnce) { var boundGesture = void 0; // Error type checking. if (element && typeof element.tagName === 'undefined') { throw new Error('Parameter element is an invalid object.'); } if (typeof handler !== 'function') { throw new Error('Parameter handler is invalid.'); } if (typeof gesture === 'string' && Object.keys(this.registeredGestures).indexOf(gesture) === -1) { throw new Error('Parameter ' + gesture + ' is not a registered gesture'); } else if ((typeof gesture === 'undefined' ? 'undefined' : _typeof(gesture)) === 'object' && !(gesture instanceof _Gesture2.default)) { throw new Error('Parameter for the gesture is not of a Gesture type'); } if (typeof gesture === 'string') { boundGesture = this.registeredGestures[gesture]; } else { boundGesture = gesture; if (boundGesture.id === '') { this.assignGestureId(boundGesture); } } this.bindings.push(new _Binding2.default(element, boundGesture, handler, capture, bindOnce)); element.addEventListener(boundGesture.getId(), handler, capture); } /** * Retrieves the Binding by which an element is associated to. * @param {Element} element - The element to find bindings to. * @return {Array} - An array of Bindings to which that element is bound */ }, { key: 'retrieveBindingsByElement', value: function retrieveBindingsByElement(element) { var matches = []; this.bindings.map(function (binding) { if (binding.element === element) { matches.push(binding); } }); return matches; } /** * Retrieves all bindings based upon the initial X/Y position of the inputs. * e.g. if gesture started on the correct target element, * but diverted away into the correct region, this would still be valid. * @return {Array} - An array of Bindings to which that element is bound */ }, { key: 'retrieveBindingsByInitialPos', value: function retrieveBindingsByInitialPos() { var _this = this; var matches = []; this.bindings.forEach(function (binding) { // Determine if at least one input is in the target element. // They should all be in the region based upon a prior check var inputsInside = _this.inputs.filter(function (input) { return _util2.default.isInside(input.initial.x, input.initial.y, binding.element); }); if (inputsInside.length > 0) { matches.push(binding); } }); return matches; } /** * Updates the inputs with new information based upon a new event being fired. * @param {Event} event - The event being captured. * @param {Element} regionElement - The element where * this current Region is bound to. * @return {boolean} - returns true for a successful update, * false if the event is invalid. */ }, { key: 'updateInputs', value: function updateInputs(event, regionElement) { var identifier = DEFAULT_MOUSE_ID; var eventType = event.touches ? 'TouchEvent' : event.pointerType ? 'PointerEvent' : 'MouseEvent'; switch (eventType) { case 'TouchEvent': for (var index in event.changedTouches) { if (event.changedTouches.hasOwnProperty(index) && _util2.default.isInteger(parseInt(index))) { identifier = event.changedTouches[index].identifier; update(event, this, identifier, regionElement); } } break; case 'PointerEvent': identifier = event.pointerId; update(event, this, identifier, regionElement); break; case 'MouseEvent': default: update(event, this, DEFAULT_MOUSE_ID, regionElement); break; } return true; function update(event, state, identifier, regionElement) { var eventType = _util2.default.normalizeEvent(event.type); var input = findInputById(state.inputs, identifier); // A starting input was not cleaned up properly and still exists. if (eventType === 'start' && input) { state.resetInputs(); return; } // An input has moved outside the region. if (eventType !== 'start' && input && !_util2.default.isInside(input.current.x, input.current.y, regionElement)) { state.resetInputs(); return; } if (eventType !== 'start' && !input) { state.resetInputs(); return; } if (eventType === 'start') { state.inputs.push(new _Input2.default(event, identifier)); } else { input.update(event, identifier); } } } /** * Removes all inputs from the state, allowing for a new gesture. */ }, { key: 'resetInputs', value: function resetInputs() { this.inputs = []; } /** * Counts the number of active inputs at any given time. * @return {Number} - The number of active inputs. */ }, { key: 'numActiveInputs', value: function numActiveInputs() { var endType = this.inputs.filter(function (input) { return input.current.type !== 'end'; }); return endType.length; } /** * Register the gesture to the current region. * @param {Object} gesture - The gesture to register * @param {String} key - The key to define the new gesture as. */ }, { key: 'registerGesture', value: function registerGesture(gesture, key) { this.assignGestureId(gesture); this.registeredGestures[key] = gesture; } /** * Tracks the gesture to this state object to become uniquely identifiable. * Useful for nested Regions. * @param {Gesture} gesture - The gesture to track */ }, { key: 'assignGestureId', value: function assignGestureId(gesture) { gesture.setId(this.regionId + '-' + this.numGestures++); } }]); return State; }(); /** * Searches through each input, comparing the browser's identifier key * for touches, to the stored one in each input * @param {Array} inputs - The array of inputs in state. * @param {String} identifier - The identifier the browser has assigned. * @return {Input} - The input object with the corresponding identifier, * null if it did not find any. */ function findInputById(inputs, identifier) { for (var i = 0; i < inputs.length; i++) { if (inputs[i].identifier === identifier) { return inputs[i]; } } return null; } exports.default = State; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _Distance2 = __webpack_require__(11); var _Distance3 = _interopRequireDefault(_Distance2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file Expand.js * Contains the Expand class */ /** * An Expand is defined as two inputs moving farther away from each other. * This gesture does not account for any start/end events to allow for the * event to interact with the Pan and Pinch events. * @class Expand */ var Expand = function (_Distance) { _inherits(Expand, _Distance); /** * Constructor function for the Expand class. * @param {object} options */ function Expand(options) { _classCallCheck(this, Expand); /** * The type of the Gesture. * @type {String} */ var _this = _possibleConstructorReturn(this, (Expand.__proto__ || Object.getPrototypeOf(Expand)).call(this, options)); _this.type = 'expand'; return _this; } return Expand; }(_Distance3.default); exports.default = Expand; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _Gesture2 = __webpack_require__(4); var _Gesture3 = _interopRequireDefault(_Gesture2); var _util = __webpack_require__(5); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file Distance.js * Contains the abstract Distance class */ var DEFAULT_INPUTS = 2; var DEFAULT_MIN_THRESHOLD = 1; /** * A Distance is defined as two inputs moving either together or apart. * @class Distance */ var Distance = function (_Gesture) { _inherits(Distance, _Gesture); /** * Constructor function for the Distance class. * @param {Object} options */ function Distance(options) { _classCallCheck(this, Distance); /** * The type of the Gesture. * @type {String} */ var _this = _possibleConstructorReturn(this, (Distance.__proto__ || Object.getPrototypeOf(Distance)).call(this)); _this.type = 'distance'; /** * The minimum amount in pixels the inputs must move until it is fired. * @type {Number} */ _this.threshold = options && options.threshold ? options.threshold : DEFAULT_MIN_THRESHOLD; return _this; } /** * Event hook for the start of a gesture. Initialized the lastEmitted * gesture and stores it in the first input for reference events. * @param {Array} inputs */ _createClass(Distance, [{ key: 'start', value: function start(inputs, state, element) { if (!this.isValid(inputs, state, element)) { return null; } if (inputs.length === DEFAULT_INPUTS) { // Store the progress in the first input. var progress = inputs[0].getGestureProgress(this.type); progress.lastEmittedDistance = _util2.default.distanceBetweenTwoPoints(inputs[0].current.x, inputs[1].current.x, inputs[0].current.y, inputs[1].current.y); } } /** * Event hook for the move of a gesture. * Determines if the two points are moved in the expected direction relative * to the current distance and the last distance. * @param {Array} inputs - The array of Inputs on the screen. * @param {Object} state - The state object of the current region. * @param {Element} element - The element associated to the binding. * @return {Object | null} - Returns the distance in pixels between two inputs */ }, { key: 'move', value: function move(inputs, state, element) { if (state.numActiveInputs() === DEFAULT_INPUTS) { var currentDistance = _util2.default.distanceBetweenTwoPoints(inputs[0].current.x, inputs[1].current.x, inputs[0].current.y, inputs[1].current.y); var lastDistance = _util2.default.distanceBetweenTwoPoints(inputs[0].previous.x, inputs[1].previous.x, inputs[0].previous.y, inputs[1].previous.y); var centerPoint = _util2.default.getMidpoint(inputs[0].current.x, inputs[1].current.x, inputs[0].current.y, inputs[1].current.y); // Retrieve the first input's progress. var progress = inputs[0].getGestureProgress(this.type); if (this.type === 'expand') { if (currentDistance < lastDistance) { progress.lastEmittedDistance = currentDistance; } else if (currentDistance - progress.lastEmittedDistance >= this.threshold) { progress.lastEmittedDistance = currentDistance; return { distance: currentDistance, center: centerPoint }; } } else { if (currentDistance > lastDistance) { progress.lastEmittedDistance = currentDistance; } else if (currentDistance < lastDistance && progress.lastEmittedDistance - currentDistance >= this.threshold) { progress.lastEmittedDistance = currentDistance; return { distance: currentDistance, center: centerPoint }; } } return null; } } }]); return Distance; }(_Gesture3.default); exports.default = Distance; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _Gesture2 = __webpack_require__(4); var _Gesture3 = _interopRequireDefault(_Gesture2); var _util = __webpack_require__(5); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file Pan.js * Contains the Pan class */ var DEFAULT_INPUTS = 1; var DEFAULT_MIN_THRESHOLD = 1; /** * A Pan is defined as a normal movement in any direction on a screen. * Pan gestures do not track start events and can interact with pinch and \ * expand gestures. * @class Pan */ var Pan = function (_Gesture) { _inherits(Pan, _Gesture); /** * Constructor function for the Pan class. * @param {Object} [options] - The options object. * @param {Number} [options.numInputs=1] - Number of inputs for the * Pan gesture. * @param {Number} [options.threshold=1] - The minimum number of * pixels the input has to move to trigger this gesture. */ function Pan(options) { _classCallCheck(this, Pan); /** * The type of the Gesture. * @type {String} */ var _this = _possibleConstructorReturn(this, (Pan.__proto__ || Object.getPrototypeOf(Pan)).call(this)); _this.type = 'pan'; /** * The number of inputs to trigger a Pan can be variable, * and the maximum number being a factor of the browser. * @type {Number} */ _this.numInputs = options && options.numInputs ? options.numInputs : DEFAULT_INPUTS; /** * The minimum amount in pixels the pan must move until it is fired. * @type {Number} */ _this.threshold = options && options.threshold ? options.threshold : DEFAULT_MIN_THRESHOLD; return _this; } /** * Event hook for the start of a gesture. Marks each input as active, * so it can invalidate any end events. * @param {Array} inputs */ _createClass(Pan, [{ key: 'start', value: function start(inputs) { var _this2 = this; inputs.forEach(function (input) { var progress = input.getGestureProgress(_this2.getId()); progress.active = true; progress.lastEmitted = { x: input.current.x, y: input.current.y }; }); } /** * move() - Event hook for the move of a gesture. * Fired whenever the input length is met, and keeps a boolean flag that * the gesture has fired at least once. * @param {Array} inputs - The array of Inputs on the screen * @param {Object} state - The state object of the current region. * @param {Element} element - The element associated to the binding. * @return {Object} - Returns the distance in pixels between the two inputs. */ }, { key: 'move', value: function move(inputs, state, element) { if (this.numInputs === inputs.length) { var output = { data: [] }; for (var i = 0; i < inputs.length; i++) { var progress = inputs[i].getGestureProgress(this.getId()); var reachedThreshold = false; // Check threshold distance var yThreshold = Math.abs(inputs[i].current.y - progress.lastEmitted.y) > this.threshold; var xThreshold = Math.abs(inputs[i].current.x - progress.lastEmitted.x) > this.threshold; reachedThreshold = yThreshold || xThreshold; if (progress.active && reachedThreshold) { output.data[i] = { distanceFromOrigin: _util2.default.distanceBetweenTwoPoints(inputs[i].initial.x, inputs[i].current.x, inputs[i].initial.y, inputs[i].current.y), directionFromOrigin: _util2.default.getAngle(inputs[i].initial.x, inputs[i].initial.y, inputs[i].current.x, inputs[i].current.y), currentDirection: _util2.default.getAngle(progress.lastEmitted.x, progress.lastEmitted.y, inputs[i].current.x, inputs[i].current.y) }; progress.lastEmitted.x = inputs[i].current.x; progress.lastEmitted.y = inputs[i].current.y; } else { return null; } } } return output; } /* move*/ /** * end() - Event hook for the end of a gesture. If the gesture has at least * fired once, then it ends on the first end event such that any remaining * inputs will not trigger the event until all inputs have reached the * touchend event. Any touchend->touchstart events that occur before all * inputs are fully off the screen should not fire. * @param {Array} inputs - The array of Inputs on the screen * @return {null} - null if the gesture is not to be emitted, * Object with information otherwise. */ }, { key: 'end', value: function end(inputs) { var _this3 = this; inputs.forEach(function (input) { var progress = input.getGestureProgress(_this3.getId()); progress.active = false; }); return null; } /* end*/ }]); return Pan; }(_Gesture3.default); exports.default = Pan; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _Distance2 = __webpack_require__(11); var _Distance3 = _interopRequireDefault(_Distance2); var _util = __webpack_require__(5); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file Pinch.js * Contains the Pinch class */ /** * An Pinch is defined as two inputs moving closer to each other. * This gesture does not account for any start/end events to allow for the event * to interact with the Pan and Pinch events. * @class Pinch */ var Pinch = function (_Distance) { _inherits(Pinch, _Distance); /** * Constructor function for the Pinch class. * @param {Object} options */ function Pinch(options) { _classCallCheck(this, Pinch); /** * The type of the Gesture. * @type {String} */ var _this = _possibleConstructorReturn(this, (Pinch.__proto__ || Object.getPrototypeOf(Pinch)).call(this, options)); _this.type = 'pinch'; return _this; } return Pinch; }(_Distance3.default); exports.default = Pinch; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _Gesture2 = __webpack_require__(4); var _Gesture3 = _interopRequireDefault(_Gesture2); var _util = __webpack_require__(5); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file Rotate.js * Contains the Rotate class */ var MAX_INPUTS = 2; /** * A Rotate is defined as two inputs moving about a circle, * maintaining a relatively equal radius. * @class Rotate */ var Rotate = function (_Gesture) { _inherits(Rotate, _Gesture); /** * Constructor function for the Rotate class. */ function Rotate() { _classCallCheck(this, Rotate); /** * The type of the Gesture. * @type {String} */ var _this = _possibleConstructorReturn(this, (Rotate.__proto__ || Object.getPrototypeOf(Rotate)).call(this)); _this.type = 'rotate'; return _this; } /** * move() - Event hook for the move of a gesture. Obtains the midpoint of two * the two inputs and calculates the projection of the right most input along * a unit circle to obtain an angle. This angle is compared to the previously * calculated angle to output the change of distance, and is compared to the * initial angle to output the distance from the initial angle to the current * angle. * @param {Array} inputs - The array of Inputs on the screen * @param {Object} state - The state object of the current listener. * @param {Element} element - The element associated to the binding. * @return {null} - null if this event did not occur * @return {Object} obj.angle - The current angle along the unit circle * @return {Object} obj.distanceFromOrigin - The angular distance travelled * from the initial right most point. * @return {Object} obj.distanceFromLast - The change of angle between the * last position and the current position. */ _createClass(Rotate, [{ key: 'move', value: function move(inputs, state, element) { if (state.numActiveInputs() <= MAX_INPUTS) { var referencePivot = void 0; var diffX = void 0; var diffY = void 0; var input = void 0; if (state.numActiveInputs() === 1) { var bRect = element.getBoundingClientRect(); referencePivot = { x: bRect.left + bRect.width / 2, y: bRect.top + bRect.height / 2 }; input = inputs[0]; diffX = diffY = 0; } else { referencePivot = _util2.default.getMidpoint(inputs[0].initial.x, inputs[1].initial.x, inputs[0].initial.y, inputs[1].initial.y); var currentPivot = _util2.default.getMidpoint(inputs[0].current.x, inputs[1].current.x, inputs[0].current.y, inputs[1].current.y); diffX = referencePivot.x - currentPivot.x; diffY = referencePivot.y - currentPivot.y; input = _util2.default.getRightMostInput(inputs); } // Translate the current pivot point. var currentAngle = _util2.default.getAngle(referencePivot.x, referencePivot.y, input.current.x + diffX, input.current.y + diffY); var progress = input.getGestureProgress(this.getId()); if (!progress.initialAngle) { progress.initialAngle = progress.previousAngle = currentAngle; progress.distance = progress.change = 0; } else { progress.change = _util2.default.getAngularDistance(progress.previousAngle, currentAngle); progress.distance = progress.distance + progress.change; } progress.previousAngle = currentAngle; return { angle: currentAngle, distanceFromOrigin: progress.distance, distanceFromLast: progress.change }; } return null; } /* move*/ }]); return Rotate; }(_Gesture3.default); exports.default = Rotate; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _Gesture2 = __webpack_require__(4); var _Gesture3 = _interopRequireDefault(_Gesture2); var _util = __webpack_require__(5); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file Swipe.js * Contains the Swipe class */ var DEFAULT_INPUTS = 1; var DEFAULT_MAX_REST_TIME = 100; var DEFAULT_ESCAPE_VELOCITY = 0.2; var DEFAULT_TIME_DISTORTION = 100; var DEFAULT_MAX_PROGRESS_STACK = 10; /** * A swipe is defined as input(s) moving in the same direction in an relatively * increasing velocity and leaving the screen at some point before it drops * below it's escape velocity. * @class Swipe */ var Swipe = function (_Gesture) { _inherits(Swipe, _Gesture); /** * Constructor function for the Swipe class. * @param {Object} [options] - The options object. * @param {Number} [options.numInputs] - The number of inputs to trigger a * Swipe can be variable, and the maximum number being a factor of the browser * move and current move events. * @param {Number} [options.maxRestTime] - The maximum resting time a point * has between it's last * @param {Number} [options.escapeVelocity] - The minimum velocity the input * has to be at to emit a swipe. * @param {Number} [options.timeDistortion] - (EXPERIMENTAL) A value of time * in milliseconds to distort between events. * @param {Number} [options.maxProgressStack] - (EXPERIMENTAL)The maximum * amount of move events to keep * track of for a swipe. */ function Swipe(options) { _classCallCheck(this, Swipe); /** * The type of the Gesture * @type {String} */ var _this = _possibleConstructorReturn(this, (Swipe.__proto__ || Object.getPrototypeOf(Swipe)).call(this)); _this.type = 'swipe'; /** * The number of inputs to trigger a Swipe can be variable, * and the maximum number being a factor of the browser. * @type {Number} */ _this.numInputs = options && options.numInputs ? options.numInputs : DEFAULT_INPUTS; /** * The maximum resting time a point has between it's last move and * current move events. * @type {Number} */ _this.maxRestTime = options && options.maxRestTime ? options.maxRestTime : DEFAULT_MAX_REST_TIME; /** * The minimum velocity the input has to be at to emit a swipe. * This is useful for determining the difference between * a swipe and a pan gesture. * @type {number} */ _this.escapeVelocity = options && options.escapeVelocity ? options.escapeVelocity : DEFAULT_ESCAPE_VELOCITY; /** * (EXPERIMENTAL) A value of time in milliseconds to distort between events. * Browsers do not accurately measure time with the Date constructor in * milliseconds, so consecutive events sometimes display the same timestamp * but different x/y coordinates. This will distort a previous time * in such cases by the timeDistortion's value. * @type {number} */ _this.timeDistortion = options && options.timeDistortion ? options.timeDistortion : DEFAULT_TIME_DISTORTION; /** * (EXPERIMENTAL) The maximum amount of move events to keep track of for a * swipe. This helps give a more accurate estimate of the user's velocity. * @type {number} */ _this.maxProgressStack = options && options.maxProgressStack ? options.maxProgressStack : DEFAULT_MAX_PROGRESS_STACK; return _this; } /** * Event hook for the move of a gesture. Captures an input's x/y coordinates * and the time of it's event on a stack. * @param {Array} inputs - The array of Inputs on the screen. * @param {Object} state - The state object of the current region. * @param {Element} element - The element associated to the binding. * @return {null} - Swipe does not emit from a move. */ _createClass(Swipe, [{ key: 'move', value: function move(inputs, state, element) { if (this.numInputs === inputs.length) { for (var i = 0; i < inputs.length; i++) { var progress = inputs[i].getGestureProgress(this.getId()); if (!progress.moves) { progress.moves = []; } progress.moves.push({ time: new Date().getTime(), x: inputs[i].current.x, y: inputs[i].current.y }); if (progress.length > this.maxProgressStack) { progress.moves.shift(); } } } return null; } /* move*/ /** * Determines if the input's history validates a swipe motion. * Determines if it did not come to a complete stop (maxRestTime), and if it * had enough of a velocity to be considered (ESCAPE_VELOCITY). * @param {Array} inputs - The array of Inputs on the screen * @return {null|Object} - null if the gesture is not to be emitted, * Object with information otherwise. */ }, { key: 'end', value: function end(inputs) { if (this.numInputs === inputs.length) { var output = { data: [] }; for (var i = 0; i < inputs.length; i++) { // Determine if all input events are on the 'end' event. if (inputs[i].current.type !== 'end') { return; } var progress = inputs[i].getGestureProgress(this.getId()); if (progress.moves && progress.moves.length > 2) { // CHECK : Return if the input has not moved in maxRestTime ms. var currentMove = progress.moves.pop(); if (new Date().getTime() - currentMove.time > this.maxRestTime) { return null; } var lastMove = void 0; var index = progress.moves.length - 1; /* Date is unreliable, so we retrieve the last move event where the time is not the same. */ while (index !== -1) { if (progress.moves[index].time !== currentMove.time) { lastMove = progress.moves[index]; break; } index--; } /* If the date is REALLY unreliable, we apply a time distortion to the last event. */ if (!lastMove) { lastMove = progress.moves.pop(); lastMove.time += this.timeDistortion; } var velocity = _util2.default.getVelocity(lastMove.x, lastMove.y, lastMove.time, currentMove.x, currentMove.y, currentMove.time); output.data[i] = { velocity: velocity, currentDirection: _util2.default.getAngle(lastMove.x, lastMove.y, currentMove.x, currentMove.y) }; } } for (var i = 0; i < output.data.length; i++) { if (velocity < this.escapeVelocity) { return null; } } if (output.data.length > 0) { return output; } } return null; } /* end*/ }]); return Swipe; }(_Gesture3.default); exports.default = Swipe; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _Gesture2 = __webpack_require__(4); var _Gesture3 = _interopRequireDefault(_Gesture2); var _util = __webpack_require__(5); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file Tap.js * Contains the Tap class */ var DEFAULT_MIN_DELAY_MS = 0; var DEFAULT_MAX_DELAY_MS = 300; var DEFAULT_INPUTS = 1; var DEFAULT_MOVE_PX_TOLERANCE = 10; /** * A Tap is defined as a touchstart to touchend event in quick succession. * @class Tap */ var Tap = function (_Gesture) { _inherits(Tap, _Gesture); /** * Constructor function for the Tap class. * @param {Object} [options] - The options object. * @param {Number} [options.minDelay=0] - The minimum delay between a * touchstart and touchend can be configured in milliseconds. * @param {Number} [options.maxDelay=300] - The maximum delay between a * touchstart and touchend can be configured in milliseconds. * @param {Number} [options.numInputs=1] - Number of inputs for Tap gesture. * @param {Number} [options.tolerance=10] - The tolerance in pixels * a user can move. */ function Tap(options) { _classCallCheck(this, Tap); /** * The type of the Gesture. * @type {String} */ var _this = _possibleConstructorReturn(this, (Tap.__proto__ || Object.getPrototypeOf(Tap)).call(this)); _this.type = 'tap'; /** * The minimum amount between a touchstart and a touchend can be configured * in milliseconds. The minimum delay starts to count down when the expected * number of inputs are on the screen, and ends when ALL inputs are off the * screen. * @type {Number} */ _this.minDelay = options && options.minDelay ? options.minDelay : DEFAULT_MIN_DELAY_MS; /** * The maximum delay between a touchstart and touchend can be configured in * milliseconds. The maximum delay starts to count down when the expected * number of inputs are on the screen, and ends when ALL inputs are off the * screen. * @type {Number} */ _this.maxDelay = options && options.maxDelay ? options.maxDelay : DEFAULT_MAX_DELAY_MS; /** * The number of inputs to trigger a Tap can be variable, * and the maximum number being a factor of the browser. * @type {Number} */ _this.numInputs = options && options.numInputs ? options.numInputs : DEFAULT_INPUTS; /** * A move tolerance in pixels allows some slop between a user's start to end * events. This allows the Tap gesture to be triggered more easily. * @type {number} */ _this.tolerance = options && options.tolerance ? options.tolerance : DEFAULT_MOVE_PX_TOLERANCE; return _this; } /* constructor*/ /** * Event hook for the start of a gesture. Keeps track of when the inputs * trigger the start event. * @param {Array} inputs - The array of Inputs on the screen. * @return {null} - Tap does not trigger on a start event. */ _createClass(Tap, [{ key: 'start', value: function start(inputs) { var _this2 = this; if (inputs.length === this.numInputs) { inputs.forEach(function (input) { var progress = input.getGestureProgress(_this2.type); progress.start = new Date().getTime(); }); } return null; } /* start*/ /** * Event hook for the move of a gesture. The Tap event reaches here if the * user starts to move their input before an 'end' event is reached. * @param {Array} inputs - The array of Inputs on the screen. * @param {Object} state - The state object of the current region. * @param {Element} element - The element associated to the binding. * @return {null} - Tap does not trigger on a move event. */ }, { key: 'move', value: function move(inputs, state, element) { var _this3 = this; for (var i = 0; i < inputs.length; i++) { if (inputs[i].getCurrentEventType() === 'move') { var current = inputs[i].current; var previous = inputs[i].previous; if (!_util2.default.isWithin(current.x, current.y, previous.x, previous.y, this.tolerance)) { var _ret = function () { var type = _this3.type; inputs.forEach(function (input) { input.resetProgress(type); }); return { v: null }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } } } return null; } /* move*/ /** * Event hook for the end of a gesture. * Determines if this the tap event can be fired if the delay and tolerance * constraints are met. Also waits for all of the inputs to be off the screen * before determining if the gesture is triggered. * @param {Array} inputs - The array of Inputs on the screen. * @return {null|Object} - null if the gesture is not to be emitted, * Object with information otherwise. Returns the interval time between start * and end events. */ }, { key: 'end', value: function end(inputs) { var _this4 = this; if (inputs.length !== this.numInputs) { return null; } var startTime = Number.MAX_VALUE; for (var i = 0; i < inputs.length; i++) { if (inputs[i].getCurrentEventType() !== 'end') { return null; } var progress = inputs[i].getGestureProgress(this.type); if (!progress.start) { return null; } // Find the most recent input's startTime if (progress.start < startTime) { startTime = progress.start; } } var interval = new Date().getTime() - startTime; if (this.minDelay <= interval && this.maxDelay >= interval) { return { interval: interval }; } else { var _ret2 = function () { var type = _this4.type; inputs.forEach(function (input) { input.resetProgress(type); }); return { v: null }; }(); if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v; } } /* end*/ }]); return Tap; }(_Gesture3.default); exports.default = Tap; /***/ }, /* 17 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * @file Binding.js */ /** * Responsible for creating a binding between an element and a gesture. * @class Binding */ var Binding = /** * Constructor function for the Binding class. * @param {Element} element - The element to associate the gesture to. * @param {Gesture} gesture - A instance of the Gesture type. * @param {Function} handler - The function handler to execute when a * gesture is recognized * on the associated element. * @param {Boolean} [capture=false] - A boolean signifying if the event is * to be emitted during * the capture or bubble phase. * @param {Boolean} [bindOnce=false] - A boolean flag * used for the bindOnce syntax. */ function Binding(element, gesture, handler, capture, bindOnce) { _classCallCheck(this, Binding); /** * The element to associate the gesture to. * @type {Element} */ this.element = element; /** * A instance of the Gesture type. * @type {Gesture} */ this.gesture = gesture; /** * The function handler to execute when a gesture is * recognized on the associated element. * @type {Function} */ this.handler = handler; /** * A boolean signifying if the event is to be * emitted during the capture or bubble phase. * @type {Boolean} */ this.capture = typeof capture !== 'undefined' ? capture : false; /** * A boolean flag used for the bindOnce syntax. * @type {Boolean} */ this.bindOnce = typeof bindOnce !== 'undefined' ? bindOnce : false; }; exports.default = Binding; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /** * @file Input.js */ var _ZingEvent = __webpack_require__(19); var _ZingEvent2 = _interopRequireDefault(_ZingEvent); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Tracks a single input and contains information about the * current, previous, and initial events. * Contains the progress of each Input and it's associated gestures. * @class Input */ var Input = function () { /** * Constructor function for the Input class. * @param {Event} event - The Event object from the window * @param {Number} [identifier=0] - The identifier for each input event * (taken from event.changedTouches) */ function Input(event, identifier) { _classCallCheck(this, Input); var currentEvent = new _ZingEvent2.default(event, identifier); /** * Holds the initial event object. A touchstart/mousedown event. * @type {ZingEvent} */ this.initial = currentEvent; /** * Holds the most current event for this Input, disregarding any other past, * current, and future events that other Inputs participate in. * e.g. This event ended in an 'end' event, but another Input is still * participating in events -- this will not be updated in such cases. * @type {ZingEvent} */ this.current = currentEvent; /** * Holds the previous event that took place. * @type {ZingEvent} */ this.previous = currentEvent; /** * Refers to the event.touches index, or 0 if a simple mouse event occurred. * @type {Number} */ this.identifier = typeof identifier !== 'undefined' ? identifier : 0; /** * Stores internal state between events for * each gesture based off of the gesture's id. * @type {Object} */ this.progress = {}; } /** * Receives an input, updates the internal state of what the input has done. * @param {Event} event - The event object to wrap with a ZingEvent. * @param {Number} touchIdentifier - The index of inputs, from event.touches */ _createClass(Input, [{ key: 'update', value: function update(event, touchIdentifier) { this.previous = this.current; this.current = new _ZingEvent2.default(event, touchIdentifier); } /** * Returns the progress of the specified gesture. * @param {String} id - The identifier for each unique Gesture's progress. * @return {Object} - The progress of the gesture. * Creates an empty object if no progress has begun. */ }, { key: 'getGestureProgress', value: function getGestureProgress(id) { if (!this.progress[id]) { this.progress[id] = {}; } return this.progress[id]; } /** * Returns the normalized current Event's type. * @return {String} The current event's type ( start | move | end ) */ }, { key: 'getCurrentEventType', value: function getCurrentEventType() { return this.current.type; } /** * Resets a progress/state object of the specified gesture. * @param {String} id - The identifier of the specified gesture */ }, { key: 'resetProgress', value: function resetProgress(id) { this.progress[id] = {}; } }]); return Input; }(); exports.default = Input; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _util = __webpack_require__(5); var _util2 = _interopRequireDefault(_util); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * @file ZingEvent.js * Contains logic for ZingEvents */ var INITIAL_COORDINATE = 0; /** * An event wrapper that normalizes events across browsers and input devices * @class ZingEvent */ var ZingEvent = /** * @constructor * @param {Event} event - The event object being wrapped. * @param {Array} event.touches - The number of touches on * a screen (mobile only). * @param {Object} event.changedTouches - The TouchList representing * points that participated in the event. * @param {Number} touchIdentifier - The index of touch if applicable */ function ZingEvent(event, touchIdentifier) { _classCallCheck(this, ZingEvent); /** * The original event object. * @type {Event} */ this.originalEvent = event; /** * The type of event or null if it is an event not predetermined. * @see util.normalizeEvent * @type {String | null} */ this.type = _util2.default.normalizeEvent(event.type); /** * The X coordinate for the event, based off of the client. * @type {number} */ this.x = INITIAL_COORDINATE; /** * The Y coordinate for the event, based off of the client. * @type {number} */ this.y = INITIAL_COORDINATE; var eventObj = void 0; if (event.touches && event.changedTouches) { for (var i = 0; i < event.changedTouches.length; i++) { if (event.changedTouches[i].identifier === touchIdentifier) { eventObj = event.changedTouches[i]; break; } } } else { eventObj = event; } this.x = this.clientX = eventObj.clientX; this.y = this.clientY = eventObj.clientY; this.pageX = eventObj.pageX; this.pageY = eventObj.pageY; this.screenX = eventObj.screenX; this.screenY = eventObj.screenY; }; exports.default = ZingEvent; /***/ } /******/ ]); //# sourceMappingURL=zingtouch.js.map
sashberd/cdnjs
ajax/libs/zingtouch/1.0.5/zingtouch.js
JavaScript
mit
108,494
var formatFailedStep = function(step) { var stack = step.trace.stack; var message = step.message; if (stack) { // remove the trailing dot var firstLine = stack.substring(0, stack.indexOf('\n') - 1); if (message && message.indexOf(firstLine) === -1) { stack = message + '\n' + stack; } // remove jasmine stack entries return stack.replace(/\n.+jasmine\.js\?\d*\:.+(?=(\n|$))/g, ''); } return message; }; var indexOf = function(collection, item) { if (collection.indexOf) { return collection.indexOf(item); } for (var i = 0, ii = collection.length; i < ii; i++) { if (collection[i] === item) { return i; } } return -1; }; /** * Very simple reporter for jasmine */ var TestacularReporter = function(tc) { var failedIds = []; this.reportRunnerStarting = function(runner) { tc.info({total: runner.specs().length}); }; this.reportRunnerResults = function(runner) { tc.store('jasmine.lastFailedIds', failedIds); tc.complete({ coverage: window.__coverage__ }); }; this.reportSuiteResults = function(suite) { // memory clean up suite.after_ = null; suite.before_ = null; suite.queue = null; }; this.reportSpecStarting = function(spec) { spec.results_.time = new Date().getTime(); }; this.reportSpecResults = function(spec) { var result = { id: spec.id, description: spec.description, suite: [], success: spec.results_.failedCount === 0, skipped: spec.results_.skipped, time: spec.results_.skipped ? 0 : new Date().getTime() - spec.results_.time, log: [] }; var suitePointer = spec.suite; while (suitePointer) { result.suite.unshift(suitePointer.description); suitePointer = suitePointer.parentSuite; } if (!result.success) { var steps = spec.results_.items_; for (var i = 0; i < steps.length; i++) { if (!steps[i].passed_) { result.log.push(formatFailedStep(steps[i])); } } failedIds.push(result.id); } tc.result(result); // memory clean up spec.results_ = null; spec.spies_ = null; spec.queue = null; }; this.log = function() {}; }; var createStartFn = function(tc, jasmineEnvPassedIn) { return function(config) { // we pass jasmineEnv during testing // in production we ask for it lazily, so that adapter can be loaded even before jasmine var jasmineEnv = jasmineEnvPassedIn || window.jasmine.getEnv(); var currentSpecsCount = jasmineEnv.nextSpecId_; var lastCount = tc.store('jasmine.lastCount'); var lastFailedIds = tc.store('jasmine.lastFailedIds'); tc.store('jasmine.lastCount', currentSpecsCount); tc.store('jasmine.lastFailedIds', []); // filter only last failed specs if (lastCount === currentSpecsCount && // still same number of specs lastFailedIds.length > 0 && // at least one fail last run !jasmineEnv.exclusive_) { // no exclusive mode (iit, ddesc) jasmineEnv.specFilter = function(spec) { return indexOf(lastFailedIds, spec.id) !== -1; }; } jasmineEnv.addReporter(new TestacularReporter(tc)); jasmineEnv.execute(); }; }; var createDumpFn = function(tc, serialize) { return function() { var args = Array.prototype.slice.call(arguments, 0); if (serialize) { for (var i = 0; i < args.length; i++) { args[i] = serialize(args[i]); } } tc.info({dump: args}); }; };
vsdev1/testacular
adapter/jasmine.src.js
JavaScript
mit
3,535
var getAllMatches = function(string, regex) { //var regex = new RegExp(regex_str,"g"); var matches = []; var match; while (match = regex.exec(string)) { var allmatches = []; for (var index = 0; index < match.length; index++) { allmatches.push(match[index]); } matches.push(allmatches); } return matches; } var Node = function(tagname,parent){ this.tagname = tagname; this.parent = parent; this.child = []; //this.val = ""; this.addChild = function (child){ this.child.push(child); } } var tagsRegx = new RegExp("<(\\/?[a-zA-Z0-9_:]+)","g"); //var tagsRegx = new RegExp("<(\\/?[^\S<>]+)","g"); var valsRegx = new RegExp(">([^<]+)<","g"); var xml2json = function (xmlData){ xmlData = xmlData.replace(/>(\s+)/g, "");//Remove spaces and make it single line. var tags = getAllMatches(xmlData,tagsRegx); var values = getAllMatches(xmlData,valsRegx); // for (var j = 0; j < values.length; j++) { // console.log(values[j][1]); // } var rootNode = new Node(tags[0][1]); var currentNode = rootNode; for (var i = 1,j=0; i < tags.length -1 ; i++) { var tag = tags[i][1]; var nexttag = tags[i+1][1]; if( ("/" + tag) === nexttag){ //leaf node var val; if(values[j]){ val = values[j++][1]; if(isNaN(val)){ val = "" + val ; }else{ if(val.indexOf(".") !== -1){ val = Number.parseFloat(val); }else{ val = Number.parseInt(val); } } } var childNode = new Node(tag,currentNode); childNode.val = val; currentNode.addChild(childNode); i++; }else if(tag.indexOf("/") === 0){ currentNode = currentNode.parent; continue; }else{ var cNode = new Node(tag,currentNode); currentNode.addChild(cNode); currentNode = cNode; } } //include root node as well var xmlObj = new Node('_xml'); rootNode.param = xmlObj; xmlObj.addChild(rootNode); return convertToJson(xmlObj); } function convertToJson(node){ var jObj = {}; if(node.val) { return node.val; }else{ for (var index = 0; index < node.child.length; index++) { var prop = node.child[index].tagname; var obj = convertToJson(node.child[index]); if(jObj[prop]){ if(!Array.isArray(jObj[prop])){ var swap = jObj[prop]; jObj[prop] = []; jObj[prop].push(swap); } jObj[prop].push(obj); }else{ jObj[prop] = obj; } } } return jObj; }
froala/cdnjs
ajax/libs/fast-xml-parser/1.1.1/fastxmlparser.js
JavaScript
mit
2,896
YUI.add('dataschema-base', function (Y, NAME) { /** * The DataSchema utility provides a common configurable interface for widgets to * apply a given schema to a variety of data. * * @module dataschema * @main dataschema */ /** * Provides the base DataSchema implementation, which can be extended to * create DataSchemas for specific data formats, such XML, JSON, text and * arrays. * * @module dataschema * @submodule dataschema-base */ var LANG = Y.Lang, /** * Base class for the YUI DataSchema Utility. * @class DataSchema.Base * @static */ SchemaBase = { /** * Overridable method returns data as-is. * * @method apply * @param schema {Object} Schema to apply. * @param data {Object} Data. * @return {Object} Schema-parsed data. * @static */ apply: function(schema, data) { return data; }, /** * Applies field parser, if defined * * @method parse * @param value {Object} Original value. * @param field {Object} Field. * @return {Object} Type-converted value. */ parse: function(value, field) { if(field.parser) { var parser = (LANG.isFunction(field.parser)) ? field.parser : Y.Parsers[field.parser+'']; if(parser) { value = parser.call(this, value); } else { Y.log("Could not find parser for field " + Y.dump(field), "warn", "dataschema-json"); } } return value; } }; Y.namespace("DataSchema").Base = SchemaBase; Y.namespace("Parsers"); }, '3.14.1', {"requires": ["base"]});
aqt01/math_problems
node_modules/yui/dataschema-base/dataschema-base-debug.js
JavaScript
gpl-2.0
1,640
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * DefaultTaskDialog contains a message, a list box, an ok button, and a * cancel button. * This dialog should be used as task picker for file operations. */ cr.define('cr.filebrowser', function() { /** * Creates dialog in DOM tree. * * @param {HTMLElement} parentNode Node to be parent for this dialog. * @constructor * @extends {FileManagerDialogBase} */ function DefaultTaskDialog(parentNode) { FileManagerDialogBase.call(this, parentNode); this.frame_.id = 'default-task-dialog'; this.list_ = new cr.ui.List(); this.list_.id = 'default-tasks-list'; this.frame_.insertBefore(this.list_, this.text_.nextSibling); this.selectionModel_ = this.list_.selectionModel = new cr.ui.ListSingleSelectionModel(); this.dataModel_ = this.list_.dataModel = new cr.ui.ArrayDataModel([]); // List has max-height defined at css, so that list grows automatically, // but doesn't exceed predefined size. this.list_.autoExpands = true; this.list_.activateItemAtIndex = this.activateItemAtIndex_.bind(this); // Use 'click' instead of 'change' for keyboard users. this.list_.addEventListener('click', this.onSelected_.bind(this)); this.initialFocusElement_ = this.list_; var self = this; // Binding stuff doesn't work with constructors, so we have to create // closure here. this.list_.itemConstructor = function(item) { return self.renderItem(item); }; } DefaultTaskDialog.prototype = { __proto__: FileManagerDialogBase.prototype }; /** * Renders item for list. * @param {Object} item Item to render. */ DefaultTaskDialog.prototype.renderItem = function(item) { var result = this.document_.createElement('li'); var div = this.document_.createElement('div'); div.textContent = item.label; if (item.iconType) { div.setAttribute('file-type-icon', item.iconType); } else if (item.iconUrl) { div.style.backgroundImage = 'url(' + item.iconUrl + ')'; } if (item.class) div.classList.add(item.class); result.appendChild(div); cr.defineProperty(result, 'lead', cr.PropertyKind.BOOL_ATTR); cr.defineProperty(result, 'selected', cr.PropertyKind.BOOL_ATTR); return result; }; /** * Shows dialog. * * @param {string} title Title in dialog caption. * @param {string} message Message in dialog caption. * @param {Array<Object>} items Items to render in the list. * @param {number} defaultIndex Item to select by default. * @param {function(Object)} onSelectedItem Callback which is called when an * item is selected. */ DefaultTaskDialog.prototype.showDefaultTaskDialog = function(title, message, items, defaultIndex, onSelectedItem) { this.onSelectedItemCallback_ = onSelectedItem; var show = FileManagerDialogBase.prototype.showTitleAndTextDialog.call( this, title, message); if (!show) { console.error('DefaultTaskDialog can\'t be shown.'); return; } if (!message) { this.text_.setAttribute('hidden', 'hidden'); } else { this.text_.removeAttribute('hidden'); } this.list_.startBatchUpdates(); this.dataModel_.splice(0, this.dataModel_.length); for (var i = 0; i < items.length; i++) { this.dataModel_.push(items[i]); } this.selectionModel_.selectedIndex = defaultIndex; this.list_.endBatchUpdates(); }; /** * List activation handler. Closes dialog and calls 'ok' callback. * @param {number} index Activated index. */ DefaultTaskDialog.prototype.activateItemAtIndex_ = function(index) { this.hide(); this.onSelectedItemCallback_(this.dataModel_.item(index)); }; /** * Closes dialog and invokes callback with currently-selected item. */ DefaultTaskDialog.prototype.onSelected_ = function() { if (this.selectionModel_.selectedIndex !== -1) this.activateItemAtIndex_(this.selectionModel_.selectedIndex); }; /** * @override */ DefaultTaskDialog.prototype.onContainerKeyDown_ = function(event) { // Handle Escape. if (event.keyCode == 27) { this.hide(); event.preventDefault(); } else if (event.keyCode == 32 || event.keyCode == 13) { this.onSelected_(); event.preventDefault(); } }; return {DefaultTaskDialog: DefaultTaskDialog}; });
js0701/chromium-crosswalk
ui/file_manager/file_manager/foreground/js/ui/default_task_dialog.js
JavaScript
bsd-3-clause
4,532
/*! * # Semantic UI x.x - Checkbox * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2014 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.checkbox = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = $.extend(true, {}, $.fn.checkbox.settings, parameters), className = settings.className, namespace = settings.namespace, selector = settings.selector, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $module = $(this), $label = $(this).find(selector.label).first(), $input = $(this).find(selector.input), instance = $module.data(moduleNamespace), observer, element = this, module ; module = { initialize: function() { module.verbose('Initializing checkbox', settings); module.create.label(); module.add.events(); if( module.is.checked() ) { module.set.checked(); if(settings.fireOnInit) { settings.onChecked.call($input.get()); } } else { module.remove.checked(); if(settings.fireOnInit) { settings.onUnchecked.call($input.get()); } } module.observeChanges(); module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying module'); module.remove.events(); $module .removeData(moduleNamespace) ; }, refresh: function() { $module = $(this); $label = $(this).find(selector.label).first(); $input = $(this).find(selector.input); }, observeChanges: function() { if('MutationObserver' in window) { observer = new MutationObserver(function(mutations) { module.debug('DOM tree modified, updating selector cache'); module.refresh(); }); observer.observe(element, { childList : true, subtree : true }); module.debug('Setting up mutation observer', observer); } }, attachEvents: function(selector, event) { var $element = $(selector) ; event = $.isFunction(module[event]) ? module[event] : module.toggle ; if($element.length > 0) { module.debug('Attaching checkbox events to element', selector, event); $element .on('click' + eventNamespace, event) ; } else { module.error(error.notFound); } }, event: { keydown: function(event) { var key = event.which, keyCode = { enter : 13, space : 32, escape : 27 } ; if( key == keyCode.escape) { module.verbose('Escape key pressed blurring field'); $module .blur() ; } if(!event.ctrlKey && (key == keyCode.enter || key == keyCode.space)) { module.verbose('Enter key pressed, toggling checkbox'); module.toggle.call(this); event.preventDefault(); } } }, is: { radio: function() { return $module.hasClass(className.radio); }, checked: function() { return $input.prop('checked') !== undefined && $input.prop('checked'); }, unchecked: function() { return !module.is.checked(); } }, can: { change: function() { return !( $module.hasClass(className.disabled) || $module.hasClass(className.readOnly) || $input.prop('disabled') ); }, uncheck: function() { return (typeof settings.uncheckable === 'boolean') ? settings.uncheckable : !module.is.radio() ; } }, set: { checked: function() { $module.addClass(className.checked); }, tab: function() { if( $input.attr('tabindex') === undefined) { $input .attr('tabindex', 0) ; } } }, create: { label: function() { if($input.prevAll(selector.label).length > 0) { $input.prev(selector.label).detach().insertAfter($input); module.debug('Moving existing label', $label); } else if( !module.has.label() ) { $label = $('<label>').insertAfter($input); module.debug('Creating label', $label); } } }, has: { label: function() { return ($label.length > 0); } }, add: { events: function() { module.verbose('Attaching checkbox events'); $module .on('click' + eventNamespace, module.toggle) .on('keydown' + eventNamespace, selector.input, module.event.keydown) ; } }, remove: { checked: function() { $module.removeClass(className.checked); }, events: function() { module.debug('Removing events'); $module .off(eventNamespace) .removeData(moduleNamespace) ; $input .off(eventNamespace, module.event.keydown) ; $label .off(eventNamespace) ; } }, enable: function() { module.debug('Enabling checkbox functionality'); $module.removeClass(className.disabled); $input.prop('disabled', false); settings.onEnabled.call($input.get()); }, disable: function() { module.debug('Disabling checkbox functionality'); $module.addClass(className.disabled); $input.prop('disabled', 'disabled'); settings.onDisabled.call($input.get()); }, check: function() { module.debug('Enabling checkbox', $input); $input .prop('checked', true) .trigger('change') ; module.set.checked(); $input.trigger('blur'); settings.onChange.call($input.get()); settings.onChecked.call($input.get()); }, uncheck: function() { module.debug('Disabling checkbox'); $input .prop('checked', false) .trigger('change') ; module.remove.checked(); $input.trigger('blur'); settings.onChange.call($input.get()); settings.onUnchecked.call($input.get()); }, toggle: function(event) { if( !module.can.change() ) { console.log(module.can.change()); module.debug('Checkbox is read-only or disabled, ignoring toggle'); return; } module.verbose('Determining new checkbox state'); if( module.is.unchecked() ) { module.check(); } else if( module.is.checked() && module.can.uncheck() ) { module.uncheck(); } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 100); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.checkbox.settings = { name : 'Checkbox', namespace : 'checkbox', debug : false, verbose : true, performance : true, // delegated event context uncheckable : 'auto', fireOnInit : true, onChange : function(){}, onChecked : function(){}, onUnchecked : function(){}, onEnabled : function(){}, onDisabled : function(){}, className : { checked : 'checked', disabled : 'disabled', radio : 'radio', readOnly : 'read-only' }, error : { method : 'The method you called is not defined' }, selector : { input : 'input[type="checkbox"], input[type="radio"]', label : 'label' } }; })( jQuery, window , document );
jw-psychopomp/ScotchDigital-portfolio
semantic/dist/components/checkbox.js
JavaScript
mit
14,832
/* eslint-env node */ 'use strict'; var path = require('path'); module.exports = { entry: { word_cloud: 'word_cloud', }, output: { path: path.resolve(__dirname, 'public/js'), filename: '[name].js', }, module: { rules: [ { test: /\.(js|jsx)$/, use: 'babel-loader', }, { test: /d3.min/, use: [ 'babel-loader', { loader: 'exports-loader', options: { d3: true, }, }, ], }, ], }, resolve: { modules: [ path.resolve(__dirname, 'src/js'), path.resolve(__dirname, '../../../../../../node_modules'), ], alias: { 'edx-ui-toolkit': 'edx-ui-toolkit/src/', // @TODO: some paths in toolkit are not valid relative paths }, extensions: ['.js', '.jsx', '.json'], }, externals: { gettext: 'gettext', canvas: 'canvas', jquery: 'jQuery', $: 'jQuery', underscore: '_', }, };
eduNEXT/edx-platform
common/lib/xmodule/xmodule/assets/word_cloud/webpack.config.js
JavaScript
agpl-3.0
1,004
/** * html5tooltips.js * Light and clean tooltips with CSS3 animation. * https://github.com/ytiurin/html5tooltipsjs * * Yevhen Tiurin <yevhentiurin@gmail.com> * The MIT License (MIT) * http://opensource.org/licenses/MIT * * July 22, 2015 **/ (function() { var tt, tModels, options, activeElements, html5tooltipsPredefined = { animateFunction: { fadeIn: "fadein", foldIn: "foldin", foldOut: "foldout", roll: "roll", scaleIn: "scalein", slideIn: "slidein", spin: "spin" }, color: { "daffodil": {r: 255, g: 230, b: 23, a: 0.95}, "daisy": {r: 250, g: 211, b: 28, a: 0.95}, "mustard": {r: 253, g: 183, b: 23, a: 0.95}, "citrus zest": {r: 250, g: 170, b: 33, a: 0.95}, "pumpkin": {r: 241, g: 117, b: 63, a: 0.95}, "tangerine": {r: 237, g: 87, b: 36, a: 0.95}, "salmon": {r: 240, g: 70, b: 57, a: 0.95}, "persimmon": {r: 234, g: 40, b: 48, a: 0.95}, "rouge": {r: 188, g: 35, b: 38, a: 0.95}, "scarlet": {r: 140, g: 12, b: 3, a: 0.95}, "hot pink": {r: 229, g: 24, b: 93, a: 0.95}, "princess": {r: 243, g: 132, b: 174, a: 0.95}, "petal": {r: 250, g: 198, b: 210, a: 0.95}, "lilac": {r: 178, g: 150, b: 199, a: 0.95}, "lavender": {r: 123, g: 103, b: 174, a: 0.95}, "violet": {r: 95, g: 53, b: 119, a: 0.95}, "cloud": {r: 195, g: 222, b: 241, a: 0.95}, "dream": {r: 85, g: 190, b: 237, a: 0.95}, "gulf": {r: 49, g: 168, b: 224, a: 0.95}, "turquoise": {r: 35, g: 138, b: 204, a: 0.95}, "sky": {r: 13, g: 96, b: 174, a: 0.95}, "indigo": {r: 20, g: 59, b: 134, a: 0.95}, "navy": {r: 0, g: 27, b: 74, a: 0.95}, "sea foam": {r: 125, g: 205, b: 194, a: 0.95}, "teal": {r: 0, g: 168, b: 168, a: 0.95}, "peacock": {r: 18, g: 149, b: 159, a: 0.95}, "ceadon": {r: 193, g: 209, b: 138, a: 0.95}, "olive": {r: 121, g: 145, b: 85, a: 0.95}, "bamboo": {r: 128, g: 188, b: 66, a: 0.95}, "grass": {r: 74, g: 160, b: 63, a: 0.95}, "kelly": {r: 22, g: 136, b: 74, a: 0.95}, "forrest": {r: 0, g: 63, b: 46, a: 0.95}, "chocolate": {r: 56, g: 30, b: 17, a: 0.95}, "terra cotta": {r: 192, g: 92, b: 32, a: 0.95}, "camel": {r: 191, g: 155, b: 107, a: 0.95}, "linen": {r: 233, g: 212, b: 167, a: 0.95}, "stone": {r: 231, g: 230, b: 225, a: 0.95}, "smoke": {r: 207, g: 208, b: 210, a: 0.95}, "steel": {r: 138, g: 139, b: 143, a: 0.95}, "slate": {r: 119, g: 133, b: 144, a: 0.95}, "charcoal": {r: 71, g: 77, b: 77, a: 0.95}, "black": {r: 5, g: 6, b: 8, a: 0.95}, "white": {r: 255, g: 255, b: 255, a: 0.95}, "metalic silver": {r: 152, g: 162, b: 171, a: 0.95}, "metalic gold": {r: 159, g: 135, b: 89, a: 0.95}, "metalic copper": {r: 140, g: 102, b: 65, a: 0.95} }, stickTo: { bottom: "bottom", left: "left", right: "right", top: "top" } }, typeTooltipModel = { animateDuration: 300, animateFunction: html5tooltipsPredefined.animateFunction.fadeIn, color: null, contentText: "", contentMore: "", disableAnimation: false, stickTo: html5tooltipsPredefined.stickTo.bottom, stickDistance: 10, targetElements: [], targetSelector: "", targetXPath: "", maxWidth: null }, defaultOptions = { animateDuration: null, animateFunction: null, color: null, HTMLTemplate: null, disableAnimation: null, stickTo: null, maxWidth: null }, template = { HTML: [ "<div class='html5tooltip' style='box-sizing:border-box;position:fixed;'>", "<div class='html5tooltip-box'>", "<div class='html5tooltip-text'></div>", "<div class='html5tooltip-more' style='overflow:hidden;'>", "<div class='html5tooltip-hr'></div>", "<div class='html5tooltip-text'></div>", "</div>", "<div class='html5tooltip-pointer'><div class='html5tooltip-po'></div><div class='html5tooltip-pi'></div></div>", "</div>", "</div>" ].join(""), hookClasses: { tooltip: 'html5tooltip', tooltipBox: 'html5tooltip-box', tooltipText: 'html5tooltip-text', tooltipMore: 'html5tooltip-more', tooltipMoreText: 'html5tooltip-text', tooltipPointer: 'html5tooltip-pointer' } }; function toArray(obj) { return Array.prototype.slice.call(obj); } function getElementsByXPath(xpath, context) { var nodes = []; try { var result = document.evaluate(xpath, (context || document), null, XPathResult.ANY_TYPE, null); for (var item = result.iterateNext(); item; item = result.iterateNext()) nodes.push(item); } catch (exc) { // Invalid xpath expressions make their way here sometimes. If that happens, // we still want to return an empty set without an exception. } return nodes; } function getElementsBySelector(selector, context) { var nodes = []; try { nodes = toArray((context || document).querySelectorAll(selector)); } catch (exc) {} return nodes; } function getElementsByAttribute(attr, context) { var nodeList = (context || document).getElementsByTagName('*'), nodes = []; for (var i = 0, node; node = nodeList[i]; i++) { if ( node.getAttribute(attr) ) nodes.push(node); } return nodes; } function extend(targetObj) { for (var i = 1; i < arguments.length; i++) { if (typeof arguments[i] === "object") { for (var property in arguments[i]) { if (arguments[i].hasOwnProperty(property)) { targetObj[property] = arguments[i][property]; } } } } return targetObj; } function Tooltip() { var ttElement, ttModel, targetElement, elBox, elText, elMore, elMoreText, elPointer; function animateElementClass(el, updateHandler) { if (!ttModel.disableAnimation) { // magic fix: refresh the animation queue el.offsetWidth = el.offsetWidth; el.classList.add("animating"); updateHandler(); setTimeout(function() { el.classList.remove("animating"); }, ttModel.animateDuration); } else updateHandler(); } function applyAnimationClass(el, fromClass, toClass, updateHandler) { if (!ttModel.disableAnimation) { el.classList.add(fromClass); // magic fix: refresh the animation queue el.offsetWidth = el.offsetWidth; el.classList.add("animating"); el.classList.remove(fromClass); el.classList.add(toClass); if (updateHandler) updateHandler(); setTimeout(function() { el.classList.remove("animating"); el.classList.remove(toClass); }, ttModel.animateDuration); } else if (updateHandler) updateHandler(); } function destroy() { document.removeChild(ttElement); } function hideAll() { if (ttElement.style.visibility !== 'collapse') ttElement.style.visibility = 'collapse'; ttElement.style.left = '-9999px'; ttElement.style.top = '-9999px'; if (elMore.style.display !== 'none') { elMore.style.display = 'none'; elMore.style.visibility = 'collapse'; elMore.style.height = 'auto'; } return this; } function init() { var tmplNode = document.createElement("div"); tmplNode.innerHTML = options.HTMLTemplate ? options.HTMLTemplate : template.HTML; ttElement = tmplNode.firstChild; elBox = ttElement.getElementsByClassName(template.hookClasses.tooltipBox)[0]; elText = ttElement.getElementsByClassName(template.hookClasses.tooltipText)[0]; elMore = ttElement.getElementsByClassName(template.hookClasses.tooltipMore)[0]; elMoreText = elMore.getElementsByClassName(template.hookClasses.tooltipMoreText)[0]; elPointer = ttElement.getElementsByClassName(template.hookClasses.tooltipPointer)[0]; hideAll(); ttModel = extend({}, typeTooltipModel); } function model(userTTModel) { if (!userTTModel) return ttModel; if (ttModel !== userTTModel) { ttModel = extend({}, typeTooltipModel, userTTModel); updateModel(); } return this; } function showBrief() { if (ttElement.style.visibility !== 'visible') { ttElement.style.visibility = 'visible'; updatePos(); applyAnimationClass(elBox, ttModel.animateFunction + "-from", ttModel.animateFunction + "-to"); } return this; } function showAll() { if (ttElement.style.visibility !== 'visible') { ttElement.style.visibility = 'visible'; applyAnimationClass(elBox, ttModel.animateFunction + "-from", ttModel.animateFunction + "-to"); if (ttModel.contentMore) { elMore.style.display = 'block'; elMore.style.visibility = 'visible'; } updatePos(); } else if (elMore.style.display !== 'block' && ttModel.contentMore) { elMore.style.display = 'block'; updateTooltipPos(); // animate pointer animateElementClass(elPointer, updatePointerPos); var h = elMore.getBoundingClientRect().height; elMore.style.visibility = 'visible'; elMore.style.height = '0px'; // animate more content animateElementClass(elMore, function() { elMore.style.height = h > 0 ? h + 'px' : "auto"; }); } return this; } function target(userTargetElement) { if (!userTargetElement) return targetElement; if (targetElement !== userTargetElement) { targetElement = userTargetElement; } return this; } function updatePos() { updateTooltipPos(); updatePointerPos(); } function updatePointerPos() { var ttRect; if (!targetElement) return; // position depend on target and tt width ttRect = ttElement.getBoundingClientRect(); pointerRect = elPointer.getBoundingClientRect(); switch (ttModel.stickTo) { case html5tooltipsPredefined.stickTo.bottom: elPointer.style.left = parseInt((ttRect.width - pointerRect.width) / 2) + "px"; elPointer.style.top = -1 * pointerRect.height + "px"; break; case html5tooltipsPredefined.stickTo.left: elPointer.style.left = ttRect.width - 2 + "px"; elPointer.style.top = parseInt((ttRect.height - pointerRect.height) / 2) + "px"; break; case html5tooltipsPredefined.stickTo.right: elPointer.style.left = -1 * pointerRect.width + 1 + "px"; elPointer.style.top = parseInt((ttRect.height - pointerRect.height) / 2) + "px"; break; case html5tooltipsPredefined.stickTo.top: elPointer.style.left = parseInt((ttRect.width - pointerRect.width) / 2) + "px"; elPointer.style.top = ttRect.height - 2 + "px"; break; } } function updateTooltipPos() { var targetRect, ttRect; if (!targetElement) return; // update width ttElement.style.width = "auto"; ttRect = ttElement.getBoundingClientRect(); var maxWidth = ttModel.maxWidth || options.maxWidth; if (maxWidth) ttElement.style.width = ttRect.width > maxWidth ? maxWidth + "px" : "auto"; // position depend on target and tt width targetRect = targetElement.getBoundingClientRect(); ttRect = ttElement.getBoundingClientRect(); switch (ttModel.stickTo) { case html5tooltipsPredefined.stickTo.bottom: ttElement.style.left = targetRect.left + parseInt((targetRect.width - ttRect.width) / 2) + "px"; ttElement.style.top = targetRect.top + targetRect.height + parseInt(ttModel.stickDistance) + "px"; break; case html5tooltipsPredefined.stickTo.left: ttElement.style.left = targetRect.left - ttRect.width - parseInt(ttModel.stickDistance) + "px"; ttElement.style.top = targetRect.top + (targetRect.height - ttRect.height) / 2 + "px"; break; case html5tooltipsPredefined.stickTo.right: ttElement.style.left = targetRect.left + targetRect.width + parseInt(ttModel.stickDistance) + "px"; ttElement.style.top = targetRect.top + (targetRect.height - ttRect.height) / 2 + "px"; break; case html5tooltipsPredefined.stickTo.top: ttElement.style.left = targetRect.left + (targetRect.width - ttRect.width) / 2 + "px"; ttElement.style.top = targetRect.top - ttRect.height - parseInt(ttModel.stickDistance) + "px"; break; } } function updateModel() { elText.innerHTML = ttModel.contentText ? ttModel.contentText : ""; elMoreText.innerHTML = ttModel.contentMore ? ttModel.contentMore : ""; // update animation ttModel.animateDuration = options.animateDuration ? options.animateDuration : ttModel.animateDuration; ttModel.animateFunction = options.animateFunction ? options.animateFunction : ttModel.animateFunction; ttModel.disableAnimation = options.disableAnimation ? options.disableAnimation : ttModel.disableAnimation; // update color ttModel.color = options.color ? options.color : ttModel.color; if (html5tooltipsPredefined.color[ttModel.color]) { ttModel.color = html5tooltipsPredefined.color[ttModel.color]; ttModel.color = "rgba(" + ttModel.color.r + ", " + ttModel.color.g + ", " + ttModel.color.b + ", " + ttModel.color.a + ")"; } elBox.style.backgroundColor = ttModel.color||''; elPointer.style.borderColor = ttModel.color||''; // update pointer ttElement.className = template.hookClasses.tooltip + "-" + ttModel.stickTo; if (document.body && ttElement.parentNode !== document.body) document.body.appendChild(ttElement); } init(); return { destroy: destroy, hideAll: hideAll, model: model, showAll: showAll, showBrief: showBrief, target: target, updatePos: updatePos }; } function pickDocumentDataTargets() { var pickedElements = getElementsByAttribute("data-tooltip"); pickedElements.forEach(function(elTarget) { var tm = { contentText: elTarget.getAttribute("data-tooltip"), targetElements: [elTarget] }; if (elTarget.getAttribute("data-tooltip-animate-function") !== null) tm.animateFunction = elTarget.getAttribute("data-tooltip-animate-function"); if (elTarget.getAttribute("data-tooltip-color") !== null) tm.color = elTarget.getAttribute("data-tooltip-color"); if (elTarget.getAttribute("data-tooltip-more") !== null) tm.contentMore = elTarget.getAttribute("data-tooltip-more"); if (elTarget.getAttribute("data-tooltip-stickto") !== null) tm.stickTo = elTarget.getAttribute("data-tooltip-stickto"); if (elTarget.getAttribute("data-tooltip-maxwidth") !== null) tm.maxWidth = elTarget.getAttribute("data-tooltip-maxwidth"); tModels.push(extend({}, typeTooltipModel, tm)); }); } function tieTooltips() { tModels.forEach(function(tModel, i) { tModel = extend({}, typeTooltipModel, tModel); if (!tModel.targetElements.length && tModel.targetSelector) tModel.targetElements = getElementsBySelector(tModel.targetSelector); if (!tModel.targetElements.length && tModel.targetXPath) tModel.targetElements = getElementsByXPath(tModel.targetXPath); tModel.targetElements.forEach(function(el) { el.addEventListener("mouseover", function() { var hoverTarget = this; if (activeElements.hovered === hoverTarget || activeElements.focused !== null) return; activeElements.hovered = hoverTarget; tt.target(this).model(tModel); setTimeout(function() { if (activeElements.hovered === hoverTarget) tt.showBrief(); }, 300); }); el.addEventListener("mouseout", function() { activeElements.hovered = null; if (activeElements.focused !== null) return; tt.hideAll(); }); el.addEventListener("focus", function() { if (["INPUT", "TEXTAREA"].indexOf(this.tagName) === -1 && this.getAttribute("contenteditable") === null) return; activeElements.focused = this; tt.target(this).model(tModel); tt.showAll(); }); el.addEventListener("blur", function() { activeElements.focused = null; tt.hideAll(); }); }); tModels[i] = tModel; }); } function init() { if (!tt) { options = {}; tt = Tooltip(); tModels = []; } activeElements = { focused: null, hovered: null }; } function html5tooltipsGlobal(userTModels, userOptions) { if (userTModels.length) // merge arrays Array.prototype.push.apply(tModels, userTModels); else if (typeof userTModels === "object") tModels.push(userTModels); options = userOptions ? extend({}, userOptions) : options; tieTooltips(); } var html5tooltipsAMD=function(userTModels, userOptions) { init(); html5tooltipsGlobal(userTModels, userOptions); }; //Provides html property reading for AMD html5tooltipsAMD.autoinit=function(){ init(); pickDocumentDataTargets(); tieTooltips(); }; function documentReadyHandler() { document.removeEventListener("DOMContentLoaded", documentReadyHandler, false); window.removeEventListener("load", documentReadyHandler, false); pickDocumentDataTargets(); tieTooltips(); } if (window.define) { // AMD define(function () { return html5tooltipsAMD; }); } else { // global object init(); if (document.readyState === "complete") { documentReadyHandler(); } else { document.addEventListener("DOMContentLoaded", documentReadyHandler, false); window.addEventListener( "load", documentReadyHandler, false ); } if (window.html5tooltips === undefined) { window.html5tooltipsPredefined = html5tooltipsPredefined; window.html5tooltips = html5tooltipsGlobal; } } window.addEventListener("scroll", function() { tt.updatePos(); }, false ); })();
jackrosenhauer/html5tooltipsjs
html5tooltips.js
JavaScript
mit
17,672
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("uicolor","de",{title:"UI-Farbpipette",options:"Farboptionen",highlight:"Highlight",selected:"Ausgewählte Farbe",predefined:"Vordefinierte Farbsätze",config:"Fügen Sie diese Zeichenfolge in die Datei config.js ein."});
gitee2008/glaf
webapps/glaf/static/AdminLTE/bower_components/ckeditor/plugins/uicolor/lang/de.js
JavaScript
apache-2.0
414
var Waterline = require('../../../lib/waterline'), assert = require('assert'); describe('Model', function() { describe('associations Many To Many', function() { describe('.add() with an id', function() { ///////////////////////////////////////////////////// // TEST SETUP //////////////////////////////////////////////////// var collections = {}; var prefValues = []; before(function(done) { var waterline = new Waterline(); var User = Waterline.Collection.extend({ connection: 'my_foo', tableName: 'person', attributes: { preferences: { collection: 'preference', via: 'people', dominant: true } } }); var Preference = Waterline.Collection.extend({ connection: 'my_foo', tableName: 'preference', attributes: { foo: 'string', people: { collection: 'person', via: 'preferences' } } }); waterline.loadCollection(User); waterline.loadCollection(Preference); var _values = [ { id: 1, preference: [{ foo: 'bar' }, { foo: 'foobar' }] }, { id: 2, preference: [{ foo: 'a' }, { foo: 'b' }] }, ]; var i = 1; var adapterDef = { find: function(con, col, criteria, cb) { if(col === 'person_preferences__preference_people') return cb(null, []); cb(null, _values); }, update: function(con, col, criteria, values, cb) { if(col === 'preference') { prefValues.push(values); } return cb(null, values); }, create: function(con, col, values, cb) { prefValues.push(values); return cb(null, values); }, }; var connections = { 'my_foo': { adapter: 'foobar' } }; waterline.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) { if(err) done(err); collections = colls.collections; done(); }); }); ///////////////////////////////////////////////////// // TEST METHODS //////////////////////////////////////////////////// it('should pass foreign key values to update method for each relationship', function(done) { collections.person.find().exec(function(err, models) { if(err) return done(err); var person = models[0]; person.preferences.add(1); person.preferences.add(2); person.save(function(err) { if(err) return done(err); assert(prefValues.length === 2); assert(prefValues[0].preference_people === 1); assert(prefValues[1].preference_people === 2); done(); }); }); }); }); }); });
contra/waterline
test/integration/model/association.add.manyToMany.id.js
JavaScript
mit
3,026
/* ** Copyright (c) 2018 The Khronos Group Inc. ** ** Permission is hereby granted, free of charge, to any person obtaining a ** copy of this software and/or associated documentation files (the ** "Materials"), to deal in the Materials without restriction, including ** without limitation the rights to use, copy, modify, merge, publish, ** distribute, sublicense, and/or sell copies of the Materials, and to ** permit persons to whom the Materials are 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 Materials. ** ** THE MATERIALS ARE 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 ** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. */ 'use strict'; description("Verifies that lines, both aliased and antialiased, have acceptable quality."); let wtu = WebGLTestUtils; let gl; let aa_fbo; function setupWebGL1Test(canvasId, useAntialiasing) { gl = wtu.create3DContext(canvasId, { antialias: useAntialiasing }, contextVersion); wtu.glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors during WebGL 1.0 setup"); } function setupWebGL2Test(canvasId, useAntialiasing) { gl = wtu.create3DContext(canvasId, { antialias: false }, contextVersion); // In WebGL 2.0, we always allocate the back buffer without // antialiasing. The only question is whether we allocate a // framebuffer with a multisampled renderbuffer attachment. aa_fbo = null; if (useAntialiasing) { aa_fbo = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, aa_fbo); let rb = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, rb); let supported = gl.getInternalformatParameter(gl.RENDERBUFFER, gl.RGBA8, gl.SAMPLES); // Prefer 4, then 8, then max. let preferred = [4, 8]; let allocated = false; for (let value of preferred) { if (supported.indexOf(value) >= 0) { gl.renderbufferStorageMultisample(gl.RENDERBUFFER, value, gl.RGBA8, gl.drawingBufferWidth, gl.drawingBufferHeight); allocated = true; break; } } if (!allocated) { gl.renderbufferStorageMultisample(gl.RENDERBUFFER, supported[supported.length - 1], gl.RGBA8, gl.drawingBufferWidth, gl.drawingBufferHeight); } gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, rb); } wtu.glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors during WebGL 2.0 setup"); } function setupLines() { let prog = wtu.setupSimpleColorProgram(gl, 0); let loc = gl.getUniformLocation(prog, 'u_color'); if (loc == null) { testFailed('Failed to fetch color uniform'); } wtu.glErrorShouldBe(gl, gl.NO_ERROR, "After setup of line program"); gl.uniform4f(loc, 1.0, 1.0, 1.0, 1.0); let buffer = gl.createBuffer(); let scale = 0.5; gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ -scale, -scale, 0.0, 1.0, -scale, scale, 0.0, 1.0, scale, scale, 0.0, 1.0, scale, -scale, 0.0, 1.0, -scale, -scale, 0.0, 1.0, ]), gl.STATIC_DRAW); wtu.glErrorShouldBe(gl, gl.NO_ERROR, "After setup of buffer"); gl.vertexAttribPointer(0, 4, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(0); wtu.glErrorShouldBe(gl, gl.NO_ERROR, "After setup of attribute array"); } function renderLines(contextVersion, useAntialiasing) { gl.clearColor(0.0, 0.0, 0.5, 1.0); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.LINE_STRIP, 0, 5); if (contextVersion == 2 && useAntialiasing) { // Blit aa_fbo into the real back buffer. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, aa_fbo); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); let w = gl.drawingBufferWidth; let h = gl.drawingBufferHeight; gl.blitFramebuffer(0, 0, w, h, 0, 0, w, h, gl.COLOR_BUFFER_BIT, gl.NEAREST); gl.bindFramebuffer(gl.FRAMEBUFFER, null); } } function pixelAboveThreshold(arr, pixelIndex, threshold) { return (arr[4 * pixelIndex + 0] >= threshold && arr[4 * pixelIndex + 1] >= threshold && arr[4 * pixelIndex + 2] >= threshold && arr[4 * pixelIndex + 3] >= threshold); } function checkLine(arr, threshold, direction) { // Count number of crossings from below threshold to above (or equal // to) threshold. Must be equal to 2. let numPixels = arr.length / 4; let numUpCrossings = 0; let numDownCrossings = 0; for (let index = 0; index < numPixels - 1; ++index) { let curPixel = pixelAboveThreshold(arr, index, threshold); let nextPixel = pixelAboveThreshold(arr, index + 1, threshold); if (!curPixel && nextPixel) { ++numUpCrossings; } else if (curPixel && !nextPixel) { ++numDownCrossings; } } if (numUpCrossings != numDownCrossings) { testFailed('Found differing numbers of up->down and down->up transitions'); } if (numUpCrossings == 2) { testPassed('Found 2 lines, looking in the ' + direction + ' direction'); } else { testFailed('Found ' + numUpCrossings + ' lines, looking in the ' + direction + ' direction, expected 2'); } } function checkResults() { // Check the middle horizontal and middle vertical line of the canvas. let w = gl.drawingBufferWidth; let h = gl.drawingBufferHeight; let t = 100; let arr = new Uint8Array(4 * w); gl.readPixels(0, Math.floor(h / 2), w, 1, gl.RGBA, gl.UNSIGNED_BYTE, arr); checkLine(arr, t, 'horizontal'); arr = new Uint8Array(4 * h); gl.readPixels(Math.floor(w / 2), 0, 1, h, gl.RGBA, gl.UNSIGNED_BYTE, arr); checkLine(arr, t, 'vertical'); } function runTest(contextVersion, canvasId, useAntialiasing) { switch (contextVersion) { case 1: { setupWebGL1Test(canvasId, useAntialiasing); break; } case 2: { setupWebGL2Test(canvasId, useAntialiasing); } } setupLines(); renderLines(contextVersion, useAntialiasing); checkResults(); } function runTests() { runTest(contextVersion, 'testbed', false); runTest(contextVersion, 'testbed2', true); } runTests(); let successfullyParsed = true;
paulrouget/servo
tests/wpt/webgl/tests/js/tests/line-rendering-quality.js
JavaScript
mpl-2.0
6,605
/* * blueimp Gallery JS 2.7.4 * https://github.com/blueimp/Gallery * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Swipe implementation based on * https://github.com/bradbirdsall/Swipe * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint regexp: true */ /*global define, window, document, DocumentTouch */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['./blueimp-helper'], factory); } else { // Browser globals: window.blueimp = window.blueimp || {}; window.blueimp.Gallery = factory( window.blueimp.helper || window.jQuery ); } }(function ($) { 'use strict'; function Gallery(list, options) { if (!list || !list.length || document.body.style.maxHeight === undefined) { // document.body.style.maxHeight is undefined on IE6 and lower return false; } if (!this || this.options !== Gallery.prototype.options) { // Called as function instead of as constructor, // so we simply return a new instance: return new Gallery(list, options); } this.list = list; this.num = list.length; this.initOptions(options); this.initialize(); } $.extend(Gallery.prototype, { options: { // The Id, element or querySelector of the gallery widget: container: '#blueimp-gallery', // The tag name, Id, element or querySelector of the slides container: slidesContainer: 'div', // The tag name, Id, element or querySelector of the title element: titleElement: 'h3', // The class to add when the gallery is visible: displayClass: 'blueimp-gallery-display', // The class to add when the gallery controls are visible: controlsClass: 'blueimp-gallery-controls', // The class to add when the gallery only displays one element: singleClass: 'blueimp-gallery-single', // The class to add when the left edge has been reached: leftEdgeClass: 'blueimp-gallery-left', // The class to add when the right edge has been reached: rightEdgeClass: 'blueimp-gallery-right', // The class to add when the automatic slideshow is active: playingClass: 'blueimp-gallery-playing', // The class for all slides: slideClass: 'slide', // The slide class for loading elements: slideLoadingClass: 'slide-loading', // The slide class for elements that failed to load: slideErrorClass: 'slide-error', // The class for the content element loaded into each slide: slideContentClass: 'slide-content', // The class for the "toggle" control: toggleClass: 'toggle', // The class for the "prev" control: prevClass: 'prev', // The class for the "next" control: nextClass: 'next', // The class for the "close" control: closeClass: 'close', // The class for the "play-pause" toggle control: playPauseClass: 'play-pause', // The list object property (or data attribute) with the object type: typeProperty: 'type', // The list object property (or data attribute) with the object title: titleProperty: 'title', // The list object property (or data attribute) with the object URL: urlProperty: 'href', // Defines if the gallery slides are cleared from the gallery modal, // or reused for the next gallery initialization: clearSlides: true, // Defines if images should be stretched to fill the available space, // while maintaining their aspect ratio (will only be enabled for browsers // supporting background-size="contain", which excludes IE < 9): stretchImages: false, // Toggle the controls on pressing the Return key: toggleControlsOnReturn: true, // Toggle the automatic slideshow interval on pressing the Space key: toggleSlideshowOnSpace: true, // Navigate the gallery by pressing left and right on the keyboard: enableKeyboardNavigation: true, // Close the gallery on pressing the Esc key: closeOnEscape: true, // Close the gallery when clicking on an empty slide area: closeOnSlideClick: true, // Close the gallery by swiping up or down: closeOnSwipeUpOrDown: true, // Emulate touch events on mouse-pointer devices such as desktop browsers: emulateTouchEvents: true, // Hide the page scrollbars: hidePageScrollbars: true, // Stops any touches on the container from scrolling the page: disableScroll: true, // Carousel mode (shortcut for carousel specific options): carousel: false, // Allow continuous navigation, moving from last to first // and from first to last slide: continuous: true, // Remove elements outside of the preload range from the DOM: unloadElements: true, // Start with the automatic slideshow: startSlideshow: false, // Delay in milliseconds between slides for the automatic slideshow: slideshowInterval: 5000, // The starting index as integer. // Can also be an object of the given list, // or an equal object with the same url property: index: 0, // The number of elements to load around the current index: preloadRange: 2, // The transition speed between slide changes in milliseconds: transitionSpeed: 400, // The transition speed for automatic slide changes, set to an integer // greater 0 to override the default transition speed: slideshowTransitionSpeed: undefined, // The event object for which the default action will be canceled // on Gallery initialization (e.g. the click event to open the Gallery): event: undefined, // Callback function executed when the Gallery is initialized. // Is called with the gallery instance as "this" object: onopen: undefined, // Callback function executed on slide change. // Is called with the gallery instance as "this" object and the // current index and slide as arguments: onslide: undefined, // Callback function executed after the slide change transition. // Is called with the gallery instance as "this" object and the // current index and slide as arguments: onslideend: undefined, // Callback function executed on slide content load. // Is called with the gallery instance as "this" object and the // slide index and slide element as arguments: onslidecomplete: undefined, // Callback function executed when the Gallery is closed. // Is called with the gallery instance as "this" object: onclose: undefined }, carouselOptions: { hidePageScrollbars: false, toggleControlsOnReturn: false, toggleSlideshowOnSpace: false, enableKeyboardNavigation: false, closeOnEscape: false, closeOnSlideClick: false, closeOnSwipeUpOrDown: false, disableScroll: false, startSlideshow: true }, // Detect touch, transition, transform and background-size support: support: (function (element) { var support = { touch: window.ontouchstart !== undefined || (window.DocumentTouch && document instanceof DocumentTouch) }, transitions = { webkitTransition: { end: 'webkitTransitionEnd', prefix: '-webkit-' }, MozTransition: { end: 'transitionend', prefix: '-moz-' }, OTransition: { end: 'otransitionend', prefix: '-o-' }, transition: { end: 'transitionend', prefix: '' } }, prop, transition, translateZ, elementTests = function () { document.body.appendChild(element); if (transition) { prop = transition.name.slice(0, -9) + 'ransform'; if (element.style[prop] !== undefined) { element.style[prop] = 'translateZ(0)'; translateZ = window.getComputedStyle(element) .getPropertyValue(transition.prefix + 'transform'); support.transform = { prefix: transition.prefix, name: prop, translate: true, translateZ: !!translateZ && translateZ !== 'none' }; } } if (element.style.backgroundSize !== undefined) { element.style.backgroundSize = 'contain'; support.backgroundSize = { contain: window.getComputedStyle(element) .getPropertyValue('background-size') === 'contain' }; } document.body.removeChild(element); }; for (prop in transitions) { if (transitions.hasOwnProperty(prop) && element.style[prop] !== undefined) { transition = transitions[prop]; transition.name = prop; support.transition = transition; break; } } if (document.body) { elementTests(); } else { $(document).on('DOMContentLoaded', elementTests); } return support; // Test element, has to be standard HTML and must not be hidden // for the CSS3 tests using window.getComputedStyle to be applicable: }(document.createElement('div'))), initialize: function () { this.initStartIndex(); if (this.initWidget() === false) { return false; } this.initEventListeners(); if (this.options.onopen) { this.options.onopen.call(this); } // Load the slide at the given index: this.onslide(this.index); // Manually trigger the slideend event for the initial slide: this.ontransitionend(); // Start the automatic slideshow if applicable: if (this.options.startSlideshow) { this.play(); } }, slide: function (to, speed) { window.clearTimeout(this.timeout); var index = this.index, direction, natural_direction, diff; if (index === to || this.num === 1) { return; } if (!speed) { speed = this.options.transitionSpeed; } if (this.support.transition) { if (!this.options.continuous) { to = this.circle(to); } // 1: backward, -1: forward: direction = Math.abs(index - to) / (index - to); // Get the actual position of the slide: if (this.options.continuous) { natural_direction = direction; direction = -this.positions[this.circle(to)] / this.slideWidth; // If going forward but to < index, use to = slides.length + to // If going backward but to > index, use to = -slides.length + to if (direction !== natural_direction) { to = -direction * this.num + to; } } diff = Math.abs(index - to) - 1; // Move all the slides between index and to in the right direction: while (diff) { diff -= 1; this.move( this.circle((to > index ? to : index) - diff - 1), this.slideWidth * direction, 0 ); } to = this.circle(to); this.move(index, this.slideWidth * direction, speed); this.move(to, 0, speed); if (this.options.continuous) { this.move( this.circle(to - direction), -(this.slideWidth * direction), 0 ); } } else { to = this.circle(to); this.animate(index * -this.slideWidth, to * -this.slideWidth, speed); } this.onslide(to); }, getIndex: function () { return this.index; }, getNumber: function () { return this.num; }, prev: function () { if (this.options.continuous || this.index) { this.slide(this.index - 1); } }, next: function () { if (this.options.continuous || this.index < this.num - 1) { this.slide(this.index + 1); } }, play: function (time) { window.clearTimeout(this.timeout); this.interval = time || this.options.slideshowInterval; if (this.elements[this.index] > 1) { this.timeout = this.setTimeout( this.slide, [this.index + 1, this.options.slideshowTransitionSpeed], this.interval ); } this.container.addClass(this.options.playingClass); }, pause: function () { window.clearTimeout(this.timeout); this.interval = null; this.container.removeClass(this.options.playingClass); }, add: function (list) { var i; this.list = this.list.concat(list); this.num = this.list.length; if (this.num > 2 && this.options.continuous === null) { this.options.continuous = true; this.container.removeClass(this.options.leftEdgeClass); } this.container .removeClass(this.options.rightEdgeClass) .removeClass(this.options.singleClass); for (i = this.num - list.length; i < this.num; i += 1) { this.addSlide(i); this.positionSlide(i); } this.positions.length = this.num; this.initSlides(true); }, resetSlides: function () { this.slidesContainer.empty(); this.slides = []; }, close: function () { var options = this.options; this.destroyEventListeners(); // Cancel the slideshow: this.pause(); this.container[0].style.display = 'none'; this.container .removeClass(options.displayClass) .removeClass(options.singleClass) .removeClass(options.leftEdgeClass) .removeClass(options.rightEdgeClass); if (options.hidePageScrollbars) { document.body.style.overflow = this.bodyOverflowStyle; } if (this.options.clearSlides) { this.resetSlides(); } if (this.options.onclose) { this.options.onclose.call(this); } }, circle: function (index) { // Always return a number inside of the slides index range: return (this.num + (index % this.num)) % this.num; }, move: function (index, dist, speed) { this.translateX(index, dist, speed); this.positions[index] = dist; }, translate: function (index, x, y, speed) { var style = this.slides[index].style, transition = this.support.transition, transform = this.support.transform; style[transition.name + 'Duration'] = speed + 'ms'; style[transform.name] = 'translate(' + x + 'px, ' + y + 'px)' + (transform.translateZ ? ' translateZ(0)' : ''); }, translateX: function (index, x, speed) { this.translate(index, x, 0, speed); }, translateY: function (index, y, speed) { this.translate(index, 0, y, speed); }, animate: function (from, to, speed) { if (!speed) { this.slidesContainer[0].style.left = to + 'px'; return; } var that = this, start = new Date().getTime(), timer = window.setInterval(function () { var timeElap = new Date().getTime() - start; if (timeElap > speed) { that.slidesContainer[0].style.left = to + 'px'; that.ontransitionend(); window.clearInterval(timer); return; } that.slidesContainer[0].style.left = (((to - from) * (Math.floor((timeElap / speed) * 100) / 100)) + from) + 'px'; }, 4); }, preventDefault: function (event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } }, onresize: function () { this.initSlides(true); }, onmousedown: function (event) { // Trigger on clicks of the left mouse button only: if (event.which && event.which === 1) { // Preventing the default mousedown action is required // to make touch emulation work with Firefox: event.preventDefault(); (event.originalEvent || event).touches = [{ pageX: event.pageX, pageY: event.pageY }]; this.ontouchstart(event); } }, onmousemove: function (event) { if (this.touchStart) { (event.originalEvent || event).touches = [{ pageX: event.pageX, pageY: event.pageY }]; this.ontouchmove(event); } }, onmouseup: function (event) { if (this.touchStart) { this.ontouchend(event); delete this.touchStart; } }, onmouseout: function (event) { if (this.touchStart) { var target = event.target, related = event.relatedTarget; if (!related || (related !== target && !$.contains(target, related))) { this.onmouseup(event); } } }, ontouchstart: function (event) { // jQuery doesn't copy touch event properties by default, // so we have to access the originalEvent object: var touches = (event.originalEvent || event).touches[0]; this.touchStart = { // Remember the initial touch coordinates: x: touches.pageX, y: touches.pageY, // Store the time to determine touch duration: time: Date.now() }; // Helper variable to detect scroll movement: this.isScrolling = undefined; // Reset delta values: this.touchDelta = {}; }, ontouchmove: function (event) { // jQuery doesn't copy touch event properties by default, // so we have to access the originalEvent object: var touches = (event.originalEvent || event).touches[0], scale = (event.originalEvent || event).scale, index = this.index, touchDeltaX, indices; // Ensure this is a one touch swipe and not, e.g. a pinch: if (touches.length > 1 || (scale && scale !== 1)) { return; } if (this.options.disableScroll) { event.preventDefault(); } // Measure change in x and y coordinates: this.touchDelta = { x: touches.pageX - this.touchStart.x, y: touches.pageY - this.touchStart.y }; touchDeltaX = this.touchDelta.x; // Detect if this is a vertical scroll movement (run only once per touch): if (this.isScrolling === undefined) { this.isScrolling = this.isScrolling || Math.abs(touchDeltaX) < Math.abs(this.touchDelta.y); } if (!this.isScrolling) { // Always prevent horizontal scroll: event.preventDefault(); // Stop the slideshow: window.clearTimeout(this.timeout); if (this.options.continuous) { indices = [ this.circle(index + 1), index, this.circle(index - 1) ]; } else { // Increase resistance if first slide and sliding left // or last slide and sliding right: this.touchDelta.x = touchDeltaX = touchDeltaX / (((!index && touchDeltaX > 0) || (index === this.num - 1 && touchDeltaX < 0)) ? (Math.abs(touchDeltaX) / this.slideWidth + 1) : 1); indices = [index]; if (index) { indices.push(index - 1); } if (index < this.num - 1) { indices.unshift(index + 1); } } while (indices.length) { index = indices.pop(); this.translateX(index, touchDeltaX + this.positions[index], 0); } } else if (this.options.closeOnSwipeUpOrDown) { this.translateY(index, this.touchDelta.y + this.positions[index], 0); } }, ontouchend: function () { var index = this.index, speed = this.options.transitionSpeed, slideWidth = this.slideWidth, isShortDuration = Number(Date.now() - this.touchStart.time) < 250, // Determine if slide attempt triggers next/prev slide: isValidSlide = (isShortDuration && Math.abs(this.touchDelta.x) > 20) || Math.abs(this.touchDelta.x) > slideWidth / 2, // Determine if slide attempt is past start or end: isPastBounds = (!index && this.touchDelta.x > 0) || (index === this.num - 1 && this.touchDelta.x < 0), isValidClose = !isValidSlide && this.options.closeOnSwipeUpOrDown && ((isShortDuration && Math.abs(this.touchDelta.y) > 20) || Math.abs(this.touchDelta.y) > this.slideHeight / 2), direction, indexForward, indexBackward, distanceForward, distanceBackward; if (this.options.continuous) { isPastBounds = false; } // Determine direction of swipe (true: right, false: left): direction = this.touchDelta.x < 0 ? -1 : 1; if (!this.isScrolling) { if (isValidSlide && !isPastBounds) { indexForward = index + direction; indexBackward = index - direction; distanceForward = slideWidth * direction; distanceBackward = -slideWidth * direction; if (this.options.continuous) { this.move(this.circle(indexForward), distanceForward, 0); this.move(this.circle(index - 2 * direction), distanceBackward, 0); } else if (indexForward >= 0 && indexForward < this.num) { this.move(indexForward, distanceForward, 0); } this.move(index, this.positions[index] + distanceForward, speed); this.move( this.circle(indexBackward), this.positions[this.circle(indexBackward)] + distanceForward, speed ); index = this.circle(indexBackward); this.onslide(index); } else { // Move back into position if (this.options.continuous) { this.move(this.circle(index - 1), -slideWidth, speed); this.move(index, 0, speed); this.move(this.circle(index + 1), slideWidth, speed); } else { if (index) { this.move(index - 1, -slideWidth, speed); } this.move(index, 0, speed); if (index < this.num - 1) { this.move(index + 1, slideWidth, speed); } } } } else { if (isValidClose) { this.close(); } else { // Move back into position this.translateY(index, 0, speed); } } }, ontransitionend: function (event) { var slide = this.slides[this.index]; if (!event || slide === event.target) { if (this.interval) { this.play(); } this.setTimeout( this.options.onslideend, [this.index, slide] ); } }, oncomplete: function (event) { var target = event.target || event.srcElement, parent = target && target.parentNode, index; if (!target || !parent) { return; } index = this.getNodeIndex(parent); $(parent).removeClass(this.options.slideLoadingClass); if (event.type === 'error') { $(parent).addClass(this.options.slideErrorClass); this.elements[index] = 3; // Fail } else { this.elements[index] = 2; // Done } // Fix for IE7's lack of support for percentage max-height: if (target.clientHeight > this.container[0].clientHeight) { target.style.maxHeight = this.container[0].clientHeight; } if (this.interval && this.slides[this.index] === parent) { this.play(); } this.setTimeout( this.options.onslidecomplete, [index, parent] ); }, onload: function (event) { this.oncomplete(event); }, onerror: function (event) { this.oncomplete(event); }, onkeydown: function (event) { switch (event.which || event.keyCode) { case 13: // Return if (this.options.toggleControlsOnReturn) { this.preventDefault(event); this.toggleControls(); } break; case 27: // Esc if (this.options.closeOnEscape) { this.close(); } break; case 32: // Space if (this.options.toggleSlideshowOnSpace) { this.preventDefault(event); this.toggleSlideshow(); } break; case 37: // Left if (this.options.enableKeyboardNavigation) { this.preventDefault(event); this.prev(); } break; case 39: // Right if (this.options.enableKeyboardNavigation) { this.preventDefault(event); this.next(); } break; } }, handleClick: function (event) { var options = this.options, target = event.target || event.srcElement, parent = target.parentNode, isTarget = function (className) { return $(target).hasClass(className) || $(parent).hasClass(className); }; if (parent === this.slidesContainer[0]) { // Click on slide background this.preventDefault(event); if (options.closeOnSlideClick) { this.close(); } else { this.toggleControls(); } } else if (parent.parentNode && parent.parentNode === this.slidesContainer[0]) { // Click on displayed element this.preventDefault(event); this.toggleControls(); } else if (isTarget(options.toggleClass)) { // Click on "toggle" control this.preventDefault(event); this.toggleControls(); } else if (isTarget(options.prevClass)) { // Click on "prev" control this.preventDefault(event); this.prev(); } else if (isTarget(options.nextClass)) { // Click on "next" control this.preventDefault(event); this.next(); } else if (isTarget(options.closeClass)) { // Click on "close" control this.preventDefault(event); this.close(); } else if (isTarget(options.playPauseClass)) { // Click on "play-pause" control this.preventDefault(event); this.toggleSlideshow(); } }, onclick: function (event) { if (this.options.emulateTouchEvents && this.touchDelta && (Math.abs(this.touchDelta.x) > 20 || Math.abs(this.touchDelta.y) > 20)) { delete this.touchDelta; return; } return this.handleClick(event); }, updateEdgeClasses: function (index) { if (!index) { this.container.addClass(this.options.leftEdgeClass); } else { this.container.removeClass(this.options.leftEdgeClass); } if (index === this.num - 1) { this.container.addClass(this.options.rightEdgeClass); } else { this.container.removeClass(this.options.rightEdgeClass); } }, handleSlide: function (index) { if (!this.options.continuous) { this.updateEdgeClasses(index); } this.loadElements(index); if (this.options.unloadElements) { this.unloadElements(index); } this.setTitle(index); }, onslide: function (index) { this.index = index; this.handleSlide(index); this.setTimeout(this.options.onslide, [index, this.slides[index]]); }, setTitle: function (index) { var text = this.slides[index].firstChild.title, titleElement = this.titleElement; if (titleElement.length) { this.titleElement.empty(); if (text) { titleElement[0].appendChild(document.createTextNode(text)); } } }, setTimeout: function (func, args, wait) { var that = this; return func && window.setTimeout(function () { func.apply(that, args || []); }, wait || 0); }, imageFactory: function (obj, callback) { var that = this, img = this.imagePrototype.cloneNode(false), url = obj, contain = this.options.stretchImages && this.support.backgroundSize && this.support.backgroundSize.contain, called, element, callbackWrapper = function (event) { if (!called) { event = { type: event.type, target: element }; if (!element.parentNode) { // Fix for IE7 firing the load event for // cached images before the element could // be added to the DOM: return that.setTimeout(callbackWrapper, [event]); } called = true; $(img).off('load error', callbackWrapper); if (contain) { if (event.type === 'load') { element.style.background = 'url("' + url + '") center no-repeat'; element.style.backgroundSize = 'contain'; } } callback(event); } }, title; if (typeof url !== 'string') { url = this.getItemProperty(obj, this.options.urlProperty); title = this.getItemProperty(obj, this.options.titleProperty); } if (contain) { element = this.elementPrototype.cloneNode(false); } else { element = img; img.draggable = false; } if (title) { element.title = title; } $(img).on('load error', callbackWrapper); img.src = url; return element; }, createElement: function (obj, callback) { var type = obj && this.getItemProperty(obj, this.options.typeProperty), factory = (type && this[type.split('/')[0] + 'Factory']) || this.imageFactory, element = obj && factory.call(this, obj, callback); if (!element) { element = this.elementPrototype.cloneNode(false); this.setTimeout(callback, [{ type: 'error', target: element }]); } $(element).addClass(this.options.slideContentClass); return element; }, loadElement: function (index) { if (!this.elements[index]) { if (this.slides[index].firstChild) { this.elements[index] = $(this.slides[index]) .hasClass(this.options.slideErrorClass) ? 3 : 2; } else { this.elements[index] = 1; // Loading $(this.slides[index]).addClass(this.options.slideLoadingClass); this.slides[index].appendChild(this.createElement( this.list[index], this.proxyListener )); } } }, loadElements: function (index) { var limit = Math.min(this.num, this.options.preloadRange * 2 + 1), j = index, i; for (i = 0; i < limit; i += 1) { // First load the current slide element (0), // then the next one (+1), // then the previous one (-2), // then the next after next (+2), etc.: j += i * (i % 2 === 0 ? -1 : 1); // Connect the ends of the list to load slide elements for // continuous navigation: j = this.circle(j); this.loadElement(j); } }, unloadElements: function (index) { var i, slide, diff; for (i in this.elements) { if (this.elements.hasOwnProperty(i)) { diff = Math.abs(index - i); if (diff > this.options.preloadRange && diff + this.options.preloadRange < this.num) { slide = this.slides[i]; slide.removeChild(slide.firstChild); delete this.elements[i]; } } } }, addSlide: function (index) { var slide = this.slidePrototype.cloneNode(false); slide.setAttribute('data-index', index); this.slidesContainer[0].appendChild(slide); this.slides.push(slide); }, positionSlide: function (index) { var slide = this.slides[index]; slide.style.width = this.slideWidth + 'px'; if (this.support.transition) { slide.style.left = (index * -this.slideWidth) + 'px'; this.move(index, this.index > index ? -this.slideWidth : (this.index < index ? this.slideWidth : 0), 0); } }, initSlides: function (reload) { var clearSlides, i; if (!reload) { this.positions = []; this.positions.length = this.num; this.elements = {}; this.imagePrototype = document.createElement('img'); this.elementPrototype = document.createElement('div'); this.slidePrototype = document.createElement('div'); $(this.slidePrototype).addClass(this.options.slideClass); this.slides = this.slidesContainer[0].children; clearSlides = this.options.clearSlides || this.slides.length !== this.num; } this.slideWidth = this.container[0].offsetWidth; this.slideHeight = this.container[0].offsetHeight; this.slidesContainer[0].style.width = (this.num * this.slideWidth) + 'px'; if (clearSlides) { this.resetSlides(); } for (i = 0; i < this.num; i += 1) { if (clearSlides) { this.addSlide(i); } this.positionSlide(i); } // Reposition the slides before and after the given index: if (this.options.continuous && this.support.transition) { this.move(this.circle(this.index - 1), -this.slideWidth, 0); this.move(this.circle(this.index + 1), this.slideWidth, 0); } if (!this.support.transition) { this.slidesContainer[0].style.left = (this.index * -this.slideWidth) + 'px'; } }, toggleControls: function () { var controlsClass = this.options.controlsClass; if (this.container.hasClass(controlsClass)) { this.container.removeClass(controlsClass); } else { this.container.addClass(controlsClass); } }, toggleSlideshow: function () { if (!this.interval) { this.play(); } else { this.pause(); } }, getNodeIndex: function (element) { return parseInt(element.getAttribute('data-index'), 10); }, getNestedProperty: function (obj, property) { property.replace( // Matches native JavaScript notation in a String, // e.g. '["doubleQuoteProp"].dotProp[2]' /\[(?:'([^']+)'|"([^"]+)"|(\d+))\]|(?:(?:^|\.)([^\.\[]+))/g, function (str, singleQuoteProp, doubleQuoteProp, arrayIndex, dotProp) { var prop = dotProp || singleQuoteProp || doubleQuoteProp || (arrayIndex && parseInt(arrayIndex, 10)); if (str && obj) { obj = obj[prop]; } } ); return obj; }, getItemProperty: function (obj, property) { return obj[property] || (obj.getAttribute && obj.getAttribute('data-' + property)) || this.getNestedProperty(obj, property); }, initStartIndex: function () { var index = this.options.index, urlProperty = this.options.urlProperty, i; // Check if the index is given as a list object: if (index && typeof index !== 'number') { for (i = 0; i < this.num; i += 1) { if (this.list[i] === index || this.getItemProperty(this.list[i], urlProperty) === this.getItemProperty(index, urlProperty)) { index = i; break; } } } // Make sure the index is in the list range: this.index = this.circle(parseInt(index, 10) || 0); }, initEventListeners: function () { var that = this, slidesContainer = this.slidesContainer, proxyListener = function (event) { var type = that.support.transition && that.support.transition.end === event.type ? 'transitionend' : event.type; that['on' + type](event); }; $(window).on('resize', proxyListener); $(document.body).on('keydown', proxyListener); this.container.on('click', proxyListener); if (this.support.touch) { slidesContainer .on('touchstart touchmove touchend', proxyListener); } else if (this.options.emulateTouchEvents && this.support.transition) { slidesContainer .on('mousedown mousemove mouseup mouseout', proxyListener); } if (this.support.transition) { slidesContainer.on( this.support.transition.end, proxyListener ); } this.proxyListener = proxyListener; }, destroyEventListeners: function () { var slidesContainer = this.slidesContainer, proxyListener = this.proxyListener; $(window).off('resize', proxyListener); $(document.body).off('keydown', proxyListener); this.container.off('click', proxyListener); if (this.support.touch) { slidesContainer .off('touchstart touchmove touchend', proxyListener); } else if (this.options.emulateTouchEvents && this.support.transition) { slidesContainer .off('mousedown mousemove mouseup mouseout', proxyListener); } if (this.support.transition) { slidesContainer.off( this.support.transition.end, proxyListener ); } }, initWidget: function () { this.container = $(this.options.container); if (!this.container.length) { return false; } this.slidesContainer = this.container.find( this.options.slidesContainer ); if (!this.slidesContainer.length) { return false; } this.titleElement = this.container.find( this.options.titleElement ); if (this.options.hidePageScrollbars) { // Hide the page scrollbars: this.bodyOverflowStyle = document.body.style.overflow; document.body.style.overflow = 'hidden'; } if (this.num === 1) { this.container.addClass(this.options.singleClass); } this.container[0].style.display = 'block'; this.initSlides(); this.container.addClass(this.options.displayClass); }, initOptions: function (options) { // Create a copy of the prototype options: this.options = $.extend({}, this.options); // Check if carousel mode is enabled: if ((options && options.carousel) || (this.options.carousel && (!options || options.carousel !== false))) { $.extend(this.options, this.carouselOptions); } // Override any given options: $.extend(this.options, options); if (this.num < 3) { // 1 or 2 slides cannot be displayed continuous, // remember the original option by setting to null instead of false: this.options.continuous = this.options.continuous ? null : false; } if (!this.support.transition) { this.options.emulateTouchEvents = false; } if (this.options.event) { this.preventDefault(this.options.event); } } }); return Gallery; }));
joacub/zf-joacub-uploader-twb
vendor/jQuery-File-Upload/Gallery/js/blueimp-gallery.js
JavaScript
bsd-3-clause
47,446
import EmberError from 'ember-metal/error'; /** @module ember @submodule ember-metal */ var SPLIT_REGEX = /\{|\}/; /** Expands `pattern`, invoking `callback` for each expansion. The only pattern supported is brace-expansion, anything else will be passed once to `callback` directly. Example ```js function echo(arg){ console.log(arg); } Ember.expandProperties('foo.bar', echo); //=> 'foo.bar' Ember.expandProperties('{foo,bar}', echo); //=> 'foo', 'bar' Ember.expandProperties('foo.{bar,baz}', echo); //=> 'foo.bar', 'foo.baz' Ember.expandProperties('{foo,bar}.baz', echo); //=> 'foo.baz', 'bar.baz' Ember.expandProperties('foo.{bar,baz}.@each', echo) //=> 'foo.bar.@each', 'foo.baz.@each' Ember.expandProperties('{foo,bar}.{spam,eggs}', echo) //=> 'foo.spam', 'foo.eggs', 'bar.spam', 'bar.eggs' Ember.expandProperties('{foo}.bar.{baz}') //=> 'foo.bar.baz' ``` @method @private @param {String} pattern The property pattern to expand. @param {Function} callback The callback to invoke. It is invoked once per expansion, and is passed the expansion. */ export default function expandProperties(pattern, callback) { if (pattern.indexOf(' ') > -1) { throw new EmberError(`Brace expanded properties cannot contain spaces, e.g. 'user.{firstName, lastName}' should be 'user.{firstName,lastName}'`); } if ('string' === typeof pattern) { var parts = pattern.split(SPLIT_REGEX); var properties = [parts]; parts.forEach((part, index) => { if (part.indexOf(',') >= 0) { properties = duplicateAndReplace(properties, part.split(','), index); } }); properties.forEach((property) => { callback(property.join('')); }); } else { callback(pattern); } } function duplicateAndReplace(properties, currentParts, index) { var all = []; properties.forEach((property) => { currentParts.forEach((part) => { var current = property.slice(0); current[index] = part; all.push(current); }); }); return all; }
cjc343/ember.js
packages/ember-metal/lib/expand_properties.js
JavaScript
mit
2,084
'use strict'; const concat = require('../utils').concat; function isRelative (module) { return module.startsWith('./') || module.startsWith('../'); } function formatFileList (files) { const length = files.length; if (!length) return ''; return ` in ${files[0]}${files[1] ? `, ${files[1]}` : ''}${length > 2 ? ` and ${length - 2} other${length === 3 ? '' : 's'}` : ''}`; } function formatGroup (group) { const files = group.errors.map(e => e.file).filter(Boolean); return `* ${group.module}${formatFileList(files)}`; } function forgetToInstall (missingDependencies) { const moduleNames = missingDependencies.map(missingDependency => missingDependency.module); if (missingDependencies.length === 1) { return `To install it, you can run: npm install --save ${moduleNames.join(' ')}`; } return `To install them, you can run: npm install --save ${moduleNames.join(' ')}`; } function dependenciesNotFound (dependencies) { if (dependencies.length === 0) return; return concat( dependencies.length === 1 ? 'This dependency was not found:' : 'These dependencies were not found:', '', dependencies.map(formatGroup), '', forgetToInstall(dependencies) ); } function relativeModulesNotFound (modules) { if (modules.length === 0) return; return concat( modules.length === 1 ? 'This relative module was not found:' : 'These relative modules were not found:', '', modules.map(formatGroup) ); } function groupModules (errors) { const missingModule = new Map(); errors.forEach((error) => { if (!missingModule.has(error.module)) { missingModule.set(error.module, []) } missingModule.get(error.module).push(error); }); return Array.from(missingModule.keys()).map(module => ({ module: module, relative: isRelative(module), errors: missingModule.get(module), })); } function formatErrors (errors) { if (errors.length === 0) { return []; } const groups = groupModules(errors); const dependencies = groups.filter(group => !group.relative); const relativeModules = groups.filter(group => group.relative); return concat( dependenciesNotFound(dependencies), dependencies.length && relativeModules.length ? ['', ''] : null, relativeModulesNotFound(relativeModules) ); } function format (errors) { return formatErrors(errors.filter((e) => ( e.type === 'module-not-found' ))); } module.exports = format;
niuzz/ci
vue-source/node_modules/friendly-errors-webpack-plugin/src/formatters/moduleNotFound.js
JavaScript
mit
2,440
// Model App.Mailbox = Em.Object.extend(); App.Mailbox.reopenClass({ find: function(id) { if (id) { return App.FIXTURES.findBy('id', id); } else { return App.FIXTURES; } } }); // Routes App.Router.map(function() { this.resource('mailbox', { path: '/:mailbox_id' }, function() { this.resource('mail', { path: '/:message_id' }); }); }); App.ApplicationRoute = Em.Route.extend({ model: function() { return App.Mailbox.find(); } }); App.MailRoute = Em.Route.extend({ model: function(params) { return this.modelFor('mailbox').messages.findBy('id', params.message_id); } }); // Handlebars helper Ember.Handlebars.registerBoundHelper('date', function(date) { return moment(date).format('MMM Do'); });
elidupuis/website
source/javascripts/app/examples/routing/app.js
JavaScript
mit
756
'use strict'; var resolveCommand = require('./util/resolveCommand'); var hasEmptyArgumentBug = require('./util/hasEmptyArgumentBug'); var escapeArgument = require('./util/escapeArgument'); var escapeCommand = require('./util/escapeCommand'); var readShebang = require('./util/readShebang'); var isWin = process.platform === 'win32'; var skipShellRegExp = /\.(?:com|exe)$/i; var supportsShellOption = parseInt(process.version.substr(1).split('.')[0], 10) >= 6; function parseNonShell(parsed) { var shebang; var needsShell; var applyQuotes; if (!isWin) { return parsed; } // Detect & add support for shebangs parsed.file = resolveCommand(parsed.command); parsed.file = parsed.file || resolveCommand(parsed.command, true); shebang = parsed.file && readShebang(parsed.file); if (shebang) { parsed.args.unshift(parsed.file); parsed.command = shebang; needsShell = hasEmptyArgumentBug || !skipShellRegExp.test(resolveCommand(shebang) || resolveCommand(shebang, true)); } else { needsShell = hasEmptyArgumentBug || !skipShellRegExp.test(parsed.file); } // If a shell is required, use cmd.exe and take care of escaping everything correctly if (needsShell) { // Escape command & arguments applyQuotes = (parsed.command !== 'echo'); // Do not quote arguments for the special "echo" command parsed.command = escapeCommand(parsed.command); parsed.args = parsed.args.map(function (arg) { return escapeArgument(arg, applyQuotes); }); // Make use of cmd.exe parsed.args = ['/d', '/s', '/c', '"' + parsed.command + (parsed.args.length ? ' ' + parsed.args.join(' ') : '') + '"']; parsed.command = process.env.comspec || 'cmd.exe'; parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped } return parsed; } function parseShell(parsed) { var shellCommand; // If node supports the shell option, there's no need to mimic its behavior if (supportsShellOption) { return parsed; } // Mimic node shell option, see: https://github.com/nodejs/node/blob/b9f6a2dc059a1062776133f3d4fd848c4da7d150/lib/child_process.js#L335 shellCommand = [parsed.command].concat(parsed.args).join(' '); if (isWin) { parsed.command = typeof parsed.options.shell === 'string' ? parsed.options.shell : process.env.comspec || 'cmd.exe'; parsed.args = ['/d', '/s', '/c', '"' + shellCommand + '"']; parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped } else { if (typeof parsed.options.shell === 'string') { parsed.command = parsed.options.shell; } else if (process.platform === 'android') { parsed.command = '/system/bin/sh'; } else { parsed.command = '/bin/sh'; } parsed.args = ['-c', shellCommand]; } return parsed; } // ------------------------------------------------ function parse(command, args, options) { var parsed; // Normalize arguments, similar to nodejs if (args && !Array.isArray(args)) { options = args; args = null; } args = args ? args.slice(0) : []; // Clone array to avoid changing the original options = options || {}; // Build our parsed object parsed = { command: command, args: args, options: options, file: undefined, original: command, }; // Delegate further parsing to shell or non-shell return options.shell ? parseShell(parsed) : parseNonShell(parsed); } module.exports = parse;
mikemcdaid/getonupband
sites/all/themes/getonupband/node_modules/cross-spawn/lib/parse.js
JavaScript
gpl-2.0
3,725
/** * @fileoverview Rule to flag block statements that do not use the one true brace style * @author Ian Christian Myers */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = function(context) { var style = context.options[0] || "1tbs"; var params = context.options[1] || {}; var OPEN_MESSAGE = "Opening curly brace does not appear on the same line as controlling statement.", OPEN_MESSAGE_ALLMAN = "Opening curly brace appears on the same line as controlling statement.", BODY_MESSAGE = "Statement inside of curly braces should be on next line.", CLOSE_MESSAGE = "Closing curly brace does not appear on the same line as the subsequent block.", CLOSE_MESSAGE_SINGLE = "Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.", CLOSE_MESSAGE_STROUSTRUP_ALLMAN = "Closing curly brace appears on the same line as the subsequent block."; //-------------------------------------------------------------------------- // Helpers //-------------------------------------------------------------------------- /** * Determines if a given node is a block statement. * @param {ASTNode} node The node to check. * @returns {boolean} True if the node is a block statement, false if not. * @private */ function isBlock(node) { return node && node.type === "BlockStatement"; } /** * Check if the token is an punctuator with a value of curly brace * @param {object} token - Token to check * @returns {boolean} true if its a curly punctuator * @private */ function isCurlyPunctuator(token) { return token.value === "{" || token.value === "}"; } /** * Binds a list of properties to a function that verifies that the opening * curly brace is on the same line as its controlling statement of a given * node. * @param {...string} The properties to check on the node. * @returns {Function} A function that will perform the check on a node * @private */ function checkBlock() { var blockProperties = arguments; return function(node) { [].forEach.call(blockProperties, function(blockProp) { var block = node[blockProp], previousToken, curlyToken, curlyTokenEnd, curlyTokensOnSameLine; if (!isBlock(block)) { return; } previousToken = context.getTokenBefore(block); curlyToken = context.getFirstToken(block); curlyTokenEnd = context.getLastToken(block); curlyTokensOnSameLine = curlyToken.loc.start.line === curlyTokenEnd.loc.start.line; if (style !== "allman" && previousToken.loc.start.line !== curlyToken.loc.start.line) { context.report(node, OPEN_MESSAGE); } else if (style === "allman" && previousToken.loc.start.line === curlyToken.loc.start.line && !params.allowSingleLine) { context.report(node, OPEN_MESSAGE_ALLMAN); } if (!block.body.length || curlyTokensOnSameLine && params.allowSingleLine) { return; } if (curlyToken.loc.start.line === block.body[0].loc.start.line) { context.report(block.body[0], BODY_MESSAGE); } else if (curlyTokenEnd.loc.start.line === block.body[block.body.length - 1].loc.start.line) { context.report(block.body[block.body.length - 1], CLOSE_MESSAGE_SINGLE); } }); }; } /** * Enforces the configured brace style on IfStatements * @param {ASTNode} node An IfStatement node. * @returns {void} * @private */ function checkIfStatement(node) { var tokens, alternateIsBlock = false, alternateIsIfBlock = false; checkBlock("consequent", "alternate")(node); if (node.alternate) { alternateIsBlock = isBlock(node.alternate); alternateIsIfBlock = node.alternate.type === "IfStatement" && isBlock(node.alternate.consequent); if (alternateIsBlock || alternateIsIfBlock) { tokens = context.getTokensBefore(node.alternate, 2); if (style === "1tbs") { if (tokens[0].loc.start.line !== tokens[1].loc.start.line && isCurlyPunctuator(tokens[0]) ) { context.report(node.alternate, CLOSE_MESSAGE); } } else if (tokens[0].loc.start.line === tokens[1].loc.start.line) { context.report(node.alternate, CLOSE_MESSAGE_STROUSTRUP_ALLMAN); } } } } /** * Enforces the configured brace style on TryStatements * @param {ASTNode} node A TryStatement node. * @returns {void} * @private */ function checkTryStatement(node) { var tokens; checkBlock("block", "finalizer")(node); if (isBlock(node.finalizer)) { tokens = context.getTokensBefore(node.finalizer, 2); if (style === "1tbs") { if (tokens[0].loc.start.line !== tokens[1].loc.start.line) { context.report(node.finalizer, CLOSE_MESSAGE); } } else if (tokens[0].loc.start.line === tokens[1].loc.start.line) { context.report(node.finalizer, CLOSE_MESSAGE_STROUSTRUP_ALLMAN); } } } /** * Enforces the configured brace style on CatchClauses * @param {ASTNode} node A CatchClause node. * @returns {void} * @private */ function checkCatchClause(node) { var previousToken = context.getTokenBefore(node), firstToken = context.getFirstToken(node); checkBlock("body")(node); if (isBlock(node.body)) { if (style === "1tbs") { if (previousToken.loc.start.line !== firstToken.loc.start.line) { context.report(node, CLOSE_MESSAGE); } } else { if (previousToken.loc.start.line === firstToken.loc.start.line) { context.report(node, CLOSE_MESSAGE_STROUSTRUP_ALLMAN); } } } } /** * Enforces the configured brace style on SwitchStatements * @param {ASTNode} node A SwitchStatement node. * @returns {void} * @private */ function checkSwitchStatement(node) { var tokens; if (node.cases && node.cases.length) { tokens = context.getTokensBefore(node.cases[0], 2); if (tokens[0].loc.start.line !== tokens[1].loc.start.line) { context.report(node, OPEN_MESSAGE); } } else { tokens = context.getLastTokens(node, 3); if (tokens[0].loc.start.line !== tokens[1].loc.start.line) { context.report(node, OPEN_MESSAGE); } } } //-------------------------------------------------------------------------- // Public API //-------------------------------------------------------------------------- return { "FunctionDeclaration": checkBlock("body"), "FunctionExpression": checkBlock("body"), "ArrowFunctionExpression": checkBlock("body"), "IfStatement": checkIfStatement, "TryStatement": checkTryStatement, "CatchClause": checkCatchClause, "DoWhileStatement": checkBlock("body"), "WhileStatement": checkBlock("body"), "WithStatement": checkBlock("body"), "ForStatement": checkBlock("body"), "ForInStatement": checkBlock("body"), "ForOfStatement": checkBlock("body"), "SwitchStatement": checkSwitchStatement }; }; module.exports.schema = [ { "enum": ["1tbs", "stroustrup", "allman"] }, { "type": "object", "properties": { "allowSingleLine": { "type": "boolean" } }, "additionalProperties": false } ];
BabbleCar/demo-mirrorlink-cordova
plugins/cordova-plugin-mirrorlink/www/node_modules/eslint/lib/rules/brace-style.js
JavaScript
mit
8,342
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * conditional catch should result in error with -nse * * @option -nse * @test/compile-error */ try { func(); } catch (e if e instanceof ReferenceError) { }
JetBrains/jdk8u_nashorn
test/script/error/conditional_catch_nse.js
JavaScript
gpl-2.0
1,222
"use strict"; /** * @class elFinder folders tree * * @author Dmitry (dio) Levashov **/ $.fn.elfindertree = function(fm, opts) { var treeclass = fm.res('class', 'tree'); this.not('.'+treeclass).each(function() { var c = 'class', /** * Root directory class name * * @type String */ root = fm.res(c, 'treeroot'), /** * Open root dir if not opened yet * * @type Boolean */ openRoot = opts.openRootOnLoad, /** * Subtree class name * * @type String */ subtree = fm.res(c, 'navsubtree'), /** * Directory class name * * @type String */ navdir = fm.res(c, 'treedir'), /** * Collapsed arrow class name * * @type String */ collapsed = fm.res(c, 'navcollapse'), /** * Expanded arrow class name * * @type String */ expanded = fm.res(c, 'navexpand'), /** * Class name to mark arrow for directory with already loaded children * * @type String */ loaded = 'elfinder-subtree-loaded', /** * Arraw class name * * @type String */ arrow = fm.res(c, 'navarrow'), /** * Current directory class name * * @type String */ active = fm.res(c, 'active'), /** * Droppable dirs dropover class * * @type String */ dropover = fm.res(c, 'adroppable'), /** * Hover class name * * @type String */ hover = fm.res(c, 'hover'), /** * Disabled dir class name * * @type String */ disabled = fm.res(c, 'disabled'), /** * Draggable dir class name * * @type String */ draggable = fm.res(c, 'draggable'), /** * Droppable dir class name * * @type String */ droppable = fm.res(c, 'droppable'), /** * Droppable options * * @type Object */ droppableopts = $.extend({}, fm.droppable, { hoverClass : hover+' '+dropover, // show subfolders on dropover over : function() { var link = $(this); if (link.is('.'+collapsed+':not(.'+expanded+')')) { setTimeout(function() { link.is('.'+dropover) && link.children('.'+arrow).click(); }, 500); } } }), spinner = $(fm.res('tpl', 'navspinner')), /** * Directory html template * * @type String */ tpl = fm.res('tpl', 'navdir'), /** * Permissions marker html template * * @type String */ ptpl = fm.res('tpl', 'perms'), /** * Symlink marker html template * * @type String */ stpl = fm.res('tpl', 'symlink'), /** * Html template replacement methods * * @type Object */ replace = { id : function(dir) { return fm.navHash2Id(dir.hash) }, cssclass : function(dir) { return (dir.phash ? '' : root)+' '+navdir+' '+fm.perms2class(dir)+' '+(dir.dirs && !dir.link ? collapsed : ''); }, permissions : function(dir) { return !dir.read || !dir.write ? ptpl : ''; }, symlink : function(dir) { return dir.alias ? stpl : ''; } }, /** * Return html for given dir * * @param Object directory * @return String */ itemhtml = function(dir) { dir.name = fm.escape(dir.name); return tpl.replace(/(?:\{([a-z]+)\})/ig, function(m, key) { return dir[key] || (replace[key] ? replace[key](dir) : ''); }); }, /** * Return only dirs from files list * * @param Array files list * @return Array */ filter = function(files) { return $.map(files||[], function(f) { return f.mime == 'directory' ? f : null }); }, /** * Find parent subtree for required directory * * @param String dir hash * @return jQuery */ findSubtree = function(hash) { return hash ? tree.find('#'+fm.navHash2Id(hash)).next('.'+subtree) : tree; }, /** * Find directory (wrapper) in required node * before which we can insert new directory * * @param jQuery parent directory * @param Object new directory * @return jQuery */ findSibling = function(subtree, dir) { var node = subtree.children(':first'), info; while (node.length) { if ((info = fm.file(fm.navId2Hash(node.children('[id]').attr('id')))) && dir.name.localeCompare(info.name) < 0) { return node; } node = node.next(); } return $(''); }, /** * Add new dirs in tree * * @param Array dirs list * @return void */ updateTree = function(dirs) { var length = dirs.length, orphans = [], i, dir, html, parent, sibling; for (i = 0; i < length; i++) { dir = dirs[i]; if (tree.find('#'+fm.navHash2Id(dir.hash)).length) { continue; } if ((parent = findSubtree(dir.phash)).length) { html = itemhtml(dir); if (dir.phash && (sibling = findSibling(parent, dir)).length) { sibling.before(html); } else { parent.append(html); } } else { orphans.push(dir); } } if (orphans.length && orphans.length < length) { return updateTree(orphans); } updateDroppable(); }, /** * Mark current directory as active * If current directory is not in tree - load it and its parents * * @return void */ sync = function() { var cwd = fm.cwd().hash, current = tree.find('#'+fm.navHash2Id(cwd)), rootNode; if (openRoot) { rootNode = tree.find('#'+fm.navHash2Id(fm.root())); rootNode.is('.'+loaded) && rootNode.addClass(expanded).next('.'+subtree).show(); openRoot = false; } if (!current.is('.'+active)) { tree.find('.'+navdir+'.'+active).removeClass(active); current.addClass(active); } if (opts.syncTree) { if (current.length) { current.parentsUntil('.'+root).filter('.'+subtree).show().prev('.'+navdir).addClass(expanded); } else if (fm.newAPI) { fm.request({ data : {cmd : 'parents', target : cwd}, preventFail : true }) .done(function(data) { var dirs = filter(data.tree); updateTree(dirs); updateArrows(dirs, loaded) cwd == fm.cwd().hash && sync(); }); } } }, /** * Make writable and not root dirs droppable * * @return void */ updateDroppable = function() { tree.find('.'+navdir+':not(.'+droppable+',.elfinder-ro,.elfinder-na)').droppable(droppableopts); }, /** * Check required folders for subfolders and update arrow classes * * @param Array folders to check * @param String css class * @return void */ updateArrows = function(dirs, cls) { var sel = cls == loaded ? '.'+collapsed+':not(.'+loaded+')' : ':not(.'+collapsed+')'; //tree.find('.'+subtree+':has(*)').prev(':not(.'+collapsed+')').addClass(collapsed) $.each(dirs, function(i, dir) { tree.find('#'+fm.navHash2Id(dir.phash)+sel) .filter(function() { return $(this).next('.'+subtree).children().length > 0 }) .addClass(cls); }) }, /** * Navigation tree * * @type JQuery */ tree = $(this).addClass(treeclass) // make dirs draggable and toggle hover class .delegate('.'+navdir, 'hover', function(e) { var link = $(this), enter = e.type == 'mouseenter'; if (!link.is('.'+dropover+' ,.'+disabled)) { enter && !link.is('.'+root+',.'+draggable+',.elfinder-na,.elfinder-wo') && link.draggable(fm.draggable); link.toggleClass(hover, enter); } }) // add/remove dropover css class .delegate('.'+navdir, 'dropover dropout drop', function(e) { $(this)[e.type == 'dropover' ? 'addClass' : 'removeClass'](dropover+' '+hover); }) // open dir or open subfolders in tree .delegate('.'+navdir, 'click', function(e) { var link = $(this), hash = fm.navId2Hash(link.attr('id')), file = fm.file(hash); fm.trigger('searchend'); if (hash != fm.cwd().hash && !link.is('.'+disabled)) { fm.exec('open', file.thash || hash); } else if (link.is('.'+collapsed)) { link.children('.'+arrow).click(); } }) // toggle subfolders in tree .delegate('.'+navdir+'.'+collapsed+' .'+arrow, 'click', function(e) { var arrow = $(this), link = arrow.parent('.'+navdir), stree = link.next('.'+subtree); e.stopPropagation(); if (link.is('.'+loaded)) { link.toggleClass(expanded); stree.slideToggle() } else { spinner.insertBefore(arrow); link.removeClass(collapsed); fm.request({cmd : 'tree', target : fm.navId2Hash(link.attr('id'))}) .done(function(data) { updateTree(filter(data.tree)); if (stree.children().length) { link.addClass(collapsed+' '+expanded); stree.slideDown(); } sync(); }) .always(function(data) { spinner.remove(); link.addClass(loaded); }); } }) .delegate('.'+navdir, 'contextmenu', function(e) { e.preventDefault(); fm.trigger('contextmenu', { 'type' : 'navbar', 'targets' : [fm.navId2Hash($(this).attr('id'))], 'x' : e.clientX, 'y' : e.clientY }); }) ; // move tree into navbar tree.parent().find('.elfinder-navbar').append(tree).show(); fm.open(function(e) { var data = e.data, dirs = filter(data.files); data.init && tree.empty(); if (dirs.length) { updateTree(dirs); updateArrows(dirs, loaded); } sync(); }) // add new dirs .add(function(e) { var dirs = filter(e.data.added); if (dirs.length) { updateTree(dirs); updateArrows(dirs, collapsed); } }) // update changed dirs .change(function(e) { var dirs = filter(e.data.changed), l = dirs.length, dir, node, tmp, realParent, reqParent, realSibling, reqSibling, isExpanded, isLoaded; while (l--) { dir = dirs[l]; if ((node = tree.find('#'+fm.navHash2Id(dir.hash))).length) { if (dir.phash) { realParent = node.closest('.'+subtree); reqParent = findSubtree(dir.phash); realSibling = node.parent().next(); reqSibling = findSibling(reqParent, dir); if (!reqParent.length) { continue; } if (reqParent[0] !== realParent[0] || realSibling.get(0) !== reqSibling.get(0)) { reqSibling.length ? reqSibling.before(node) : reqParent.append(node); } } isExpanded = node.is('.'+expanded); isLoaded = node.is('.'+loaded); tmp = $(itemhtml(dir)); node.replaceWith(tmp.children('.'+navdir)); if (dir.dirs && (isExpanded || isLoaded) && (node = tree.find('#'+fm.navHash2Id(dir.hash))) && node.next('.'+subtree).children().length) { isExpanded && node.addClass(expanded); isLoaded && node.addClass(loaded); } } } sync(); updateDroppable(); }) // remove dirs .remove(function(e) { var dirs = e.data.removed, l = dirs.length, node, stree; while (l--) { if ((node = tree.find('#'+fm.navHash2Id(dirs[l]))).length) { stree = node.closest('.'+subtree); node.parent().detach(); if (!stree.children().length) { stree.hide().prev('.'+navdir).removeClass(collapsed+' '+expanded+' '+loaded); } } } }) // add/remove active class for current dir .bind('search searchend', function(e) { tree.find('#'+fm.navHash2Id(fm.cwd().hash))[e.type == 'search' ? 'removeClass' : 'addClass'](active); }) // lock/unlock dirs while moving .bind('lockfiles unlockfiles', function(e) { var lock = e.type == 'lockfiles', act = lock ? 'disable' : 'enable', dirs = $.map(e.data.files||[], function(h) { var dir = fm.file(h); return dir && dir.mime == 'directory' ? h : null; }) $.each(dirs, function(i, hash) { var dir = tree.find('#'+fm.navHash2Id(hash)); if (dir.length) { dir.is('.'+draggable) && dir.draggable(act); dir.is('.'+droppable) && dir.droppable(active); dir[lock ? 'addClass' : 'removeClass'](disabled); } }); }) }); return this; }
BROcart/2.7.8
www/admin/elfinder/js/ui/tree.js
JavaScript
gpl-3.0
12,339
/** * Push badges to backpack. * @deprecated since 3.7 */ function addtobackpack(event, args) { var badgetable = Y.one('#issued-badge-table'); var errordiv = Y.one('#addtobackpack-error'); var errortext = M.util.get_string('error:backpackproblem', 'badges'); var errorhtml = '<div id="addtobackpack-error" class="box boxaligncenter notifyproblem">' + errortext + '</div>'; if (typeof OpenBadges !== 'undefined') { OpenBadges.issue([args.assertion], function(errors, successes) { }); } else { // Add error div if it doesn't exist yet. if (!errordiv) { var badgerror = Y.Node.create(errorhtml); badgetable.insert(badgerror, 'before'); } } } /** * Check if website is externally accessible from the backpack. * @deprecated since 3.7 */ function check_site_access() { var add = Y.one('#check_connection'); var callback = { method: "GET", on: { success: function(id, o) { var data = Y.JSON.parse(o.responseText); if (data.code == 'http-unreachable') { add.setHTML(data.response); add.removeClass('hide'); } M.util.js_complete('badge/backpack::check_site_access'); }, failure: function() { M.util.js_complete('badge/backpack::check_site_access'); } } }; Y.use('io-base', function(Y) { M.util.js_pending('badge/backpack::check_site_access'); Y.io('ajax.php', callback); }); return false; }
enovation/moodle
badges/backpack.js
JavaScript
gpl-3.0
1,670
/// <reference path="Definitions/jsnlog_interfaces.d.ts"/> var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; function JL(loggerName) { // If name is empty, return the root logger if (!loggerName) { return JL.__; } // Implements Array.reduce. JSNLog supports IE8+ and reduce is not supported in that browser. // Same interface as the standard reduce, except that if (!Array.prototype.reduce) { Array.prototype.reduce = function (callback, initialValue) { var previousValue = initialValue; for (var i = 0; i < this.length; i++) { previousValue = callback(previousValue, this[i], i, this); } return previousValue; }; } var accumulatedLoggerName = ''; var logger = ('.' + loggerName).split('.').reduce(function (prev, curr, idx, arr) { // if loggername is a.b.c, than currentLogger will be set to the loggers // root (prev: JL, curr: '') // a (prev: JL.__, curr: 'a') // a.b (prev: JL.__.__a, curr: 'b') // a.b.c (prev: JL.__.__a.__a.b, curr: 'c') // Note that when a new logger name is encountered (such as 'a.b.c'), // a new logger object is created and added as a property to the parent ('a.b'). // The root logger is added as a property of the JL object itself. // It is essential that the name of the property containing the child logger // contains the full 'path' name of the child logger ('a.b.c') instead of // just the bit after the last period ('c'). // This is because the parent inherits properties from its ancestors. // So if the root has a child logger 'c' (stored in a property 'c' of the root logger), // then logger 'a.b' has that same property 'c' through inheritance. // The names of the logger properties start with __, so the root logger // (which has name ''), has a nice property name '__'. // accumulatedLoggerName evaluates false ('' is falsy) in first iteration when prev is the root logger. // accumulatedLoggerName will be the logger name corresponding with the logger in currentLogger. // Keep in mind that the currentLogger may not be defined yet, so can't get the name from // the currentLogger object itself. if (accumulatedLoggerName) { accumulatedLoggerName += '.' + curr; } else { accumulatedLoggerName = curr; } var currentLogger = prev['__' + accumulatedLoggerName]; // If the currentLogger (or the actual logger being sought) does not yet exist, // create it now. if (currentLogger === undefined) { // Set the prototype of the Logger constructor function to the parent of the logger // to be created. This way, __proto of the new logger object will point at the parent. // When logger.level is evaluated and is not present, the JavaScript runtime will // walk down the prototype chain to find the first ancestor with a level property. // // Note that prev at this point refers to the parent logger. JL.Logger.prototype = prev; currentLogger = new JL.Logger(accumulatedLoggerName); prev['__' + accumulatedLoggerName] = currentLogger; } return currentLogger; }, JL.__); return logger; } var JL; (function (JL) { JL.enabled; JL.maxMessages; JL.defaultAjaxUrl; JL.clientIP; JL.defaultBeforeSend; // Initialise requestId to empty string. If you don't do this and the user // does not set it via setOptions, then the JSNLog-RequestId header will // have value "undefined", which doesn't look good in a log. // // Note that you always want to send a requestId as part of log requests, // otherwise the server side component doesn't know this is a log request // and may create a new request id for the log request, causing confusion // in the log. JL.requestId = ''; /** Copies the value of a property from one object to the other. This is used to copy property values as part of setOption for loggers and appenders. Because loggers inherit property values from their parents, it is important never to create a property on a logger if the intent is to inherit from the parent. Copying rules: 1) if the from property is undefined (for example, not mentioned in a JSON object), the to property is not affected at all. 2) if the from property is null, the to property is deleted (so the logger will inherit from its parent). 3) Otherwise, the from property is copied to the to property. */ function copyProperty(propertyName, from, to) { if (from[propertyName] === undefined) { return; } if (from[propertyName] === null) { delete to[propertyName]; return; } to[propertyName] = from[propertyName]; } /** Returns true if a log should go ahead. Does not check level. @param filters Filters that determine whether a log can go ahead. */ function allow(filters) { // If enabled is not null or undefined, then if it is false, then return false // Note that undefined==null (!) if (!(JL.enabled == null)) { if (!JL.enabled) { return false; } } // If maxMessages is not null or undefined, then if it is 0, then return false. // Note that maxMessages contains number of messages that are still allowed to send. // It is decremented each time messages are sent. It can be negative when batch size > 1. // Note that undefined==null (!) if (!(JL.maxMessages == null)) { if (JL.maxMessages < 1) { return false; } } try { if (filters.userAgentRegex) { if (!new RegExp(filters.userAgentRegex).test(navigator.userAgent)) { return false; } } } catch (e) { } try { if (filters.ipRegex && JL.clientIP) { if (!new RegExp(filters.ipRegex).test(JL.clientIP)) { return false; } } } catch (e) { } return true; } /** Returns true if a log should go ahead, based on the message. @param filters Filters that determine whether a log can go ahead. @param message Message to be logged. */ function allowMessage(filters, message) { try { if (filters.disallow) { if (new RegExp(filters.disallow).test(message)) { return false; } } } catch (e) { } return true; } // If logObject is a function, the function is evaluated (without parameters) // and the result returned. // Otherwise, logObject itself is returned. function stringifyLogObjectFunction(logObject) { if (typeof logObject == "function") { if (logObject instanceof RegExp) { return logObject.toString(); } else { return logObject(); } } return logObject; } var StringifiedLogObject = (function () { // * msg - // if the logObject is a scalar (after possible function evaluation), this is set to // string representing the scalar. Otherwise it is left undefined. // * meta - // if the logObject is an object (after possible function evaluation), this is set to // that object. Otherwise it is left undefined. // * finalString - // This is set to the string representation of logObject (after possible function evaluation), // regardless of whether it is an scalar or an object. An object is stringified to a JSON string. // Note that you can't call this field "final", because as some point this was a reserved // JavaScript keyword and using final trips up some minifiers. function StringifiedLogObject(msg, meta, finalString) { this.msg = msg; this.meta = meta; this.finalString = finalString; } return StringifiedLogObject; })(); // Takes a logObject, which can be // * a scalar // * an object // * a parameterless function, which returns the scalar or object to log. // Returns a stringifiedLogObject function stringifyLogObject(logObject) { // Note that this works if logObject is null. // typeof null is object. // JSON.stringify(null) returns "null". var actualLogObject = stringifyLogObjectFunction(logObject); var finalString; switch (typeof actualLogObject) { case "string": return new StringifiedLogObject(actualLogObject, null, actualLogObject); case "number": finalString = actualLogObject.toString(); return new StringifiedLogObject(finalString, null, finalString); case "boolean": finalString = actualLogObject.toString(); return new StringifiedLogObject(finalString, null, finalString); case "undefined": return new StringifiedLogObject("undefined", null, "undefined"); case "object": if ((actualLogObject instanceof RegExp) || (actualLogObject instanceof String) || (actualLogObject instanceof Number) || (actualLogObject instanceof Boolean)) { finalString = actualLogObject.toString(); return new StringifiedLogObject(finalString, null, finalString); } else { return new StringifiedLogObject(null, actualLogObject, JSON.stringify(actualLogObject)); } default: return new StringifiedLogObject("unknown", null, "unknown"); } } function setOptions(options) { copyProperty("enabled", options, this); copyProperty("maxMessages", options, this); copyProperty("defaultAjaxUrl", options, this); copyProperty("clientIP", options, this); copyProperty("requestId", options, this); copyProperty("defaultBeforeSend", options, this); return this; } JL.setOptions = setOptions; function getAllLevel() { return -2147483648; } JL.getAllLevel = getAllLevel; function getTraceLevel() { return 1000; } JL.getTraceLevel = getTraceLevel; function getDebugLevel() { return 2000; } JL.getDebugLevel = getDebugLevel; function getInfoLevel() { return 3000; } JL.getInfoLevel = getInfoLevel; function getWarnLevel() { return 4000; } JL.getWarnLevel = getWarnLevel; function getErrorLevel() { return 5000; } JL.getErrorLevel = getErrorLevel; function getFatalLevel() { return 6000; } JL.getFatalLevel = getFatalLevel; function getOffLevel() { return 2147483647; } JL.getOffLevel = getOffLevel; function levelToString(level) { if (level <= 1000) { return "trace"; } if (level <= 2000) { return "debug"; } if (level <= 3000) { return "info"; } if (level <= 4000) { return "warn"; } if (level <= 5000) { return "error"; } return "fatal"; } // --------------------- var Exception = (function () { // data replaces message. It takes not just strings, but also objects and functions, just like the log function. // internally, the string representation is stored in the message property (inherited from Error) // // inner: inner exception. Can be null or undefined. function Exception(data, inner) { this.inner = inner; this.name = "JL.Exception"; this.message = stringifyLogObject(data).finalString; } return Exception; })(); JL.Exception = Exception; // Derive Exception from Error (a Host object), so browsers // are more likely to produce a stack trace for it in their console. // // Note that instanceof against an object created with this constructor // will return true in these cases: // <object> instanceof JL.Exception); // <object> instanceof Error); Exception.prototype = new Error(); // --------------------- var LogItem = (function () { // l: level // m: message // n: logger name // t (timeStamp) is number of milliseconds since 1 January 1970 00:00:00 UTC // // Keeping the property names really short, because they will be sent in the // JSON payload to the server. function LogItem(l, m, n, t) { this.l = l; this.m = m; this.n = n; this.t = t; } return LogItem; })(); JL.LogItem = LogItem; // --------------------- var Appender = (function () { // sendLogItems takes an array of log items. It will be called when // the appender has items to process (such as, send to the server). // Note that after sendLogItems returns, the appender may truncate // the LogItem array, so the function has to copy the content of the array // in some fashion (eg. serialize) before returning. function Appender(appenderName, sendLogItems) { this.appenderName = appenderName; this.sendLogItems = sendLogItems; this.level = JL.getTraceLevel(); // set to super high level, so if user increases level, level is unlikely to get // above sendWithBufferLevel this.sendWithBufferLevel = 2147483647; this.storeInBufferLevel = -2147483648; this.bufferSize = 0; this.batchSize = 1; // Holds all log items with levels higher than storeInBufferLevel // but lower than level. These items may never be sent. this.buffer = []; // Holds all items that we do want to send, until we have a full // batch (as determined by batchSize). this.batchBuffer = []; } Appender.prototype.setOptions = function (options) { copyProperty("level", options, this); copyProperty("ipRegex", options, this); copyProperty("userAgentRegex", options, this); copyProperty("disallow", options, this); copyProperty("sendWithBufferLevel", options, this); copyProperty("storeInBufferLevel", options, this); copyProperty("bufferSize", options, this); copyProperty("batchSize", options, this); if (this.bufferSize < this.buffer.length) { this.buffer.length = this.bufferSize; } return this; }; /** Called by a logger to log a log item. If in response to this call one or more log items need to be processed (eg., sent to the server), this method calls this.sendLogItems with an array with all items to be processed. Note that the name and parameters of this function must match those of the log function of a Winston transport object, so that users can use these transports as appenders. That is why there are many parameters that are not actually used by this function. level - string with the level ("trace", "debug", etc.) Only used by Winston transports. msg - human readable message. Undefined if the log item is an object. Only used by Winston transports. meta - log object. Always defined, because at least it contains the logger name. Only used by Winston transports. callback - function that is called when the log item has been logged. Only used by Winston transports. levelNbr - level as a number. Not used by Winston transports. message - log item. If the user logged an object, this is the JSON string. Not used by Winston transports. loggerName: name of the logger. Not used by Winston transports. */ Appender.prototype.log = function (level, msg, meta, callback, levelNbr, message, loggerName) { var logItem; if (!allow(this)) { return; } if (!allowMessage(this, message)) { return; } if (levelNbr < this.storeInBufferLevel) { // Ignore the log item completely return; } logItem = new LogItem(levelNbr, message, loggerName, (new Date).getTime()); if (levelNbr < this.level) { // Store in the hold buffer. Do not send. if (this.bufferSize > 0) { this.buffer.push(logItem); // If we exceeded max buffer size, remove oldest item if (this.buffer.length > this.bufferSize) { this.buffer.shift(); } } return; } if (levelNbr < this.sendWithBufferLevel) { // Want to send the item, but not the contents of the buffer this.batchBuffer.push(logItem); } else { // Want to send both the item and the contents of the buffer. // Send contents of buffer first, because logically they happened first. if (this.buffer.length) { this.batchBuffer = this.batchBuffer.concat(this.buffer); this.buffer.length = 0; } this.batchBuffer.push(logItem); } if (this.batchBuffer.length >= this.batchSize) { this.sendBatch(); return; } }; // Processes the batch buffer Appender.prototype.sendBatch = function () { if (this.batchBuffer.length == 0) { return; } if (!(JL.maxMessages == null)) { if (JL.maxMessages < 1) { return; } } // If maxMessages is not null or undefined, then decrease it by the batch size. // This can result in a negative maxMessages. // Note that undefined==null (!) if (!(JL.maxMessages == null)) { JL.maxMessages -= this.batchBuffer.length; } this.sendLogItems(this.batchBuffer); this.batchBuffer.length = 0; }; return Appender; })(); JL.Appender = Appender; // --------------------- var AjaxAppender = (function (_super) { __extends(AjaxAppender, _super); function AjaxAppender(appenderName) { _super.call(this, appenderName, AjaxAppender.prototype.sendLogItemsAjax); } AjaxAppender.prototype.setOptions = function (options) { copyProperty("url", options, this); copyProperty("beforeSend", options, this); _super.prototype.setOptions.call(this, options); return this; }; AjaxAppender.prototype.sendLogItemsAjax = function (logItems) { try { // Only determine the url right before you send a log request. // Do not set the url when constructing the appender. // // This is because the server side component sets defaultAjaxUrl // in a call to setOptions, AFTER the JL object and the default appender // have been created. var ajaxUrl = "/jsnlog.logger"; // This evaluates to true if defaultAjaxUrl is null or undefined if (!(JL.defaultAjaxUrl == null)) { ajaxUrl = JL.defaultAjaxUrl; } if (this.url) { ajaxUrl = this.url; } var json = JSON.stringify({ r: JL.requestId, lg: logItems }); // Send the json to the server. // Note that there is no event handling here. If the send is not // successful, nothing can be done about it. var xhr = this.getXhr(ajaxUrl); // call beforeSend callback // first try the callback on the appender // then the global defaultBeforeSend callback if (typeof this.beforeSend === 'function') { this.beforeSend.call(this, xhr); } else if (typeof JL.defaultBeforeSend === 'function') { JL.defaultBeforeSend.call(this, xhr); } xhr.send(json); } catch (e) { } }; // Creates the Xhr object to use to send the log request. // Sets out to create an Xhr object that can be used for CORS. // However, if there seems to be no CORS support on the browser, // returns a non-CORS capable Xhr. AjaxAppender.prototype.getXhr = function (ajaxUrl) { var xhr = new XMLHttpRequest(); // Check whether this xhr is CORS capable by checking whether it has // withCredentials. // "withCredentials" only exists on XMLHTTPRequest2 objects. if (!("withCredentials" in xhr)) { // Just found that no XMLHttpRequest2 available. // Check if XDomainRequest is available. // This only exists in IE, and is IE's way of making CORS requests. if (typeof XDomainRequest != "undefined") { // Note that here we're not setting request headers on the XDomainRequest // object. This is because this object doesn't let you do that: // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx // This means that for IE8 and IE9, CORS logging requests do not carry request ids. var xdr = new XDomainRequest(); xdr.open('POST', ajaxUrl); return xdr; } } // At this point, we're going with XMLHttpRequest, whether it is CORS capable or not. // If it is not CORS capable, at least will handle the non-CORS requests. xhr.open('POST', ajaxUrl); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.setRequestHeader('JSNLog-RequestId', JL.requestId); return xhr; }; return AjaxAppender; })(Appender); JL.AjaxAppender = AjaxAppender; // --------------------- var ConsoleAppender = (function (_super) { __extends(ConsoleAppender, _super); function ConsoleAppender(appenderName) { _super.call(this, appenderName, ConsoleAppender.prototype.sendLogItemsConsole); } ConsoleAppender.prototype.clog = function (logEntry) { console.log(logEntry); }; ConsoleAppender.prototype.cerror = function (logEntry) { if (console.error) { console.error(logEntry); } else { this.clog(logEntry); } }; ConsoleAppender.prototype.cwarn = function (logEntry) { if (console.warn) { console.warn(logEntry); } else { this.clog(logEntry); } }; ConsoleAppender.prototype.cinfo = function (logEntry) { if (console.info) { console.info(logEntry); } else { this.clog(logEntry); } }; // IE11 has a console.debug function. But its console doesn't have // the option to show/hide debug messages (the same way Chrome and FF do), // even though it does have such buttons for Error, Warn, Info. // // For now, this means that debug messages can not be hidden on IE. // Live with this, seeing that it works fine on FF and Chrome, which // will be much more popular with developers. ConsoleAppender.prototype.cdebug = function (logEntry) { if (console.debug) { console.debug(logEntry); } else { this.cinfo(logEntry); } }; ConsoleAppender.prototype.sendLogItemsConsole = function (logItems) { try { if (!console) { return; } var i; for (i = 0; i < logItems.length; ++i) { var li = logItems[i]; var msg = li.n + ": " + li.m; // Only log the timestamp if we're on the server // (window is undefined). On the browser, the user // sees the log entry probably immediately, so in that case // the timestamp is clutter. if (typeof window === 'undefined') { msg = new Date(li.t) + " | " + msg; } if (li.l <= JL.getDebugLevel()) { this.cdebug(msg); } else if (li.l <= JL.getInfoLevel()) { this.cinfo(msg); } else if (li.l <= JL.getWarnLevel()) { this.cwarn(msg); } else { this.cerror(msg); } } } catch (e) { } }; return ConsoleAppender; })(Appender); JL.ConsoleAppender = ConsoleAppender; // -------------------- var Logger = (function () { function Logger(loggerName) { this.loggerName = loggerName; // Create seenRexes, otherwise this logger will use the seenRexes // of its parent via the prototype chain. this.seenRegexes = []; } Logger.prototype.setOptions = function (options) { copyProperty("level", options, this); copyProperty("userAgentRegex", options, this); copyProperty("disallow", options, this); copyProperty("ipRegex", options, this); copyProperty("appenders", options, this); copyProperty("onceOnly", options, this); // Reset seenRegexes, in case onceOnly has been changed. this.seenRegexes = []; return this; }; // Turns an exception into an object that can be sent to the server. Logger.prototype.buildExceptionObject = function (e) { var excObject = {}; if (e.stack) { excObject.stack = e.stack; } else { excObject.e = e; } if (e.message) { excObject.message = e.message; } if (e.name) { excObject.name = e.name; } if (e.data) { excObject.data = e.data; } if (e.inner) { excObject.inner = this.buildExceptionObject(e.inner); } return excObject; }; // Logs a log item. // Parameter e contains an exception (or null or undefined). // // Reason that processing exceptions is done at this low level is that // 1) no need to spend the cpu cycles if the logger is switched off // 2) fatalException takes both a logObject and an exception, and the logObject // may be a function that should only be executed if the logger is switched on. // // If an exception is passed in, the contents of logObject is attached to the exception // object in a new property logData. // The resulting exception object is than worked into a message to the server. // // If there is no exception, logObject itself is worked into the message to the server. Logger.prototype.log = function (level, logObject, e) { var i = 0; var compositeMessage; var excObject; // If we can't find any appenders, do nothing if (!this.appenders) { return this; } if (((level >= this.level)) && allow(this)) { if (e) { excObject = this.buildExceptionObject(e); excObject.logData = stringifyLogObjectFunction(logObject); } else { excObject = logObject; } compositeMessage = stringifyLogObject(excObject); if (allowMessage(this, compositeMessage.finalString)) { // See whether message is a duplicate if (this.onceOnly) { i = this.onceOnly.length - 1; while (i >= 0) { if (new RegExp(this.onceOnly[i]).test(compositeMessage.finalString)) { if (this.seenRegexes[i]) { return this; } this.seenRegexes[i] = true; } i--; } } // Pass message to all appenders // Note that these appenders could be Winston transports // https://github.com/flatiron/winston // // These transports do not take the logger name as a parameter. // So add it to the meta information, so even Winston transports will // store this info. compositeMessage.meta = compositeMessage.meta || {}; compositeMessage.meta.loggerName = this.loggerName; i = this.appenders.length - 1; while (i >= 0) { this.appenders[i].log(levelToString(level), compositeMessage.msg, compositeMessage.meta, function () { }, level, compositeMessage.finalString, this.loggerName); i--; } } } return this; }; Logger.prototype.trace = function (logObject) { return this.log(getTraceLevel(), logObject); }; Logger.prototype.debug = function (logObject) { return this.log(getDebugLevel(), logObject); }; Logger.prototype.info = function (logObject) { return this.log(getInfoLevel(), logObject); }; Logger.prototype.warn = function (logObject) { return this.log(getWarnLevel(), logObject); }; Logger.prototype.error = function (logObject) { return this.log(getErrorLevel(), logObject); }; Logger.prototype.fatal = function (logObject) { return this.log(getFatalLevel(), logObject); }; Logger.prototype.fatalException = function (logObject, e) { return this.log(getFatalLevel(), logObject, e); }; return Logger; })(); JL.Logger = Logger; function createAjaxAppender(appenderName) { return new AjaxAppender(appenderName); } JL.createAjaxAppender = createAjaxAppender; function createConsoleAppender(appenderName) { return new ConsoleAppender(appenderName); } JL.createConsoleAppender = createConsoleAppender; // ----------------------- // In the browser, the default appender is the AjaxAppender. // Under nodejs (where there is no "window"), use the ConsoleAppender instead. var defaultAppender = new AjaxAppender(""); if (typeof window === 'undefined') { defaultAppender = new ConsoleAppender(""); } // Create root logger // // Note that this is the parent of all other loggers. // Logger "x" will be stored at // JL.__.x // Logger "x.y" at // JL.__.x.y JL.__ = new JL.Logger(""); JL.__.setOptions({ level: JL.getDebugLevel(), appenders: [defaultAppender] }); })(JL || (JL = {})); // Support CommonJS module format var exports; if (typeof exports !== 'undefined') { exports.JL = JL; } // Support AMD module format var define; if (typeof define == 'function' && define.amd) { define('jsnlog', [], function () { return JL; }); } // If the __jsnlog_configure global function has been // created, call it now. This allows you to create a global function // setting logger options etc. inline in the page before jsnlog.js // has been loaded. if (typeof __jsnlog_configure == 'function') { __jsnlog_configure(JL); } //# sourceMappingURL=jsnlog.js.map
sitna/api-sitna
lib/jsnlog/jsnlog.js
JavaScript
bsd-2-clause
33,564
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule XMLHttpRequest * @flow */ 'use strict'; var RCTDataManager = require('NativeModules').DataManager; var crc32 = require('crc32'); var XMLHttpRequestBase = require('XMLHttpRequestBase'); class XMLHttpRequest extends XMLHttpRequestBase { sendImpl(method: ?string, url: ?string, headers: Object, data: any): void { RCTDataManager.queryData( 'http', JSON.stringify({ method: method, url: url, data: data, headers: headers, }), 'h' + crc32(method + '|' + url + '|' + data), (result) => { result = JSON.parse(result); this.callback(result.status, result.responseHeaders, result.responseText); } ); } abortImpl(): void { console.warn( 'XMLHttpRequest: abort() cancels JS callbacks ' + 'but not native HTTP request.' ); } } module.exports = XMLHttpRequest;
foxsofter/RealtimeMessaging-ReactNative
node_modules/react-native/Libraries/Network/XMLHttpRequest.ios.js
JavaScript
mit
1,204
/** * These objects store the data about the DOM nodes we create, as well as some * extra data. They can then be transformed into real DOM nodes with the * `toNode` function or HTML markup using `toMarkup`. They are useful for both * storing extra properties on the nodes, as well as providing a way to easily * work with the DOM. * * Similar functions for working with MathML nodes exist in mathMLTree.js. */ var utils = require("./utils"); /** * Create an HTML className based on a list of classes. In addition to joining * with spaces, we also remove null or empty classes. */ var createClass = function(classes) { classes = classes.slice(); for (var i = classes.length - 1; i >= 0; i--) { if (!classes[i]) { classes.splice(i, 1); } } return classes.join(" "); }; /** * This node represents a span node, with a className, a list of children, and * an inline style. It also contains information about its height, depth, and * maxFontSize. */ function span(classes, children, height, depth, maxFontSize, style) { this.classes = classes || []; this.children = children || []; this.height = height || 0; this.depth = depth || 0; this.maxFontSize = maxFontSize || 0; this.style = style || {}; this.attributes = {}; } /** * Sets an arbitrary attribute on the span. Warning: use this wisely. Not all * browsers support attributes the same, and having too many custom attributes * is probably bad. */ span.prototype.setAttribute = function(attribute, value) { this.attributes[attribute] = value; }; /** * Convert the span into an HTML node */ span.prototype.toNode = function() { var span = document.createElement("span"); // Apply the class span.className = createClass(this.classes); // Apply inline styles for (var style in this.style) { if (Object.prototype.hasOwnProperty.call(this.style, style)) { span.style[style] = this.style[style]; } } // Apply attributes for (var attr in this.attributes) { if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) { span.setAttribute(attr, this.attributes[attr]); } } // Append the children, also as HTML nodes for (var i = 0; i < this.children.length; i++) { span.appendChild(this.children[i].toNode()); } return span; }; /** * Convert the span into an HTML markup string */ span.prototype.toMarkup = function() { var markup = "<span"; // Add the class if (this.classes.length) { markup += " class=\""; markup += utils.escape(createClass(this.classes)); markup += "\""; } var styles = ""; // Add the styles, after hyphenation for (var style in this.style) { if (this.style.hasOwnProperty(style)) { styles += utils.hyphenate(style) + ":" + this.style[style] + ";"; } } if (styles) { markup += " style=\"" + utils.escape(styles) + "\""; } // Add the attributes for (var attr in this.attributes) { if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) { markup += " " + attr + "=\""; markup += utils.escape(this.attributes[attr]); markup += "\""; } } markup += ">"; // Add the markup of the children, also as markup for (var i = 0; i < this.children.length; i++) { markup += this.children[i].toMarkup(); } markup += "</span>"; return markup; }; /** * This node represents a document fragment, which contains elements, but when * placed into the DOM doesn't have any representation itself. Thus, it only * contains children and doesn't have any HTML properties. It also keeps track * of a height, depth, and maxFontSize. */ function documentFragment(children, height, depth, maxFontSize) { this.children = children || []; this.height = height || 0; this.depth = depth || 0; this.maxFontSize = maxFontSize || 0; } /** * Convert the fragment into a node */ documentFragment.prototype.toNode = function() { // Create a fragment var frag = document.createDocumentFragment(); // Append the children for (var i = 0; i < this.children.length; i++) { frag.appendChild(this.children[i].toNode()); } return frag; }; /** * Convert the fragment into HTML markup */ documentFragment.prototype.toMarkup = function() { var markup = ""; // Simply concatenate the markup for the children together for (var i = 0; i < this.children.length; i++) { markup += this.children[i].toMarkup(); } return markup; }; /** * A symbol node contains information about a single symbol. It either renders * to a single text node, or a span with a single text node in it, depending on * whether it has CSS classes, styles, or needs italic correction. */ function symbolNode(value, height, depth, italic, skew, classes, style) { this.value = value || ""; this.height = height || 0; this.depth = depth || 0; this.italic = italic || 0; this.skew = skew || 0; this.classes = classes || []; this.style = style || {}; this.maxFontSize = 0; } /** * Creates a text node or span from a symbol node. Note that a span is only * created if it is needed. */ symbolNode.prototype.toNode = function() { var node = document.createTextNode(this.value); var span = null; if (this.italic > 0) { span = document.createElement("span"); span.style.marginRight = this.italic + "em"; } if (this.classes.length > 0) { span = span || document.createElement("span"); span.className = createClass(this.classes); } for (var style in this.style) { if (this.style.hasOwnProperty(style)) { span = span || document.createElement("span"); span.style[style] = this.style[style]; } } if (span) { span.appendChild(node); return span; } else { return node; } }; /** * Creates markup for a symbol node. */ symbolNode.prototype.toMarkup = function() { // TODO(alpert): More duplication than I'd like from // span.prototype.toMarkup and symbolNode.prototype.toNode... var needsSpan = false; var markup = "<span"; if (this.classes.length) { needsSpan = true; markup += " class=\""; markup += utils.escape(createClass(this.classes)); markup += "\""; } var styles = ""; if (this.italic > 0) { styles += "margin-right:" + this.italic + "em;"; } for (var style in this.style) { if (this.style.hasOwnProperty(style)) { styles += utils.hyphenate(style) + ":" + this.style[style] + ";"; } } if (styles) { needsSpan = true; markup += " style=\"" + utils.escape(styles) + "\""; } var escaped = utils.escape(this.value); if (needsSpan) { markup += ">"; markup += escaped; markup += "</span>"; return markup; } else { return escaped; } }; module.exports = { span: span, documentFragment: documentFragment, symbolNode: symbolNode, };
cyanlime/platform
webapp/non_npm_dependencies/katex/src/domTree.js
JavaScript
agpl-3.0
7,224
// HTML block 'use strict'; var block_names = require('../common/html_blocks'); var HTML_TAG_OPEN_RE = /^<([a-zA-Z][a-zA-Z0-9]{0,14})[\s\/>]/; var HTML_TAG_CLOSE_RE = /^<\/([a-zA-Z][a-zA-Z0-9]{0,14})[\s>]/; function isLetter(ch) { /*eslint no-bitwise:0*/ var lc = ch | 0x20; // to lower case return (lc >= 0x61/* a */) && (lc <= 0x7a/* z */); } module.exports = function html_block(state, startLine, endLine, silent) { var ch, match, nextLine, token, pos = state.bMarks[startLine], max = state.eMarks[startLine], shift = state.tShift[startLine]; pos += shift; if (!state.md.options.html) { return false; } if (shift > 3 || pos + 2 >= max) { return false; } if (state.src.charCodeAt(pos) !== 0x3C/* < */) { return false; } ch = state.src.charCodeAt(pos + 1); if (ch === 0x21/* ! */ || ch === 0x3F/* ? */) { // Directive start / comment start / processing instruction start if (silent) { return true; } } else if (ch === 0x2F/* / */ || isLetter(ch)) { // Probably start or end of tag if (ch === 0x2F/* \ */) { // closing tag match = state.src.slice(pos, max).match(HTML_TAG_CLOSE_RE); if (!match) { return false; } } else { // opening tag match = state.src.slice(pos, max).match(HTML_TAG_OPEN_RE); if (!match) { return false; } } // Make sure tag name is valid if (block_names[match[1].toLowerCase()] !== true) { return false; } if (silent) { return true; } } else { return false; } // If we are here - we detected HTML block. // Let's roll down till empty line (block end). nextLine = startLine + 1; while (nextLine < state.lineMax && !state.isEmpty(nextLine)) { nextLine++; } state.line = nextLine; token = state.push('html_block', '', 0); token.map = [ startLine, state.line ]; token.content = state.getLines(startLine, nextLine, 0, true); return true; };
waddedMeat/ember-proxy-example
test-app/node_modules/ember-cli/node_modules/markdown-it/lib/rules_block/html_block.js
JavaScript
mit
1,933
module.exports = { up(queryInterface, DataTypes) { return queryInterface.createTable( 'Topics', { id: { type: DataTypes.STRING, primaryKey: true }, text: { type: DataTypes.STRING }, count: { type: DataTypes.INTEGER }, date: { type: DataTypes.DATE, defaultValue: DataTypes.fn('NOW') } } ); }, down(queryInterface) { return queryInterface.dropTable('Topics'); } };
reactGo/reactGo
server_pg/db/sequelize/migrations/20160416222221-add-topics.js
JavaScript
mit
520
/*prettydiff.com topcoms: true, insize: 4, inchar: " ", vertical: true */ /*jshint laxbreak: true*/ /*global __dirname, ace, console, define, global, module, options, process, require */ /* Execute in a NodeJS app: var prettydiff = require("prettydiff"), args = { source: "asdf", diff : "asdd", lang : "text" }, output = prettydiff(args); Execute on command line with NodeJS: prettydiff source:"c:\mydirectory\myfile.js" readmethod:"file" diff:"c:\myotherfile.js" Execute with WSH: cscript prettydiff.wsf /source:"myFile.xml" /mode:"beautify" Execute from JavaScript: var global = {}, args = { source: "asdf", diff : "asdd", lang : "text" }, output = prettydiff(args); ******* license start ******* @source: http://prettydiff.com/prettydiff.js @documentation - English: http://prettydiff.com/documentation.xhtml @licstart The following is the entire license notice for Pretty Diff. This code may not be used or redistributed unless the following conditions are met: * Prettydiff created by Austin Cheney originally on 3 Mar 2009. http://prettydiff.com/ * The use of diffview.js and prettydiff.js must contain the following copyright: Copyright (c) 2007, Snowtide Informatics Systems, Inc. All rights reserved. - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Snowtide Informatics Systems nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - used as diffview function http://prettydiff.com/lib/diffview.js * The code mentioned above has significantly expanded documentation in each of the respective function's external JS file as linked from the documentation page: http://prettydiff.com/documentation.php * In addition to the previously stated requirements any use of any component, aside from directly using the full files in their entirety, must restate the license mentioned at the top of each concerned file. If each and all these conditions are met use, extension, alteration, and redistribution of Pretty Diff and its required assets is unlimited and free without author permission. @licend The above is the entire license notice for Pretty Diff. ******* license end ******* Special thanks to: * Harry Whitfield for the numerous test cases provided against JSPretty. http://g6auc.me.uk/ * Andreas Greuel for contributing samples to test diffview.js https://plus.google.com/105958105635636993368/posts */ (function prettydiff_init() { "use strict"; if (typeof global.prettydiff !== "object") { global.prettydiff = {}; } if (typeof global.prettydiff.meta !== "object") { // schema for global.prettydiff.meta lang - array, language detection time - string, // proctime (total execution time minus visual rendering) insize - number, input // size outsize - number, output size difftotal - number, difference count // difflines - number, difference lines global.prettydiff.meta = { difflines: 0, difftotal: 0, error : "", insize : 0, lang : [ "", "", "" ], outsize : 0, time : "" }; } if (typeof require === "function" && (typeof ace !== "object" || ace.prettydiffid === undefined)) { (function glib_prettydiff() { var localPath = (typeof process === "object" && typeof process.cwd === "function" && (process.cwd() === "/" || (/^([a-z]:\\)$/).test(process.cwd()) === true) && typeof __dirname === "string") ? __dirname : "."; if (global.prettydiff.language === undefined) { global.prettydiff.language = require(localPath + "/lib/language.js"); } if (global.prettydiff.finalFile === undefined) { global.prettydiff.finalFile = require(localPath + "/lib/finalFile.js"); } if (global.prettydiff.csspretty === undefined) { global.prettydiff.csspretty = require(localPath + "/lib/csspretty.js"); } if (global.prettydiff.csvpretty === undefined) { global.prettydiff.csvpretty = require(localPath + "/lib/csvpretty.js"); } if (global.prettydiff.diffview === undefined) { global.prettydiff.diffview = require(localPath + "/lib/diffview.js"); } if (global.prettydiff.jspretty === undefined) { global.prettydiff.jspretty = require(localPath + "/lib/jspretty.js"); } if (global.prettydiff.options === undefined) { global.prettydiff.options = require(localPath + "/lib/options.js"); } if (global.prettydiff.safeSort === undefined) { global.prettydiff.safeSort = require(localPath + "/lib/safeSort.js"); } if (global.prettydiff.markuppretty === undefined) { global.prettydiff.markuppretty = require(localPath + "/lib/markuppretty.js"); } }()); } var prettydiff = function prettydiff_(api) { var startTime = (typeof Date.now === "function") ? Date.now() : (function prettydiff__dateShim() { var dateItem = new Date(); return Date.parse(dateItem); }()), core = function core_(api) { var spacetest = (/^\s+$/g), apioutput = "", apidiffout = "", metaerror = "", finalFile = global.prettydiff.finalFile, options = global.prettydiff.options.functions.validate(api), jspretty = function core__jspretty() { var jsout = global.prettydiff.jspretty(options); if (options.nodeasync === true) { metaerror = jsout[1]; return jsout[0]; } metaerror = global.prettydiff.meta.error; return jsout; }, markuppretty = function core__markuppretty() { var markout = global.prettydiff.markuppretty(options); if (options.nodeasync === true) { metaerror = markout[1]; if (options.mode === "beautify" && options.inchar !== "\t") { markout[0] = markout[0].replace(/\r?\n[\t]*\u0020\/>/g, ""); } else if (options.mode === "diff") { markout[0] = markout[0].replace(/\r?\n[\t]*\u0020\/>/g, ""); } return markout[0]; } metaerror = global.prettydiff.meta.error; if (options.mode === "beautify" && options.inchar !== "\t") { markout = markout.replace(/\r?\n[\t]*\u0020\/>/g, ""); } else if (options.mode === "diff") { markout = markout.replace(/\r?\n[\t]*\u0020\/>/g, ""); } return markout; }, csspretty = function core__markupcss() { var cssout = global.prettydiff.csspretty(options); if (options.nodeasync === true) { metaerror = cssout[1]; return cssout[0]; } metaerror = global.prettydiff.meta.error; return cssout; }, proctime = function core__proctime() { var minuteString = "", hourString = "", minutes = 0, hours = 0, elapsed = (typeof Date.now === "function") ? ((Date.now() - startTime) / 1000) : (function core__proctime_dateShim() { var dateitem = new Date(); return Date.parse(dateitem); }()), secondString = elapsed.toFixed(3), plural = function core__proctime_plural(x, y) { var a = x + y; if (x !== 1) { a = a + "s"; } if (y !== " second") { a = a + " "; } return a; }, minute = function core__proctime_minute() { minutes = parseInt((elapsed / 60), 10); minuteString = plural(minutes, " minute"); minutes = elapsed - (minutes * 60); secondString = (minutes === 1) ? "1 second" : minutes.toFixed(3) + " seconds"; }; if (elapsed >= 60 && elapsed < 3600) { minute(); } else if (elapsed >= 3600) { hours = parseInt((elapsed / 3600), 10); hourString = hours.toString(); elapsed = elapsed - (hours * 3600); hourString = plural(hours, " hour"); minute(); } else { secondString = plural(secondString, " second"); } return hourString + minuteString + secondString; }, output = function core__output(finalProduct, difftotal, difflines) { var meta = { difflines: 0, difftotal: 0, error : "", insize : 0, lang : [ "", "", "" ], outsize : 0, time : "" }; meta.lang = options.autoval; meta.time = proctime(); meta.insize = (options.mode === "diff") ? options.source.length + options.diff.length : options.source.length; if (options.mode === "parse" && options.lang !== "text" && typeof finalProduct === "object" && (options.autoval[0] !== "" || options.lang !== "auto")) { if (options.parseFormat === "sequential" || options.parseFormat === "htmltable") { meta.outsize = finalProduct.data.length; } else { meta.outsize = finalProduct.data.token.length; } } else { meta.outsize = finalProduct.length; } if (options.autoval[0] === "text" && options.mode !== "diff") { if (options.autoval[2] === "unknown") { meta.error = "Language is set to auto, but could not be detected. File not parsed."; } else { meta.error = "Language is set to text, but plain text is only supported in diff mode. File not" + " parsed."; } } if (difftotal !== undefined) { meta.difftotal = difftotal; } if (difflines !== undefined) { meta.difflines = difflines; } meta.error = metaerror; if (options.nodeasync === true) { return [finalProduct, meta]; } global.prettydiff.meta = meta; return finalProduct; }; if (options.source === "" && (options.mode === "beautify" || options.mode === "minify" || options.mode === "analysis" || (options.mode === "diff" && options.diffcli === false) || (options.mode === "parse" && options.parseFormat === "htmltable"))) { metaerror = "options.source is empty!"; return output(""); } if (options.mode === "diff" && options.diffcli === false) { if (options.diff === "") { metaerror = "options.mode is 'diff' and options.diff is empty!"; return output(""); } if (options.lang === "csv") { options.lang = "text"; } } if (options.autoval[0] === "text" && options.mode !== "diff") { metaerror = "Language is either text or undetermined, but text is only allowed for the 'diff'" + " mode!"; return output(options.source); } finalFile.order[7] = options.color; if (options.mode === "diff") { options.vertical = false; options.jsscope = "none"; options.preserve = 0; if (options.diffcomments === false) { options.comments = "nocomment"; } if (options.lang === "css") { apioutput = csspretty(); options.source = options.diff; apidiffout = csspretty(); } else if (options.lang === "csv") { apioutput = global.prettydiff.csvpretty(options); apidiffout = global.prettydiff.csvpretty(options); } else if (options.lang === "markup") { apioutput = markuppretty(); options.source = options.diff; apidiffout = markuppretty(); } else if (options.lang === "text") { apioutput = options.source; apidiffout = options.diff; } else { apioutput = jspretty(); options.source = options.diff; apidiffout = jspretty(); } if (options.quote === true) { apioutput = apioutput.replace(/'/g, "\""); apidiffout = apidiffout.replace(/'/g, "\""); } if (options.semicolon === true) { apioutput = apioutput .replace(/;\r\n/g, "\r\n") .replace(/;\n/g, "\n"); apidiffout = apidiffout .replace(/;\r\n/g, "\r\n") .replace(/;\n/g, "\n"); } if (options.sourcelabel === "" || spacetest.test(options.sourcelabel)) { options.sourcelabel = "Base Text"; } if (options.difflabel === "" || spacetest.test(options.difflabel)) { options.difflabel = "New Text"; } if (options.jsx === true) { options.autoval = ["jsx", "javascript", "React JSX"]; } return (function core__diff() { var a = ""; options.diff = apidiffout; options.source = apioutput; if (options.diffcli === true) { return output(global.prettydiff.diffview(options)); } if (apioutput === "Error: This does not appear to be JavaScript." || apidiffout === "Error: This does not appear to be JavaScript.") { return output("<p><strong>Error:</strong> Please try using the option labeled <em>Plain Text (d" + "iff only)</em>. <span style='display:block'>The input does not appear to be mark" + "up, CSS, or JavaScript.</span></p>"); } if (options.lang === "text") { options.inchar = ""; } a = global.prettydiff.diffview(options); if (options.jsx === true) { options.autoval = ["jsx", "javascript", "React JSX"]; } if (options.api === "") { finalFile.order[10] = a[0]; finalFile.order[12] = finalFile.script.diff; return output(finalFile.order.join(""), a[1], a[2]); } return output(a[0], a[1], a[2]); }()); } else { if (options.mode === "analysis") { options.accessibility = true; } if (options.lang === "css") { apioutput = csspretty(); } else if (options.lang === "csv") { apioutput = global.prettydiff.csvpretty(options); } else if (options.lang === "markup") { apioutput = markuppretty(); } else if (options.lang === "text") { apioutput = options.source; apidiffout = ""; } else { apioutput = jspretty(); } if (options.api === "") { if (options.mode === "analysis" || (options.mode === "parse" && options.parseFormat === "htmltable")) { finalFile.order[10] = apidiffout; apioutput = finalFile.order.join(""); } else if (options.mode === "beautify" && options.jsscope !== "none" && options.lang === "javascript") { finalFile.order[10] = apidiffout; finalFile.order[12] = finalFile.script.beautify; apioutput = finalFile.order.join(""); } } if (options.jsx === true) { options.autoval = ["jsx", "javascript", "React JSX"]; } return output(apioutput); } }; return core(api); }; global.prettydiff.edition = { addon : { ace: 160307 }, api : { dom : 161002, //dom.js nodeLocal: 160816 //node-local.js }, css : 160814, //css files csspretty : 160902, //csspretty lib csvpretty : 160816, //csvpretty lib diffview : 161002, //diffview lib documentation: 160828, //documentation.xhtml and various guide pages finalFile : 160816, //HTML report generator jspretty : 161002, //jspretty lib language : 160921, //language lib latest : 0, lint : 161002, //unit test and lint automation as test/lint.js markuppretty : 161002, //markuppretty lib options : 161002, //options management prettydiff : 161002, //this file safeSort : 160816, //safeSort lib version : "2.1.12", //version number webtool : 160827 }; global.prettydiff.edition.latest = (function edition_latest() { return Math.max(global.prettydiff.edition.css, global.prettydiff.edition.csspretty, global.prettydiff.edition.csvpretty, global.prettydiff.edition.diffview, global.prettydiff.edition.documentation, global.prettydiff.edition.finalFile, global.prettydiff.edition.jspretty, global.prettydiff.edition.language, global.prettydiff.edition.markuppretty, global.prettydiff.edition.options, global.prettydiff.edition.prettydiff, global.prettydiff.edition.webtool, global.prettydiff.edition.api.dom, global.prettydiff.edition.api.nodeLocal); }()); if (typeof module === "object" && typeof module.parent === "object") { //commonjs and nodejs support module.exports.edition = global.prettydiff.edition; module.exports.meta = global.prettydiff.meta; module.exports = function commonjs_prettydiff(x) { return prettydiff(x); }; if (process.argv.length === 2 && process.argv[1].indexOf("prettydiff.js") > -1) { console.log("Please try: node api/node-local.js"); } } else if ((typeof define === "object" || typeof define === "function") && (typeof ace !== "object" || ace.prettydiffid === undefined)) { //requirejs support define(function requirejs(require, module) { module.exports.edition = global.prettydiff.edition; module.exports.meta = global.prettydiff.meta; module.exports = function requirejs_prettydiff_export(x) { return prettydiff(x); }; //worthless if block to appease RequireJS and JSLint if (typeof require === "number") { return require; } return function requirejs_prettydiff_module(x) { prettydiff(x); }; }); } else { global.prettydiff.prettydiff = prettydiff; } }());
dc-js/cdnjs
ajax/libs/prettydiff/2.1.12/prettydiff.js
JavaScript
mit
23,178
// 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. // Copyright 2006 Google Inc. All Rights Reserved. /** * @fileoverview Generics method for collection-like classes and objects. * * * This file contains functions to work with collections. It supports using * Map, Set, Array and Object and other classes that implement collection-like * methods. * */ goog.provide('goog.structs'); goog.require('goog.array'); goog.require('goog.object'); // We treat an object as a dictionary if it has getKeys or it is an object that // isn't arrayLike. /** * Returns the number of values in the collection-like object. * @param {Object} col The collection-like object. * @return {number} The number of values in the collection-like object. */ goog.structs.getCount = function(col) { if (typeof col.getCount == 'function') { return col.getCount(); } if (goog.isArrayLike(col) || goog.isString(col)) { return col.length; } return goog.object.getCount(col); }; /** * Returns the values of the collection-like object. * @param {Object} col The collection-like object. * @return {!Array} The values in the collection-like object. */ goog.structs.getValues = function(col) { if (typeof col.getValues == 'function') { return col.getValues(); } if (goog.isString(col)) { return col.split(''); } if (goog.isArrayLike(col)) { var rv = []; var l = col.length; for (var i = 0; i < l; i++) { rv.push(col[i]); } return rv; } return goog.object.getValues(col); }; /** * Returns the keys of the collection. Some collections have no notion of * keys/indexes and this function will return undefined in those cases. * @param {Object} col The collection-like object. * @return {!Array|undefined} The keys in the collection. */ goog.structs.getKeys = function(col) { if (typeof col.getKeys == 'function') { return col.getKeys(); } // if we have getValues but no getKeys we know this is a key-less collection if (typeof col.getValues == 'function') { return undefined; } if (goog.isArrayLike(col) || goog.isString(col)) { var rv = []; var l = col.length; for (var i = 0; i < l; i++) { rv.push(i); } return rv; } return goog.object.getKeys(col); }; /** * Whether the collection contains the given value. This is O(n) and uses * equals (==) to test the existence. * @param {Object} col The collection-like object. * @param {*} val The value to check for. * @return {boolean} True if the map contains the value. */ goog.structs.contains = function(col, val) { if (typeof col.contains == 'function') { return col.contains(val); } if (typeof col.containsValue == 'function') { return col.containsValue(val); } if (goog.isArrayLike(col) || goog.isString(col)) { return goog.array.contains(/** @type {Array} */ (col), val); } return goog.object.containsValue(col, val); }; /** * Whether the collection is empty. * @param {Object} col The collection-like object. * @return {boolean} True if empty. */ goog.structs.isEmpty = function(col) { if (typeof col.isEmpty == 'function') { return col.isEmpty(); } // We do not use goog.string.isEmpty because here we treat the string as // collection and as such even whitespace matters if (goog.isArrayLike(col) || goog.isString(col)) { return goog.array.isEmpty(/** @type {Array} */ (col)); } return goog.object.isEmpty(col); }; /** * Removes all the elements from the collection. * @param {Object} col The collection-like object. */ goog.structs.clear = function(col) { // NOTE: This should not contain strings because strings are immutable if (typeof col.clear == 'function') { col.clear(); } else if (goog.isArrayLike(col)) { goog.array.clear((/** @type {goog.array.ArrayLike} */ col)); } else { goog.object.clear(col); } }; /** * Calls a function for each value in a collection. The function takes * three arguments; the value, the key and the collection. * * @param {Object} col The collection-like object. * @param {Function} f The function to call for every value. This function takes * 3 arguments (the value, the key or undefined if the collection has no * notion of keys, and the collection) and the return value is irrelevant. * @param {Object} opt_obj The object to be used as the value of 'this' * within {@code f}. */ goog.structs.forEach = function(col, f, opt_obj) { if (typeof col.forEach == 'function') { col.forEach(f, opt_obj); } else if (goog.isArrayLike(col) || goog.isString(col)) { goog.array.forEach(/** @type {Array} */ (col), f, opt_obj); } else { var keys = goog.structs.getKeys(col); var values = goog.structs.getValues(col); var l = values.length; for (var i = 0; i < l; i++) { f.call(opt_obj, values[i], keys && keys[i], col); } } }; /** * Calls a function for every value in the collection. When a call returns true, * adds the value to a new collection (Array is returned by default). * * @param {Object} col The collection-like object. * @param {Function} f The function to call for every value. This function takes * 3 arguments (the value, the key or undefined if the collection has no * notion of keys, and the collection) and should return a Boolean. If the * return value is true the value is added to the result collection. If it * is false the value is not included. * @param {Object} opt_obj The object to be used as the value of 'this' * within {@code f}. * @return {!Object|!Array} A new collection where the passed values are * present. If col is a key-less collection an array is returned. If col * has keys and values a plain old JS object is returned. */ goog.structs.filter = function(col, f, opt_obj) { if (typeof col.filter == 'function') { return col.filter(f, opt_obj); } if (goog.isArrayLike(col) || goog.isString(col)) { return goog.array.filter(/** @type {!Array} */ (col), f, opt_obj); } var rv; var keys = goog.structs.getKeys(col); var values = goog.structs.getValues(col); var l = values.length; if (keys) { rv = {}; for (var i = 0; i < l; i++) { if (f.call(opt_obj, values[i], keys[i], col)) { rv[keys[i]] = values[i]; } } } else { // We should not use goog.array.filter here since we want to make sure that // the index is undefined as well as make sure that col is passed to the // function. rv = []; for (var i = 0; i < l; i++) { if (f.call(opt_obj, values[i], undefined, col)) { rv.push(values[i]); } } } return rv; }; /** * Calls a function for every value in the collection and adds the result into a * new collection (defaults to creating a new Array). * * @param {Object} col The collection-like object. * @param {Function} f The function to call for every value. This function * takes 3 arguments (the value, the key or undefined if the collection has * no notion of keys, and the collection) and should return something. The * result will be used as the value in the new collection. * @param {Object} opt_obj The object to be used as the value of 'this' * within {@code f}. * @return {!Object|!Array} A new collection with the new values. If col is a * key-less collection an array is returned. If col has keys and values a * plain old JS object is returned. */ goog.structs.map = function(col, f, opt_obj) { if (typeof col.map == 'function') { return col.map(f, opt_obj); } if (goog.isArrayLike(col) || goog.isString(col)) { return goog.array.map(/** @type {!Array} */ (col), f, opt_obj); } var rv; var keys = goog.structs.getKeys(col); var values = goog.structs.getValues(col); var l = values.length; if (keys) { rv = {}; for (var i = 0; i < l; i++) { rv[keys[i]] = f.call(opt_obj, values[i], keys[i], col); } } else { // We should not use goog.array.map here since we want to make sure that // the index is undefined as well as make sure that col is passed to the // function. rv = []; for (var i = 0; i < l; i++) { rv[i] = f.call(opt_obj, values[i], undefined, col); } } return rv; }; /** * Calls f for each value in a collection. If any call returns true this returns * true (without checking the rest). If all returns false this returns false. * * @param {Object|Array|string} col The collection-like object. * @param {Function} f The function to call for every value. This function takes * 3 arguments (the value, the key or undefined if the collection has no * notion of keys, and the collection) and should return a Boolean. * @param {Object} opt_obj The object to be used as the value of 'this' * within {@code f}. * @return {boolean} True if any value passes the test. */ goog.structs.some = function(col, f, opt_obj) { if (typeof col.some == 'function') { return col.some(f, opt_obj); } if (goog.isArrayLike(col) || goog.isString(col)) { return goog.array.some(/** @type {!Array} */ (col), f, opt_obj); } var keys = goog.structs.getKeys(col); var values = goog.structs.getValues(col); var l = values.length; for (var i = 0; i < l; i++) { if (f.call(opt_obj, values[i], keys && keys[i], col)) { return true; } } return false; }; /** * Calls f for each value in a collection. If all calls return true this return * true this returns true. If any returns false this returns false at this point * and does not continue to check the remaining values. * * @param {Object} col The collection-like object. * @param {Function} f The function to call for every value. This function takes * 3 arguments (the value, the key or undefined if the collection has no * notion of keys, and the collection) and should return a Boolean. * @param {Object} opt_obj The object to be used as the value of 'this' * within {@code f}. * @return {boolean} True if all key-value pairs pass the test. */ goog.structs.every = function(col, f, opt_obj) { if (typeof col.every == 'function') { return col.every(f, opt_obj); } if (goog.isArrayLike(col) || goog.isString(col)) { return goog.array.every(/** @type {!Array} */ (col), f, opt_obj); } var keys = goog.structs.getKeys(col); var values = goog.structs.getValues(col); var l = values.length; for (var i = 0; i < l; i++) { if (!f.call(opt_obj, values[i], keys && keys[i], col)) { return false; } } return true; };
yesudeep/puppy
tools/google-closure-library/closure/goog/structs/structs.js
JavaScript
mit
11,046
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v5.0.0-alpha.0 * @link http://www.ag-grid.com/ * @license MIT */ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var utils_1 = require("../utils"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var rowNode_1 = require("../entities/rowNode"); var context_1 = require("../context/context"); var eventService_1 = require("../eventService"); var selectionController_1 = require("../selectionController"); var events_1 = require("../events"); var sortController_1 = require("../sortController"); var filterManager_1 = require("../filter/filterManager"); var constants_1 = require("../constants"); /* * This row controller is used for infinite scrolling only. For normal 'in memory' table, * or standard pagination, the inMemoryRowController is used. */ var logging = false; var VirtualPageRowModel = (function () { function VirtualPageRowModel() { this.datasourceVersion = 0; } VirtualPageRowModel.prototype.init = function () { var _this = this; this.rowHeight = this.gridOptionsWrapper.getRowHeightAsNumber(); var virtualEnabled = this.gridOptionsWrapper.isRowModelVirtual(); this.eventService.addEventListener(events_1.Events.EVENT_FILTER_CHANGED, function () { if (virtualEnabled && _this.gridOptionsWrapper.isEnableServerSideFilter()) { _this.reset(); } }); this.eventService.addEventListener(events_1.Events.EVENT_SORT_CHANGED, function () { if (virtualEnabled && _this.gridOptionsWrapper.isEnableServerSideSorting()) { _this.reset(); } }); if (virtualEnabled && this.gridOptionsWrapper.getDatasource()) { this.setDatasource(this.gridOptionsWrapper.getDatasource()); } }; VirtualPageRowModel.prototype.getType = function () { return constants_1.Constants.ROW_MODEL_TYPE_VIRTUAL; }; VirtualPageRowModel.prototype.setDatasource = function (datasource) { this.datasource = datasource; if (!datasource) { // only continue if we have a valid datasource to working with return; } this.reset(); }; VirtualPageRowModel.prototype.isEmpty = function () { return !this.datasource; }; VirtualPageRowModel.prototype.isRowsToRender = function () { return utils_1.Utils.exists(this.datasource); }; VirtualPageRowModel.prototype.reset = function () { // important to return here, as the user could be setting filter or sort before // data-source is set if (utils_1.Utils.missing(this.datasource)) { return; } this.selectionController.reset(); // see if datasource knows how many rows there are if (typeof this.datasource.rowCount === 'number' && this.datasource.rowCount >= 0) { this.virtualRowCount = this.datasource.rowCount; this.foundMaxRow = true; } else { this.virtualRowCount = 0; this.foundMaxRow = false; } // in case any daemon requests coming from datasource, we know it ignore them this.datasourceVersion++; // map of page numbers to rows in that page this.pageCache = {}; this.pageCacheSize = 0; // if a number is in this array, it means we are pending a load from it this.pageLoadsInProgress = []; this.pageLoadsQueued = []; this.pageAccessTimes = {}; // keeps a record of when each page was last viewed, used for LRU cache this.accessTime = 0; // rather than using the clock, we use this counter // the number of concurrent loads we are allowed to the server if (typeof this.datasource.maxConcurrentRequests === 'number' && this.datasource.maxConcurrentRequests > 0) { this.maxConcurrentDatasourceRequests = this.datasource.maxConcurrentRequests; } else { this.maxConcurrentDatasourceRequests = 2; } // the number of pages to keep in browser cache if (typeof this.datasource.maxPagesInCache === 'number' && this.datasource.maxPagesInCache > 0) { this.maxPagesInCache = this.datasource.maxPagesInCache; } else { // null is default, means don't have any max size on the cache this.maxPagesInCache = null; } this.pageSize = this.datasource.pageSize; // take a copy of page size, we don't want it changing this.overflowSize = this.datasource.overflowSize; // take a copy of page size, we don't want it changing this.doLoadOrQueue(0); this.rowRenderer.refreshView(); }; VirtualPageRowModel.prototype.createNodesFromRows = function (pageNumber, rows) { var nodes = []; if (rows) { for (var i = 0, j = rows.length; i < j; i++) { var virtualRowIndex = (pageNumber * this.pageSize) + i; var node = this.createNode(rows[i], virtualRowIndex, true); nodes.push(node); } } return nodes; }; VirtualPageRowModel.prototype.createNode = function (data, virtualRowIndex, realNode) { var rowHeight = this.rowHeight; var top = rowHeight * virtualRowIndex; var rowNode; if (realNode) { // if a real node, then always create a new one rowNode = new rowNode_1.RowNode(); this.context.wireBean(rowNode); rowNode.id = virtualRowIndex; rowNode.data = data; // and see if the previous one was selected, and if yes, swap it out this.selectionController.syncInRowNode(rowNode); } else { // if creating a proxy node, see if there is a copy in selected memory that we can use var rowNode = this.selectionController.getNodeForIdIfSelected(virtualRowIndex); if (!rowNode) { rowNode = new rowNode_1.RowNode(); this.context.wireBean(rowNode); rowNode.id = virtualRowIndex; rowNode.data = data; } } rowNode.rowTop = top; rowNode.rowHeight = rowHeight; return rowNode; }; VirtualPageRowModel.prototype.removeFromLoading = function (pageNumber) { var index = this.pageLoadsInProgress.indexOf(pageNumber); this.pageLoadsInProgress.splice(index, 1); }; VirtualPageRowModel.prototype.pageLoadFailed = function (pageNumber) { this.removeFromLoading(pageNumber); this.checkQueueForNextLoad(); }; VirtualPageRowModel.prototype.pageLoaded = function (pageNumber, rows, lastRow) { this.putPageIntoCacheAndPurge(pageNumber, rows); this.checkMaxRowAndInformRowRenderer(pageNumber, lastRow); this.removeFromLoading(pageNumber); this.checkQueueForNextLoad(); }; VirtualPageRowModel.prototype.putPageIntoCacheAndPurge = function (pageNumber, rows) { this.pageCache[pageNumber] = this.createNodesFromRows(pageNumber, rows); this.pageCacheSize++; if (logging) { console.log('adding page ' + pageNumber); } var needToPurge = this.maxPagesInCache && this.maxPagesInCache < this.pageCacheSize; if (needToPurge) { // find the LRU page var youngestPageIndex = this.findLeastRecentlyAccessedPage(Object.keys(this.pageCache)); if (logging) { console.log('purging page ' + youngestPageIndex + ' from cache ' + Object.keys(this.pageCache)); } delete this.pageCache[youngestPageIndex]; this.pageCacheSize--; } }; VirtualPageRowModel.prototype.checkMaxRowAndInformRowRenderer = function (pageNumber, lastRow) { if (!this.foundMaxRow) { // if we know the last row, use if if (typeof lastRow === 'number' && lastRow >= 0) { this.virtualRowCount = lastRow; this.foundMaxRow = true; } else { // otherwise, see if we need to add some virtual rows var thisPagePlusBuffer = ((pageNumber + 1) * this.pageSize) + this.overflowSize; if (this.virtualRowCount < thisPagePlusBuffer) { this.virtualRowCount = thisPagePlusBuffer; } } // if rowCount changes, refreshView, otherwise just refreshAllVirtualRows this.rowRenderer.refreshView(); } else { this.rowRenderer.refreshAllVirtualRows(); } }; VirtualPageRowModel.prototype.isPageAlreadyLoading = function (pageNumber) { var result = this.pageLoadsInProgress.indexOf(pageNumber) >= 0 || this.pageLoadsQueued.indexOf(pageNumber) >= 0; return result; }; VirtualPageRowModel.prototype.doLoadOrQueue = function (pageNumber) { // if we already tried to load this page, then ignore the request, // otherwise server would be hit 50 times just to display one page, the // first row to find the page missing is enough. if (this.isPageAlreadyLoading(pageNumber)) { return; } // try the page load - if not already doing a load, then we can go ahead if (this.pageLoadsInProgress.length < this.maxConcurrentDatasourceRequests) { // go ahead, load the page this.loadPage(pageNumber); } else { // otherwise, queue the request this.addToQueueAndPurgeQueue(pageNumber); } }; VirtualPageRowModel.prototype.addToQueueAndPurgeQueue = function (pageNumber) { if (logging) { console.log('queueing ' + pageNumber + ' - ' + this.pageLoadsQueued); } this.pageLoadsQueued.push(pageNumber); // see if there are more pages queued that are actually in our cache, if so there is // no point in loading them all as some will be purged as soon as loaded var needToPurge = this.maxPagesInCache && this.maxPagesInCache < this.pageLoadsQueued.length; if (needToPurge) { // find the LRU page var youngestPageIndex = this.findLeastRecentlyAccessedPage(this.pageLoadsQueued); if (logging) { console.log('de-queueing ' + pageNumber + ' - ' + this.pageLoadsQueued); } var indexToRemove = this.pageLoadsQueued.indexOf(youngestPageIndex); this.pageLoadsQueued.splice(indexToRemove, 1); } }; VirtualPageRowModel.prototype.findLeastRecentlyAccessedPage = function (pageIndexes) { var youngestPageIndex = -1; var youngestPageAccessTime = Number.MAX_VALUE; var that = this; pageIndexes.forEach(function (pageIndex) { var accessTimeThisPage = that.pageAccessTimes[pageIndex]; if (accessTimeThisPage < youngestPageAccessTime) { youngestPageAccessTime = accessTimeThisPage; youngestPageIndex = pageIndex; } }); return youngestPageIndex; }; VirtualPageRowModel.prototype.checkQueueForNextLoad = function () { if (this.pageLoadsQueued.length > 0) { // take from the front of the queue var pageToLoad = this.pageLoadsQueued[0]; this.pageLoadsQueued.splice(0, 1); if (logging) { console.log('dequeueing ' + pageToLoad + ' - ' + this.pageLoadsQueued); } this.loadPage(pageToLoad); } }; VirtualPageRowModel.prototype.loadPage = function (pageNumber) { this.pageLoadsInProgress.push(pageNumber); var startRow = pageNumber * this.pageSize; var endRow = (pageNumber + 1) * this.pageSize; var that = this; var datasourceVersionCopy = this.datasourceVersion; var sortModel; if (this.gridOptionsWrapper.isEnableServerSideSorting()) { sortModel = this.sortController.getSortModel(); } var filterModel; if (this.gridOptionsWrapper.isEnableServerSideFilter()) { filterModel = this.filterManager.getFilterModel(); } var params = { startRow: startRow, endRow: endRow, successCallback: successCallback, failCallback: failCallback, sortModel: sortModel, filterModel: filterModel, context: this.gridOptionsWrapper.getContext() }; // check if old version of datasource used var getRowsParams = utils_1.Utils.getFunctionParameters(this.datasource.getRows); if (getRowsParams.length > 1) { console.warn('ag-grid: It looks like your paging datasource is of the old type, taking more than one parameter.'); console.warn('ag-grid: From ag-grid 1.9.0, now the getRows takes one parameter. See the documentation for details.'); } this.datasource.getRows(params); function successCallback(rows, lastRowIndex) { if (that.requestIsDaemon(datasourceVersionCopy)) { return; } that.pageLoaded(pageNumber, rows, lastRowIndex); } function failCallback() { if (that.requestIsDaemon(datasourceVersionCopy)) { return; } that.pageLoadFailed(pageNumber); } }; VirtualPageRowModel.prototype.expandOrCollapseAll = function (expand) { console.warn('ag-Grid: can not expand or collapse all when doing virtual pagination'); }; // check that the datasource has not changed since the lats time we did a request VirtualPageRowModel.prototype.requestIsDaemon = function (datasourceVersionCopy) { return this.datasourceVersion !== datasourceVersionCopy; }; VirtualPageRowModel.prototype.getRow = function (rowIndex) { if (rowIndex > this.virtualRowCount) { return null; } var pageNumber = Math.floor(rowIndex / this.pageSize); var page = this.pageCache[pageNumber]; // for LRU cache, track when this page was last hit this.pageAccessTimes[pageNumber] = this.accessTime++; if (!page) { this.doLoadOrQueue(pageNumber); // return back an empty row, so table can at least render empty cells var dummyNode = this.createNode(null, rowIndex, false); return dummyNode; } else { var indexInThisPage = rowIndex % this.pageSize; return page[indexInThisPage]; } }; VirtualPageRowModel.prototype.forEachNode = function (callback) { var pageKeys = Object.keys(this.pageCache); for (var i = 0; i < pageKeys.length; i++) { var pageKey = pageKeys[i]; var page = this.pageCache[pageKey]; for (var j = 0; j < page.length; j++) { var node = page[j]; callback(node); } } }; VirtualPageRowModel.prototype.getRowCombinedHeight = function () { return this.virtualRowCount * this.rowHeight; }; VirtualPageRowModel.prototype.getRowIndexAtPixel = function (pixel) { if (this.rowHeight !== 0) { return Math.floor(pixel / this.rowHeight); } else { return 0; } }; VirtualPageRowModel.prototype.getRowCount = function () { return this.virtualRowCount; }; VirtualPageRowModel.prototype.setRowData = function (rows, refresh, firstId) { console.warn('setRowData - does not work with virtual pagination'); }; VirtualPageRowModel.prototype.forEachNodeAfterFilter = function (callback) { console.warn('forEachNodeAfterFilter - does not work with virtual pagination'); }; VirtualPageRowModel.prototype.forEachNodeAfterFilterAndSort = function (callback) { console.warn('forEachNodeAfterFilter - does not work with virtual pagination'); }; VirtualPageRowModel.prototype.refreshModel = function () { console.warn('forEachNodeAfterFilter - does not work with virtual pagination'); }; VirtualPageRowModel.prototype.getTopLevelNodes = function () { console.warn('getTopLevelNodes - does not work with virtual pagination'); return null; }; __decorate([ context_1.Autowired('rowRenderer'), __metadata('design:type', Object) ], VirtualPageRowModel.prototype, "rowRenderer", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper) ], VirtualPageRowModel.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('filterManager'), __metadata('design:type', filterManager_1.FilterManager) ], VirtualPageRowModel.prototype, "filterManager", void 0); __decorate([ context_1.Autowired('sortController'), __metadata('design:type', sortController_1.SortController) ], VirtualPageRowModel.prototype, "sortController", void 0); __decorate([ context_1.Autowired('selectionController'), __metadata('design:type', selectionController_1.SelectionController) ], VirtualPageRowModel.prototype, "selectionController", void 0); __decorate([ context_1.Autowired('eventService'), __metadata('design:type', eventService_1.EventService) ], VirtualPageRowModel.prototype, "eventService", void 0); __decorate([ context_1.Autowired('context'), __metadata('design:type', context_1.Context) ], VirtualPageRowModel.prototype, "context", void 0); __decorate([ context_1.PostConstruct, __metadata('design:type', Function), __metadata('design:paramtypes', []), __metadata('design:returntype', void 0) ], VirtualPageRowModel.prototype, "init", null); VirtualPageRowModel = __decorate([ context_1.Bean('rowModel'), __metadata('design:paramtypes', []) ], VirtualPageRowModel); return VirtualPageRowModel; })(); exports.VirtualPageRowModel = VirtualPageRowModel;
holtkamp/cdnjs
ajax/libs/ag-grid/5.0.0-alpha.0/lib/rowControllers/virtualPageRowModel.js
JavaScript
mit
19,039
define(function () { return {"zones":{"America/Lower_Princes":["z",{"wallclock":-157766400000,"format":"AST","abbrev":"AST","offset":-14400000,"posix":-157750200000,"save":0},{"wallclock":-1826755200000,"format":"ANT","abbrev":"ANT","offset":-16200000,"posix":-1826738653000,"save":0},{"wallclock":-1.7976931348623157e+308,"format":"LMT","abbrev":"LMT","offset":-16547000,"posix":-1.7976931348623157e+308,"save":0}]},"rules":{}} });
usmschuck/canvas
public/javascripts/vendor/timezone/America/Lower_Princes.js
JavaScript
agpl-3.0
432
/** * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * JMediaManager behavior for media component * * @package Joomla.Extensions * @subpackage Media * @since 1.5 */ (function() { var MediaManager = this.MediaManager = { initialize: function() { this.folderframe = document.id('folderframe'); this.folderpath = document.id('folderpath'); this.updatepaths = $$('input.update-folder'); this.frame = window.frames['folderframe']; this.frameurl = this.frame.location.href; //this.frameurl = window.frames['folderframe'].location.href; /* this.tree = new MooTreeControl({ div: 'media-tree_tree', mode: 'folders', grid: true, theme: '../media/system/images/mootree.gif', onClick: function(node){ target = node.data.target != null ? node.data.target : '_self'; // Get the current URL. uri = this._getUriObject(this.frameurl); current = uri.file+'?'+uri.query; if (current != 'undefined?undefined' && current != node.data.url) { window.frames[target].location.href = node.data.url; } }.bind(this) },{ text: '', open: true, data: { url: 'index.php?option=com_media&view=mediaList&tmpl=component', target: 'folderframe'}}); this.tree.adopt('media-tree'); */ }, submit: function(task) { form = window.frames['folderframe'].document.id('mediamanager-form'); form.task.value = task; if (document.id('username')) { form.username.value = document.id('username').value; form.password.value = document.id('password').value; } form.submit(); }, onloadframe: function() { // Update the frame url this.frameurl = this.frame.location.href; var folder = this.getFolder(); if (folder) { this.updatepaths.each(function(path){ path.value =folder; }); this.folderpath.value = basepath+'/'+folder; // node = this.tree.get('node_'+folder); node.toggle(false, true); } else { this.updatepaths.each(function(path){ path.value = ''; }); this.folderpath.value = basepath; // node = this.tree.root; } /* if (node) { this.tree.select(node, true); } */ document.id(viewstyle).addClass('active'); a = this._getUriObject(document.id('uploadForm').getProperty('action')); q = new Hash(this._getQueryObject(a.query)); q.set('folder', folder); var query = []; q.each(function(v, k){ if (v != null) { this.push(k+'='+v); } }, query); a.query = query.join('&'); if (a.port) { document.id('uploadForm').setProperty('action', a.scheme+'://'+a.domain+':'+a.port+a.path+'?'+a.query); } else { document.id('uploadForm').setProperty('action', a.scheme+'://'+a.domain+a.path+'?'+a.query); } }, oncreatefolder: function() { if (document.id('foldername').value.length) { document.id('dirpath').value = this.getFolder(); Joomla.submitbutton('createfolder'); } }, setViewType: function(type) { document.id(type).addClass('active'); document.id(viewstyle).removeClass('active'); viewstyle = type; var folder = this.getFolder(); this._setFrameUrl('index.php?option=com_media&view=mediaList&tmpl=component&folder='+folder+'&layout='+type); }, refreshFrame: function() { this._setFrameUrl(); }, getFolder: function() { var url = this.frame.location.search.substring(1); var args = this.parseQuery(url); if (args['folder'] == "undefined") { args['folder'] = ""; } return args['folder']; }, parseQuery: function(query) { var params = new Object(); if (!query) { return params; } var pairs = query.split(/[;&]/); for ( var i = 0; i < pairs.length; i++ ) { var KeyVal = pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) { continue; } var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ).replace(/\+ /g, ' '); params[key] = val; } return params; }, _setFrameUrl: function(url) { if (url != null) { this.frameurl = url; } this.frame.location.href = this.frameurl; }, _getQueryObject: function(q) { var vars = q.split(/[&;]/); var rs = {}; if (vars.length) vars.each(function(val) { var keys = val.split('='); if (keys.length && keys.length == 2) rs[encodeURIComponent(keys[0])] = encodeURIComponent(keys[1]); }); return rs; }, _getUriObject: function(u){ var bits = u.match(/^(?:([^:\/?#.]+):)?(?:\/\/)?(([^:\/?#]*)(?::(\d*))?)((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[\?#]|$)))*\/?)?([^?#\/]*))?(?:\?([^#]*))?(?:#(.*))?/); return (bits) ? bits.associate(['uri', 'scheme', 'authority', 'domain', 'port', 'path', 'directory', 'file', 'query', 'fragment']) : null; } }; })(document.id); window.addEvent('domready', function(){ // Added to populate data on iframe load MediaManager.initialize(); MediaManager.trace = 'start'; document.updateUploader = function() { MediaManager.onloadframe(); }; MediaManager.onloadframe(); });
AxelFG/ckbran-inf
old/media/media/js/mediamanager.js
JavaScript
gpl-2.0
4,948
/** * Based on bootstrap-slider-knockout-binding, written by Cosmin Stefan-Dobrin, https://github.com/cosminstefanxp, * licensed under MIT License * * Github: https://github.com/cosminstefanxp/bootstrap-slider-knockout-binding */ ko.bindingHandlers.slider = { init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { var params = valueAccessor(); // Check whether the value observable is either placed directly or in the paramaters object. if (!(ko.isObservable(params) || params['value'])) throw "You need to define an observable value for the sliderValue. Either pass the observable directly or as the 'value' field in the parameters."; // Identify the value and initialize the slider var valueObservable; if (ko.isObservable(params)) { valueObservable = params; $(element).slider({value: ko.utils.unwrapObservable(params)}); } else { valueObservable = params['value']; // Replace the 'value' field in the options object with the actual value params['value'] = ko.utils.unwrapObservable(valueObservable); $(element).slider(params); } // Make sure we update the observable when changing the slider value $(element).on('slide', function (ev) { valueObservable(ev.value); }); }, update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { var modelValue = valueAccessor(); var valueObservable; if (ko.isObservable(modelValue)) { valueObservable = modelValue; } else { valueObservable = modelValue['value']; } $(element).slider('setValue', parseFloat(ko.isObservable(valueObservable) ? valueObservable() : valueObservable)); } };
dragondgold/OctoPrint
src/octoprint/static/js/lib/bootstrap-slider-knockout-binding.js
JavaScript
agpl-3.0
1,654
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var widgetRole = { abstract: true, accessibleNameRequired: false, baseConcepts: [], childrenPresentational: false, nameFrom: [], props: {}, relatedConcepts: [], requireContextRole: [], requiredOwnedElements: [], requiredProps: {}, superClass: [['roletype']] }; exports.default = widgetRole;
grshane/monthofmud
web/themes/custom/mom/node_modules/aria-query/lib/etc/roles/abstract/widgetRole.js
JavaScript
mit
393
/* BigVideo - The jQuery Plugin for Big Background Video (and Images) by John Polacek (@johnpolacek) Dual licensed under MIT and GPL. Dependencies: jQuery, jQuery UI (Slider), Video.js, ImagesLoaded */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'videojs', 'imagesloaded', 'jquery-ui' ], factory); } else { factory(jQuery, videojs); } })(function($, videojs) { $.BigVideo = function(options) { var defaults = { // If you want to use a single mp4 source, set as true useFlashForFirefox:true, // If you are doing a playlist, the video won't play the first time // on a touchscreen unless the play event is attached to a user click forceAutoplay:false, controls:false, doLoop:false, container:$('body'), shrinkable:false }; var BigVideo = this, player, vidEl = '#big-video-vid', wrap = $('<div id="big-video-wrap"></div>'), video = $(''), mediaAspect = 16/9, vidDur = 0, defaultVolume = 0.8, isInitialized = false, isSeeking = false, isPlaying = false, isQueued = false, isAmbient = false, playlist = [], currMediaIndex, currMediaType; var settings = $.extend({}, defaults, options); function updateSize() { var containerW = settings.container.width() < $(window).width() ? settings.container.width() : $(window).width(), containerH = settings.container.height() < $(window).height() ? settings.container.height() : $(window).height(), containerAspect = containerW/containerH; if (settings.container.is($('body'))) { $('html,body').css('height',$(window).height() > $('body').css('height','auto').height() ? '100%' : 'auto'); } if (containerAspect < mediaAspect) { // taller if (currMediaType === 'video') { player .width(containerH*mediaAspect) .height(containerH); if (!settings.shrinkable) { $(vidEl) .css('top',0) .css('left',-(containerH*mediaAspect-containerW)/2) .css('height',containerH); } else { $(vidEl) .css('top',-(containerW/mediaAspect-containerH)/2) .css('left',0) .css('height',containerW/mediaAspect); } $(vidEl+'_html5_api') .css('width',containerH*mediaAspect) .css('height',containerH); $(vidEl+'_flash_api') .css('width',containerH*mediaAspect) .css('height',containerH); } else { // is image $('#big-video-image') .css({ width: 'auto', height: containerH, top:0, left:-(containerH*mediaAspect-containerW)/2 }); } } else { // wider if (currMediaType === 'video') { player .width(containerW) .height(containerW/mediaAspect); $(vidEl) .css('top',-(containerW/mediaAspect-containerH)/2) .css('left',0) .css('height',containerW/mediaAspect); $(vidEl+'_html5_api') .css('width',$(vidEl+'_html5_api').parent().width()+"px") .css('height','auto'); $(vidEl+'_flash_api') .css('width',containerW) .css('height',containerW/mediaAspect); } else { // is image $('#big-video-image') .css({ width: containerW, height: 'auto', top:-(containerW/mediaAspect-containerH)/2, left:0 }); } } } function initPlayControl() { // create video controller var markup = '<div id="big-video-control-container">'; markup += '<div id="big-video-control">'; markup += '<a href="#" id="big-video-control-play"></a>'; markup += '<div id="big-video-control-middle">'; markup += '<div id="big-video-control-bar">'; markup += '<div id="big-video-control-bound-left"></div>'; markup += '<div id="big-video-control-progress"></div>'; markup += '<div id="big-video-control-track"></div>'; markup += '<div id="big-video-control-bound-right"></div>'; markup += '</div>'; markup += '</div>'; markup += '<div id="big-video-control-timer"></div>'; markup += '</div>'; markup += '</div>'; settings.container.append(markup); // hide until playVideo $('#big-video-control-container').css('display','none'); $('#big-video-control-timer').css('display','none'); // add events $('#big-video-control-track').slider({ animate: true, step: 0.01, slide: function(e,ui) { isSeeking = true; $('#big-video-control-progress').css('width',(ui.value-0.16)+'%'); player.currentTime((ui.value/100)*player.duration()); }, stop:function(e,ui) { isSeeking = false; player.currentTime((ui.value/100)*player.duration()); } }); $('#big-video-control-bar').click(function(e) { player.currentTime((e.offsetX/$(this).width())*player.duration()); }); $('#big-video-control-play').click(function(e) { e.preventDefault(); playControl('toggle'); }); player.on('timeupdate', function() { if (!isSeeking && (player.currentTime()/player.duration())) { var currTime = player.currentTime(); var minutes = Math.floor(currTime/60); var seconds = Math.floor(currTime) - (60*minutes); if (seconds < 10) seconds='0'+seconds; var progress = player.currentTime()/player.duration()*100; $('#big-video-control-track').slider('value',progress); $('#big-video-control-progress').css('width',(progress-0.16)+'%'); $('#big-video-control-timer').text(minutes+':'+seconds+'/'+vidDur); } }); } function playControl(a) { var action = a || 'toggle'; if (action === 'toggle') action = isPlaying ? 'pause' : 'play'; if (action === 'pause') { player.pause(); $('#big-video-control-play').css('background-position','-16px'); isPlaying = false; } else if (action === 'play') { player.play(); $('#big-video-control-play').css('background-position','0'); isPlaying = true; } else if (action === 'skip') { nextMedia(); } } function setUpAutoPlay() { player.play(); settings.container.off('click',setUpAutoPlay); } function nextMedia() { currMediaIndex++; if (currMediaIndex === playlist.length) currMediaIndex=0; playVideo(playlist[currMediaIndex]); } function playVideo(source) { // clear image $(vidEl).css('display','block'); currMediaType = 'video'; player.src(source); isPlaying = true; if (isAmbient) { $('#big-video-control-container').css('display','none'); player.ready(function(){ player.volume(0); }); doLoop = true; } else { $('#big-video-control-container').css('display','block'); player.ready(function(){ player.volume(defaultVolume); }); doLoop = false; } $('#big-video-image').css('display','none'); $(vidEl).css('display','block'); } function showPoster(source) { // remove old image $('#big-video-image').remove(); // hide video player.pause(); $(vidEl).css('display','none'); $('#big-video-control-container').css('display','none'); // show image currMediaType = 'image'; var bgImage = $('<img id="big-video-image" src='+source+' />'); wrap.append(bgImage); $('#big-video-image').imagesLoaded(function() { mediaAspect = $('#big-video-image').width() / $('#big-video-image').height(); updateSize(); }); } BigVideo.init = function() { if (!isInitialized) { // create player settings.container.prepend(wrap); var autoPlayString = settings.forceAutoplay ? 'autoplay' : ''; player = $('<video id="'+vidEl.substr(1)+'" class="video-js vjs-default-skin" preload="auto" data-setup="{}" '+autoPlayString+' webkit-playsinline></video>'); player.css('position','absolute'); wrap.append(player); var videoTechOrder = ['html5','flash']; // If only using mp4s and on firefox, use flash fallback var ua = navigator.userAgent.toLowerCase(); var isFirefox = ua.indexOf('firefox') != -1; if (settings.useFlashForFirefox && (isFirefox)) { videoTechOrder = ['flash', 'html5']; } player = videojs(vidEl.substr(1), { controls:false, autoplay:true, preload:'auto', techOrder:videoTechOrder }); // add controls if (settings.controls) initPlayControl(); // set initial state updateSize(); isInitialized = true; isPlaying = false; if (settings.forceAutoplay) { $('body').on('click', setUpAutoPlay); } $('#big-video-vid_flash_api') .attr('scale','noborder') .attr('width','100%') .attr('height','100%'); // set events $(window).on('resize.bigvideo', function() { updateSize(); }); player.on('loadedmetadata', function(data) { if (document.getElementById('big-video-vid_flash_api')) { // use flash callback to get mediaAspect ratio mediaAspect = document.getElementById('big-video-vid_flash_api').vjs_getProperty('videoWidth')/document.getElementById('big-video-vid_flash_api').vjs_getProperty('videoHeight'); } else { // use html5 player to get mediaAspect mediaAspect = $('#big-video-vid_html5_api').prop('videoWidth')/$('#big-video-vid_html5_api').prop('videoHeight'); } updateSize(); var dur = Math.round(player.duration()); var durMinutes = Math.floor(dur/60); var durSeconds = dur - durMinutes*60; if (durSeconds < 10) durSeconds='0'+durSeconds; vidDur = durMinutes+':'+durSeconds; }); player.on('ended', function() { if (settings.doLoop) { player.currentTime(0); player.play(); } if (isQueued) { nextMedia(); } }); } }; /** * Show video or image file * * @param source: The file to show, can be: * - an array with objects for video files types * - a string to a single video file * - a string to a image file * @param options: An object with those possible attributes: * - boolean "ambient" to set video to loop * - function onShown */ BigVideo.show = function(source,options) { if (options === undefined) options = {}; isAmbient = options.ambient === true; if (isAmbient || options.doLoop) settings.doLoop = true; if (typeof(source) === 'string') { // if input was a string, try show that image or video var ext = source.substring(source.lastIndexOf('.')+1); if (ext === 'jpg' || ext === 'gif' || ext === 'png') { showPoster(source); } else if (ext === 'mp4', 'ogg', 'ogv', 'webm') { playVideo(source); if (options.onShown) options.onShown(); isQueued = false; } } else if ($.isArray(source)) { // if the input was an array, pass it to videojs playVideo(source); } else if (typeof(source) === "object" && source.src && source.type) { // if the input was an object with valid attributes, wrap it in an // array and pass it to videojs playVideo([source]); } else { // fail without valid input throw("BigVideo.show received invalid input for parameter source"); } }; /** * Show a playlist of video files * * @param files: array of elements to pass to BigVideo.show in sequence * @param options: An object with those possible attributes: * - boolean "ambient" to set video to loop * - function onShown */ BigVideo.showPlaylist = function (files, options) { if (!$.isArray(files)) { throw("BigVideo.showPlaylist parameter files accepts only arrays"); } if (options === undefined) options = {}; isAmbient = options.ambient === true; if (isAmbient || options.doLoop) settings.doLoop = true; playlist = files; currMediaIndex = 0; this.show(playlist[currMediaIndex]); if (options.onShown) options.onShown(); isQueued = true; } // Expose Video.js player BigVideo.getPlayer = function() { return player; }; // Remove/dispose the player BigVideo.remove = BigVideo.dispose = function() { isInitialized = false; wrap.remove(); $(window).off('resize.bigvideo'); if(player) { player.off('loadedmetadata'); player.off('ended'); player.dispose(); } }; // Expose BigVideoJS player actions play, pause, skip (if a playlist is available) // Example: BigVideo.triggerPlayer('skip') BigVideo.triggerPlayer = function(action){ playControl(action); }; }; });
pkrulik/scentovation
js/vendor/BigVideo.js-master/lib/bigvideo.js
JavaScript
mit
12,341
var m1_a1 = 10; var m1_c1 = (function () { function m1_c1() { } return m1_c1; }()); var m1_instance1 = new m1_c1(); function m1_f1() { return m1_instance1; } /// <reference path='ref/m1.ts'/> var a1 = 10; var c1 = (function () { function c1() { } return c1; }()); var instance1 = new c1(); function f1() { return instance1; } //# sourceMappingURL=/tests/cases/projects/outputdir_subfolder/mapFiles/test.js.map
AbubakerB/TypeScript
tests/baselines/reference/project/mapRootAbsolutePathSubfolderSpecifyOutputFile/node/bin/test.js
JavaScript
apache-2.0
462
// Copyright 2016 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit Test for the unsafe API of the HTML Sanitizer. */ goog.setTestOnly(); goog.require('goog.html.SafeHtml'); goog.require('goog.html.sanitizer.HtmlSanitizer'); goog.require('goog.html.sanitizer.TagBlacklist'); goog.require('goog.html.sanitizer.unsafe'); goog.require('goog.string.Const'); goog.require('goog.testing.dom'); goog.require('goog.testing.jsunit'); goog.require('goog.userAgent'); /** * @return {boolean} Whether the browser is IE8 or below. */ function isIE8() { return goog.userAgent.IE && !goog.userAgent.isVersionOrHigher(9); } /** * @return {boolean} Whether the browser is IE9. */ function isIE9() { return goog.userAgent.IE && !goog.userAgent.isVersionOrHigher(10) && !isIE8(); } var just = goog.string.Const.from('test'); /** * Sanitizes the original HTML and asserts that it is the same as the expected * HTML. Supports adding tags and attributes through the unsafe API. * @param {string} originalHtml * @param {string} expectedHtml * @param {?Array<string>=} opt_tags * @param {?Array<(string|!goog.html.sanitizer.HtmlSanitizerAttributePolicy)>=} * opt_attrs * @param {?goog.html.sanitizer.HtmlSanitizer.Builder=} opt_builder */ function assertSanitizedHtml( originalHtml, expectedHtml, opt_tags, opt_attrs, opt_builder) { var builder = opt_builder || new goog.html.sanitizer.HtmlSanitizer.Builder(); if (opt_tags) builder = goog.html.sanitizer.unsafe.alsoAllowTags(just, builder, opt_tags); if (opt_attrs) builder = goog.html.sanitizer.unsafe.alsoAllowAttributes( just, builder, opt_attrs); var sanitizer = builder.build(); try { var sanitized = sanitizer.sanitize(originalHtml); if (isIE9()) { assertEquals('', goog.html.SafeHtml.unwrap(sanitized)); return; } goog.testing.dom.assertHtmlMatches( expectedHtml, goog.html.SafeHtml.unwrap(sanitized), true /* opt_strictAttributes */); } catch (err) { if (!isIE8()) { throw err; } } } function testAllowEmptyTagList() { var input = '<sdf><aaa></aaa></sdf><b></b>'; var expected = '<span><span></span></span><b></b>'; assertSanitizedHtml(input, expected, []); } function testAllowBlacklistedTag() { var input = '<div><script>aaa</script></div>'; var expected = '<div></div>'; assertSanitizedHtml(input, expected, ['SCriPT']); } function testAllowUnknownTags() { var input = '<hello><bye>aaa</bye></hello><zzz></zzz>'; var expected = '<hello><span>aaa</span></hello><zzz></zzz>'; assertSanitizedHtml(input, expected, ['HElLO', 'zZZ']); } function testAllowAlreadyWhiteListedTag() { var input = '<hello><p><zzz></zzz></p></hello>'; var expected = '<span><p><zzz></zzz></p></span>'; assertSanitizedHtml(input, expected, ['p', 'ZZZ']); } function testAllowEmptyAttrList() { var input = '<a href="#" qwe="nope">b</a>'; var expected = '<a href="#">b</a>'; assertSanitizedHtml(input, expected, null, []); } function testAllowUnknownAttributeSimple() { var input = '<qqq zzz="3" nnn="no"></qqq>'; var expected = '<span zzz="3"></span>'; assertSanitizedHtml(input, expected, null, ['Zzz']); } function testAllowUnknownAttributeWildCard() { var input = '<div ab="yes" bb="no"><img ab="yep" bb="no" /></div>'; var expected = '<div ab="yes"><img ab="yep" /></div>'; assertSanitizedHtml( input, expected, null, [{tagName: '*', attributeName: 'aB'}]); } function testAllowUnknownAttributeOnSpecificTag() { var input = '<a www="3" zzz="4">fff</a><img www="3" />'; var expected = '<a www="3">fff</a><img />'; assertSanitizedHtml( input, expected, null, [{tagName: 'a', attributeName: 'WwW'}]); } function testAllowUnknownAttributePolicy() { var input = '<img ab="yes" /><img ab="no" />'; var expected = '<img ab="yes" /><img />'; assertSanitizedHtml(input, expected, null, [{ tagName: '*', attributeName: 'aB', policy: function(value, hints) { assertEquals(hints.attributeName, 'ab'); return value === 'yes' ? value : null; } }]); } function testAllowOverwriteAttrPolicy() { var input = '<a href="yes"></a><a href="no"></a>'; var expected = '<a href="yes"></a><a></a>'; assertSanitizedHtml( input, expected, null, [{ tagName: 'a', attributeName: 'href', policy: function(value) { return value === 'yes' ? value : null; } }]); } function testWhitelistAliasing() { var builder = new goog.html.sanitizer.HtmlSanitizer.Builder(); goog.html.sanitizer.unsafe.alsoAllowTags(just, builder, ['QqQ']); goog.html.sanitizer.unsafe.alsoAllowAttributes(just, builder, ['QqQ']); builder.build(); assertUndefined(goog.html.sanitizer.TagWhitelist['QQQ']); assertUndefined(goog.html.sanitizer.TagWhitelist['QqQ']); assertUndefined(goog.html.sanitizer.TagWhitelist['qqq']); assertUndefined(goog.html.sanitizer.AttributeWhitelist['* QQQ']); assertUndefined(goog.html.sanitizer.AttributeWhitelist['* QqQ']); assertUndefined(goog.html.sanitizer.AttributeWhitelist['* qqq']); } function testTemplateUnsanitized() { if (!goog.html.sanitizer.HTML_SANITIZER_TEMPLATE_SUPPORTED) { return; } var input = '<template><div>a</div><script>qqq</script>' + '<template>a</template></template>'; // TODO(pelizzi): use unblockTag once it's available delete goog.html.sanitizer.TagBlacklist['TEMPLATE']; var builder = new goog.html.sanitizer.HtmlSanitizer.Builder(); goog.html.sanitizer.unsafe.keepUnsanitizedTemplateContents(just, builder); assertSanitizedHtml(input, input, ['TEMPLATE'], null, builder); goog.html.sanitizer.TagBlacklist['TEMPLATE'] = true; } function testTemplateSanitizedUnsanitizedXSS() { if (!goog.html.sanitizer.HTML_SANITIZER_TEMPLATE_SUPPORTED) { return; } var input = '<template><p>a</p><script>aaaa;</script></template>'; var expected = '<span><p>a</p></span>'; delete goog.html.sanitizer.TagBlacklist['TEMPLATE']; var builder = new goog.html.sanitizer.HtmlSanitizer.Builder(); goog.html.sanitizer.unsafe.keepUnsanitizedTemplateContents(just, builder); assertSanitizedHtml(input, expected, null, null, builder); goog.html.sanitizer.TagBlacklist['TEMPLATE'] = true; } function testTemplateUnsanitizedThrowsIE() { if (goog.html.sanitizer.HTML_SANITIZER_TEMPLATE_SUPPORTED) { return; } var builder = new goog.html.sanitizer.HtmlSanitizer.Builder(); assertThrows(function() { goog.html.sanitizer.unsafe.keepUnsanitizedTemplateContents(just, builder); }); } function testAllowRelaxExistingAttributePolicyWildcard() { var input = '<a href="javascript:alert(1)"></a>'; // define a tag-specific one, takes precedence assertSanitizedHtml( input, input, null, [{tagName: 'a', attributeName: 'href', policy: goog.functions.identity}]); // overwrite the global one assertSanitizedHtml( input, input, null, [{tagName: '*', attributeName: 'href', policy: goog.functions.identity}]); } function testAllowRelaxExistingAttributePolicySpecific() { var input = '<a target="foo"></a>'; var expected = '<a></a>'; // overwrite the global one, the specific one still has precedence assertSanitizedHtml(input, expected, null, [ {tagName: '*', attributeName: 'target', policy: goog.functions.identity} ]); // overwrite the tag-specific one, this one should take precedence assertSanitizedHtml(input, input, null, [ {tagName: 'a', attributeName: 'target', policy: goog.functions.identity} ]); }
joshbruning/selenium
third_party/closure/goog/html/sanitizer/unsafe_test.js
JavaScript
apache-2.0
8,241