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 |
|---|---|---|---|---|---|
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
for (var i = data.sigBytes - 1; i >= 0; i--) {
if (((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
data.sigBytes = i + 1;
break;
}
}
}
};
return CryptoJS.pad.ZeroPadding;
})); | cloudfoundry-community/asp.net5-buildpack | fixtures/node_apps/angular_dotnet/ClientApp/node_modules/crypto-js/pad-zeropadding.js | JavaScript | apache-2.0 | 1,110 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* The length property of sort has the attribute DontEnum
*
* @path ch15/15.4/15.4.4/15.4.4.11/S15.4.4.11_A7.1.js
* @description Checking use propertyIsEnumerable, for-in
*/
//CHECK#1
if (Array.prototype.sort.propertyIsEnumerable('length') !== false) {
$ERROR('#1: Array.prototype.sort.propertyIsEnumerable(\'length\') === false. Actual: ' + (Array.prototype.sort.propertyIsEnumerable('length')));
}
//CHECK#2
var result = true;
for (var p in Array.sort){
if (p === "length") {
result = false;
}
}
if (result !== true) {
$ERROR('#2: result = true; for (p in Array.sort) { if (p === "length") result = false; } result === true;');
}
| hippich/typescript | tests/Fidelity/test262/suite/ch15/15.4/15.4.4/15.4.4.11/S15.4.4.11_A7.1.js | JavaScript | apache-2.0 | 793 |
import {formatQS} from './url';
import {getWinningBids} from './targeting';
// Adserver parent class
const AdServer = function(attr) {
this.name = attr.adserver;
this.code = attr.code;
this.getWinningBidByCode = function() {
return getWinningBids(this.code)[0];
};
};
// DFP ad server
exports.dfpAdserver = function (options, urlComponents) {
var adserver = new AdServer(options);
adserver.urlComponents = urlComponents;
var dfpReqParams = {
'env': 'vp',
'gdfp_req': '1',
'impl': 's',
'unviewed_position_start': '1'
};
var dfpParamsWithVariableValue = ['output', 'iu', 'sz', 'url', 'correlator', 'description_url', 'hl'];
var getCustomParams = function(targeting) {
return encodeURIComponent(formatQS(targeting));
};
adserver.appendQueryParams = function() {
var bid = adserver.getWinningBidByCode();
if (bid) {
this.urlComponents.search.description_url = encodeURIComponent(bid.descriptionUrl);
this.urlComponents.search.cust_params = getCustomParams(bid.adserverTargeting);
this.urlComponents.search.correlator = Date.now();
}
};
adserver.verifyAdserverTag = function() {
for (var key in dfpReqParams) {
if (!this.urlComponents.search.hasOwnProperty(key) || this.urlComponents.search[key] !== dfpReqParams[key]) {
return false;
}
}
for (var i in dfpParamsWithVariableValue) {
if (!this.urlComponents.search.hasOwnProperty(dfpParamsWithVariableValue[i])) {
return false;
}
}
return true;
};
return adserver;
};
| hadarpeer/Prebid.js | src/adserver.js | JavaScript | apache-2.0 | 1,566 |
/*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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.
*/
define(['external/lodash/lodash.min',
'webida-lib/util/path',
'plugins/webida.editor.code-editor/content-assist/file-server',
'plugins/webida.editor.code-editor/content-assist/reference'],
function (_, pathUtil, fileServer, reference) {
'use strict';
var csshint = {};
function findCompletions(body) {
var result = {};
var token = body.query.token;
if (token) {
if ((token.type === 'tag' || token.type === 'qualifier') && /^\./.test(token.string)) {
token.type = 'class';
token.start = token.start + 1;
token.string = token.string.substr(1);
} else if (token.type === 'builtin' && /^#/.test(token.string)) {
token.type = 'id';
token.start = token.start + 1;
token.string = token.string.substr(1);
}
if (token.type === 'id' || token.type === 'class') {
var htmls = reference.getReferenceFroms(body.query.file);
if (pathUtil.isHtml(body.query.file)) {
htmls = _.union(htmls, [body.query.file]);
}
_.each(htmls, function (htmlpath) {
var html = fileServer.getLocalFile(htmlpath);
if (html) {
if (token.type === 'id') {
result.list = _.union(result, html.getHtmlIds());
} else if (token.type === 'class') {
result.list = _.union(result, html.getHtmlClasses());
}
}
});
if (result.list) {
result.to = body.query.end;
result.from = {
line: body.query.end.line,
ch: body.query.end.ch - token.string.length
};
}
}
}
return result;
}
/**
* @param {files: [{name, type, text}], query: {type: string, end:{line,ch}, file: string}} body
* @returns {from: {line, ch}, to: {line, ch}, list: [string]}
**/
csshint.request = function (serverId, body, c) {
_.each(body.files, function (file) {
if (file.type === 'full') {
fileServer.setText(file.name, file.text);
file.type = null;
}
});
body.files = _.filter(body.files, function (file) {
return file.type !== null;
});
var result = {};
if (body.query.type === 'completions') {
result = findCompletions(body);
}
c(undefined, result);
};
return csshint;
});
| happibum/webida-client | apps/ide/src/plugins/webida.editor.code-editor.content-assist.css.css-smart/css-hint-server.js | JavaScript | apache-2.0 | 3,359 |
var RxOld = require("rx");
var RxNew = require("../../../../index");
module.exports = function (suite) {
var oldFlatMapWithCurrentThreadScheduler = RxOld.Observable.range(0, 25, RxOld.Scheduler.currentThread).flatMap(RxOld.Observable.return(0, RxOld.Scheduler.currentThread));
var newFlatMapWithCurrentThreadScheduler = RxNew.Observable.range(0, 25, RxNew.Scheduler.immediate).flatMapTo(RxNew.Observable.return(0, RxNew.Scheduler.immediate));
return suite
.add('old flatMap (scalar Observable) with current thread scheduler', function () {
oldFlatMapWithCurrentThreadScheduler.subscribe(_next, _error, _complete);
})
.add('new flatMap (scalar Observable) with current thread scheduler', function () {
newFlatMapWithCurrentThreadScheduler.subscribe(_next, _error, _complete);
});
function _next(x) { }
function _error(e){ }
function _complete(){ }
}; | smaye81/RxJS | perf/micro/current-thread-scheduler/operators/flat-map-observable-scalar.js | JavaScript | apache-2.0 | 932 |
/**
* 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 {getFormAsObject} from '../../src/form.js';
describes.realWin('getFormAsObject', {}, env => {
let form;
beforeEach(() => {
form = env.win.document.createElement('form');
env.win.document.body.appendChild(form);
});
it('excludes disabled input', () => {
const input = env.win.document.createElement('input');
input.type = 'text';
input.name = 'foo';
input.value = 'bar';
input.disabled = true;
form.appendChild(input);
expect(getFormAsObject(form)).to.be.an('object').that.is.empty;
});
it('excludes input without name', () => {
const input = env.win.document.createElement('input');
input.type = 'text';
input.value = 'bar';
form.appendChild(input);
expect(getFormAsObject(form)).to.be.an('object').that.is.empty;
});
it('returns text input entries', () => {
const input = env.win.document.createElement('input');
input.type = 'text';
input.name = 'foo';
input.value = 'bar';
form.appendChild(input);
expect(getFormAsObject(form)).to.deep.equal({'foo': ['bar']});
});
it('returns text input entries with empty value', () => {
const input = env.win.document.createElement('input');
input.type = 'text';
input.name = 'foo';
form.appendChild(input);
expect(getFormAsObject(form)).to.deep.equal({'foo': ['']});
});
it('returns textarea entries', () => {
const textarea = env.win.document.createElement('textarea');
textarea.name = 'foo';
textarea.value = 'bar';
form.appendChild(textarea);
expect(getFormAsObject(form)).to.deep.equal({'foo': ['bar']});
});
it('returns checked checkbox entries', () => {
const input = env.win.document.createElement('input');
input.type = 'checkbox';
input.name = 'foo';
input.value = 'bar';
input.checked = true;
form.appendChild(input);
expect(getFormAsObject(form)).to.deep.equal({'foo': ['bar']});
});
it('excludes unchecked checkbox entries', () => {
const input = env.win.document.createElement('input');
input.type = 'checkbox';
input.name = 'foo';
input.value = 'bar';
input.checked = false;
form.appendChild(input);
expect(getFormAsObject(form)).to.be.an('object').that.is.empty;
});
it('returns checked radio button entries', () => {
const input = env.win.document.createElement('input');
input.type = 'radio';
input.name = 'foo';
input.value = 'bar';
input.checked = true;
form.appendChild(input);
expect(getFormAsObject(form)).to.deep.equal({'foo': ['bar']});
});
it('excludes unchecked radio button entries', () => {
const input = env.win.document.createElement('input');
input.type = 'radio';
input.name = 'foo';
input.value = 'bar';
input.checked = false;
form.appendChild(input);
expect(getFormAsObject(form)).to.be.an('object').that.is.empty;
});
it('returns first option for select with nothing selected', () => {
const select = env.win.document.createElement('select');
select.name = 'foo';
select.multiple = false;
const selectedOption = env.win.document.createElement('option');
selectedOption.value = 'bar';
selectedOption.selected = false;
const unselectedOption = env.win.document.createElement('option');
unselectedOption.value = 'bang';
unselectedOption.selected = false;
select.appendChild(selectedOption);
select.appendChild(unselectedOption);
form.appendChild(select);
expect(getFormAsObject(form)).to.deep.equal({'foo': ['bar']});
});
it('returns empty for multi-select with nothing selected', () => {
const select = env.win.document.createElement('select');
select.name = 'foo';
select.multiple = true;
const selectedOption = env.win.document.createElement('option');
selectedOption.value = 'bar';
selectedOption.selected = false;
const unselectedOption = env.win.document.createElement('option');
unselectedOption.value = 'bang';
unselectedOption.selected = false;
select.appendChild(selectedOption);
select.appendChild(unselectedOption);
form.appendChild(select);
expect(getFormAsObject(form)).to.deep.equal({});
});
it('returns selected entry in single-select', () => {
const select = env.win.document.createElement('select');
select.name = 'foo';
select.multiple = false;
const selectedOption = env.win.document.createElement('option');
selectedOption.value = 'bar';
selectedOption.selected = true;
const unselectedOption = env.win.document.createElement('option');
unselectedOption.value = 'bang';
unselectedOption.selected = false;
select.appendChild(selectedOption);
select.appendChild(unselectedOption);
form.appendChild(select);
expect(getFormAsObject(form)).to.deep.equal({'foo': ['bar']});
});
it('returns single selected entry in multi-select', () => {
const select = env.win.document.createElement('select');
select.name = 'foo';
select.multiple = true;
const selectedOption = env.win.document.createElement('option');
selectedOption.value = 'bar';
selectedOption.selected = true;
const unselectedOption = env.win.document.createElement('option');
unselectedOption.value = 'bang';
unselectedOption.selected = false;
select.appendChild(selectedOption);
select.appendChild(unselectedOption);
form.appendChild(select);
expect(getFormAsObject(form)).to.deep.equal({'foo': ['bar']});
});
it('returns multiple selected entries in multi-select', () => {
const select = env.win.document.createElement('select');
select.name = 'foo';
select.multiple = true;
const selectedOption = env.win.document.createElement('option');
selectedOption.value = 'bar';
selectedOption.selected = true;
const unselectedOption = env.win.document.createElement('option');
unselectedOption.value = 'bang';
unselectedOption.selected = true;
select.appendChild(selectedOption);
select.appendChild(unselectedOption);
form.appendChild(select);
expect(getFormAsObject(form)).to.deep.equal({'foo': ['bar', 'bang']});
});
it('returns focused submit input entries', () => {
const input = env.win.document.createElement('input');
input.type = 'submit';
input.name = 'foo';
input.value = 'bar';
form.appendChild(input);
expect(getFormAsObject(form)).to.deep.equal({});
Object.defineProperty(form, 'ownerDocument', {get() {
return {activeElement: input};
}});
expect(getFormAsObject(form)).to.deep.equal({'foo': ['bar']});
});
it('returns focused button input entries', () => {
const input = env.win.document.createElement('button');
input.name = 'foo';
input.value = 'bar';
form.appendChild(input);
expect(getFormAsObject(form)).to.deep.equal({});
Object.defineProperty(form, 'ownerDocument', {get() {
return {activeElement: input};
}});
expect(getFormAsObject(form)).to.deep.equal({'foo': ['bar']});
});
it('returns multiple form entries', () => {
const form = env.win.document.createElement('form');
const input = env.win.document.createElement('input');
input.type = 'text';
input.name = 'foo1';
input.value = 'bar';
const checkbox = env.win.document.createElement('input');
checkbox.type = 'checkbox';
checkbox.name = 'foo';
checkbox.value = 'bar';
checkbox.checked = true;
const textarea = env.win.document.createElement('textarea');
textarea.name = 'foo2';
textarea.value = 'bar';
const select = env.win.document.createElement('select');
select.name = 'foo';
select.multiple = false;
const selectedOption = env.win.document.createElement('option');
selectedOption.value = 'baz';
selectedOption.selected = true;
select.appendChild(selectedOption);
form.appendChild(input);
form.appendChild(checkbox);
form.appendChild(textarea);
form.appendChild(select);
const formDataObject = getFormAsObject(form);
expect(formDataObject).to.be.an('object')
.that.has.all.keys('foo', 'foo1', 'foo2');
expect(formDataObject).to.have.property('foo')
.that.has.deep.members(['bar', 'baz']);
expect(formDataObject).to.have.property('foo1')
.that.has.deep.members(['bar']);
expect(formDataObject).to.have.property('foo2')
.that.has.deep.members(['bar']);
});
});
| widespace-os/amphtml | test/unit/test-form.js | JavaScript | apache-2.0 | 9,073 |
/// <reference path="jquery-1.4.4-vsdoc.js" />
$(document).ready(function () {
function updateGrid(e) {
e.preventDefault();
// find the containing element's id then reload the grid
var url = $(this).attr('href');
var grid = $(this).parents('.ajaxGrid'); // get the grid
var id = grid.attr('id');
grid.load(url + ' #' + id);
};
$('.ajaxGrid table thead tr a').live('click', updateGrid); // hook up ajax refresh for sorting links
$('.ajaxGrid table tfoot tr a').live('click', updateGrid); // hook up ajax refresh for paging links (note: this doesn't handle the separate Pager() call!)
}); | priyaaggarwal24/manifest | packages/WebGridMvc.1.0.0/content/scripts/webGrid.js | JavaScript | artistic-2.0 | 654 |
// This file was procedurally generated from the following sources:
// - src/dstr-binding/ary-init-iter-close.case
// - src/dstr-binding/default/cls-decl-async-gen-meth-dflt.template
/*---
description: Iterator is closed when not exhausted by pattern evaluation (class expression async generator method (default parameters))
esid: sec-class-definitions-runtime-semantics-evaluation
features: [Symbol.iterator, async-iteration]
flags: [generated, async]
info: |
ClassDeclaration : class BindingIdentifier ClassTail
1. Let className be StringValue of BindingIdentifier.
2. Let value be the result of ClassDefinitionEvaluation of ClassTail with
argument className.
[...]
14.5.14 Runtime Semantics: ClassDefinitionEvaluation
21. For each ClassElement m in order from methods
a. If IsStatic of m is false, then
i. Let status be the result of performing
PropertyDefinitionEvaluation for m with arguments proto and
false.
[...]
Runtime Semantics: PropertyDefinitionEvaluation
AsyncGeneratorMethod :
async [no LineTerminator here] * PropertyName ( UniqueFormalParameters )
{ AsyncGeneratorBody }
1. Let propKey be the result of evaluating PropertyName.
2. ReturnIfAbrupt(propKey).
3. If the function code for this AsyncGeneratorMethod is strict mode code, let strict be true.
Otherwise let strict be false.
4. Let scope be the running execution context's LexicalEnvironment.
5. Let closure be ! AsyncGeneratorFunctionCreate(Method, UniqueFormalParameters,
AsyncGeneratorBody, scope, strict).
[...]
13.3.3.5 Runtime Semantics: BindingInitialization
BindingPattern : ArrayBindingPattern
[...]
4. If iteratorRecord.[[done]] is false, return ? IteratorClose(iterator,
result).
[...]
---*/
var doneCallCount = 0;
var iter = {};
iter[Symbol.iterator] = function() {
return {
next: function() {
return { value: null, done: false };
},
return: function() {
doneCallCount += 1;
return {};
}
};
};
var callCount = 0;
class C {
async *method([x] = iter) {
assert.sameValue(doneCallCount, 1);
callCount = callCount + 1;
}
};
new C().method().next().then(() => {
assert.sameValue(callCount, 1, 'invoked exactly once');
}).then($DONE, $DONE);
| sebastienros/jint | Jint.Tests.Test262/test/language/statements/class/dstr-async-gen-meth-dflt-ary-init-iter-close.js | JavaScript | bsd-2-clause | 2,372 |
/* 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/. */
"use strict";
const runtime = require("sdk/system/runtime");
const system = require("sdk/system");
exports["test system architecture and compiler"] = function(assert) {
if (system.architecture !== null) {
assert.equal(
runtime.XPCOMABI.indexOf(system.architecture), 0,
"system.architecture is starting substring of runtime.XPCOMABI"
);
}
if (system.compiler !== null) {
assert.equal(
runtime.XPCOMABI.indexOf(system.compiler),
runtime.XPCOMABI.length - system.compiler.length,
"system.compiler is trailing substring of runtime.XPCOMABI"
);
}
assert.ok(
system.architecture === null || typeof(system.architecture) === "string",
"system.architecture is string or null if not supported by platform"
);
assert.ok(
system.compiler === null || typeof(system.compiler) === "string",
"system.compiler is string or null if not supported by platform"
);
};
require("test").run(exports);
| grammarly/browser-extensions | firefox/addon-sdk/test/test-system.js | JavaScript | bsd-3-clause | 1,167 |
/* Suppress initial rendering of result list, but only if we can show it with JS later on */
document.write('<style type="text/css">#result_list { display: none }</style>');
treeadmin.jQuery(function($){
// recolor tree after expand/collapse
$.extend($.fn.recolorRows = function() {
$('tr:visible:even', this).removeClass('row2').addClass('row1');
$('tr:visible:odd', this).removeClass('row1').addClass('row2');
});
function isExpandedNode(id) {
return treeadmin.collapsed_nodes.indexOf(id) == -1;
}
function markNodeAsExpanded(id) {
// remove itemId from array of collapsed nodes
var idx = treeadmin.collapsed_nodes.indexOf(id);
if(idx >= 0)
treeadmin.collapsed_nodes.splice(idx, 1);
}
function markNodeAsCollapsed(id) {
if(isExpandedNode(id))
treeadmin.collapsed_nodes.push(id);
}
// toggle children
function doToggle(id, show) {
var children = treeadmin.tree_structure[id];
for (var i=0; i<children.length; ++i) {
var childId = children[i];
if(show) {
$('#item-' + childId).show();
// only reveal children if current node is not collapsed
if(isExpandedNode(childId)) {
doToggle(childId, show);
}
} else {
$('#item-' + childId).hide();
// always recursively hide children
doToggle(childId, show);
}
}
}
function rowLevel($row) {
return parseInt($row.attr('rel').replace(/[^\d]/ig, ''));
}
/*
* FeinCMS Drag-n-drop tree reordering.
* Based upon code by bright4 for Radiant CMS, rewritten for
* FeinCMS by Bjorn Post.
*
* September 2010
*
*/
$.extend($.fn.feinTree = function() {
$('tr', this).each(function(i, el) {
// adds 'children' class to all parents
var pageId = extract_item_id($('.page_marker', el).attr('id'));
$(el).attr('id', 'item-' + pageId);
if (treeadmin.tree_structure[pageId].length) {
$('.page_marker', el).addClass('children');
}
// set 'level' on rel attribute
var pixels = $('.page_marker', el).css('width').replace(/[^\d]/ig,"");
var rel = Math.round(pixels/18);
$(el).attr('rel', rel);
});
$('div.drag_handle').bind('mousedown', function(event) {
BEFORE = 0;
AFTER = 1;
CHILD = 2;
CHILD_PAD = 20;
var originalRow = $(event.target).closest('tr');
var rowHeight = originalRow.height();
var childEdge = $(event.target).offset().left + $(event.target).width();
var moveTo = new Object();
var expandObj = new Object();
$("body").addClass('dragging').disableSelection().bind('mousemove', function(event) {
// attach dragged item to mouse
var cloned = originalRow.html();
if($('#ghost').length == 0) {
$('<div id="ghost"></div>').appendTo('body');
}
$('#ghost').html(cloned).css({
'opacity': .8,
'position': 'absolute',
'top': event.pageY,
'left': event.pageX-30,
'width': 600
});
// check on edge of screen
if(event.pageY+100 > $(window).height()+$(window).scrollTop()) {
$('html,body').stop().animate({scrollTop: $(window).scrollTop()+250 }, 500);
} else if(event.pageY-50 < $(window).scrollTop()) {
$('html,body').stop().animate({scrollTop: $(window).scrollTop()-250 }, 500);
}
// check if drag_line element already exists, else append
if($("#drag_line").length < 1) {
$("body").append('<div id="drag_line" style="position:absolute">line<div></div></div>');
}
// loop trough all rows
$("tr", originalRow.parent()).each(function(index, element) {
var element = $(element),
top = element.offset().top;
// check if mouse is over a row
if (event.pageY >= top && event.pageY < top + rowHeight) {
var targetRow = null,
targetLoc = null,
elementLevel = rowLevel(element);
if (event.pageY >= top && event.pageY < top + rowHeight / 3) {
targetRow = element;
targetLoc = BEFORE;
} else if (event.pageY >= top + rowHeight / 3 && event.pageY < top + rowHeight * 2 / 3) {
var next = element.next();
// there's no point in allowing adding children when there are some already
// better move the items to the correct place right away
if (!next.length || rowLevel(next) <= elementLevel) {
targetRow = element;
targetLoc = CHILD;
}
} else if (event.pageY >= top + rowHeight * 2 / 3 && event.pageY < top + rowHeight) {
var next = element.next();
if (!next.length || rowLevel(next) <= elementLevel) {
targetRow = element;
targetLoc = AFTER;
}
}
if(targetRow) {
var padding = 37 + element.attr('rel') * CHILD_PAD + (targetLoc == CHILD ? CHILD_PAD : 0 );
$("#drag_line").css({
'width': targetRow.width() - padding,
'left': targetRow.offset().left + padding,
'top': targetRow.offset().top + (targetLoc == AFTER || targetLoc == CHILD ? rowHeight: 0) -1
});
// Store the found row and options
moveTo.hovering = element;
moveTo.relativeTo = targetRow;
moveTo.side = targetLoc;
return true;
}
}
});
});
$('body').keydown(function(event) {
if (event.which == '27') {
$("#drag_line").remove();
$("#ghost").remove();
$("body").removeClass('dragging').enableSelection().unbind('mousemove').unbind('mouseup');
event.preventDefault();
}
});
$("body").bind('mouseup', function(event) {
if(moveTo.relativeTo) {
var cutItem = extract_item_id(originalRow.find('.page_marker').attr('id'));
var pastedOn = extract_item_id(moveTo.relativeTo.find('.page_marker').attr('id'));
// get out early if items are the same
if(cutItem != pastedOn) {
var isParent = (moveTo.relativeTo.next().attr('rel') > moveTo.relativeTo.attr('rel'));
var position = '';
// determine position
if(moveTo.side == CHILD && !isParent) {
position = 'last-child';
} else if (moveTo.side == BEFORE) {
position = 'left';
} else {
position = 'right';
}
// save
$.post('.', {
'__cmd': 'move_node',
'position': position,
'cut_item': cutItem,
'pasted_on': pastedOn
}, function(data) {
window.location.reload();
});
} else {
$("#drag_line").remove();
$("#ghost").remove();
}
$("body").removeClass('dragging').enableSelection().unbind('mousemove').unbind('mouseup');
}
});
});
return this;
});
/* Every time the user expands or collapses a part of the tree, we remember
the current state of the tree so we can restore it on a reload.
Note: We might use html5's session storage? */
function storeCollapsedNodes(nodes) {
$.cookie('treeadmin_collapsed_nodes', "[" + nodes.join(",") + "]", { expires: 7 });
}
function retrieveCollapsedNodes() {
var n = $.cookie('treeadmin_collapsed_nodes');
if(n != null) {
try {
n = $.parseJSON(n);
} catch(e) {
n = null;
}
}
return n;
}
function expandOrCollapseNode(item) {
var show = true;
if(!item.hasClass('children'))
return;
var itemId = extract_item_id(item.attr('id'));
if(!isExpandedNode(itemId)) {
item.removeClass('closed');
markNodeAsExpanded(itemId);
} else {
item.addClass('closed');
show = false;
markNodeAsCollapsed(itemId);
}
storeCollapsedNodes(treeadmin.collapsed_nodes);
doToggle(itemId, show);
$('#result_list tbody').recolorRows();
}
$.extend($.fn.feinTreeToggleItem = function() {
$(this).click(function(event){
expandOrCollapseNode($(this));
if(event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
return false;
});
return this;
});
// bind the collapse all children event
$.extend($.fn.bindCollapseTreeEvent = function() {
$(this).click(function() {
rlist = $("#result_list");
rlist.hide();
$('tbody tr', rlist).each(function(i, el) {
var marker = $('.page_marker', el);
if(marker.hasClass('children')) {
var itemId = extract_item_id(marker.attr('id'));
doToggle(itemId, false);
marker.addClass('closed');
markNodeAsCollapsed(itemId);
}
});
storeCollapsedNodes(treeadmin.collapsed_nodes);
rlist.show();
$('tbody', rlist).recolorRows();
});
return this;
});
// bind the open all children event
$.extend($.fn.bindOpenTreeEvent = function() {
$(this).click(function() {
rlist = $("#result_list");
rlist.hide();
$('tbody tr', rlist).each(function(i, el) {
var marker = $('span.page_marker', el);
if(marker.hasClass('children')) {
var itemId = extract_item_id($('span.page_marker', el).attr('id'));
doToggle(itemId, true);
marker.removeClass('closed');
markNodeAsExpanded(itemId);
}
});
storeCollapsedNodes([]);
rlist.show();
$('tbody', rlist).recolorRows();
});
return this;
});
var changelist_tab = function(elem, event, direction) {
event.preventDefault();
elem = $(elem);
var ne = (direction > 0) ? elem.nextAll(':visible:first') : elem.prevAll(':visible:first');
if(ne) {
elem.attr('tabindex', -1);
ne.attr('tabindex', '0');
ne.focus();
}
};
function keyboardNavigationHandler(event) {
// console.log('keydown', this, event.keyCode);
switch(event.keyCode) {
case 40: // down
changelist_tab(this, event, 1);
break;
case 38: // up
changelist_tab(this, event, -1);
break;
case 37: // left
case 39: // right
expandOrCollapseNode($(this).find('.page_marker'));
break;
case 13: // return
where_to = extract_item_id($('span', this).attr('id'));
document.location = document.location.pathname + where_to + '/'
break;
default:
break;
};
}
// fire!
rlist = $("#result_list");
if($('tbody tr', rlist).length > 1) {
rlist.hide();
$('tbody', rlist).feinTree();
$('span.page_marker', rlist).feinTreeToggleItem();
$('#collapse_entire_tree').bindCollapseTreeEvent();
$('#open_entire_tree').bindOpenTreeEvent();
// Disable things user cannot do anyway (object level permissions)
non_editable_fields = $('.tree-item-not-editable', rlist).parents('tr');
non_editable_fields.addClass('non-editable');
$('input:checkbox', non_editable_fields).attr('disabled', 'disabled');
$('a:first', non_editable_fields).click(function(e){e.preventDefault()});
$('.drag_handle', non_editable_fields).removeClass('drag_handle');
/* Enable focussing, put focus on first result, add handler for keyboard navigation */
$('tr', rlist).attr('tabindex', -1);
$('tbody tr:first', rlist).attr('tabindex', 0).focus();
$('tr', rlist).keydown(keyboardNavigationHandler);
treeadmin.collapsed_nodes = [];
var storedNodes = retrieveCollapsedNodes();
if(storedNodes == null) {
$('#collapse_entire_tree').click();
} else {
for(var i=0; i<storedNodes.length; i++) {
$('#page_marker-' + storedNodes[i]).click();
}
}
}
rlist.show();
$('tbody', rlist).recolorRows();
}); | extertioner/django-treeadmin | treeadmin/static/treeadmin/js/treeadmin.js | JavaScript | bsd-3-clause | 10,938 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = undefined;
var _asyncToGenerator2;
function _load_asyncToGenerator() {
return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}
let updateCwd = (() => {
var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config) {
yield config.init({
cwd: config.globalFolder,
binLinks: true,
globalFolder: config.globalFolder,
cacheFolder: config.cacheFolder,
linkFolder: config.linkFolder
});
});
return function updateCwd(_x) {
return _ref.apply(this, arguments);
};
})();
let getBins = (() => {
var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config) {
// build up list of registry folders to search for binaries
const dirs = [];
for (const registryName of Object.keys((_index || _load_index()).registries)) {
const registry = config.registries[registryName];
dirs.push(registry.loc);
}
// build up list of binary files
const paths = new Set();
for (const dir of dirs) {
const binDir = path.join(dir, '.bin');
if (!(yield (_fs || _load_fs()).exists(binDir))) {
continue;
}
for (const name of yield (_fs || _load_fs()).readdir(binDir)) {
paths.add(path.join(binDir, name));
}
}
return paths;
});
return function getBins(_x2) {
return _ref2.apply(this, arguments);
};
})();
let initUpdateBins = (() => {
var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags) {
const beforeBins = yield getBins(config);
const binFolder = getBinFolder(config, flags);
function throwPermError(err, dest) {
if (err.code === 'EACCES') {
throw new (_errors || _load_errors()).MessageError(reporter.lang('noFilePermission', dest));
} else {
throw err;
}
}
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
const afterBins = yield getBins(config);
// remove old bins
for (const src of beforeBins) {
if (afterBins.has(src)) {
// not old
continue;
}
// remove old bin
const dest = path.join(binFolder, path.basename(src));
try {
yield (_fs || _load_fs()).unlink(dest);
} catch (err) {
throwPermError(err, dest);
}
}
// add new bins
for (const src of afterBins) {
if (beforeBins.has(src)) {
// already inserted
continue;
}
// insert new bin
const dest = path.join(binFolder, path.basename(src));
try {
yield (_fs || _load_fs()).unlink(dest);
yield (0, (_packageLinker || _load_packageLinker()).linkBin)(src, dest);
if (process.platform === 'win32' && dest.indexOf('.cmd') !== -1) {
yield (_fs || _load_fs()).rename(dest + '.cmd', dest);
}
} catch (err) {
throwPermError(err, dest);
}
}
});
});
return function initUpdateBins(_x3, _x4, _x5) {
return _ref3.apply(this, arguments);
};
})();
exports.hasWrapper = hasWrapper;
exports.getBinFolder = getBinFolder;
exports.setFlags = setFlags;
var _errors;
function _load_errors() {
return _errors = require('../../errors.js');
}
var _index;
function _load_index() {
return _index = require('../../registries/index.js');
}
var _baseReporter;
function _load_baseReporter() {
return _baseReporter = _interopRequireDefault(require('../../reporters/base-reporter.js'));
}
var _buildSubCommands2;
function _load_buildSubCommands() {
return _buildSubCommands2 = _interopRequireDefault(require('./_build-sub-commands.js'));
}
var _wrapper;
function _load_wrapper() {
return _wrapper = _interopRequireDefault(require('../../lockfile/wrapper.js'));
}
var _install;
function _load_install() {
return _install = require('./install.js');
}
var _add;
function _load_add() {
return _add = require('./add.js');
}
var _remove;
function _load_remove() {
return _remove = require('./remove.js');
}
var _upgrade;
function _load_upgrade() {
return _upgrade = require('./upgrade.js');
}
var _packageLinker;
function _load_packageLinker() {
return _packageLinker = require('../../package-linker.js');
}
var _fs;
function _load_fs() {
return _fs = _interopRequireWildcard(require('../../util/fs.js'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class GlobalAdd extends (_add || _load_add()).Add {
maybeOutputSaveTree() {
for (const pattern of this.addedPatterns) {
const manifest = this.resolver.getStrictResolvedPattern(pattern);
ls(manifest, this.reporter, true);
}
return Promise.resolve();
}
_logSuccessSaveLockfile() {
// noop
}
}
const path = require('path');
function hasWrapper(flags, args) {
return args[0] !== 'bin';
}
function getGlobalPrefix(config, flags) {
if (flags.prefix) {
return flags.prefix;
} else if (config.getOption('prefix')) {
return String(config.getOption('prefix'));
} else if (process.env.PREFIX) {
return process.env.PREFIX;
} else if (process.platform === 'win32') {
// c:\node\node.exe --> prefix=c:\node\
return path.dirname(process.execPath);
} else {
// /usr/local/bin/node --> prefix=/usr/local
let prefix = path.dirname(path.dirname(process.execPath));
// destdir only is respected on Unix
if (process.env.DESTDIR) {
prefix = path.join(process.env.DESTDIR, prefix);
}
return prefix;
}
}
function getBinFolder(config, flags) {
const prefix = getGlobalPrefix(config, flags);
if (process.platform === 'win32') {
return prefix;
} else {
return path.resolve(prefix, 'bin');
}
}
function ls(manifest, reporter, saved) {
const bins = manifest.bin ? Object.keys(manifest.bin) : [];
const human = `${manifest.name}@${manifest.version}`;
if (bins.length) {
if (saved) {
reporter.success(reporter.lang('packageInstalledWithBinaries', human));
} else {
reporter.info(reporter.lang('packageHasBinaries', human));
}
reporter.list(`bins-${manifest.name}`, bins);
} else if (saved) {
reporter.warn(reporter.lang('packageHasNoBinaries'));
}
}
var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('global', {
add(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield updateCwd(config);
const updateBins = yield initUpdateBins(config, reporter, flags);
// install module
const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd);
const install = new GlobalAdd(args, flags, config, reporter, lockfile);
yield install.init();
// link binaries
yield updateBins();
})();
},
bin(config, reporter, flags, args) {
console.log(getBinFolder(config, flags));
},
ls(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield updateCwd(config);
// install so we get hard file paths
const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd);
const install = new (_install || _load_install()).Install({ skipIntegrity: true }, config, new (_baseReporter || _load_baseReporter()).default(), lockfile);
const patterns = yield install.init();
// dump global modules
for (const pattern of patterns) {
const manifest = install.resolver.getStrictResolvedPattern(pattern);
ls(manifest, reporter, false);
}
})();
},
remove(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield updateCwd(config);
const updateBins = yield initUpdateBins(config, reporter, flags);
// remove module
yield (0, (_remove || _load_remove()).run)(config, reporter, flags, args);
// remove binaries
yield updateBins();
})();
},
upgrade(config, reporter, flags, args) {
return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
yield updateCwd(config);
const updateBins = yield initUpdateBins(config, reporter, flags);
// upgrade module
yield (0, (_upgrade || _load_upgrade()).run)(config, reporter, flags, args);
// update binaries
yield updateBins();
})();
}
});
const run = _buildSubCommands.run,
_setFlags = _buildSubCommands.setFlags;
exports.run = run;
function setFlags(commander) {
_setFlags(commander);
commander.option('--prefix <prefix>', 'bin prefix to use to install binaries');
} | rafaeltomesouza/frontend-class1 | aula2/a9/linkedin/client/.gradle/yarn/node_modules/yarn/lib/cli/commands/global.js | JavaScript | mit | 9,186 |
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import invariant from 'fbjs/lib/invariant';
import warning from 'fbjs/lib/warning';
import {isEndish, isMoveish, isStartish} from './EventPluginUtils';
/**
* Tracks the position and time of each active touch by `touch.identifier`. We
* should typically only see IDs in the range of 1-20 because IDs get recycled
* when touches end and start again.
*/
type TouchRecord = {
touchActive: boolean,
startPageX: number,
startPageY: number,
startTimeStamp: number,
currentPageX: number,
currentPageY: number,
currentTimeStamp: number,
previousPageX: number,
previousPageY: number,
previousTimeStamp: number,
};
const MAX_TOUCH_BANK = 20;
const touchBank: Array<TouchRecord> = [];
const touchHistory = {
touchBank,
numberActiveTouches: 0,
// If there is only one active touch, we remember its location. This prevents
// us having to loop through all of the touches all the time in the most
// common case.
indexOfSingleActiveTouch: -1,
mostRecentTimeStamp: 0,
};
type Touch = {
identifier: ?number,
pageX: number,
pageY: number,
timestamp: number,
};
type TouchEvent = {
changedTouches: Array<Touch>,
touches: Array<Touch>,
};
function timestampForTouch(touch: Touch): number {
// The legacy internal implementation provides "timeStamp", which has been
// renamed to "timestamp". Let both work for now while we iron it out
// TODO (evv): rename timeStamp to timestamp in internal code
return (touch: any).timeStamp || touch.timestamp;
}
/**
* TODO: Instead of making gestures recompute filtered velocity, we could
* include a built in velocity computation that can be reused globally.
*/
function createTouchRecord(touch: Touch): TouchRecord {
return {
touchActive: true,
startPageX: touch.pageX,
startPageY: touch.pageY,
startTimeStamp: timestampForTouch(touch),
currentPageX: touch.pageX,
currentPageY: touch.pageY,
currentTimeStamp: timestampForTouch(touch),
previousPageX: touch.pageX,
previousPageY: touch.pageY,
previousTimeStamp: timestampForTouch(touch),
};
}
function resetTouchRecord(touchRecord: TouchRecord, touch: Touch): void {
touchRecord.touchActive = true;
touchRecord.startPageX = touch.pageX;
touchRecord.startPageY = touch.pageY;
touchRecord.startTimeStamp = timestampForTouch(touch);
touchRecord.currentPageX = touch.pageX;
touchRecord.currentPageY = touch.pageY;
touchRecord.currentTimeStamp = timestampForTouch(touch);
touchRecord.previousPageX = touch.pageX;
touchRecord.previousPageY = touch.pageY;
touchRecord.previousTimeStamp = timestampForTouch(touch);
}
function getTouchIdentifier({identifier}: Touch): number {
invariant(identifier != null, 'Touch object is missing identifier.');
if (__DEV__) {
warning(
identifier <= MAX_TOUCH_BANK,
'Touch identifier %s is greater than maximum supported %s which causes ' +
'performance issues backfilling array locations for all of the indices.',
identifier,
MAX_TOUCH_BANK,
);
}
return identifier;
}
function recordTouchStart(touch: Touch): void {
const identifier = getTouchIdentifier(touch);
const touchRecord = touchBank[identifier];
if (touchRecord) {
resetTouchRecord(touchRecord, touch);
} else {
touchBank[identifier] = createTouchRecord(touch);
}
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
}
function recordTouchMove(touch: Touch): void {
const touchRecord = touchBank[getTouchIdentifier(touch)];
if (touchRecord) {
touchRecord.touchActive = true;
touchRecord.previousPageX = touchRecord.currentPageX;
touchRecord.previousPageY = touchRecord.currentPageY;
touchRecord.previousTimeStamp = touchRecord.currentTimeStamp;
touchRecord.currentPageX = touch.pageX;
touchRecord.currentPageY = touch.pageY;
touchRecord.currentTimeStamp = timestampForTouch(touch);
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
} else {
console.error(
'Cannot record touch move without a touch start.\n' + 'Touch Move: %s\n',
'Touch Bank: %s',
printTouch(touch),
printTouchBank(),
);
}
}
function recordTouchEnd(touch: Touch): void {
const touchRecord = touchBank[getTouchIdentifier(touch)];
if (touchRecord) {
touchRecord.touchActive = false;
touchRecord.previousPageX = touchRecord.currentPageX;
touchRecord.previousPageY = touchRecord.currentPageY;
touchRecord.previousTimeStamp = touchRecord.currentTimeStamp;
touchRecord.currentPageX = touch.pageX;
touchRecord.currentPageY = touch.pageY;
touchRecord.currentTimeStamp = timestampForTouch(touch);
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
} else {
console.error(
'Cannot record touch end without a touch start.\n' + 'Touch End: %s\n',
'Touch Bank: %s',
printTouch(touch),
printTouchBank(),
);
}
}
function printTouch(touch: Touch): string {
return JSON.stringify({
identifier: touch.identifier,
pageX: touch.pageX,
pageY: touch.pageY,
timestamp: timestampForTouch(touch),
});
}
function printTouchBank(): string {
let printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK));
if (touchBank.length > MAX_TOUCH_BANK) {
printed += ' (original size: ' + touchBank.length + ')';
}
return printed;
}
const ResponderTouchHistoryStore = {
recordTouchTrack(topLevelType: string, nativeEvent: TouchEvent): void {
if (isMoveish(topLevelType)) {
nativeEvent.changedTouches.forEach(recordTouchMove);
} else if (isStartish(topLevelType)) {
nativeEvent.changedTouches.forEach(recordTouchStart);
touchHistory.numberActiveTouches = nativeEvent.touches.length;
if (touchHistory.numberActiveTouches === 1) {
touchHistory.indexOfSingleActiveTouch =
nativeEvent.touches[0].identifier;
}
} else if (isEndish(topLevelType)) {
nativeEvent.changedTouches.forEach(recordTouchEnd);
touchHistory.numberActiveTouches = nativeEvent.touches.length;
if (touchHistory.numberActiveTouches === 1) {
for (let i = 0; i < touchBank.length; i++) {
const touchTrackToCheck = touchBank[i];
if (touchTrackToCheck != null && touchTrackToCheck.touchActive) {
touchHistory.indexOfSingleActiveTouch = i;
break;
}
}
if (__DEV__) {
const activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch];
warning(
activeRecord != null && activeRecord.touchActive,
'Cannot find single active touch.',
);
}
}
}
},
touchHistory,
};
export default ResponderTouchHistoryStore;
| isubham/isubham.github.io | react/react-16.2.0/packages/events/ResponderTouchHistoryStore.js | JavaScript | mit | 6,890 |
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import 'babel-polyfill';
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import expressJwt from 'express-jwt';
import expressGraphQL from 'express-graphql';
import jwt from 'jsonwebtoken';
import ReactDOM from 'react-dom/server';
import { match } from 'universal-router';
import PrettyError from 'pretty-error';
import passport from './core/passport';
import models from './data/models';
import schema from './data/schema';
import routes from './routes';
import assets from './assets';
import { port, auth, analytics } from './config';
const app = express();
//
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the
// user agent is not known.
// -----------------------------------------------------------------------------
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';
//
// Register Node.js middleware
// -----------------------------------------------------------------------------
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//
// Authentication
// -----------------------------------------------------------------------------
app.use(expressJwt({
secret: auth.jwt.secret,
credentialsRequired: false,
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
getToken: req => req.cookies.id_token,
/* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
}));
app.use(passport.initialize());
app.get('/login/facebook',
passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false })
);
app.get('/login/facebook/return',
passport.authenticate('facebook', { failureRedirect: '/login', session: false }),
(req, res) => {
const expiresIn = 60 * 60 * 24 * 180; // 180 days
const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn });
res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true });
res.redirect('/');
}
);
//
// Register API middleware
// -----------------------------------------------------------------------------
app.use('/graphql', expressGraphQL(req => ({
schema,
graphiql: true,
rootValue: { request: req },
pretty: process.env.NODE_ENV !== 'production',
})));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
app.get('*', async (req, res, next) => {
try {
let css = [];
let statusCode = 200;
const template = require('./views/index.jade');
const data = { title: '', description: '', css: '', body: '', entry: assets.main.js };
if (process.env.NODE_ENV === 'production') {
data.trackingId = analytics.google.trackingId;
}
await match(routes, {
path: req.path,
query: req.query,
context: {
insertCss: styles => css.push(styles._getCss()),
setTitle: value => (data.title = value),
setMeta: (key, value) => (data[key] = value),
},
render(component, status = 200) {
css = [];
statusCode = status;
data.body = ReactDOM.renderToString(component);
data.css = css.join('');
return true;
},
});
res.status(statusCode);
res.send(template(data));
} catch (err) {
next(err);
}
});
//
// Error handling
// -----------------------------------------------------------------------------
const pe = new PrettyError();
pe.skipNodeFiles();
pe.skipPackage('express');
app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
console.log(pe.render(err)); // eslint-disable-line no-console
const template = require('./views/error.jade');
const statusCode = err.status || 500;
res.status(statusCode);
res.send(template({
message: err.message,
stack: process.env.NODE_ENV === 'production' ? '' : err.stack,
}));
});
//
// Launch the server
// -----------------------------------------------------------------------------
/* eslint-disable no-console */
models.sync().catch(err => console.error(err.stack)).then(() => {
app.listen(port, () => {
console.log(`The server is running at http://localhost:${port}/`);
});
});
/* eslint-enable no-console */
| N4N0/resume | src/server.js | JavaScript | mit | 4,585 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ErrorHandler = require('../utils/ErrorHandler');
var startActivity = function startActivity(appPackage, appActivity) {
if (typeof appPackage !== 'string' || typeof appActivity !== 'string') {
throw new _ErrorHandler.ProtocolError('startActivity command requires two parameter (appPackage, appActivity) from type string');
}
return this.requestHandler.create('/session/:sessionId/appium/device/start_activity', { appPackage: appPackage, appActivity: appActivity });
}; /**
*
* Start an arbitrary Android activity during a session.
*
* <example>
:startActivity.js
browser.startActivity({
appPackage: 'io.appium.android.apis',
appActivity: '.view.DragAndDropDemo'
});
* </example>
*
* @param {String} appPackage name of app
* @param {String} appActivity name of activity
* @type mobile
* @for android
*
*/
exports.default = startActivity;
module.exports = exports['default'];
| deep0892/jitendrachatbot | node_modules/webdriverio/build/lib/protocol/startActivity.js | JavaScript | mit | 1,078 |
tinyMCE.addI18n('en.asciimath',{
desc : 'Add New Math'
});
tinyMCE.addI18n('en.asciimathcharmap',{
desc : 'Math Symbols'
});
| MaheshBhise/octopus-private | vendor/assets/javascripts/tinymce/plugins/asciimath/langs/en.js | JavaScript | mit | 135 |
import { Meteor } from 'meteor/meteor';
import bugsnag from 'bugsnag';
import { settings } from '../../../settings';
import { Info } from '../../../utils';
settings.get('Bugsnag_api_key', (key, value) => {
if (value) {
bugsnag.register(value);
}
});
const notify = function(message, stack) {
if (typeof stack === 'string') {
message += ` ${ stack }`;
}
let options = {};
if (Info) {
options = { app: { version: Info.version, info: Info } };
}
const error = new Error(message);
error.stack = stack;
bugsnag.notify(error, options);
};
process.on('uncaughtException', Meteor.bindEnvironment((error) => {
notify(error.message, error.stack);
throw error;
}));
const originalMeteorDebug = Meteor._debug;
Meteor._debug = function(...args) {
notify(...args);
return originalMeteorDebug(...args);
};
| Sing-Li/Rocket.Chat | app/lib/server/lib/bugsnag.js | JavaScript | mit | 816 |
/**
* @file
* Attaches behaviors for the Tour module's toolbar tab.
*/
(($, Backbone, Drupal, settings, document, Shepherd) => {
const queryString = decodeURI(window.location.search);
/**
* Attaches the tour's toolbar tab behavior.
*
* It uses the query string for:
* - tour: When ?tour=1 is present, the tour will start automatically after
* the page has loaded.
* - tips: Pass ?tips=class in the url to filter the available tips to the
* subset which match the given class.
*
* @example
* http://example.com/foo?tour=1&tips=bar
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attach tour functionality on `tour` events.
*/
Drupal.behaviors.tour = {
attach(context) {
once('tour', 'body').forEach(() => {
const model = new Drupal.tour.models.StateModel();
// eslint-disable-next-line no-new
new Drupal.tour.views.ToggleTourView({
el: $(context).find('#toolbar-tab-tour'),
model,
});
model
// Allow other scripts to respond to tour events.
.on('change:isActive', (tourModel, isActive) => {
$(document).trigger(
isActive ? 'drupalTourStarted' : 'drupalTourStopped',
);
});
// Initialization: check whether a tour is available on the current
// page.
if (settings._tour_internal) {
model.set('tour', settings._tour_internal);
}
// Start the tour immediately if toggled via query string.
if (/tour=?/i.test(queryString)) {
model.set('isActive', true);
}
});
},
};
/**
* @namespace
*/
Drupal.tour = Drupal.tour || {
/**
* @namespace Drupal.tour.models
*/
models: {},
/**
* @namespace Drupal.tour.views
*/
views: {},
};
/**
* Backbone Model for tours.
*
* @constructor
*
* @augments Backbone.Model
*/
Drupal.tour.models.StateModel = Backbone.Model.extend(
/** @lends Drupal.tour.models.StateModel# */ {
/**
* @type {object}
*/
defaults: /** @lends Drupal.tour.models.StateModel# */ {
/**
* Indicates whether the Drupal root window has a tour.
*
* @type {Array}
*/
tour: [],
/**
* Indicates whether the tour is currently running.
*
* @type {bool}
*/
isActive: false,
/**
* Indicates which tour is the active one (necessary to cleanly stop).
*
* @type {Array}
*/
activeTour: [],
},
},
);
Drupal.tour.views.ToggleTourView = Backbone.View.extend(
/** @lends Drupal.tour.views.ToggleTourView# */ {
/**
* @type {object}
*/
events: { click: 'onClick' },
/**
* Handles edit mode toggle interactions.
*
* @constructs
*
* @augments Backbone.View
*/
initialize() {
this.listenTo(this.model, 'change:tour change:isActive', this.render);
this.listenTo(this.model, 'change:isActive', this.toggleTour);
},
/**
* {@inheritdoc}
*
* @return {Drupal.tour.views.ToggleTourView}
* The `ToggleTourView` view.
*/
render() {
// Render the visibility.
this.$el.toggleClass('hidden', this._getTour().length === 0);
// Render the state.
const isActive = this.model.get('isActive');
this.$el
.find('button')
.toggleClass('is-active', isActive)
.attr('aria-pressed', isActive);
return this;
},
/**
* Model change handler; starts or stops the tour.
*/
toggleTour() {
if (this.model.get('isActive')) {
this._removeIrrelevantTourItems(this._getTour());
const tourItems = this.model.get('tour');
const that = this;
if (tourItems.length) {
// If Joyride is positioned relative to the top or bottom of an
// element, and its secondary position is right or left, then the
// arrow is also positioned right or left. Shepherd defaults to
// center positioning the arrow.
//
// In most cases, this arrow positioning difference has
// little impact. However, tours built with Joyride may have tips
// using a higher level selector than the element the tip is
// expected to point to, and relied on Joyride's arrow positioning
// to align the arrow with the expected reference element. Joyride's
// arrow positioning behavior is replicated here to prevent those
// use cases from causing UI regressions.
//
// This modifier is provided here instead of TourViewBuilder (where
// most position modifications are) because it includes adding a
// JavaScript callback function.
settings.tourShepherdConfig.defaultStepOptions.popperOptions.modifiers.push(
{
name: 'moveArrowJoyridePosition',
enabled: true,
phase: 'write',
fn({ state }) {
const { arrow } = state.elements;
const { placement } = state;
if (
arrow &&
/^top|bottom/.test(placement) &&
/-start|-end$/.test(placement)
) {
const horizontalPosition = placement.split('-')[1];
const offset =
horizontalPosition === 'start'
? 28
: state.elements.popper.clientWidth - 56;
arrow.style.transform = `translate3d(${offset}px, 0px, 0px)`;
}
},
},
);
const shepherdTour = new Shepherd.Tour(settings.tourShepherdConfig);
shepherdTour.on('cancel', () => {
that.model.set('isActive', false);
});
shepherdTour.on('complete', () => {
that.model.set('isActive', false);
});
tourItems.forEach((tourStepConfig, index) => {
// Create the configuration for a given tour step by using values
// defined in TourViewBuilder.
// @see \Drupal\tour\TourViewBuilder::viewMultiple()
const tourItemOptions = {
title: tourStepConfig.title
? Drupal.checkPlain(tourStepConfig.title)
: null,
text: () => Drupal.theme('tourItemContent', tourStepConfig),
attachTo: tourStepConfig.attachTo,
buttons: [Drupal.tour.nextButton(shepherdTour, tourStepConfig)],
classes: tourStepConfig.classes,
index,
};
tourItemOptions.when = {
show() {
const nextButton =
shepherdTour.currentStep.el.querySelector('footer button');
// Drupal disables Shepherd's built in focus after item
// creation functionality due to focus being set on the tour
// item container after every scroll and resize event. In its
// place, the 'next' button is focused here.
nextButton.focus();
// When Stable or Stable 9 are part of the active theme, the
// Drupal.tour.convertToJoyrideMarkup() function is available.
// This function converts Shepherd markup to Joyride markup,
// facilitating the use of the Shepherd library that is
// backwards compatible with customizations intended for
// Joyride.
// The Drupal.tour.convertToJoyrideMarkup() function is
// internal, and will eventually be removed from Drupal core.
if (Drupal.tour.hasOwnProperty('convertToJoyrideMarkup')) {
Drupal.tour.convertToJoyrideMarkup(shepherdTour);
}
},
};
shepherdTour.addStep(tourItemOptions);
});
shepherdTour.start();
this.model.set({ isActive: true, activeTour: shepherdTour });
}
} else {
this.model.get('activeTour').cancel();
this.model.set({ isActive: false, activeTour: [] });
}
},
/**
* Toolbar tab click event handler; toggles isActive.
*
* @param {jQuery.Event} event
* The click event.
*/
onClick(event) {
this.model.set('isActive', !this.model.get('isActive'));
event.preventDefault();
event.stopPropagation();
},
/**
* Gets the tour.
*
* @return {array}
* An array of Shepherd tour item objects.
*/
_getTour() {
return this.model.get('tour');
},
/**
* Removes tour items for elements that don't have matching page elements.
*
* Or that are explicitly filtered out via the 'tips' query string.
*
* @example
* <caption>This will filter out tips that do not have a matching
* page element or don't have the "bar" class.</caption>
* http://example.com/foo?tips=bar
*
* @param {Object[]} tourItems
* An array containing tour Step config objects.
* The object properties relevant to this function:
* - classes {string}: A string of classes to be added to the tour step
* when rendered.
* - selector {string}: The selector a tour step is associated with.
*/
_removeIrrelevantTourItems(tourItems) {
const tips = /tips=([^&]+)/.exec(queryString);
const filteredTour = tourItems.filter((tourItem) => {
// If the query parameter 'tips' is set, remove all tips that don't
// have the matching class. The `tourItem` variable is a step config
// object, and the 'classes' property is a ShepherdJS Step() config
// option that provides a string.
if (
tips &&
tourItem.hasOwnProperty('classes') &&
tourItem.classes.indexOf(tips[1]) === -1
) {
return false;
}
// If a selector is configured but there isn't a matching element,
// return false.
return !(
tourItem.selector && !document.querySelector(tourItem.selector)
);
});
// If there are tours filtered, we'll have to update model.
if (tourItems.length !== filteredTour.length) {
filteredTour.forEach((filteredTourItem, filteredTourItemId) => {
filteredTour[filteredTourItemId].counter = Drupal.t(
'!tour_item of !total',
{
'!tour_item': filteredTourItemId + 1,
'!total': filteredTour.length,
},
);
if (filteredTourItemId === filteredTour.length - 1) {
filteredTour[filteredTourItemId].cancelText =
Drupal.t('End tour');
}
});
this.model.set('tour', filteredTour);
}
},
},
);
/**
* Provides an object that will become the tour item's 'next' button.
*
* Similar to a theme function, themes can override this function to customize
* the resulting button. Unlike a theme function, it returns an object instead
* of a string, which is why it is not part of Drupal.theme.
*
* @param {Tour} shepherdTour
* A class representing a Shepherd site tour.
* @param {Object} tourStepConfig
* An object generated in TourViewBuilder used for creating the options
* passed to `Tour.addStep(options)`.
* Contains the following properties:
* - id {string}: The tour.tip ID specified by its config
* - selector {string|null}: The selector of the element the tour step is
* attaching to.
* - module {string}: The module providing the tip plugin used by this step.
* - counter {string}: A string indicating which tour step this is out of
* how many total steps.
* - attachTo {Object} This is directly mapped to the `attachTo` Step()
* option. It has two properties:
* - element {string}: The selector of the element the step attaches to.
* - on {string}: a PopperJS compatible string to specify step position.
* - classes {string}: Will be added to the class attribute of the step.
* - body {string}: Markup that is mapped to the `text` Step() option. Will
* become the step content.
* - title {string}: is mapped to the `title` Step() option.
*
* @return {{classes: string, action: string, text: string}}
* An object structured in the manner Shepherd requires to create the
* 'next' button.
*
* @see https://shepherdjs.dev/docs/Tour.html
* @see \Drupal\tour\TourViewBuilder::viewMultiple()
* @see https://shepherdjs.dev/docs/Step.html
*/
Drupal.tour.nextButton = (shepherdTour, tourStepConfig) => {
return {
classes: 'button button--primary',
text: tourStepConfig.cancelText
? tourStepConfig.cancelText
: Drupal.t('Next'),
action: tourStepConfig.cancelText
? shepherdTour.cancel
: shepherdTour.next,
};
};
/**
* Theme function for tour item content.
*
* @param {Object} tourStepConfig
* An object generated in TourViewBuilder used for creating the options
* passed to `Tour.addStep(options)`.
* Contains the following properties:
* - id {string}: The tour.tip ID specified by its config
* - selector {string|null}: The selector of the element the tour step is
* attaching to.
* - module {string}: The module providing the tip plugin used by this step.
* - counter {string}: A string indicating which tour step this is out of
* how many total steps.
* - attachTo {Object} This is directly mapped to the `attachTo` Step()
* option. It has two properties:
* - element {string}: The selector of the element the step attaches to.
* - on {string}: a PopperJS compatible string to specify step position.
* - classes {string}: Will be added to the class attribute of the step.
* - body {string}: Markup that is mapped to the `text` Step() option. Will
* become the step content.
* - title {string}: is mapped to the `title` Step() option.
*
* @return {string}
* The tour item content markup.
*
* @see \Drupal\tour\TourViewBuilder::viewMultiple()
* @see https://shepherdjs.dev/docs/Step.html
*/
Drupal.theme.tourItemContent = (tourStepConfig) =>
`${tourStepConfig.body}<div class="tour-progress">${tourStepConfig.counter}</div>`;
})(jQuery, Backbone, Drupal, drupalSettings, document, window.Shepherd);
| tobiasbuhrer/tobiasb | web/core/modules/tour/js/tour.es6.js | JavaScript | gpl-2.0 | 15,109 |
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var prefix = 'fas';
var iconName = 'map-marked-alt';
var width = 576;
var height = 512;
var ligatures = [];
var unicode = 'f5a0';
var svgPathData = 'M288 0c-69.59 0-126 56.41-126 126 0 56.26 82.35 158.8 113.9 196.02 6.39 7.54 17.82 7.54 24.2 0C331.65 284.8 414 182.26 414 126 414 56.41 357.59 0 288 0zm0 168c-23.2 0-42-18.8-42-42s18.8-42 42-42 42 18.8 42 42-18.8 42-42 42zM20.12 215.95A32.006 32.006 0 0 0 0 245.66v250.32c0 11.32 11.43 19.06 21.94 14.86L160 448V214.92c-8.84-15.98-16.07-31.54-21.25-46.42L20.12 215.95zM288 359.67c-14.07 0-27.38-6.18-36.51-16.96-19.66-23.2-40.57-49.62-59.49-76.72v182l192 64V266c-18.92 27.09-39.82 53.52-59.49 76.72-9.13 10.77-22.44 16.95-36.51 16.95zm266.06-198.51L416 224v288l139.88-55.95A31.996 31.996 0 0 0 576 426.34V176.02c0-11.32-11.43-19.06-21.94-14.86z';
exports.definition = {
prefix: prefix,
iconName: iconName,
icon: [
width,
height,
ligatures,
unicode,
svgPathData
]};
exports.faMapMarkedAlt = exports.definition;
exports.prefix = prefix;
exports.iconName = iconName;
exports.width = width;
exports.height = height;
exports.ligatures = ligatures;
exports.unicode = unicode;
exports.svgPathData = svgPathData; | cstrassburg/smarthome | modules/http/webif/gstatic/fontawesome/advanced-options/use-with-node-js/free-solid-svg-icons/faMapMarkedAlt.js | JavaScript | gpl-3.0 | 1,286 |
/* jslint node: true */
'use strict';
var binding = require('../build/Release/sodium');
var AuthKey = require('./keys/auth-key');
var toBuffer = require('./toBuffer');
var should = require('should');
/**
* Message Authentication
*
* Security model
*
* The crypto_auth function, viewed as a function of the message for a uniform
* random key, is designed to meet the standard notion of unforgeability. This
* means that an attacker cannot find authenticators for any messages not
* authenticated by the sender, even if the attacker has adaptively influenced
* the messages authenticated by the sender. For a formal definition see,
* e.g., Section 2.4 of Bellare, Kilian, and Rogaway, "The security of the
* cipher block chaining message authentication code," Journal of Computer and
* System Sciences 61 (2000), 362–399;
* http://www-cse.ucsd.edu/~mihir/papers/cbc.html.
*
* NaCl does not make any promises regarding "strong" unforgeability; perhaps
* one valid authenticator can be converted into another valid authenticator
* for the same message.
* NaCl also does not make any promises regarding "truncated unforgeability."
*
* The secretKey *MUST* remain secret or an attacker could forge valid
* authenticator tokens
*
* If key is not given a new random key is generated
*
* @param {String|Buffer|Array} [secretKey] A valid auth secret key
* @constructor
*/
module.exports = function Auth(secretKey, encoding) {
var self = this;
/** default encoding to use in all string operations */
self.defaultEncoding = undefined;
// Init key
self.secretKey = new AuthKey(secretKey, encoding);
/** Size of the authentication token */
self.bytes = function () {
return binding.crypto_auth_BYTES;
};
/** String name of the default crypto primitive used in auth operations */
self.primitive = function() {
return binding.crypto_auth_PRIMITIVE;
};
/**
* Get the auth-key secret key object
* @returns {AuthKey|*}
*/
self.key = function() {
return self.secretKey;
};
/**
* Set the default encoding to use in all string conversions
* @param {String} encoding encoding to use
*/
self.setEncoding = function(encoding) {
encoding.should.have.type('string').match(/^(?:utf8|ascii|binary|hex|utf16le|ucs2|base64)$/);
self.defaultEncoding = encoding;
};
/**
* Get the current default encoding
* @returns {undefined|String}
*/
self.getEncoding = function() {
return self.defaultEncoding;
};
/**
* Generate authentication token for message, based on the secret key
*
* @param {string|Buffer|Array} message message to authenticate
* @param {String} [encoding ] If v is a string you can specify the encoding
*/
self.generate = function(message, encoding) {
encoding = encoding || self.defaultEncoding;
var messageBuf = toBuffer(message, encoding);
return binding.crypto_auth(messageBuf, self.secretKey.get());
};
/**
* Checks if the token authenticates the message
*
* @param {String|Buffer|Array} token message token
* @param {String|Buffer|Array} message message to authenticate
* @param {String} [encoding] If v is a string you can specify the encoding
*/
self.validate = function(token, message, encoding) {
if(!self.secretKey) {
throw new Error('Auth: no secret key found');
}
encoding = encoding || self.defaultEncoding;
var tokenBuf = toBuffer(token, encoding);
var messageBuf = toBuffer(message, encoding);
return binding.crypto_auth_verify(tokenBuf, messageBuf, self.secretKey.get()) ? false : true;
};
};
| Zeipt/Mycely | www/jxcore/node_modules/sodium/lib/auth.js | JavaScript | agpl-3.0 | 3,794 |
'use strict';
/**
* @module br/test/TimeUtility
*/
var Errors = require('br/Errors');
/**
* @private
* @class
* @alias module:br/test/TimeUtility
*
* @classdesc
* Utility class containing static methods that can be useful for controlling time in tests.
*/
var TimeUtility = {};
/** @private */
TimeUtility.TIMER_ID = 0;
/** @private */
TimeUtility.MANUAL_TIME_MODE = 'Manual';
/** @private */
TimeUtility.NEXT_STEP_TIME_MODE = 'NextStep';
/** @private */
TimeUtility.timeMode = TimeUtility.NEXT_STEP_TIME_MODE;
/** @private */
TimeUtility.pCapturedTimerFunctionArgs = [];
/** @private */
TimeUtility._bHasReplacedTimerFunctions = false;
/** @private */
TimeUtility.bCaptureTimeoutAndIntervals = true;
/** @private */
TimeUtility.fCapturedTimersSort = function(firstFunction, secondFunction) {
return firstFunction[1] - secondFunction[1];
};
/**
* Reset this TimeUtility to its original state. Useful for testing.
* @private
*/
TimeUtility.reset = function() {
this.timeMode = this.NEXT_STEP_TIME_MODE;
this.bCaptureTimeoutAndIntervals = true;
this.clearCapturedFunctions();
this.releaseTimerFunctions();
};
/**
* Overrides the default <code>setTimeout</code> and <code>setInterval</code> methods. This allows the storing of all
* functions passed in to those methods.
*/
TimeUtility.captureTimerFunctions = function() {
if (this.bCaptureTimeoutAndIntervals && this._bHasReplacedTimerFunctions === false) {
this.ORIGINAL_SETTIMEOUT_FUNCTION = window.setTimeout;
this.ORIGINAL_SETINTERVAL_FUNCTION = window.setInterval;
this.ORIGINAL_CLEARTIMEOUT_FUNCTION = window.clearTimeout;
this.ORIGINAL_CLEARINTERVAL_FUNCTION = window.clearInterval;
window.setTimeout = TimeUtility.fCaptureArguments;
window.setInterval = TimeUtility.fCaptureArguments;
window.clearTimeout = TimeUtility.fClearTimer;
window.clearInterval = TimeUtility.fClearTimer;
this._bHasReplacedTimerFunctions = true;
}
};
/**
* @return {Array} A list of <code>argument</code> objects that were passed into <code>setTimeout</code> and
* <code>setInterval</code>.
*/
TimeUtility.getCapturedFunctions = function() {
var capturedFunctions = this.pCapturedTimerFunctionArgs.slice();
return capturedFunctions.sort(this.fCapturedTimersSort);
};
/** @private */
TimeUtility.clearCapturedFunctions = function() {
this.pCapturedTimerFunctionArgs.length = 0;
};
/**
* Execute all captured functions that are set to be triggered within the passed in millisecond time value. If no value
* is passed, this will execute all captured functions.
*/
TimeUtility.executeCapturedFunctions = function(nMsToExecuteTo) {
var capturedFunction, innerCapturedFunction;
this.pCapturedTimerFunctionArgs.sort(this.fCapturedTimersSort);
for (var idx = 0; idx < this.pCapturedTimerFunctionArgs.length; idx++) {
capturedFunction = this.pCapturedTimerFunctionArgs[idx];
if (nMsToExecuteTo == null || capturedFunction[1] <= nMsToExecuteTo) {
var timerArgsLength = this.pCapturedTimerFunctionArgs.length;
capturedFunction[0]();
for (var idy = timerArgsLength; idy < this.pCapturedTimerFunctionArgs.length; idy++) {
innerCapturedFunction = this.pCapturedTimerFunctionArgs[idy];
innerCapturedFunction[1] += capturedFunction[1];
}
this.pCapturedTimerFunctionArgs.splice(idx, 1);
idx--;
} else {
capturedFunction[1] -= nMsToExecuteTo;
}
}
};
/**
* Execute all captured functions if we are in NEXT_STEP_TIME_MODE. All functions will be cleared even if an error is
* thrown, although not all functions will be executed. Returns false if we are not in NEXT_STEP_TIME_MODE
*/
TimeUtility.nextStep = function() {
if (this.timeMode === this.NEXT_STEP_TIME_MODE) {
try {
this.executeCapturedFunctions();
} finally {
this.clearCapturedFunctions();
}
return true;
} else {
return false;
}
};
/**
* Sets the timer mode which controls when captured timeouts and intervals run.
*/
TimeUtility.setTimeMode = function(timeMode) {
if (timeMode === this.MANUAL_TIME_MODE || timeMode === this.NEXT_STEP_TIME_MODE) {
this.timeMode = timeMode;
} else {
throw new Errors.InvalidTestError('Incorrect time mode (' + timeMode + ') set on TimeUtility.');
}
};
/** @private */
TimeUtility.releaseTimerFunctions = function() {
if (this._bHasReplacedTimerFunctions) {
window.setTimeout = this.ORIGINAL_SETTIMEOUT_FUNCTION;
window.setInterval = this.ORIGINAL_SETINTERVAL_FUNCTION;
window.clearTimeout = this.ORIGINAL_CLEARTIMEOUT_FUNCTION;
window.clearInterval = this.ORIGINAL_CLEARINTERVAL_FUNCTION;
this._bHasReplacedTimerFunctions = false;
delete this.ORIGINAL_SETTIMEOUT_FUNCTION;
delete this.ORIGINAL_SETINTERVAL_FUNCTION;
delete this.ORIGINAL_CLEARTIMEOUT_FUNCTION;
delete this.ORIGINAL_CLEARINTERVAL_FUNCTION;
}
};
/** @private */
TimeUtility.fCaptureArguments = function() {
arguments.nTimerId = TimeUtility.TIMER_ID++;
TimeUtility.pCapturedTimerFunctionArgs.push(arguments);
return arguments.nTimerId;
};
/** @private */
TimeUtility.fClearTimer = function(timerId) {
var capturedFunctions = TimeUtility.pCapturedTimerFunctionArgs;
capturedFunctions = capturedFunctions.filter(function(capturedFunction){
return capturedFunction.nTimerId !== timerId;
});
TimeUtility.pCapturedTimerFunctionArgs = capturedFunctions;
};
module.exports = TimeUtility;
| BladeRunnerJS/brjs | brjs-sdk/sdk/libs/javascript/br-test/src/br/test/TimeUtility.js | JavaScript | lgpl-3.0 | 5,342 |
/* Copyright 2017 Mozilla Foundation
*
* 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.
*/
/* eslint-disable no-var */
"use strict";
(function () {
var baseLocation;
if (typeof document !== "undefined") {
baseLocation = new URL("./", document.currentScript.src);
} else if (typeof location !== "undefined") {
// Probably worker -- walking subfolders until we will reach root.
baseLocation = location;
while (baseLocation.href.includes("/src/")) {
baseLocation = new URL("..", baseLocation);
}
} else {
throw new Error("Cannot configure SystemJS");
}
var PluginBabelPath = "node_modules/systemjs-plugin-babel/plugin-babel.js";
var SystemJSPluginBabelPath =
"node_modules/systemjs-plugin-babel/systemjs-babel-browser.js";
var PluginBabelCachePath = "external/systemjs/plugin-babel-cached.js";
var isCachingPossible =
typeof indexedDB !== "undefined" &&
typeof TextEncoder !== "undefined" &&
typeof crypto !== "undefined" &&
typeof crypto.subtle !== "undefined";
// When we create a bundle, webpack is run on the source and it will replace
// require with __webpack_require__. When we want to use the real require,
// __non_webpack_require__ has to be used.
// In this target, we don't create a bundle, so we have to replace the
// occurrences of __non_webpack_require__ ourselves.
function babelPluginReplaceNonWebPackRequire(babel) {
return {
visitor: {
Identifier(path, state) {
if (path.node.name === "__non_webpack_require__") {
path.replaceWith(babel.types.identifier("require"));
}
},
},
};
}
SystemJS.config({
packages: {
"": {
defaultExtension: "js",
},
},
paths: {
pdfjs: new URL("src", baseLocation).href,
"pdfjs-web": new URL("web", baseLocation).href,
"pdfjs-test": new URL("test", baseLocation).href,
"pdfjs-lib": new URL("src/pdf", baseLocation).href,
"core-js": new URL("node_modules/core-js", baseLocation).href,
"web-streams-polyfill": new URL(
"node_modules/web-streams-polyfill",
baseLocation
).href,
},
meta: {
"*": {
scriptLoad: false,
esModule: true,
babelOptions: {
env: false,
plugins: [babelPluginReplaceNonWebPackRequire],
},
},
},
map: {
"plugin-babel": new URL(PluginBabelPath, baseLocation).href,
"systemjs-babel-build": new URL(SystemJSPluginBabelPath, baseLocation)
.href,
"plugin-babel-cached": new URL(PluginBabelCachePath, baseLocation).href,
},
transpiler: isCachingPossible ? "plugin-babel-cached" : "plugin-babel",
});
})();
| xavier114fch/pdf.js | systemjs.config.js | JavaScript | apache-2.0 | 3,232 |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'preview', 'en-ca', {
preview: 'Preview'
} );
| ldilov/uidb | plugins/ckeditor/plugins/preview/lang/en-ca.js | JavaScript | apache-2.0 | 219 |
/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @constructor
* @extends {WebInspector.SDKModel}
* @param {!WebInspector.Target} target
*/
WebInspector.RuntimeModel = function(target)
{
WebInspector.SDKModel.call(this, WebInspector.RuntimeModel, target);
this._agent = target.runtimeAgent();
this.target().registerRuntimeDispatcher(new WebInspector.RuntimeDispatcher(this));
if (target.hasJSContext())
this._agent.enable();
/**
* @type {!Object.<number, !WebInspector.ExecutionContext>}
*/
this._executionContextById = {};
if (!Runtime.experiments.isEnabled("customObjectFormatters"))
return;
if (WebInspector.moduleSetting("customFormatters").get())
this._agent.setCustomObjectFormatterEnabled(true);
WebInspector.moduleSetting("customFormatters").addChangeListener(this._customFormattersStateChanged.bind(this));
}
WebInspector.RuntimeModel.Events = {
ExecutionContextCreated: "ExecutionContextCreated",
ExecutionContextDestroyed: "ExecutionContextDestroyed",
}
WebInspector.RuntimeModel._privateScript = "private script";
WebInspector.RuntimeModel.prototype = {
/**
* @return {!Array.<!WebInspector.ExecutionContext>}
*/
executionContexts: function()
{
return Object.values(this._executionContextById);
},
/**
* @param {!RuntimeAgent.ExecutionContextDescription} context
*/
_executionContextCreated: function(context)
{
// The private script context should be hidden behind an experiment.
if (context.name == WebInspector.RuntimeModel._privateScript && !context.origin && !Runtime.experiments.isEnabled("privateScriptInspection")) {
return;
}
var executionContext = new WebInspector.ExecutionContext(this.target(), context.id, context.name, context.origin, !context.type, context.frameId);
this._executionContextById[executionContext.id] = executionContext;
this.dispatchEventToListeners(WebInspector.RuntimeModel.Events.ExecutionContextCreated, executionContext);
},
/**
* @param {number} executionContextId
*/
_executionContextDestroyed: function(executionContextId)
{
var executionContext = this._executionContextById[executionContextId];
if (!executionContext)
return;
delete this._executionContextById[executionContextId];
this.dispatchEventToListeners(WebInspector.RuntimeModel.Events.ExecutionContextDestroyed, executionContext);
},
_executionContextsCleared: function()
{
var contexts = this.executionContexts();
this._executionContextById = {};
for (var i = 0; i < contexts.length; ++i)
this.dispatchEventToListeners(WebInspector.RuntimeModel.Events.ExecutionContextDestroyed, contexts[i]);
},
/**
* @param {!RuntimeAgent.RemoteObject} payload
* @return {!WebInspector.RemoteObject}
*/
createRemoteObject: function(payload)
{
console.assert(typeof payload === "object", "Remote object payload should only be an object");
return new WebInspector.RemoteObjectImpl(this.target(), payload.objectId, payload.type, payload.subtype, payload.value, payload.description, payload.preview, payload.customPreview);
},
/**
* @param {!RuntimeAgent.RemoteObject} payload
* @param {!WebInspector.ScopeRef} scopeRef
* @return {!WebInspector.RemoteObject}
*/
createScopeRemoteObject: function(payload, scopeRef)
{
return new WebInspector.ScopeRemoteObject(this.target(), payload.objectId, scopeRef, payload.type, payload.subtype, payload.value, payload.description, payload.preview);
},
/**
* @param {number|string|boolean} value
* @return {!WebInspector.RemoteObject}
*/
createRemoteObjectFromPrimitiveValue: function(value)
{
return new WebInspector.RemoteObjectImpl(this.target(), undefined, typeof value, undefined, value);
},
/**
* @param {string} name
* @param {number|string|boolean} value
* @return {!WebInspector.RemoteObjectProperty}
*/
createRemotePropertyFromPrimitiveValue: function(name, value)
{
return new WebInspector.RemoteObjectProperty(name, this.createRemoteObjectFromPrimitiveValue(value));
},
/**
* @param {!WebInspector.Event} event
*/
_customFormattersStateChanged: function(event)
{
var enabled = /** @type {boolean} */ (event.data);
this._agent.setCustomObjectFormatterEnabled(enabled);
},
__proto__: WebInspector.SDKModel.prototype
}
/**
* @constructor
* @implements {RuntimeAgent.Dispatcher}
* @param {!WebInspector.RuntimeModel} runtimeModel
*/
WebInspector.RuntimeDispatcher = function(runtimeModel)
{
this._runtimeModel = runtimeModel;
}
WebInspector.RuntimeDispatcher.prototype = {
/**
* @override
* @param {!RuntimeAgent.ExecutionContextDescription} context
*/
executionContextCreated: function(context)
{
this._runtimeModel._executionContextCreated(context);
},
/**
* @override
* @param {!RuntimeAgent.ExecutionContextId} executionContextId
*/
executionContextDestroyed: function(executionContextId)
{
this._runtimeModel._executionContextDestroyed(executionContextId);
},
/**
* @override
*/
executionContextsCleared: function()
{
this._runtimeModel._executionContextsCleared();
}
}
/**
* @constructor
* @extends {WebInspector.SDKObject}
* @param {!WebInspector.Target} target
* @param {number|undefined} id
* @param {string} name
* @param {string} origin
* @param {boolean} isPageContext
* @param {string=} frameId
*/
WebInspector.ExecutionContext = function(target, id, name, origin, isPageContext, frameId)
{
WebInspector.SDKObject.call(this, target);
this.id = id;
this.name = name;
this.origin = origin;
this.isMainWorldContext = isPageContext;
this.runtimeModel = target.runtimeModel;
this.debuggerModel = WebInspector.DebuggerModel.fromTarget(target);
this.frameId = frameId;
}
/**
* @param {!WebInspector.ExecutionContext} a
* @param {!WebInspector.ExecutionContext} b
* @return {number}
*/
WebInspector.ExecutionContext.comparator = function(a, b)
{
/**
* @param {!WebInspector.Target} target
* @return {number}
*/
function targetWeight(target)
{
if (target.isPage())
return 3;
if (target.isDedicatedWorker())
return 2;
return 1;
}
var weightDiff = targetWeight(a.target()) - targetWeight(b.target());
if (weightDiff)
return -weightDiff;
var frameIdDiff = String.hashCode(a.frameId) - String.hashCode(b.frameId);
if (frameIdDiff)
return frameIdDiff;
// Main world context should always go first.
if (a.isMainWorldContext)
return -1;
if (b.isMainWorldContext)
return +1;
return a.name.localeCompare(b.name);
}
WebInspector.ExecutionContext.prototype = {
/**
* @param {string} expression
* @param {string} objectGroup
* @param {boolean} includeCommandLineAPI
* @param {boolean} doNotPauseOnExceptionsAndMuteConsole
* @param {boolean} returnByValue
* @param {boolean} generatePreview
* @param {function(?WebInspector.RemoteObject, boolean, ?RuntimeAgent.RemoteObject=, ?DebuggerAgent.ExceptionDetails=)} callback
*/
evaluate: function(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback)
{
// FIXME: It will be moved to separate ExecutionContext.
if (this.debuggerModel.selectedCallFrame()) {
this.debuggerModel.evaluateOnSelectedCallFrame(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback);
return;
}
this._evaluateGlobal.apply(this, arguments);
},
/**
* @param {string} objectGroup
* @param {boolean} returnByValue
* @param {boolean} generatePreview
* @param {function(?WebInspector.RemoteObject, boolean, ?RuntimeAgent.RemoteObject=, ?DebuggerAgent.ExceptionDetails=)} callback
*/
globalObject: function(objectGroup, returnByValue, generatePreview, callback)
{
this._evaluateGlobal("this", objectGroup, false, true, returnByValue, generatePreview, callback);
},
/**
* @param {string} expression
* @param {string} objectGroup
* @param {boolean} includeCommandLineAPI
* @param {boolean} doNotPauseOnExceptionsAndMuteConsole
* @param {boolean} returnByValue
* @param {boolean} generatePreview
* @param {function(?WebInspector.RemoteObject, boolean, ?RuntimeAgent.RemoteObject=, ?DebuggerAgent.ExceptionDetails=)} callback
*/
_evaluateGlobal: function(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback)
{
if (!expression) {
// There is no expression, so the completion should happen against global properties.
expression = "this";
}
/**
* @this {WebInspector.ExecutionContext}
* @param {?Protocol.Error} error
* @param {!RuntimeAgent.RemoteObject} result
* @param {boolean=} wasThrown
* @param {?DebuggerAgent.ExceptionDetails=} exceptionDetails
*/
function evalCallback(error, result, wasThrown, exceptionDetails)
{
if (error) {
callback(null, false);
return;
}
if (returnByValue)
callback(null, !!wasThrown, wasThrown ? null : result, exceptionDetails);
else
callback(this.runtimeModel.createRemoteObject(result), !!wasThrown, undefined, exceptionDetails);
}
this.target().runtimeAgent().evaluate(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, this.id, returnByValue, generatePreview, evalCallback.bind(this));
},
/**
* @param {string} expressionString
* @param {string} prefix
* @param {boolean} force
* @param {function(!Array.<string>, number=)} completionsReadyCallback
*/
completionsForExpression: function(expressionString, prefix, force, completionsReadyCallback)
{
var lastIndex = expressionString.length - 1;
var dotNotation = (expressionString[lastIndex] === ".");
var bracketNotation = (expressionString[lastIndex] === "[");
if (dotNotation || bracketNotation)
expressionString = expressionString.substr(0, lastIndex);
if (expressionString && parseInt(expressionString, 10) == expressionString) {
// User is entering float value, do not suggest anything.
completionsReadyCallback([]);
return;
}
if (!prefix && !expressionString && !force) {
completionsReadyCallback([]);
return;
}
if (!expressionString && this.debuggerModel.selectedCallFrame())
this.debuggerModel.selectedCallFrame().variableNames(receivedPropertyNames.bind(this));
else
this.evaluate(expressionString, "completion", true, true, false, false, evaluated.bind(this));
/**
* @this {WebInspector.ExecutionContext}
*/
function evaluated(result, wasThrown)
{
if (!result || wasThrown) {
completionsReadyCallback([]);
return;
}
/**
* @param {string=} type
* @suppressReceiverCheck
* @this {WebInspector.ExecutionContext}
*/
function getCompletions(type)
{
var object;
if (type === "string")
object = new String("");
else if (type === "number")
object = new Number(0);
else if (type === "boolean")
object = new Boolean(false);
else
object = this;
var resultSet = {};
for (var o = object; o; o = o.__proto__) {
try {
if (type === "array" && o === object && ArrayBuffer.isView(o) && o.length > 9999)
continue;
var names = Object.getOwnPropertyNames(o);
for (var i = 0; i < names.length; ++i)
resultSet[names[i]] = true;
} catch (e) {
}
}
return resultSet;
}
if (result.type === "object" || result.type === "function")
result.callFunctionJSON(getCompletions, [WebInspector.RemoteObject.toCallArgument(result.subtype)], receivedPropertyNames.bind(this));
else if (result.type === "string" || result.type === "number" || result.type === "boolean")
this.evaluate("(" + getCompletions + ")(\"" + result.type + "\")", "completion", false, true, true, false, receivedPropertyNamesFromEval.bind(this));
}
/**
* @param {?WebInspector.RemoteObject} notRelevant
* @param {boolean} wasThrown
* @param {?RuntimeAgent.RemoteObject=} result
* @this {WebInspector.ExecutionContext}
*/
function receivedPropertyNamesFromEval(notRelevant, wasThrown, result)
{
if (result && !wasThrown)
receivedPropertyNames.call(this, result.value);
else
completionsReadyCallback([]);
}
/**
* @this {WebInspector.ExecutionContext}
*/
function receivedPropertyNames(propertyNames)
{
this.target().runtimeAgent().releaseObjectGroup("completion");
if (!propertyNames) {
completionsReadyCallback([]);
return;
}
var includeCommandLineAPI = (!dotNotation && !bracketNotation);
if (includeCommandLineAPI) {
const commandLineAPI = ["dir", "dirxml", "keys", "values", "profile", "profileEnd", "monitorEvents", "unmonitorEvents", "inspect", "copy", "clear",
"getEventListeners", "debug", "undebug", "monitor", "unmonitor", "table", "$", "$$", "$x"];
for (var i = 0; i < commandLineAPI.length; ++i)
propertyNames[commandLineAPI[i]] = true;
}
this._reportCompletions(completionsReadyCallback, dotNotation, bracketNotation, expressionString, prefix, Object.keys(propertyNames));
}
},
/**
* @param {function(!Array.<string>, number=)} completionsReadyCallback
* @param {boolean} dotNotation
* @param {boolean} bracketNotation
* @param {string} expressionString
* @param {string} prefix
* @param {!Array.<string>} properties
*/
_reportCompletions: function(completionsReadyCallback, dotNotation, bracketNotation, expressionString, prefix, properties) {
if (bracketNotation) {
if (prefix.length && prefix[0] === "'")
var quoteUsed = "'";
else
var quoteUsed = "\"";
}
var results = [];
if (!expressionString) {
const keywords = ["break", "case", "catch", "continue", "default", "delete", "do", "else", "finally", "for", "function", "if", "in",
"instanceof", "new", "return", "switch", "this", "throw", "try", "typeof", "var", "void", "while", "with"];
properties = properties.concat(keywords);
}
properties.sort();
for (var i = 0; i < properties.length; ++i) {
var property = properties[i];
// Assume that all non-ASCII characters are letters and thus can be used as part of identifier.
if (dotNotation && !/^[a-zA-Z_$\u008F-\uFFFF][a-zA-Z0-9_$\u008F-\uFFFF]*$/.test(property))
continue;
if (bracketNotation) {
if (!/^[0-9]+$/.test(property))
property = quoteUsed + property.escapeCharacters(quoteUsed + "\\") + quoteUsed;
property += "]";
}
if (property.length < prefix.length)
continue;
if (prefix.length && !property.startsWith(prefix))
continue;
// Substitute actual newlines with newline characters. @see crbug.com/498421
results.push(property.split("\n").join("\\n"));
}
completionsReadyCallback(results);
},
__proto__: WebInspector.SDKObject.prototype
}
/**
* @constructor
* @extends {WebInspector.SDKObject}
* @param {!WebInspector.DebuggerModel} debuggerModel
* @param {!DOMDebuggerAgent.EventListener} payload
* @param {!RuntimeAgent.RemoteObjectId} objectId
*/
WebInspector.EventListener = function(debuggerModel, payload, objectId)
{
WebInspector.SDKObject.call(this, debuggerModel.target());
this._type = payload.type;
this._useCapture = payload.useCapture;
this._location = WebInspector.DebuggerModel.Location.fromPayload(debuggerModel, payload.location);
this._handler = payload.handler ? this.target().runtimeModel.createRemoteObject(payload.handler) : null;
var script = debuggerModel.scriptForId(payload.location.scriptId);
this._sourceName = script ? script.contentURL() : "";
this._objectId = objectId;
}
WebInspector.EventListener.prototype = {
/**
* @return {string}
*/
type: function()
{
return this._type;
},
/**
* @return {boolean}
*/
useCapture: function()
{
return this._useCapture;
},
/**
* @return {!WebInspector.DebuggerModel.Location}
*/
location: function()
{
return this._location;
},
/**
* @return {?WebInspector.RemoteObject}
*/
handler: function()
{
return this._handler;
},
/**
* @return {string}
*/
sourceName: function()
{
return this._sourceName;
},
/**
* @return {!RuntimeAgent.RemoteObjectId}
*/
objectId: function()
{
return this._objectId;
},
__proto__: WebInspector.SDKObject.prototype
}
| weolar/miniblink49 | third_party/WebKit/Source/devtools/front_end/sdk/RuntimeModel.js | JavaScript | apache-2.0 | 20,001 |
//// [tests/cases/compiler/inferredIndexerOnNamespaceImport.ts] ////
//// [foo.ts]
export const x = 3;
export const y = 5;
//// [bar.ts]
import * as foo from "./foo";
function f(map: { [k: string]: number }) {
// ...
}
f(foo);
//// [foo.js]
"use strict";
exports.__esModule = true;
exports.x = 3;
exports.y = 5;
//// [bar.js]
"use strict";
exports.__esModule = true;
var foo = require("./foo");
function f(map) {
// ...
}
f(foo);
| basarat/TypeScript | tests/baselines/reference/inferredIndexerOnNamespaceImport.js | JavaScript | apache-2.0 | 461 |
/*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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.
*/
/**
* Constructor
* PartContextMenu
*
* @see
* @since: 2015.07.15
* @author: hw.shim@samsung.com
*/
// @formatter:off
define([
'webida-lib/util/genetic',
'webida-lib/util/logger/logger-client'
], function (
genetic,
Logger
) {
'use strict';
// @formatter:on
/**
* @typedef {Object} Thenable
*/
var logger = new Logger();
//logger.setConfig('level', Logger.LEVELS.log);
//logger.off();
function PartContextMenu(allItems, part) {
logger.info('new PartContextMenu(allItems, part)');
this.setAllItems(allItems);
this.setPart(part);
}
genetic.inherits(PartContextMenu, Object, {
/**
* Creates Available Menu Items then return Thenable
* @return {Thenable}
* @abstract
*/
getAvailableItems: function () {
throw new Error('getAvailableItems() should be implemented by ' + this.constructor.name);
},
/**
* @param {Object}
*/
setAllItems: function (allItems) {
this.allItems = allItems;
},
/**
* @return {Object}
*/
getAllItems: function () {
return this.allItems;
},
/**
* @param {Part}
*/
setPart: function (part) {
this.part = part;
},
/**
* @return {Part}
*/
getPart: function () {
return this.part;
},
/**
* Convenient method
* @return {PartRegistry}
*/
getPartRegistry: function () {
var workbench = require('webida-lib/plugins/workbench/plugin');
var page = workbench.getCurrentPage();
return page.getPartRegistry();
}
});
return PartContextMenu;
});
| leechwin/webida-client | common/src/webida/plugins/workbench/ui/PartContextMenu.js | JavaScript | apache-2.0 | 2,432 |
/**
* Copyright (c) 2009
* Jan-Felix Schwarz
*
* 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 (!ORYX.Plugins) {
ORYX.Plugins = new Object();
}
ORYX.Plugins.SelectStencilSetPerspective = {
facade: undefined,
extensions : undefined,
perspectives: undefined,
construct: function(facade) {
this.facade = facade;
var panel = new Ext.Panel({
cls:'selectssperspective',
border: false,
autoWidth:true,
autoScroll:true
});
var region = this.facade.addToRegion("west", panel);
var jsonObject = this.facade.getStencilSetExtensionDefinition();
/* Determine available extensions */
this.extensions = {};
jsonObject.extensions.each(function(ext) {
this.extensions[ext.namespace] = ext;
}.bind(this));
/* Determine available extensions */
this.perspectives = {};
jsonObject.perspectives.each(function(per) {
this.perspectives[per.namespace] = per;
}.bind(this));
this.facade.getStencilSets().values().each((function(sset) {
var validPerspectives = jsonObject.perspectives.findAll(function(perspective){
if(perspective.stencilset == sset.namespace()) return true;
else return false;
});
// If one perspective is defined, load this
if (validPerspectives.size() === 1) {
this.loadPerspective(validPerspectives.first().namespace);
// If more than one perspective is defined, add a combobox and load the first one
} else if (validPerspectives.size() > 1) {
this.createPerspectivesCombobox(panel, sset, validPerspectives);
}
}).bind(this));
},
createPerspectivesCombobox: function(panel, stencilset, perspectives) {
var lang = ORYX.I18N.Language.split("_").first();
var data = [];
perspectives.each(function(perspective) {
data.push([perspective.namespace, (perspective["title_"+lang]||perspective.title).unescapeHTML(), perspective["description_"+lang]||perspective.description]);
});
var store = new Ext.data.SimpleStore({
fields: ['namespace', 'title', 'tooltip'],
data: data
});
var combobox = new Ext.form.ComboBox({
store : store,
displayField : 'title',
valueField : 'namespace',
forceSelection : true,
typeAhead : true,
mode : 'local',
allowBlank : false,
autoWidth : true,
triggerAction : 'all',
emptyText : 'Select a perspective...',
selectOnFocus : true,
tpl : '<tpl for="."><div ext:qtip="{tooltip}" class="x-combo-list-item">{[(values.title||"").escapeHTML()]}</div></tpl>'
});
//panel.on("resize", function(){combobox.setWidth(panel.body.getWidth())});
panel.add(combobox);
panel.doLayout();
combobox.on('beforeselect', this.onSelect ,this)
this.facade.registerOnEvent(ORYX.CONFIG.EVENT_LOADED, function(){
this.facade.getStencilSets().values().each(function(stencilset) {
var ext = stencilset.extensions().values()
if (ext.length > 0){
var persp = perspectives.find(function(perspective){
return (perspective.extensions && perspective.extensions.include(ext[0].namespace)) || // Check if there is the extension part of the extension in the perspectives
(perspective.addExtensions && perspective.addExtensions.any(function(add){ return // OR Check if the namespace if part of the addExtension part
(add.ifIsLoaded === stencilset.namespace() && add.add == ext[0].namespace) ||
(add.ifIsLoaded !== stencilset.namespace() && add["default"] === ext[0].namespace) // OR is some in the default
})
)
})
if (!persp){
persp = perspectives.find(function(r){ return !(r.extensions instanceof Array) || r.extensions.length <= 0 })
}
if (persp) {
combobox.setValue(data[perspectives.indexOf(persp)][1]);
throw $break;
}
}
// Force to load extension
combobox.setValue(data[0][1]);
this.loadPerspective(data[0][0]);
}.bind(this));
}.bind(this))
},
onSelect: function(combobox, record) {
if (combobox.getValue() === record.get("namespace") || combobox.getValue() === record.get("title")){
return;
}
this.loadPerspective(record.json[0]);
},
loadPerspective: function(ns){
// If there is no namespace
if (!ns){
// unload all extensions
this._loadExtensions([], [], true);
return;
}
/* Get loaded stencil set extensions */
var stencilSets = this.facade.getStencilSets();
var loadedExtensions = new Object();
var perspective = this.perspectives[ns];
stencilSets.values().each(function(ss) {
ss.extensions().values().each(function(extension) {
if(this.extensions[extension.namespace])
loadedExtensions[extension.namespace] = extension;
}.bind(this));
}.bind(this));
/* Determine extensions that are required for this perspective */
var addExtensions = new Array();
if(perspective.addExtensions||perspective.extensions) {
[]
.concat(this.perspectives[ns].addExtensions||[])
.concat(this.perspectives[ns].extensions||[])
.compact()
.each(function(ext){
if(!ext.ifIsLoaded) {
addExtensions.push(this.extensions[ext]);
return;
}
if(loadedExtensions[ext.ifIsLoaded] && this.extensions[ext.add]) {
addExtensions.push(this.extensions[ext.add]);
} else {
if(ext["default"] && this.extensions[ext["default"]]) {
addExtensions.push(this.extensions[ext["default"]]);
}
}
}.bind(this));
}
/* Determine extension that are not allowed in this perspective */
/* Check if flag to remove all other extension is set */
if(this.perspectives[ns].removeAllExtensions) {
window.setTimeout(function(){
this._loadExtensions(addExtensions, undefined, true);
}.bind(this), 10);
return;
}
/* Check on specific extensions */
var removeExtensions = new Array();
if(perspective.removeExtensions) {
perspective.removeExtensions.each(function(ns){
if (loadedExtensions[ns])
removeExtensions.push(this.extensions[ns]);
}.bind(this));
}
if (perspective.extensions && !perspective.addExtensions && !perspective.removeExtensions) {
var combined = [].concat(addExtensions).concat(removeExtensions).compact();
$H(loadedExtensions).each(function(extension){
var key = extension.key;
if (!extension.value.includeAlways&&!combined.any(function(r){ return r.namespace == key })) {
removeExtensions.push(this.extensions[key]);
}
}.bind(this))
}
window.setTimeout(function(){
this._loadExtensions(addExtensions, removeExtensions, false);
}.bind(this), 10);
},
/*
* Load all stencil set extensions specified in param extensions (key map: String -> Object)
* Unload all other extensions (method copied from addssextension plugin)
*/
_loadExtensions: function(addExtensions, removeExtensions, removeAll) {
var stencilsets = this.facade.getStencilSets();
var atLeastOne = false;
// unload unselected extensions
stencilsets.values().each(function(stencilset) {
var unselected = stencilset.extensions().values().select(function(ext) { return addExtensions[ext.namespace] == undefined });
if(removeAll) {
unselected.each(function(ext) {
stencilset.removeExtension(ext.namespace);
atLeastOne = true;
});
} else {
unselected.each(function(ext) {
var remove = removeExtensions.find(function(remExt) {
return ext.namespace === remExt.namespace;
});
if(remove) {
stencilset.removeExtension(ext.namespace);
atLeastOne = true;
}
});
}
});
// load selected extensions
addExtensions.each(function(extension) {
var stencilset = stencilsets[extension["extends"]];
if(stencilset) {
// Load absolute
if ((extension.definition || "").startsWith("/")) {
stencilset.addExtension(extension.definition);
// Load relative
} else {
stencilset.addExtension(ORYX.CONFIG.SS_EXTENSIONS_FOLDER + extension.definition);
}
atLeastOne = true;
}
}.bind(this));
if (atLeastOne) {
stencilsets.values().each(function(stencilset) {
this.facade.getRules().initializeRules(stencilset);
}.bind(this));
this.facade.raiseEvent({
type: ORYX.CONFIG.EVENT_STENCIL_SET_LOADED
});
var selection = this.facade.getSelection();
this.facade.setSelection();
this.facade.setSelection(selection);
}
}
}
ORYX.Plugins.SelectStencilSetPerspective = Clazz.extend(ORYX.Plugins.SelectStencilSetPerspective);
| padmaragl/activiti-karaf | bpmn-webui-components/bpmn-webui-editor/src/main/scripts/Plugins/selectssperspective.js | JavaScript | apache-2.0 | 9,866 |
var module = module;
//this keeps the module file from doing anything inside the jasmine tests.
//We could avoid this by making all the source be in a specific directory, but that would break backwards compatibility.
if (module) {
module.exports = function (grunt) {
'use strict';
var config, debug, environment, spec;
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.registerTask('default', ['jasmine']);
spec = grunt.option('spec') || '*';
config = grunt.file.readJSON('config.json');
return grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jasmine: {
dev: {
src: "./*.js",
options: {
vendor:["https://rally1.rallydev.com/apps/"+config.sdk+"/sdk-debug.js"],
template: 'test/specs.tmpl',
specs: "test/**/" + spec + "Spec.js",
helpers: []
}
}
},
rallydeploy: {
options: {
server: config.server,
projectOid: 0,
deployFile: "deploy.json",
credentialsFile: "credentials.json",
timeboxFilter: "none"
},
prod: {
options: {
tab: "myhome",
pageName: config.name,
shared: false
}
}
}
});
};
} | sficarrotta/FeatureProgress | Gruntfile.js | JavaScript | mit | 1,601 |
import { CONSTANT_TAG, DirtyableTag } from 'glimmer-reference';
import { meta as metaFor } from './meta';
import require from 'require';
import { isProxy } from './is_proxy';
let hasViews = () => false;
export function setHasViews(fn) {
hasViews = fn;
}
function makeTag() {
return new DirtyableTag();
}
export function tagForProperty(object, propertyKey, _meta) {
if (isProxy(object)) {
return tagFor(object, _meta);
}
if (typeof object === 'object' && object) {
let meta = _meta || metaFor(object);
let tags = meta.writableTags();
let tag = tags[propertyKey];
if (tag) { return tag; }
return tags[propertyKey] = makeTag();
} else {
return CONSTANT_TAG;
}
}
export function tagFor(object, _meta) {
if (typeof object === 'object' && object) {
let meta = _meta || metaFor(object);
return meta.writableTag(makeTag);
} else {
return CONSTANT_TAG;
}
}
export function markObjectAsDirty(meta, propertyKey) {
let objectTag = meta && meta.readableTag();
if (objectTag) {
objectTag.dirty();
}
let tags = meta && meta.readableTags();
let propertyTag = tags && tags[propertyKey];
if (propertyTag) {
propertyTag.dirty();
}
if (objectTag || propertyTag) {
ensureRunloop();
}
}
let run;
function K() {}
function ensureRunloop() {
if (!run) {
run = require('ember-metal/run_loop').default;
}
if (hasViews() && !run.backburner.currentInstance) {
run.schedule('actions', K);
}
}
| kaeufl/ember.js | packages/ember-metal/lib/tags.js | JavaScript | mit | 1,485 |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'liststyle', 'fr', {
armenian: 'Numération arménienne',
bulletedTitle: 'Propriétés de la liste à puces',
circle: 'Cercle',
decimal: 'Décimal (1, 2, 3, etc.)',
decimalLeadingZero: 'Décimal précédé par un 0 (01, 02, 03, etc.)',
disc: 'Disque',
georgian: 'Numération géorgienne (an, ban, gan, etc.)',
lowerAlpha: 'Alphabétique minuscules (a, b, c, d, e, etc.)',
lowerGreek: 'Grec minuscule (alpha, beta, gamma, etc.)',
lowerRoman: 'Nombres romains minuscules (i, ii, iii, iv, v, etc.)',
none: 'Aucun',
notset: '<Non défini>',
numberedTitle: 'Propriétés de la liste numérotée',
square: 'Carré',
start: 'Début',
type: 'Type',
upperAlpha: 'Alphabétique majuscules (A, B, C, D, E, etc.)',
upperRoman: 'Nombres romains majuscules (I, II, III, IV, V, etc.)',
validateStartNumber: 'Le premier élément de la liste doit être un nombre entier.'
});
| webmasterETSI/web | web/ckeditor/plugins/liststyle/lang/fr.js | JavaScript | mit | 1,078 |
#!/usr/bin/env mocha -R spec
var assert = require("assert");
var msgpackJS = "../index";
var isBrowser = ("undefined" !== typeof window);
var msgpack = isBrowser && window.msgpack || require(msgpackJS);
var TITLE = __filename.replace(/^.*\//, "");
var HAS_UINT8ARRAY = ("undefined" !== typeof Uint8Array);
describe(TITLE, function() {
it("createCodec()", function() {
var codec = msgpack.createCodec();
var options = {codec: codec};
assert.ok(codec);
// this codec does not have preset codec
for (var i = 0; i < 256; i++) {
test(i);
}
function test(type) {
// fixext 1 -- 0xd4
var source = new Buffer([0xd4, type, type]);
var decoded = msgpack.decode(source, options);
assert.equal(decoded.type, type);
assert.equal(decoded.buffer.length, 1);
var encoded = msgpack.encode(decoded, options);
assert.deepEqual(toArray(encoded), toArray(source));
}
});
it("addExtPacker()", function() {
var codec = msgpack.createCodec();
codec.addExtPacker(0, MyClass, myClassPacker);
codec.addExtUnpacker(0, myClassUnpacker);
var options = {codec: codec};
[0, 1, 127, 255].forEach(test);
function test(type) {
var source = new MyClass(type);
var encoded = msgpack.encode(source, options);
var decoded = msgpack.decode(encoded, options);
assert.ok(decoded instanceof MyClass);
assert.equal(decoded.value, type);
}
});
// The safe mode works as same as the default mode. It'd be hard for test it.
it("createCodec({safe: true})", function() {
var options = {codec: msgpack.createCodec({safe: true})};
var source = 1;
var encoded = msgpack.encode(source, options);
var decoded = msgpack.decode(encoded, options);
assert.equal(decoded, source);
});
it("createCodec({preset: true})", function() {
var options1 = {codec: msgpack.createCodec({preset: true})};
var options2 = {codec: msgpack.createCodec({preset: false})};
var source = new Date();
var encoded = msgpack.encode(source, options1);
assert.equal(encoded[0], 0xC7, "preset ext format failure. (128 means map format)"); // ext 8
assert.equal(encoded[1], 0x09); // 1+8
assert.equal(encoded[2], 0x0D); // Date
// decode as Boolean instance
var decoded = msgpack.decode(encoded, options1);
assert.equal(decoded - 0, source - 0);
assert.ok(decoded instanceof Date);
// decode as ExtBuffer
decoded = msgpack.decode(encoded, options2);
assert.ok(!(decoded instanceof Date));
assert.equal(decoded.type, 0x0D);
});
});
function MyClass(value) {
this.value = value & 0xFF;
}
function myClassPacker(obj) {
return new Buffer([obj.value]);
}
function myClassUnpacker(buffer) {
return new MyClass(buffer[0]);
}
function toArray(array) {
if (HAS_UINT8ARRAY && array instanceof ArrayBuffer) array = new Uint8Array(array);
return Array.prototype.slice.call(array);
}
| february29/Learning | web/vue/AccountBook-Express/node_modules/msgpack-lite/test/14.codec.js | JavaScript | mit | 2,947 |
function dec(target, name, descriptor) {
assert(target);
assert.equal(typeof name, "string");
assert.equal(typeof descriptor, "object");
target.decoratedProps = (target.decoratedProps || []).concat([name]);
let initializer = descriptor.initializer;
return {
enumerable: name.indexOf('enum') !== -1,
configurable: name.indexOf('conf') !== -1,
writable: name.indexOf('write') !== -1,
initializer: function(...args){
return '__' + initializer.apply(this, args) + '__';
},
};
}
const inst = {
@dec
enumconfwrite: 1,
@dec
enumconf: 2,
@dec
enumwrite: 3,
@dec
enum: 4,
@dec
confwrite: 5,
@dec
conf: 6,
@dec
write: 7,
@dec
_: 8,
};
assert(inst.hasOwnProperty("decoratedProps"));
assert.deepEqual(inst.decoratedProps, [
"enumconfwrite",
"enumconf",
"enumwrite",
"enum",
"confwrite",
"conf",
"write",
"_",
]);
const descs = Object.getOwnPropertyDescriptors(inst);
assert(descs.enumconfwrite.enumerable);
assert(descs.enumconfwrite.writable);
assert(descs.enumconfwrite.configurable);
assert.equal(inst.enumconfwrite, "__1__");
assert(descs.enumconf.enumerable);
assert.equal(descs.enumconf.writable, false);
assert(descs.enumconf.configurable);
assert.equal(inst.enumconf, "__2__");
assert(descs.enumwrite.enumerable);
assert(descs.enumwrite.writable);
assert.equal(descs.enumwrite.configurable, false);
assert.equal(inst.enumwrite, "__3__");
assert(descs.enum.enumerable);
assert.equal(descs.enum.writable, false);
assert.equal(descs.enum.configurable, false);
assert.equal(inst.enum, "__4__");
assert.equal(descs.confwrite.enumerable, false);
assert(descs.confwrite.writable);
assert(descs.confwrite.configurable);
assert.equal(inst.confwrite, "__5__");
assert.equal(descs.conf.enumerable, false);
assert.equal(descs.conf.writable, false);
assert(descs.conf.configurable);
assert.equal(inst.conf, "__6__");
assert.equal(descs.write.enumerable, false);
assert(descs.write.writable);
assert.equal(descs.write.configurable, false);
assert.equal(inst.write, "__7__");
assert.equal(descs._.enumerable, false);
assert.equal(descs._.writable, false);
assert.equal(descs._.configurable, false);
assert.equal(inst._, "__8__");
| ccschneidr/babel | packages/babel-plugin-transform-decorators/test/fixtures/object-properties/return-descriptor/exec.js | JavaScript | mit | 2,219 |
/*
Highcharts JS v6.1.1 (2018-06-27)
Plugin for displaying a message when there is no data visible in chart.
(c) 2010-2017 Highsoft AS
Author: Oystein Moseng
License: www.highcharts.com/license
*/
(function(d){"object"===typeof module&&module.exports?module.exports=d:d(Highcharts)})(function(d){(function(c){var d=c.seriesTypes,e=c.Chart.prototype,f=c.getOptions(),g=c.extend,h=c.each;g(f.lang,{noData:"No data to display"});f.noData={position:{x:0,y:0,align:"center",verticalAlign:"middle"}};h("bubble gauge heatmap pie sankey treemap waterfall".split(" "),function(b){d[b]&&(d[b].prototype.hasData=function(){return!!this.points.length})});c.Series.prototype.hasData=function(){return this.visible&&
void 0!==this.dataMax&&void 0!==this.dataMin};e.showNoData=function(b){var a=this.options;b=b||a&&a.lang.noData;a=a&&a.noData;!this.noDataLabel&&this.renderer&&(this.noDataLabel=this.renderer.label(b,0,0,null,null,null,a.useHTML,null,"no-data"),this.noDataLabel.add(),this.noDataLabel.align(g(this.noDataLabel.getBBox(),a.position),!1,"plotBox"))};e.hideNoData=function(){this.noDataLabel&&(this.noDataLabel=this.noDataLabel.destroy())};e.hasData=function(){for(var b=this.series||[],a=b.length;a--;)if(b[a].hasData()&&
!b[a].options.isInternal)return!0;return this.loadingShown};c.addEvent(c.Chart,"render",function(){this.hasData()?this.hideNoData():this.showNoData()})})(d)});
| seogi1004/cdnjs | ajax/libs/highcharts/6.1.1/js/modules/no-data-to-display.js | JavaScript | mit | 1,390 |
/**
* @license
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash -o ./dist/lodash.compat.js`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license>
*/
;(function() {
/** Used as a safe reference for `undefined` in pre ES5 environments */
var undefined;
/** Used to pool arrays and objects used internally */
var arrayPool = [],
objectPool = [];
/** Used to generate unique IDs */
var idCounter = 0;
/** Used internally to indicate various things */
var indicatorObject = {};
/** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */
var keyPrefix = +new Date + '';
/** Used as the size when optimizations are enabled for large arrays */
var largeArraySize = 75;
/** Used as the max size of the `arrayPool` and `objectPool` */
var maxPoolSize = 40;
/** Used to detect and test whitespace */
var whitespace = (
// whitespace
' \t\x0B\f\xA0\ufeff' +
// line terminators
'\n\r\u2028\u2029' +
// unicode category "Zs" space separators
'\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'
);
/** Used to match empty string literals in compiled template source */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
/**
* Used to match ES6 template delimiters
* http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals
*/
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
/** Used to match regexp flags from their coerced string values */
var reFlags = /\w*$/;
/** Used to detected named functions */
var reFuncName = /^\s*function[ \n\r\t]+\w/;
/** Used to match "interpolate" template delimiters */
var reInterpolate = /<%=([\s\S]+?)%>/g;
/** Used to match leading whitespace and zeros to be removed */
var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)');
/** Used to ensure capturing order of template delimiters */
var reNoMatch = /($^)/;
/** Used to detect functions containing a `this` reference */
var reThis = /\bthis\b/;
/** Used to match unescaped characters in compiled string literals */
var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
/** Used to assign default `context` object properties */
var contextProps = [
'Array', 'Boolean', 'Date', 'Error', 'Function', 'Math', 'Number', 'Object',
'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN',
'parseInt', 'setTimeout'
];
/** Used to fix the JScript [[DontEnum]] bug */
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
'toLocaleString', 'toString', 'valueOf'
];
/** Used to make template sourceURLs easier to identify */
var templateCounter = 0;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
/** Used to identify object classifications that `_.clone` supports */
var cloneableClasses = {};
cloneableClasses[funcClass] = false;
cloneableClasses[argsClass] = cloneableClasses[arrayClass] =
cloneableClasses[boolClass] = cloneableClasses[dateClass] =
cloneableClasses[numberClass] = cloneableClasses[objectClass] =
cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true;
/** Used as an internal `_.debounce` options object */
var debounceOptions = {
'leading': false,
'maxWait': 0,
'trailing': false
};
/** Used as the property descriptor for `__bindData__` */
var descriptor = {
'configurable': false,
'enumerable': false,
'value': null,
'writable': false
};
/** Used as the data object for `iteratorTemplate` */
var iteratorData = {
'args': '',
'array': null,
'bottom': '',
'firstArg': '',
'init': '',
'keys': null,
'loop': '',
'shadowedProps': null,
'support': null,
'top': '',
'useHas': false
};
/** Used to determine if values are of the language type Object */
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
/** Used to escape characters for inclusion in compiled string literals */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/** Used as a reference to the global object */
var root = (objectTypes[typeof window] && window) || this;
/** Detect free variable `exports` */
var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
/** Detect free variable `module` */
var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports` */
var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
/** Detect free variable `global` from Node.js or Browserified code and use it as `root` */
var freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
/*--------------------------------------------------------------------------*/
/**
* The base implementation of `_.indexOf` without support for binary searches
* or `fromIndex` constraints.
*
* @private
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value or `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
var index = (fromIndex || 0) - 1,
length = array ? array.length : 0;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* An implementation of `_.contains` for cache objects that mimics the return
* signature of `_.indexOf` by returning `0` if the value is found, else `-1`.
*
* @private
* @param {Object} cache The cache object to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns `0` if `value` is found, else `-1`.
*/
function cacheIndexOf(cache, value) {
var type = typeof value;
cache = cache.cache;
if (type == 'boolean' || value == null) {
return cache[value] ? 0 : -1;
}
if (type != 'number' && type != 'string') {
type = 'object';
}
var key = type == 'number' ? value : keyPrefix + value;
cache = (cache = cache[type]) && cache[key];
return type == 'object'
? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1)
: (cache ? 0 : -1);
}
/**
* Adds a given value to the corresponding cache object.
*
* @private
* @param {*} value The value to add to the cache.
*/
function cachePush(value) {
var cache = this.cache,
type = typeof value;
if (type == 'boolean' || value == null) {
cache[value] = true;
} else {
if (type != 'number' && type != 'string') {
type = 'object';
}
var key = type == 'number' ? value : keyPrefix + value,
typeCache = cache[type] || (cache[type] = {});
if (type == 'object') {
(typeCache[key] || (typeCache[key] = [])).push(value);
} else {
typeCache[key] = true;
}
}
}
/**
* Used by `_.max` and `_.min` as the default callback when a given
* collection is a string value.
*
* @private
* @param {string} value The character to inspect.
* @returns {number} Returns the code unit of given character.
*/
function charAtCallback(value) {
return value.charCodeAt(0);
}
/**
* Used by `sortBy` to compare transformed `collection` elements, stable sorting
* them in ascending order.
*
* @private
* @param {Object} a The object to compare to `b`.
* @param {Object} b The object to compare to `a`.
* @returns {number} Returns the sort order indicator of `1` or `-1`.
*/
function compareAscending(a, b) {
var ac = a.criteria,
bc = b.criteria,
index = -1,
length = ac.length;
while (++index < length) {
var value = ac[index],
other = bc[index];
if (value !== other) {
if (value > other || typeof value == 'undefined') {
return 1;
}
if (value < other || typeof other == 'undefined') {
return -1;
}
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to return the same value for
// `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247
//
// This also ensures a stable sort in V8 and other engines.
// See http://code.google.com/p/v8/issues/detail?id=90
return a.index - b.index;
}
/**
* Creates a cache object to optimize linear searches of large arrays.
*
* @private
* @param {Array} [array=[]] The array to search.
* @returns {null|Object} Returns the cache object or `null` if caching should not be used.
*/
function createCache(array) {
var index = -1,
length = array.length,
first = array[0],
mid = array[(length / 2) | 0],
last = array[length - 1];
if (first && typeof first == 'object' &&
mid && typeof mid == 'object' && last && typeof last == 'object') {
return false;
}
var cache = getObject();
cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;
var result = getObject();
result.array = array;
result.cache = cache;
result.push = cachePush;
while (++index < length) {
result.push(array[index]);
}
return result;
}
/**
* Used by `template` to escape characters for inclusion in compiled
* string literals.
*
* @private
* @param {string} match The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeStringChar(match) {
return '\\' + stringEscapes[match];
}
/**
* Gets an array from the array pool or creates a new one if the pool is empty.
*
* @private
* @returns {Array} The array from the pool.
*/
function getArray() {
return arrayPool.pop() || [];
}
/**
* Gets an object from the object pool or creates a new one if the pool is empty.
*
* @private
* @returns {Object} The object from the pool.
*/
function getObject() {
return objectPool.pop() || {
'array': null,
'cache': null,
'criteria': null,
'false': false,
'index': 0,
'null': false,
'number': null,
'object': null,
'push': null,
'string': null,
'true': false,
'undefined': false,
'value': null
};
}
/**
* Checks if `value` is a DOM node in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a DOM node, else `false`.
*/
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
/**
* Releases the given array back to the array pool.
*
* @private
* @param {Array} [array] The array to release.
*/
function releaseArray(array) {
array.length = 0;
if (arrayPool.length < maxPoolSize) {
arrayPool.push(array);
}
}
/**
* Releases the given object back to the object pool.
*
* @private
* @param {Object} [object] The object to release.
*/
function releaseObject(object) {
var cache = object.cache;
if (cache) {
releaseObject(cache);
}
object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null;
if (objectPool.length < maxPoolSize) {
objectPool.push(object);
}
}
/**
* Slices the `collection` from the `start` index up to, but not including,
* the `end` index.
*
* Note: This function is used instead of `Array#slice` to support node lists
* in IE < 9 and to ensure dense arrays are returned.
*
* @private
* @param {Array|Object|string} collection The collection to slice.
* @param {number} start The start index.
* @param {number} end The end index.
* @returns {Array} Returns the new array.
*/
function slice(array, start, end) {
start || (start = 0);
if (typeof end == 'undefined') {
end = array ? array.length : 0;
}
var index = -1,
length = end - start || 0,
result = Array(length < 0 ? 0 : length);
while (++index < length) {
result[index] = array[start + index];
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Create a new `lodash` function using the given context object.
*
* @static
* @memberOf _
* @category Utilities
* @param {Object} [context=root] The context object.
* @returns {Function} Returns the `lodash` function.
*/
function runInContext(context) {
// Avoid issues with some ES3 environments that attempt to use values, named
// after built-in constructors like `Object`, for the creation of literals.
// ES5 clears this up by stating that literals must use built-in constructors.
// See http://es5.github.io/#x11.1.5.
context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
/** Native constructor references */
var Array = context.Array,
Boolean = context.Boolean,
Date = context.Date,
Error = context.Error,
Function = context.Function,
Math = context.Math,
Number = context.Number,
Object = context.Object,
RegExp = context.RegExp,
String = context.String,
TypeError = context.TypeError;
/**
* Used for `Array` method references.
*
* Normally `Array.prototype` would suffice, however, using an array literal
* avoids issues in Narwhal.
*/
var arrayRef = [];
/** Used for native method references */
var errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype;
/** Used to restore the original `_` reference in `noConflict` */
var oldDash = context._;
/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;
/** Used to detect if a method is native */
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
/** Native method shortcuts */
var ceil = Math.ceil,
clearTimeout = context.clearTimeout,
floor = Math.floor,
fnToString = Function.prototype.toString,
getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,
hasOwnProperty = objectProto.hasOwnProperty,
push = arrayRef.push,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
setTimeout = context.setTimeout,
splice = arrayRef.splice,
unshift = arrayRef.unshift;
/** Used to set meta data on functions */
var defineProperty = (function() {
// IE 8 only accepts DOM elements
try {
var o = {},
func = isNative(func = Object.defineProperty) && func,
result = func(o, o, o) && func;
} catch(e) { }
return result;
}());
/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate,
nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray,
nativeIsFinite = context.isFinite,
nativeIsNaN = context.isNaN,
nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys,
nativeMax = Math.max,
nativeMin = Math.min,
nativeParseInt = context.parseInt,
nativeRandom = Math.random;
/** Used to lookup a built-in constructor by [[Class]] */
var ctorByClass = {};
ctorByClass[arrayClass] = Array;
ctorByClass[boolClass] = Boolean;
ctorByClass[dateClass] = Date;
ctorByClass[funcClass] = Function;
ctorByClass[objectClass] = Object;
ctorByClass[numberClass] = Number;
ctorByClass[regexpClass] = RegExp;
ctorByClass[stringClass] = String;
/** Used to avoid iterating non-enumerable properties in IE < 9 */
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
(function() {
var length = shadowedProps.length;
while (length--) {
var key = shadowedProps[length];
for (var className in nonEnumProps) {
if (hasOwnProperty.call(nonEnumProps, className) && !hasOwnProperty.call(nonEnumProps[className], key)) {
nonEnumProps[className][key] = false;
}
}
}
}());
/*--------------------------------------------------------------------------*/
/**
* Creates a `lodash` object which wraps the given value to enable intuitive
* method chaining.
*
* In addition to Lo-Dash methods, wrappers also have the following `Array` methods:
* `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
* and `unshift`
*
* Chaining is supported in custom builds as long as the `value` method is
* implicitly or explicitly included in the build.
*
* The chainable wrapper functions are:
* `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`,
* `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`,
* `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`,
* `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
* `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
* `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`,
* `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`,
* `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`,
* `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`,
* `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`,
* and `zip`
*
* The non-chainable wrapper functions are:
* `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`,
* `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`,
* `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
* `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`,
* `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`,
* `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`,
* `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`,
* `template`, `unescape`, `uniqueId`, and `value`
*
* The wrapper functions `first` and `last` return wrapped values when `n` is
* provided, otherwise they return unwrapped values.
*
* Explicit chaining can be enabled by using the `_.chain` method.
*
* @name _
* @constructor
* @category Chaining
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns a `lodash` instance.
* @example
*
* var wrapped = _([1, 2, 3]);
*
* // returns an unwrapped value
* wrapped.reduce(function(sum, num) {
* return sum + num;
* });
* // => 6
*
* // returns a wrapped value
* var squares = wrapped.map(function(num) {
* return num * num;
* });
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
// don't wrap if already wrapped, even if wrapped by a different `lodash` constructor
return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__'))
? value
: new lodashWrapper(value);
}
/**
* A fast path for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap in a `lodash` instance.
* @param {boolean} chainAll A flag to enable chaining for all methods
* @returns {Object} Returns a `lodash` instance.
*/
function lodashWrapper(value, chainAll) {
this.__chain__ = !!chainAll;
this.__wrapped__ = value;
}
// ensure `new lodashWrapper` is an instance of `lodash`
lodashWrapper.prototype = lodash.prototype;
/**
* An object used to flag environments features.
*
* @static
* @memberOf _
* @type Object
*/
var support = lodash.support = {};
(function() {
var ctor = function() { this.x = 1; },
object = { '0': 1, 'length': 1 },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
/**
* Detect if an `arguments` object's [[Class]] is resolvable (all but Firefox < 4, IE < 9).
*
* @memberOf _.support
* @type boolean
*/
support.argsClass = toString.call(arguments) == argsClass;
/**
* Detect if `arguments` objects are `Object` objects (all but Narwhal and Opera < 10.5).
*
* @memberOf _.support
* @type boolean
*/
support.argsObject = arguments.constructor == Object && !(arguments instanceof Array);
/**
* Detect if `name` or `message` properties of `Error.prototype` are
* enumerable by default. (IE < 9, Safari < 5.1)
*
* @memberOf _.support
* @type boolean
*/
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
/**
* Detect if `prototype` properties are enumerable by default.
*
* Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
* (if the prototype or a property on the prototype has been set)
* incorrectly sets a function's `prototype` property [[Enumerable]]
* value to `true`.
*
* @memberOf _.support
* @type boolean
*/
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
/**
* Detect if functions can be decompiled by `Function#toString`
* (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps).
*
* @memberOf _.support
* @type boolean
*/
support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext);
/**
* Detect if `Function#name` is supported (all but IE).
*
* @memberOf _.support
* @type boolean
*/
support.funcNames = typeof Function.name == 'string';
/**
* Detect if `arguments` object indexes are non-enumerable
* (Firefox < 4, IE < 9, PhantomJS, Safari < 5.1).
*
* @memberOf _.support
* @type boolean
*/
support.nonEnumArgs = key != 0;
/**
* Detect if properties shadowing those on `Object.prototype` are non-enumerable.
*
* In IE < 9 an objects own properties, shadowing non-enumerable ones, are
* made non-enumerable as well (a.k.a the JScript [[DontEnum]] bug).
*
* @memberOf _.support
* @type boolean
*/
support.nonEnumShadows = !/valueOf/.test(props);
/**
* Detect if own properties are iterated after inherited properties (all but IE < 9).
*
* @memberOf _.support
* @type boolean
*/
support.ownLast = props[0] != 'x';
/**
* Detect if `Array#shift` and `Array#splice` augment array-like objects correctly.
*
* Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()`
* and `splice()` functions that fail to remove the last element, `value[0]`,
* of array-like objects even though the `length` property is set to `0`.
* The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
* is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
*
* @memberOf _.support
* @type boolean
*/
support.spliceObjects = (arrayRef.splice.call(object, 0, 1), !object[0]);
/**
* Detect lack of support for accessing string characters by index.
*
* IE < 8 can't access characters by index and IE 8 can only access
* characters by index on string literals.
*
* @memberOf _.support
* @type boolean
*/
support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx';
/**
* Detect if a DOM node's [[Class]] is resolvable (all but IE < 9)
* and that the JS engine errors when attempting to coerce an object to
* a string without a `toString` function.
*
* @memberOf _.support
* @type boolean
*/
try {
support.nodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
support.nodeClass = true;
}
}(1));
/**
* By default, the template delimiters used by Lo-Dash are similar to those in
* embedded Ruby (ERB). Change the following template settings to use alternative
* delimiters.
*
* @static
* @memberOf _
* @type Object
*/
lodash.templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'escape': /<%-([\s\S]+?)%>/g,
/**
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'evaluate': /<%([\s\S]+?)%>/g,
/**
* Used to detect `data` property values to inject.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'interpolate': reInterpolate,
/**
* Used to reference the data object in the template text.
*
* @memberOf _.templateSettings
* @type string
*/
'variable': '',
/**
* Used to import variables into the compiled template.
*
* @memberOf _.templateSettings
* @type Object
*/
'imports': {
/**
* A reference to the `lodash` function.
*
* @memberOf _.templateSettings.imports
* @type Function
*/
'_': lodash
}
};
/*--------------------------------------------------------------------------*/
/**
* The template used to create iterator functions.
*
* @private
* @param {Object} data The data object used to populate the text.
* @returns {string} Returns the interpolated text.
*/
var iteratorTemplate = function(obj) {
var __p = 'var index, iterable = ' +
(obj.firstArg) +
', result = ' +
(obj.init) +
';\nif (!iterable) return result;\n' +
(obj.top) +
';';
if (obj.array) {
__p += '\nvar length = iterable.length; index = -1;\nif (' +
(obj.array) +
') { ';
if (support.unindexedChars) {
__p += '\n if (isString(iterable)) {\n iterable = iterable.split(\'\')\n } ';
}
__p += '\n while (++index < length) {\n ' +
(obj.loop) +
';\n }\n}\nelse { ';
} else if (support.nonEnumArgs) {
__p += '\n var length = iterable.length; index = -1;\n if (length && isArguments(iterable)) {\n while (++index < length) {\n index += \'\';\n ' +
(obj.loop) +
';\n }\n } else { ';
}
if (support.enumPrototypes) {
__p += '\n var skipProto = typeof iterable == \'function\';\n ';
}
if (support.enumErrorProps) {
__p += '\n var skipErrorProps = iterable === errorProto || iterable instanceof Error;\n ';
}
var conditions = []; if (support.enumPrototypes) { conditions.push('!(skipProto && index == "prototype")'); } if (support.enumErrorProps) { conditions.push('!(skipErrorProps && (index == "message" || index == "name"))'); }
if (obj.useHas && obj.keys) {
__p += '\n var ownIndex = -1,\n ownProps = objectTypes[typeof iterable] && keys(iterable),\n length = ownProps ? ownProps.length : 0;\n\n while (++ownIndex < length) {\n index = ownProps[ownIndex];\n';
if (conditions.length) {
__p += ' if (' +
(conditions.join(' && ')) +
') {\n ';
}
__p +=
(obj.loop) +
'; ';
if (conditions.length) {
__p += '\n }';
}
__p += '\n } ';
} else {
__p += '\n for (index in iterable) {\n';
if (obj.useHas) { conditions.push("hasOwnProperty.call(iterable, index)"); } if (conditions.length) {
__p += ' if (' +
(conditions.join(' && ')) +
') {\n ';
}
__p +=
(obj.loop) +
'; ';
if (conditions.length) {
__p += '\n }';
}
__p += '\n } ';
if (support.nonEnumShadows) {
__p += '\n\n if (iterable !== objectProto) {\n var ctor = iterable.constructor,\n isProto = iterable === (ctor && ctor.prototype),\n className = iterable === stringProto ? stringClass : iterable === errorProto ? errorClass : toString.call(iterable),\n nonEnum = nonEnumProps[className];\n ';
for (k = 0; k < 7; k++) {
__p += '\n index = \'' +
(obj.shadowedProps[k]) +
'\';\n if ((!(isProto && nonEnum[index]) && hasOwnProperty.call(iterable, index))';
if (!obj.useHas) {
__p += ' || (!nonEnum[index] && iterable[index] !== objectProto[index])';
}
__p += ') {\n ' +
(obj.loop) +
';\n } ';
}
__p += '\n } ';
}
}
if (obj.array || support.nonEnumArgs) {
__p += '\n}';
}
__p +=
(obj.bottom) +
';\nreturn result';
return __p
};
/*--------------------------------------------------------------------------*/
/**
* The base implementation of `_.bind` that creates the bound function and
* sets its meta data.
*
* @private
* @param {Array} bindData The bind data array.
* @returns {Function} Returns the new bound function.
*/
function baseBind(bindData) {
var func = bindData[0],
partialArgs = bindData[2],
thisArg = bindData[4];
function bound() {
// `Function#bind` spec
// http://es5.github.io/#x15.3.4.5
if (partialArgs) {
// avoid `arguments` object deoptimizations by using `slice` instead
// of `Array.prototype.slice.call` and not assigning `arguments` to a
// variable as a ternary expression
var args = slice(partialArgs);
push.apply(args, arguments);
}
// mimic the constructor's `return` behavior
// http://es5.github.io/#x13.2.2
if (this instanceof bound) {
// ensure `new bound` is an instance of `func`
var thisBinding = baseCreate(func.prototype),
result = func.apply(thisBinding, args || arguments);
return isObject(result) ? result : thisBinding;
}
return func.apply(thisArg, args || arguments);
}
setBindData(bound, bindData);
return bound;
}
/**
* The base implementation of `_.clone` without argument juggling or support
* for `thisArg` binding.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} [isDeep=false] Specify a deep clone.
* @param {Function} [callback] The function to customize cloning values.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates clones with source counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, isDeep, callback, stackA, stackB) {
if (callback) {
var result = callback(value);
if (typeof result != 'undefined') {
return result;
}
}
// inspect [[Class]]
var isObj = isObject(value);
if (isObj) {
var className = toString.call(value);
if (!cloneableClasses[className] || (!support.nodeClass && isNode(value))) {
return value;
}
var ctor = ctorByClass[className];
switch (className) {
case boolClass:
case dateClass:
return new ctor(+value);
case numberClass:
case stringClass:
return new ctor(value);
case regexpClass:
result = ctor(value.source, reFlags.exec(value));
result.lastIndex = value.lastIndex;
return result;
}
} else {
return value;
}
var isArr = isArray(value);
if (isDeep) {
// check for circular references and return corresponding clone
var initedStack = !stackA;
stackA || (stackA = getArray());
stackB || (stackB = getArray());
var length = stackA.length;
while (length--) {
if (stackA[length] == value) {
return stackB[length];
}
}
result = isArr ? ctor(value.length) : {};
}
else {
result = isArr ? slice(value) : assign({}, value);
}
// add array properties assigned by `RegExp#exec`
if (isArr) {
if (hasOwnProperty.call(value, 'index')) {
result.index = value.index;
}
if (hasOwnProperty.call(value, 'input')) {
result.input = value.input;
}
}
// exit for shallow clone
if (!isDeep) {
return result;
}
// add the source value to the stack of traversed objects
// and associate it with its clone
stackA.push(value);
stackB.push(result);
// recursively populate clone (susceptible to call stack limits)
(isArr ? baseEach : forOwn)(value, function(objValue, key) {
result[key] = baseClone(objValue, isDeep, callback, stackA, stackB);
});
if (initedStack) {
releaseArray(stackA);
releaseArray(stackB);
}
return result;
}
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} prototype The object to inherit from.
* @returns {Object} Returns the new object.
*/
function baseCreate(prototype, properties) {
return isObject(prototype) ? nativeCreate(prototype) : {};
}
// fallback for browsers without `Object.create`
if (!nativeCreate) {
baseCreate = (function() {
function Object() {}
return function(prototype) {
if (isObject(prototype)) {
Object.prototype = prototype;
var result = new Object;
Object.prototype = null;
}
return result || context.Object();
};
}());
}
/**
* The base implementation of `_.createCallback` without support for creating
* "_.pluck" or "_.where" style callbacks.
*
* @private
* @param {*} [func=identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of the created callback.
* @param {number} [argCount] The number of arguments the callback accepts.
* @returns {Function} Returns a callback function.
*/
function baseCreateCallback(func, thisArg, argCount) {
if (typeof func != 'function') {
return identity;
}
// exit early for no `thisArg` or already bound by `Function#bind`
if (typeof thisArg == 'undefined' || !('prototype' in func)) {
return func;
}
var bindData = func.__bindData__;
if (typeof bindData == 'undefined') {
if (support.funcNames) {
bindData = !func.name;
}
bindData = bindData || !support.funcDecomp;
if (!bindData) {
var source = fnToString.call(func);
if (!support.funcNames) {
bindData = !reFuncName.test(source);
}
if (!bindData) {
// checks if `func` references the `this` keyword and stores the result
bindData = reThis.test(source);
setBindData(func, bindData);
}
}
}
// exit early if there are no `this` references or `func` is bound
if (bindData === false || (bindData !== true && bindData[1] & 1)) {
return func;
}
switch (argCount) {
case 1: return function(value) {
return func.call(thisArg, value);
};
case 2: return function(a, b) {
return func.call(thisArg, a, b);
};
case 3: return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(thisArg, accumulator, value, index, collection);
};
}
return bind(func, thisArg);
}
/**
* The base implementation of `createWrapper` that creates the wrapper and
* sets its meta data.
*
* @private
* @param {Array} bindData The bind data array.
* @returns {Function} Returns the new function.
*/
function baseCreateWrapper(bindData) {
var func = bindData[0],
bitmask = bindData[1],
partialArgs = bindData[2],
partialRightArgs = bindData[3],
thisArg = bindData[4],
arity = bindData[5];
var isBind = bitmask & 1,
isBindKey = bitmask & 2,
isCurry = bitmask & 4,
isCurryBound = bitmask & 8,
key = func;
function bound() {
var thisBinding = isBind ? thisArg : this;
if (partialArgs) {
var args = slice(partialArgs);
push.apply(args, arguments);
}
if (partialRightArgs || isCurry) {
args || (args = slice(arguments));
if (partialRightArgs) {
push.apply(args, partialRightArgs);
}
if (isCurry && args.length < arity) {
bitmask |= 16 & ~32;
return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]);
}
}
args || (args = arguments);
if (isBindKey) {
func = thisBinding[key];
}
if (this instanceof bound) {
thisBinding = baseCreate(func.prototype);
var result = func.apply(thisBinding, args);
return isObject(result) ? result : thisBinding;
}
return func.apply(thisBinding, args);
}
setBindData(bound, bindData);
return bound;
}
/**
* The base implementation of `_.difference` that accepts a single array
* of values to exclude.
*
* @private
* @param {Array} array The array to process.
* @param {Array} [values] The array of values to exclude.
* @returns {Array} Returns a new array of filtered values.
*/
function baseDifference(array, values) {
var index = -1,
indexOf = getIndexOf(),
length = array ? array.length : 0,
isLarge = length >= largeArraySize && indexOf === baseIndexOf,
result = [];
if (isLarge) {
var cache = createCache(values);
if (cache) {
indexOf = cacheIndexOf;
values = cache;
} else {
isLarge = false;
}
}
while (++index < length) {
var value = array[index];
if (indexOf(values, value) < 0) {
result.push(value);
}
}
if (isLarge) {
releaseObject(values);
}
return result;
}
/**
* The base implementation of `_.flatten` without support for callback
* shorthands or `thisArg` binding.
*
* @private
* @param {Array} array The array to flatten.
* @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
* @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects.
* @param {number} [fromIndex=0] The index to start from.
* @returns {Array} Returns a new flattened array.
*/
function baseFlatten(array, isShallow, isStrict, fromIndex) {
var index = (fromIndex || 0) - 1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (value && typeof value == 'object' && typeof value.length == 'number'
&& (isArray(value) || isArguments(value))) {
// recursively flatten arrays (susceptible to call stack limits)
if (!isShallow) {
value = baseFlatten(value, isShallow, isStrict);
}
var valIndex = -1,
valLength = value.length,
resIndex = result.length;
result.length += valLength;
while (++valIndex < valLength) {
result[resIndex++] = value[valIndex];
}
} else if (!isStrict) {
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.isEqual`, without support for `thisArg` binding,
* that allows partial "_.where" style comparisons.
*
* @private
* @param {*} a The value to compare.
* @param {*} b The other value to compare.
* @param {Function} [callback] The function to customize comparing values.
* @param {Function} [isWhere=false] A flag to indicate performing partial comparisons.
* @param {Array} [stackA=[]] Tracks traversed `a` objects.
* @param {Array} [stackB=[]] Tracks traversed `b` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(a, b, callback, isWhere, stackA, stackB) {
// used to indicate that when comparing objects, `a` has at least the properties of `b`
if (callback) {
var result = callback(a, b);
if (typeof result != 'undefined') {
return !!result;
}
}
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a &&
!(a && objectTypes[type]) &&
!(b && objectTypes[otherType])) {
return false;
}
// exit early for `null` and `undefined` avoiding ES3's Function#call behavior
// http://es5.github.io/#x15.3.4.4
if (a == null || b == null) {
return a === b;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `+0` vs. `-0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// unwrap any `lodash` wrapped values
var aWrapped = hasOwnProperty.call(a, '__wrapped__'),
bWrapped = hasOwnProperty.call(b, '__wrapped__');
if (aWrapped || bWrapped) {
return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB);
}
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = getArray());
stackB || (stackB = getArray());
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result || isWhere) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (isWhere) {
while (index--) {
if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) {
break;
}
}
} else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
forIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB));
}
});
if (result && !isWhere) {
// ensure both objects have the same number of properties
forIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
if (initedStack) {
releaseArray(stackA);
releaseArray(stackB);
}
return result;
}
/**
* The base implementation of `_.merge` without argument juggling or support
* for `thisArg` binding.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} [callback] The function to customize merging properties.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
*/
function baseMerge(object, source, callback, stackA, stackB) {
(isArray(source) ? forEach : forOwn)(source, function(source, key) {
var found,
isArr,
result = source,
value = object[key];
if (source && ((isArr = isArray(source)) || isPlainObject(source))) {
// avoid merging previously merged cyclic sources
var stackLength = stackA.length;
while (stackLength--) {
if ((found = stackA[stackLength] == source)) {
value = stackB[stackLength];
break;
}
}
if (!found) {
var isShallow;
if (callback) {
result = callback(value, source);
if ((isShallow = typeof result != 'undefined')) {
value = result;
}
}
if (!isShallow) {
value = isArr
? (isArray(value) ? value : [])
: (isPlainObject(value) ? value : {});
}
// add `source` and associated `value` to the stack of traversed objects
stackA.push(source);
stackB.push(value);
// recursively merge objects and arrays (susceptible to call stack limits)
if (!isShallow) {
baseMerge(value, source, callback, stackA, stackB);
}
}
}
else {
if (callback) {
result = callback(value, source);
if (typeof result == 'undefined') {
result = source;
}
}
if (typeof result != 'undefined') {
value = result;
}
}
object[key] = value;
});
}
/**
* The base implementation of `_.random` without argument juggling or support
* for returning floating-point numbers.
*
* @private
* @param {number} min The minimum possible value.
* @param {number} max The maximum possible value.
* @returns {number} Returns a random number.
*/
function baseRandom(min, max) {
return min + floor(nativeRandom() * (max - min + 1));
}
/**
* The base implementation of `_.uniq` without support for callback shorthands
* or `thisArg` binding.
*
* @private
* @param {Array} array The array to process.
* @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
* @param {Function} [callback] The function called per iteration.
* @returns {Array} Returns a duplicate-value-free array.
*/
function baseUniq(array, isSorted, callback) {
var index = -1,
indexOf = getIndexOf(),
length = array ? array.length : 0,
result = [];
var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf,
seen = (callback || isLarge) ? getArray() : result;
if (isLarge) {
var cache = createCache(seen);
indexOf = cacheIndexOf;
seen = cache;
}
while (++index < length) {
var value = array[index],
computed = callback ? callback(value, index, array) : value;
if (isSorted
? !index || seen[seen.length - 1] !== computed
: indexOf(seen, computed) < 0
) {
if (callback || isLarge) {
seen.push(computed);
}
result.push(value);
}
}
if (isLarge) {
releaseArray(seen.array);
releaseObject(seen);
} else if (callback) {
releaseArray(seen);
}
return result;
}
/**
* Creates a function that aggregates a collection, creating an object composed
* of keys generated from the results of running each element of the collection
* through a callback. The given `setter` function sets the keys and values
* of the composed object.
*
* @private
* @param {Function} setter The setter function.
* @returns {Function} Returns the new aggregator function.
*/
function createAggregator(setter) {
return function(collection, callback, thisArg) {
var result = {};
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
setter(result, value, callback(value, index, collection), collection);
}
} else {
baseEach(collection, function(value, key, collection) {
setter(result, value, callback(value, key, collection), collection);
});
}
return result;
};
}
/**
* Creates a function that, when called, either curries or invokes `func`
* with an optional `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to reference.
* @param {number} bitmask The bitmask of method flags to compose.
* The bitmask may be composed of the following flags:
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry`
* 8 - `_.curry` (bound)
* 16 - `_.partial`
* 32 - `_.partialRight`
* @param {Array} [partialArgs] An array of arguments to prepend to those
* provided to the new function.
* @param {Array} [partialRightArgs] An array of arguments to append to those
* provided to the new function.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new function.
*/
function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) {
var isBind = bitmask & 1,
isBindKey = bitmask & 2,
isCurry = bitmask & 4,
isCurryBound = bitmask & 8,
isPartial = bitmask & 16,
isPartialRight = bitmask & 32;
if (!isBindKey && !isFunction(func)) {
throw new TypeError;
}
if (isPartial && !partialArgs.length) {
bitmask &= ~16;
isPartial = partialArgs = false;
}
if (isPartialRight && !partialRightArgs.length) {
bitmask &= ~32;
isPartialRight = partialRightArgs = false;
}
var bindData = func && func.__bindData__;
if (bindData && bindData !== true) {
// clone `bindData`
bindData = slice(bindData);
if (bindData[2]) {
bindData[2] = slice(bindData[2]);
}
if (bindData[3]) {
bindData[3] = slice(bindData[3]);
}
// set `thisBinding` is not previously bound
if (isBind && !(bindData[1] & 1)) {
bindData[4] = thisArg;
}
// set if previously bound but not currently (subsequent curried functions)
if (!isBind && bindData[1] & 1) {
bitmask |= 8;
}
// set curried arity if not yet set
if (isCurry && !(bindData[1] & 4)) {
bindData[5] = arity;
}
// append partial left arguments
if (isPartial) {
push.apply(bindData[2] || (bindData[2] = []), partialArgs);
}
// append partial right arguments
if (isPartialRight) {
unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs);
}
// merge flags
bindData[1] |= bitmask;
return createWrapper.apply(null, bindData);
}
// fast path for `_.bind`
var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper;
return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]);
}
/**
* Creates compiled iteration functions.
*
* @private
* @param {...Object} [options] The compile options object(s).
* @param {string} [options.array] Code to determine if the iterable is an array or array-like.
* @param {boolean} [options.useHas] Specify using `hasOwnProperty` checks in the object loop.
* @param {Function} [options.keys] A reference to `_.keys` for use in own property iteration.
* @param {string} [options.args] A comma separated string of iteration function arguments.
* @param {string} [options.top] Code to execute before the iteration branches.
* @param {string} [options.loop] Code to execute in the object loop.
* @param {string} [options.bottom] Code to execute after the iteration branches.
* @returns {Function} Returns the compiled function.
*/
function createIterator() {
// data properties
iteratorData.shadowedProps = shadowedProps;
// iterator options
iteratorData.array = iteratorData.bottom = iteratorData.loop = iteratorData.top = '';
iteratorData.init = 'iterable';
iteratorData.useHas = true;
// merge options into a template data object
for (var object, index = 0; object = arguments[index]; index++) {
for (var key in object) {
iteratorData[key] = object[key];
}
}
var args = iteratorData.args;
iteratorData.firstArg = /^[^,]+/.exec(args)[0];
// create the function factory
var factory = Function(
'baseCreateCallback, errorClass, errorProto, hasOwnProperty, ' +
'indicatorObject, isArguments, isArray, isString, keys, objectProto, ' +
'objectTypes, nonEnumProps, stringClass, stringProto, toString',
'return function(' + args + ') {\n' + iteratorTemplate(iteratorData) + '\n}'
);
// return the compiled function
return factory(
baseCreateCallback, errorClass, errorProto, hasOwnProperty,
indicatorObject, isArguments, isArray, isString, iteratorData.keys, objectProto,
objectTypes, nonEnumProps, stringClass, stringProto, toString
);
}
/**
* Used by `escape` to convert characters to HTML entities.
*
* @private
* @param {string} match The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeHtmlChar(match) {
return htmlEscapes[match];
}
/**
* Gets the appropriate "indexOf" function. If the `_.indexOf` method is
* customized, this method returns the custom method, otherwise it returns
* the `baseIndexOf` function.
*
* @private
* @returns {Function} Returns the "indexOf" function.
*/
function getIndexOf() {
var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result;
return result;
}
/**
* Checks if `value` is a native function.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a native function, else `false`.
*/
function isNative(value) {
return typeof value == 'function' && reNative.test(value);
}
/**
* Sets `this` binding data on a given function.
*
* @private
* @param {Function} func The function to set data on.
* @param {Array} value The data array to set.
*/
var setBindData = !defineProperty ? noop : function(func, value) {
descriptor.value = value;
defineProperty(func, '__bindData__', descriptor);
};
/**
* A fallback implementation of `isPlainObject` which checks if a given value
* is an object created by the `Object` constructor, assuming objects created
* by the `Object` constructor have no inherited enumerable properties and that
* there are no `Object.prototype` extensions.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
*/
function shimIsPlainObject(value) {
var ctor,
result;
// avoid non Object objects, `arguments` objects, and DOM elements
if (!(value && toString.call(value) == objectClass) ||
(ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor)) ||
(!support.argsClass && isArguments(value)) ||
(!support.nodeClass && isNode(value))) {
return false;
}
// IE < 9 iterates inherited properties before own properties. If the first
// iterated property is an object's own property then there are no inherited
// enumerable properties.
if (support.ownLast) {
forIn(value, function(value, key, object) {
result = hasOwnProperty.call(object, key);
return false;
});
return result !== false;
}
// In most environments an object's own properties are iterated before
// its inherited properties. If the last iterated property is an object's
// own property then there are no inherited enumerable properties.
forIn(value, function(value, key) {
result = key;
});
return typeof result == 'undefined' || hasOwnProperty.call(value, result);
}
/**
* Used by `unescape` to convert HTML entities to characters.
*
* @private
* @param {string} match The matched character to unescape.
* @returns {string} Returns the unescaped character.
*/
function unescapeHtmlChar(match) {
return htmlUnescapes[match];
}
/*--------------------------------------------------------------------------*/
/**
* Checks if `value` is an `arguments` object.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
* @example
*
* (function() { return _.isArguments(arguments); })(1, 2, 3);
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
return value && typeof value == 'object' && typeof value.length == 'number' &&
toString.call(value) == argsClass || false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!support.argsClass) {
isArguments = function(value) {
return value && typeof value == 'object' && typeof value.length == 'number' &&
hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee') || false;
};
}
/**
* Checks if `value` is an array.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is an array, else `false`.
* @example
*
* (function() { return _.isArray(arguments); })();
* // => false
*
* _.isArray([1, 2, 3]);
* // => true
*/
var isArray = nativeIsArray || function(value) {
return value && typeof value == 'object' && typeof value.length == 'number' &&
toString.call(value) == arrayClass || false;
};
/**
* A fallback implementation of `Object.keys` which produces an array of the
* given object's own enumerable property names.
*
* @private
* @type Function
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property names.
*/
var shimKeys = createIterator({
'args': 'object',
'init': '[]',
'top': 'if (!(objectTypes[typeof object])) return result',
'loop': 'result.push(index)'
});
/**
* Creates an array composed of the own enumerable property names of an object.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property names.
* @example
*
* _.keys({ 'one': 1, 'two': 2, 'three': 3 });
* // => ['one', 'two', 'three'] (property order is not guaranteed across environments)
*/
var keys = !nativeKeys ? shimKeys : function(object) {
if (!isObject(object)) {
return [];
}
if ((support.enumPrototypes && typeof object == 'function') ||
(support.nonEnumArgs && object.length && isArguments(object))) {
return shimKeys(object);
}
return nativeKeys(object);
};
/** Reusable iterator options shared by `each`, `forIn`, and `forOwn` */
var eachIteratorOptions = {
'args': 'collection, callback, thisArg',
'top': "callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3)",
'array': "typeof length == 'number'",
'keys': keys,
'loop': 'if (callback(iterable[index], index, collection) === false) return result'
};
/** Reusable iterator options for `assign` and `defaults` */
var defaultsIteratorOptions = {
'args': 'object, source, guard',
'top':
'var args = arguments,\n' +
' argsIndex = 0,\n' +
" argsLength = typeof guard == 'number' ? 2 : args.length;\n" +
'while (++argsIndex < argsLength) {\n' +
' iterable = args[argsIndex];\n' +
' if (iterable && objectTypes[typeof iterable]) {',
'keys': keys,
'loop': "if (typeof result[index] == 'undefined') result[index] = iterable[index]",
'bottom': ' }\n}'
};
/** Reusable iterator options for `forIn` and `forOwn` */
var forOwnIteratorOptions = {
'top': 'if (!objectTypes[typeof iterable]) return result;\n' + eachIteratorOptions.top,
'array': false
};
/**
* Used to convert characters to HTML entities:
*
* Though the `>` character is escaped for symmetry, characters like `>` and `/`
* don't require escaping in HTML and have no special meaning unless they're part
* of a tag or an unquoted attribute value.
* http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
*/
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
/** Used to convert HTML entities to characters */
var htmlUnescapes = invert(htmlEscapes);
/** Used to match HTML entities and HTML characters */
var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'),
reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g');
/**
* A function compiled to iterate `arguments` objects, arrays, objects, and
* strings consistenly across environments, executing the callback for each
* element in the collection. The callback is bound to `thisArg` and invoked
* with three arguments; (value, index|key, collection). Callbacks may exit
* iteration early by explicitly returning `false`.
*
* @private
* @type Function
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array|Object|string} Returns `collection`.
*/
var baseEach = createIterator(eachIteratorOptions);
/*--------------------------------------------------------------------------*/
/**
* Assigns own enumerable properties of source object(s) to the destination
* object. Subsequent sources will overwrite property assignments of previous
* sources. If a callback is provided it will be executed to produce the
* assigned values. The callback is bound to `thisArg` and invoked with two
* arguments; (objectValue, sourceValue).
*
* @static
* @memberOf _
* @type Function
* @alias extend
* @category Objects
* @param {Object} object The destination object.
* @param {...Object} [source] The source objects.
* @param {Function} [callback] The function to customize assigning values.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the destination object.
* @example
*
* _.assign({ 'name': 'fred' }, { 'employer': 'slate' });
* // => { 'name': 'fred', 'employer': 'slate' }
*
* var defaults = _.partialRight(_.assign, function(a, b) {
* return typeof a == 'undefined' ? b : a;
* });
*
* var object = { 'name': 'barney' };
* defaults(object, { 'name': 'fred', 'employer': 'slate' });
* // => { 'name': 'barney', 'employer': 'slate' }
*/
var assign = createIterator(defaultsIteratorOptions, {
'top':
defaultsIteratorOptions.top.replace(';',
';\n' +
"if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {\n" +
' var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2);\n' +
"} else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {\n" +
' callback = args[--argsLength];\n' +
'}'
),
'loop': 'result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]'
});
/**
* Creates a clone of `value`. If `isDeep` is `true` nested objects will also
* be cloned, otherwise they will be assigned by reference. If a callback
* is provided it will be executed to produce the cloned values. If the
* callback returns `undefined` cloning will be handled by the method instead.
* The callback is bound to `thisArg` and invoked with one argument; (value).
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to clone.
* @param {boolean} [isDeep=false] Specify a deep clone.
* @param {Function} [callback] The function to customize cloning values.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the cloned value.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* var shallow = _.clone(characters);
* shallow[0] === characters[0];
* // => true
*
* var deep = _.clone(characters, true);
* deep[0] === characters[0];
* // => false
*
* _.mixin({
* 'clone': _.partialRight(_.clone, function(value) {
* return _.isElement(value) ? value.cloneNode(false) : undefined;
* })
* });
*
* var clone = _.clone(document.body);
* clone.childNodes.length;
* // => 0
*/
function clone(value, isDeep, callback, thisArg) {
// allows working with "Collections" methods without using their `index`
// and `collection` arguments for `isDeep` and `callback`
if (typeof isDeep != 'boolean' && isDeep != null) {
thisArg = callback;
callback = isDeep;
isDeep = false;
}
return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
}
/**
* Creates a deep clone of `value`. If a callback is provided it will be
* executed to produce the cloned values. If the callback returns `undefined`
* cloning will be handled by the method instead. The callback is bound to
* `thisArg` and invoked with one argument; (value).
*
* Note: This method is loosely based on the structured clone algorithm. Functions
* and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and
* objects created by constructors other than `Object` are cloned to plain `Object` objects.
* See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to deep clone.
* @param {Function} [callback] The function to customize cloning values.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the deep cloned value.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* var deep = _.cloneDeep(characters);
* deep[0] === characters[0];
* // => false
*
* var view = {
* 'label': 'docs',
* 'node': element
* };
*
* var clone = _.cloneDeep(view, function(value) {
* return _.isElement(value) ? value.cloneNode(true) : undefined;
* });
*
* clone.node == view.node;
* // => false
*/
function cloneDeep(value, callback, thisArg) {
return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
}
/**
* Creates an object that inherits from the given `prototype` object. If a
* `properties` object is provided its own enumerable properties are assigned
* to the created object.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
*/
function create(prototype, properties) {
var result = baseCreate(prototype);
return properties ? assign(result, properties) : result;
}
/**
* Assigns own enumerable properties of source object(s) to the destination
* object for all destination properties that resolve to `undefined`. Once a
* property is set, additional defaults of the same property will be ignored.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {Object} object The destination object.
* @param {...Object} [source] The source objects.
* @param- {Object} [guard] Allows working with `_.reduce` without using its
* `key` and `object` arguments as sources.
* @returns {Object} Returns the destination object.
* @example
*
* var object = { 'name': 'barney' };
* _.defaults(object, { 'name': 'fred', 'employer': 'slate' });
* // => { 'name': 'barney', 'employer': 'slate' }
*/
var defaults = createIterator(defaultsIteratorOptions);
/**
* This method is like `_.findIndex` except that it returns the key of the
* first element that passes the callback check, instead of the element itself.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to search.
* @param {Function|Object|string} [callback=identity] The function called per
* iteration. If a property name or object is provided it will be used to
* create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {string|undefined} Returns the key of the found element, else `undefined`.
* @example
*
* var characters = {
* 'barney': { 'age': 36, 'blocked': false },
* 'fred': { 'age': 40, 'blocked': true },
* 'pebbles': { 'age': 1, 'blocked': false }
* };
*
* _.findKey(characters, function(chr) {
* return chr.age < 40;
* });
* // => 'barney' (property order is not guaranteed across environments)
*
* // using "_.where" callback shorthand
* _.findKey(characters, { 'age': 1 });
* // => 'pebbles'
*
* // using "_.pluck" callback shorthand
* _.findKey(characters, 'blocked');
* // => 'fred'
*/
function findKey(object, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg, 3);
forOwn(object, function(value, key, object) {
if (callback(value, key, object)) {
result = key;
return false;
}
});
return result;
}
/**
* This method is like `_.findKey` except that it iterates over elements
* of a `collection` in the opposite order.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to search.
* @param {Function|Object|string} [callback=identity] The function called per
* iteration. If a property name or object is provided it will be used to
* create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {string|undefined} Returns the key of the found element, else `undefined`.
* @example
*
* var characters = {
* 'barney': { 'age': 36, 'blocked': true },
* 'fred': { 'age': 40, 'blocked': false },
* 'pebbles': { 'age': 1, 'blocked': true }
* };
*
* _.findLastKey(characters, function(chr) {
* return chr.age < 40;
* });
* // => returns `pebbles`, assuming `_.findKey` returns `barney`
*
* // using "_.where" callback shorthand
* _.findLastKey(characters, { 'age': 40 });
* // => 'fred'
*
* // using "_.pluck" callback shorthand
* _.findLastKey(characters, 'blocked');
* // => 'pebbles'
*/
function findLastKey(object, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg, 3);
forOwnRight(object, function(value, key, object) {
if (callback(value, key, object)) {
result = key;
return false;
}
});
return result;
}
/**
* Iterates over own and inherited enumerable properties of an object,
* executing the callback for each property. The callback is bound to `thisArg`
* and invoked with three arguments; (value, key, object). Callbacks may exit
* iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* Shape.prototype.move = function(x, y) {
* this.x += x;
* this.y += y;
* };
*
* _.forIn(new Shape, function(value, key) {
* console.log(key);
* });
* // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments)
*/
var forIn = createIterator(eachIteratorOptions, forOwnIteratorOptions, {
'useHas': false
});
/**
* This method is like `_.forIn` except that it iterates over elements
* of a `collection` in the opposite order.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* Shape.prototype.move = function(x, y) {
* this.x += x;
* this.y += y;
* };
*
* _.forInRight(new Shape, function(value, key) {
* console.log(key);
* });
* // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move'
*/
function forInRight(object, callback, thisArg) {
var pairs = [];
forIn(object, function(value, key) {
pairs.push(key, value);
});
var length = pairs.length;
callback = baseCreateCallback(callback, thisArg, 3);
while (length--) {
if (callback(pairs[length--], pairs[length], object) === false) {
break;
}
}
return object;
}
/**
* Iterates over own enumerable properties of an object, executing the callback
* for each property. The callback is bound to `thisArg` and invoked with three
* arguments; (value, key, object). Callbacks may exit iteration early by
* explicitly returning `false`.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
* console.log(key);
* });
* // => logs '0', '1', and 'length' (property order is not guaranteed across environments)
*/
var forOwn = createIterator(eachIteratorOptions, forOwnIteratorOptions);
/**
* This method is like `_.forOwn` except that it iterates over elements
* of a `collection` in the opposite order.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
* console.log(key);
* });
* // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length'
*/
function forOwnRight(object, callback, thisArg) {
var props = keys(object),
length = props.length;
callback = baseCreateCallback(callback, thisArg, 3);
while (length--) {
var key = props[length];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
/**
* Creates a sorted array of property names of all enumerable properties,
* own and inherited, of `object` that have function values.
*
* @static
* @memberOf _
* @alias methods
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property names that have function values.
* @example
*
* _.functions(_);
* // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
*/
function functions(object) {
var result = [];
forIn(object, function(value, key) {
if (isFunction(value)) {
result.push(key);
}
});
return result.sort();
}
/**
* Checks if the specified property name exists as a direct property of `object`,
* instead of an inherited property.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @param {string} key The name of the property to check.
* @returns {boolean} Returns `true` if key is a direct property, else `false`.
* @example
*
* _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
* // => true
*/
function has(object, key) {
return object ? hasOwnProperty.call(object, key) : false;
}
/**
* Creates an object composed of the inverted keys and values of the given object.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to invert.
* @returns {Object} Returns the created inverted object.
* @example
*
* _.invert({ 'first': 'fred', 'second': 'barney' });
* // => { 'fred': 'first', 'barney': 'second' }
*/
function invert(object) {
var index = -1,
props = keys(object),
length = props.length,
result = {};
while (++index < length) {
var key = props[index];
result[object[key]] = key;
}
return result;
}
/**
* Checks if `value` is a boolean value.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`.
* @example
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false ||
value && typeof value == 'object' && toString.call(value) == boolClass || false;
}
/**
* Checks if `value` is a date.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a date, else `false`.
* @example
*
* _.isDate(new Date);
* // => true
*/
function isDate(value) {
return value && typeof value == 'object' && toString.call(value) == dateClass || false;
}
/**
* Checks if `value` is a DOM element.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*/
function isElement(value) {
return value && value.nodeType === 1 || false;
}
/**
* Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
* length of `0` and objects with no own enumerable properties are considered
* "empty".
*
* @static
* @memberOf _
* @category Objects
* @param {Array|Object|string} value The value to inspect.
* @returns {boolean} Returns `true` if the `value` is empty, else `false`.
* @example
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({});
* // => true
*
* _.isEmpty('');
* // => true
*/
function isEmpty(value) {
var result = true;
if (!value) {
return result;
}
var className = toString.call(value),
length = value.length;
if ((className == arrayClass || className == stringClass ||
(support.argsClass ? className == argsClass : isArguments(value))) ||
(className == objectClass && typeof length == 'number' && isFunction(value.splice))) {
return !length;
}
forOwn(value, function() {
return (result = false);
});
return result;
}
/**
* Performs a deep comparison between two values to determine if they are
* equivalent to each other. If a callback is provided it will be executed
* to compare values. If the callback returns `undefined` comparisons will
* be handled by the method instead. The callback is bound to `thisArg` and
* invoked with two arguments; (a, b).
*
* @static
* @memberOf _
* @category Objects
* @param {*} a The value to compare.
* @param {*} b The other value to compare.
* @param {Function} [callback] The function to customize comparing values.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'name': 'fred' };
* var copy = { 'name': 'fred' };
*
* object == copy;
* // => false
*
* _.isEqual(object, copy);
* // => true
*
* var words = ['hello', 'goodbye'];
* var otherWords = ['hi', 'goodbye'];
*
* _.isEqual(words, otherWords, function(a, b) {
* var reGreet = /^(?:hello|hi)$/i,
* aGreet = _.isString(a) && reGreet.test(a),
* bGreet = _.isString(b) && reGreet.test(b);
*
* return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
* });
* // => true
*/
function isEqual(a, b, callback, thisArg) {
return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2));
}
/**
* Checks if `value` is, or can be coerced to, a finite number.
*
* Note: This is not the same as native `isFinite` which will return true for
* booleans and empty strings. See http://es5.github.io/#x15.1.2.5.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is finite, else `false`.
* @example
*
* _.isFinite(-101);
* // => true
*
* _.isFinite('10');
* // => true
*
* _.isFinite(true);
* // => false
*
* _.isFinite('');
* // => false
*
* _.isFinite(Infinity);
* // => false
*/
function isFinite(value) {
return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value));
}
/**
* Checks if `value` is a function.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*/
function isFunction(value) {
return typeof value == 'function';
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == 'function' && toString.call(value) == funcClass;
};
}
/**
* Checks if `value` is the language type of Object.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// http://code.google.com/p/v8/issues/detail?id=2291
return !!(value && objectTypes[typeof value]);
}
/**
* Checks if `value` is `NaN`.
*
* Note: This is not the same as native `isNaN` which will return `true` for
* `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// `NaN` as a primitive is the only value that is not equal to itself
// (perform the [[Class]] check first to avoid errors with some host objects in IE)
return isNumber(value) && value != +value;
}
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(undefined);
* // => false
*/
function isNull(value) {
return value === null;
}
/**
* Checks if `value` is a number.
*
* Note: `NaN` is considered a number. See http://es5.github.io/#x8.5.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a number, else `false`.
* @example
*
* _.isNumber(8.4 * 5);
* // => true
*/
function isNumber(value) {
return typeof value == 'number' ||
value && typeof value == 'object' && toString.call(value) == numberClass || false;
}
/**
* Checks if `value` is an object created by the `Object` constructor.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* _.isPlainObject(new Shape);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*/
var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) {
if (!(value && toString.call(value) == objectClass) || (!support.argsClass && isArguments(value))) {
return false;
}
var valueOf = value.valueOf,
objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);
return objProto
? (value == objProto || getPrototypeOf(value) == objProto)
: shimIsPlainObject(value);
};
/**
* Checks if `value` is a regular expression.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`.
* @example
*
* _.isRegExp(/fred/);
* // => true
*/
function isRegExp(value) {
return value && objectTypes[typeof value] && toString.call(value) == regexpClass || false;
}
/**
* Checks if `value` is a string.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a string, else `false`.
* @example
*
* _.isString('fred');
* // => true
*/
function isString(value) {
return typeof value == 'string' ||
value && typeof value == 'object' && toString.call(value) == stringClass || false;
}
/**
* Checks if `value` is `undefined`.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*/
function isUndefined(value) {
return typeof value == 'undefined';
}
/**
* Creates an object with the same keys as `object` and values generated by
* running each own enumerable property of `object` through the callback.
* The callback is bound to `thisArg` and invoked with three arguments;
* (value, key, object).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new object with values of the results of each `callback` execution.
* @example
*
* _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });
* // => { 'a': 3, 'b': 6, 'c': 9 }
*
* var characters = {
* 'fred': { 'name': 'fred', 'age': 40 },
* 'pebbles': { 'name': 'pebbles', 'age': 1 }
* };
*
* // using "_.pluck" callback shorthand
* _.mapValues(characters, 'age');
* // => { 'fred': 40, 'pebbles': 1 }
*/
function mapValues(object, callback, thisArg) {
var result = {};
callback = lodash.createCallback(callback, thisArg, 3);
forOwn(object, function(value, key, object) {
result[key] = callback(value, key, object);
});
return result;
}
/**
* Recursively merges own enumerable properties of the source object(s), that
* don't resolve to `undefined` into the destination object. Subsequent sources
* will overwrite property assignments of previous sources. If a callback is
* provided it will be executed to produce the merged values of the destination
* and source properties. If the callback returns `undefined` merging will
* be handled by the method instead. The callback is bound to `thisArg` and
* invoked with two arguments; (objectValue, sourceValue).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The destination object.
* @param {...Object} [source] The source objects.
* @param {Function} [callback] The function to customize merging properties.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the destination object.
* @example
*
* var names = {
* 'characters': [
* { 'name': 'barney' },
* { 'name': 'fred' }
* ]
* };
*
* var ages = {
* 'characters': [
* { 'age': 36 },
* { 'age': 40 }
* ]
* };
*
* _.merge(names, ages);
* // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] }
*
* var food = {
* 'fruits': ['apple'],
* 'vegetables': ['beet']
* };
*
* var otherFood = {
* 'fruits': ['banana'],
* 'vegetables': ['carrot']
* };
*
* _.merge(food, otherFood, function(a, b) {
* return _.isArray(a) ? a.concat(b) : undefined;
* });
* // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }
*/
function merge(object) {
var args = arguments,
length = 2;
if (!isObject(object)) {
return object;
}
// allows working with `_.reduce` and `_.reduceRight` without using
// their `index` and `collection` arguments
if (typeof args[2] != 'number') {
length = args.length;
}
if (length > 3 && typeof args[length - 2] == 'function') {
var callback = baseCreateCallback(args[--length - 1], args[length--], 2);
} else if (length > 2 && typeof args[length - 1] == 'function') {
callback = args[--length];
}
var sources = slice(arguments, 1, length),
index = -1,
stackA = getArray(),
stackB = getArray();
while (++index < length) {
baseMerge(object, sources[index], callback, stackA, stackB);
}
releaseArray(stackA);
releaseArray(stackB);
return object;
}
/**
* Creates a shallow clone of `object` excluding the specified properties.
* Property names may be specified as individual arguments or as arrays of
* property names. If a callback is provided it will be executed for each
* property of `object` omitting the properties the callback returns truey
* for. The callback is bound to `thisArg` and invoked with three arguments;
* (value, key, object).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The source object.
* @param {Function|...string|string[]} [callback] The properties to omit or the
* function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns an object without the omitted properties.
* @example
*
* _.omit({ 'name': 'fred', 'age': 40 }, 'age');
* // => { 'name': 'fred' }
*
* _.omit({ 'name': 'fred', 'age': 40 }, function(value) {
* return typeof value == 'number';
* });
* // => { 'name': 'fred' }
*/
function omit(object, callback, thisArg) {
var result = {};
if (typeof callback != 'function') {
var props = [];
forIn(object, function(value, key) {
props.push(key);
});
props = baseDifference(props, baseFlatten(arguments, true, false, 1));
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
result[key] = object[key];
}
} else {
callback = lodash.createCallback(callback, thisArg, 3);
forIn(object, function(value, key, object) {
if (!callback(value, key, object)) {
result[key] = value;
}
});
}
return result;
}
/**
* Creates a two dimensional array of an object's key-value pairs,
* i.e. `[[key1, value1], [key2, value2]]`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns new array of key-value pairs.
* @example
*
* _.pairs({ 'barney': 36, 'fred': 40 });
* // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments)
*/
function pairs(object) {
var index = -1,
props = keys(object),
length = props.length,
result = Array(length);
while (++index < length) {
var key = props[index];
result[index] = [key, object[key]];
}
return result;
}
/**
* Creates a shallow clone of `object` composed of the specified properties.
* Property names may be specified as individual arguments or as arrays of
* property names. If a callback is provided it will be executed for each
* property of `object` picking the properties the callback returns truey
* for. The callback is bound to `thisArg` and invoked with three arguments;
* (value, key, object).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The source object.
* @param {Function|...string|string[]} [callback] The function called per
* iteration or property names to pick, specified as individual property
* names or arrays of property names.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns an object composed of the picked properties.
* @example
*
* _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name');
* // => { 'name': 'fred' }
*
* _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) {
* return key.charAt(0) != '_';
* });
* // => { 'name': 'fred' }
*/
function pick(object, callback, thisArg) {
var result = {};
if (typeof callback != 'function') {
var index = -1,
props = baseFlatten(arguments, true, false, 1),
length = isObject(object) ? props.length : 0;
while (++index < length) {
var key = props[index];
if (key in object) {
result[key] = object[key];
}
}
} else {
callback = lodash.createCallback(callback, thisArg, 3);
forIn(object, function(value, key, object) {
if (callback(value, key, object)) {
result[key] = value;
}
});
}
return result;
}
/**
* An alternative to `_.reduce` this method transforms `object` to a new
* `accumulator` object which is the result of running each of its own
* enumerable properties through a callback, with each callback execution
* potentially mutating the `accumulator` object. The callback is bound to
* `thisArg` and invoked with four arguments; (accumulator, value, key, object).
* Callbacks may exit iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @category Objects
* @param {Array|Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [accumulator] The custom accumulator value.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the accumulated value.
* @example
*
* var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) {
* num *= num;
* if (num % 2) {
* return result.push(num) < 3;
* }
* });
* // => [1, 9, 25]
*
* var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
* result[key] = num * 3;
* });
* // => { 'a': 3, 'b': 6, 'c': 9 }
*/
function transform(object, callback, accumulator, thisArg) {
var isArr = isArray(object);
if (accumulator == null) {
if (isArr) {
accumulator = [];
} else {
var ctor = object && object.constructor,
proto = ctor && ctor.prototype;
accumulator = baseCreate(proto);
}
}
if (callback) {
callback = lodash.createCallback(callback, thisArg, 4);
(isArr ? baseEach : forOwn)(object, function(value, index, object) {
return callback(accumulator, value, index, object);
});
}
return accumulator;
}
/**
* Creates an array composed of the own enumerable property values of `object`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property values.
* @example
*
* _.values({ 'one': 1, 'two': 2, 'three': 3 });
* // => [1, 2, 3] (property order is not guaranteed across environments)
*/
function values(object) {
var index = -1,
props = keys(object),
length = props.length,
result = Array(length);
while (++index < length) {
result[index] = object[props[index]];
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Creates an array of elements from the specified indexes, or keys, of the
* `collection`. Indexes may be specified as individual arguments or as arrays
* of indexes.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {...(number|number[]|string|string[])} [index] The indexes of `collection`
* to retrieve, specified as individual indexes or arrays of indexes.
* @returns {Array} Returns a new array of elements corresponding to the
* provided indexes.
* @example
*
* _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
* // => ['a', 'c', 'e']
*
* _.at(['fred', 'barney', 'pebbles'], 0, 2);
* // => ['fred', 'pebbles']
*/
function at(collection) {
var args = arguments,
index = -1,
props = baseFlatten(args, true, false, 1),
length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length,
result = Array(length);
if (support.unindexedChars && isString(collection)) {
collection = collection.split('');
}
while(++index < length) {
result[index] = collection[props[index]];
}
return result;
}
/**
* Checks if a given value is present in a collection using strict equality
* for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the
* offset from the end of the collection.
*
* @static
* @memberOf _
* @alias include
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {*} target The value to check for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {boolean} Returns `true` if the `target` element is found, else `false`.
* @example
*
* _.contains([1, 2, 3], 1);
* // => true
*
* _.contains([1, 2, 3], 1, 2);
* // => false
*
* _.contains({ 'name': 'fred', 'age': 40 }, 'fred');
* // => true
*
* _.contains('pebbles', 'eb');
* // => true
*/
function contains(collection, target, fromIndex) {
var index = -1,
indexOf = getIndexOf(),
length = collection ? collection.length : 0,
result = false;
fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0;
if (isArray(collection)) {
result = indexOf(collection, target, fromIndex) > -1;
} else if (typeof length == 'number') {
result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1;
} else {
baseEach(collection, function(value) {
if (++index >= fromIndex) {
return !(result = value === target);
}
});
}
return result;
}
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` through the callback. The corresponding value
* of each key is the number of times the key was returned by the callback.
* The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
* // => { '4': 1, '6': 2 }
*
* _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
* // => { '4': 1, '6': 2 }
*
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
*/
var countBy = createAggregator(function(result, value, key) {
(hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
});
/**
* Checks if the given callback returns truey value for **all** elements of
* a collection. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias all
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {boolean} Returns `true` if all elements passed the callback check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes']);
* // => false
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* // using "_.pluck" callback shorthand
* _.every(characters, 'age');
* // => true
*
* // using "_.where" callback shorthand
* _.every(characters, { 'age': 36 });
* // => false
*/
function every(collection, callback, thisArg) {
var result = true;
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
if (!(result = !!callback(collection[index], index, collection))) {
break;
}
}
} else {
baseEach(collection, function(value, index, collection) {
return (result = !!callback(value, index, collection));
});
}
return result;
}
/**
* Iterates over elements of a collection, returning an array of all elements
* the callback returns truey for. The callback is bound to `thisArg` and
* invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias select
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of elements that passed the callback check.
* @example
*
* var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [2, 4, 6]
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true }
* ];
*
* // using "_.pluck" callback shorthand
* _.filter(characters, 'blocked');
* // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
*
* // using "_.where" callback shorthand
* _.filter(characters, { 'age': 36 });
* // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
*/
function filter(collection, callback, thisArg) {
var result = [];
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (callback(value, index, collection)) {
result.push(value);
}
}
} else {
baseEach(collection, function(value, index, collection) {
if (callback(value, index, collection)) {
result.push(value);
}
});
}
return result;
}
/**
* Iterates over elements of a collection, returning the first element that
* the callback returns truey for. The callback is bound to `thisArg` and
* invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias detect, findWhere
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the found element, else `undefined`.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true },
* { 'name': 'pebbles', 'age': 1, 'blocked': false }
* ];
*
* _.find(characters, function(chr) {
* return chr.age < 40;
* });
* // => { 'name': 'barney', 'age': 36, 'blocked': false }
*
* // using "_.where" callback shorthand
* _.find(characters, { 'age': 1 });
* // => { 'name': 'pebbles', 'age': 1, 'blocked': false }
*
* // using "_.pluck" callback shorthand
* _.find(characters, 'blocked');
* // => { 'name': 'fred', 'age': 40, 'blocked': true }
*/
function find(collection, callback, thisArg) {
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (callback(value, index, collection)) {
return value;
}
}
} else {
var result;
baseEach(collection, function(value, index, collection) {
if (callback(value, index, collection)) {
result = value;
return false;
}
});
return result;
}
}
/**
* This method is like `_.find` except that it iterates over elements
* of a `collection` from right to left.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the found element, else `undefined`.
* @example
*
* _.findLast([1, 2, 3, 4], function(num) {
* return num % 2 == 1;
* });
* // => 3
*/
function findLast(collection, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg, 3);
forEachRight(collection, function(value, index, collection) {
if (callback(value, index, collection)) {
result = value;
return false;
}
});
return result;
}
/**
* Iterates over elements of a collection, executing the callback for each
* element. The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection). Callbacks may exit iteration early by
* explicitly returning `false`.
*
* Note: As with other "Collections" methods, objects with a `length` property
* are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
* may be used for object iteration.
*
* @static
* @memberOf _
* @alias each
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array|Object|string} Returns `collection`.
* @example
*
* _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');
* // => logs each number and returns '1,2,3'
*
* _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
* // => logs each number and returns the object (property order is not guaranteed across environments)
*/
function forEach(collection, callback, thisArg) {
if (callback && typeof thisArg == 'undefined' && isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
if (callback(collection[index], index, collection) === false) {
break;
}
}
} else {
baseEach(collection, callback, thisArg);
}
return collection;
}
/**
* This method is like `_.forEach` except that it iterates over elements
* of a `collection` from right to left.
*
* @static
* @memberOf _
* @alias eachRight
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array|Object|string} Returns `collection`.
* @example
*
* _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(',');
* // => logs each number from right to left and returns '3,2,1'
*/
function forEachRight(collection, callback, thisArg) {
var iterable = collection,
length = collection ? collection.length : 0;
callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
if (isArray(collection)) {
while (length--) {
if (callback(collection[length], length, collection) === false) {
break;
}
}
} else {
if (typeof length != 'number') {
var props = keys(collection);
length = props.length;
} else if (support.unindexedChars && isString(collection)) {
iterable = collection.split('');
}
baseEach(collection, function(value, key, collection) {
key = props ? props[--length] : --length;
return callback(iterable[key], key, collection);
});
}
return collection;
}
/**
* Creates an object composed of keys generated from the results of running
* each element of a collection through the callback. The corresponding value
* of each key is an array of the elements responsible for generating the key.
* The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
* // => { '4': [4.2], '6': [6.1, 6.4] }
*
* _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
* // => { '4': [4.2], '6': [6.1, 6.4] }
*
* // using "_.pluck" callback shorthand
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
var groupBy = createAggregator(function(result, value, key) {
(hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value);
});
/**
* Creates an object composed of keys generated from the results of running
* each element of the collection through the given callback. The corresponding
* value of each key is the last element responsible for generating the key.
* The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* var keys = [
* { 'dir': 'left', 'code': 97 },
* { 'dir': 'right', 'code': 100 }
* ];
*
* _.indexBy(keys, 'dir');
* // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
*
* _.indexBy(keys, function(key) { return String.fromCharCode(key.code); });
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*
* _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String);
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*/
var indexBy = createAggregator(function(result, value, key) {
result[key] = value;
});
/**
* Invokes the method named by `methodName` on each element in the `collection`
* returning an array of the results of each invoked method. Additional arguments
* will be provided to each invoked method. If `methodName` is a function it
* will be invoked for, and `this` bound to, each element in the `collection`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|string} methodName The name of the method to invoke or
* the function invoked per iteration.
* @param {...*} [arg] Arguments to invoke the method with.
* @returns {Array} Returns a new array of the results of each invoked method.
* @example
*
* _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*
* _.invoke([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
*/
function invoke(collection, methodName) {
var args = slice(arguments, 2),
index = -1,
isFunc = typeof methodName == 'function',
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
forEach(collection, function(value) {
result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args);
});
return result;
}
/**
* Creates an array of values by running each element in the collection
* through the callback. The callback is bound to `thisArg` and invoked with
* three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias collect
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of the results of each `callback` execution.
* @example
*
* _.map([1, 2, 3], function(num) { return num * 3; });
* // => [3, 6, 9]
*
* _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
* // => [3, 6, 9] (property order is not guaranteed across environments)
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* // using "_.pluck" callback shorthand
* _.map(characters, 'name');
* // => ['barney', 'fred']
*/
function map(collection, callback, thisArg) {
var index = -1,
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
while (++index < length) {
result[index] = callback(collection[index], index, collection);
}
} else {
baseEach(collection, function(value, key, collection) {
result[++index] = callback(value, key, collection);
});
}
return result;
}
/**
* Retrieves the maximum value of a collection. If the collection is empty or
* falsey `-Infinity` is returned. If a callback is provided it will be executed
* for each value in the collection to generate the criterion by which the value
* is ranked. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the maximum value.
* @example
*
* _.max([4, 2, 8, 6]);
* // => 8
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* _.max(characters, function(chr) { return chr.age; });
* // => { 'name': 'fred', 'age': 40 };
*
* // using "_.pluck" callback shorthand
* _.max(characters, 'age');
* // => { 'name': 'fred', 'age': 40 };
*/
function max(collection, callback, thisArg) {
var computed = -Infinity,
result = computed;
// allows working with functions like `_.map` without using
// their `index` argument as a callback
if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) {
callback = null;
}
if (callback == null && isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (value > result) {
result = value;
}
}
} else {
callback = (callback == null && isString(collection))
? charAtCallback
: lodash.createCallback(callback, thisArg, 3);
baseEach(collection, function(value, index, collection) {
var current = callback(value, index, collection);
if (current > computed) {
computed = current;
result = value;
}
});
}
return result;
}
/**
* Retrieves the minimum value of a collection. If the collection is empty or
* falsey `Infinity` is returned. If a callback is provided it will be executed
* for each value in the collection to generate the criterion by which the value
* is ranked. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the minimum value.
* @example
*
* _.min([4, 2, 8, 6]);
* // => 2
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* _.min(characters, function(chr) { return chr.age; });
* // => { 'name': 'barney', 'age': 36 };
*
* // using "_.pluck" callback shorthand
* _.min(characters, 'age');
* // => { 'name': 'barney', 'age': 36 };
*/
function min(collection, callback, thisArg) {
var computed = Infinity,
result = computed;
// allows working with functions like `_.map` without using
// their `index` argument as a callback
if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) {
callback = null;
}
if (callback == null && isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (value < result) {
result = value;
}
}
} else {
callback = (callback == null && isString(collection))
? charAtCallback
: lodash.createCallback(callback, thisArg, 3);
baseEach(collection, function(value, index, collection) {
var current = callback(value, index, collection);
if (current < computed) {
computed = current;
result = value;
}
});
}
return result;
}
/**
* Retrieves the value of a specified property from all elements in the collection.
*
* @static
* @memberOf _
* @type Function
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {string} property The name of the property to pluck.
* @returns {Array} Returns a new array of property values.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* _.pluck(characters, 'name');
* // => ['barney', 'fred']
*/
var pluck = map;
/**
* Reduces a collection to a value which is the accumulated result of running
* each element in the collection through the callback, where each successive
* callback execution consumes the return value of the previous execution. If
* `accumulator` is not provided the first element of the collection will be
* used as the initial `accumulator` value. The callback is bound to `thisArg`
* and invoked with four arguments; (accumulator, value, index|key, collection).
*
* @static
* @memberOf _
* @alias foldl, inject
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [accumulator] Initial value of the accumulator.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the accumulated value.
* @example
*
* var sum = _.reduce([1, 2, 3], function(sum, num) {
* return sum + num;
* });
* // => 6
*
* var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
* result[key] = num * 3;
* return result;
* }, {});
* // => { 'a': 3, 'b': 6, 'c': 9 }
*/
function reduce(collection, callback, accumulator, thisArg) {
var noaccum = arguments.length < 3;
callback = lodash.createCallback(callback, thisArg, 4);
if (isArray(collection)) {
var index = -1,
length = collection.length;
if (noaccum) {
accumulator = collection[++index];
}
while (++index < length) {
accumulator = callback(accumulator, collection[index], index, collection);
}
} else {
baseEach(collection, function(value, index, collection) {
accumulator = noaccum
? (noaccum = false, value)
: callback(accumulator, value, index, collection)
});
}
return accumulator;
}
/**
* This method is like `_.reduce` except that it iterates over elements
* of a `collection` from right to left.
*
* @static
* @memberOf _
* @alias foldr
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [accumulator] Initial value of the accumulator.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the accumulated value.
* @example
*
* var list = [[0, 1], [2, 3], [4, 5]];
* var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
function reduceRight(collection, callback, accumulator, thisArg) {
var noaccum = arguments.length < 3;
callback = lodash.createCallback(callback, thisArg, 4);
forEachRight(collection, function(value, index, collection) {
accumulator = noaccum
? (noaccum = false, value)
: callback(accumulator, value, index, collection);
});
return accumulator;
}
/**
* The opposite of `_.filter` this method returns the elements of a
* collection that the callback does **not** return truey for.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of elements that failed the callback check.
* @example
*
* var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [1, 3, 5]
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true }
* ];
*
* // using "_.pluck" callback shorthand
* _.reject(characters, 'blocked');
* // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
*
* // using "_.where" callback shorthand
* _.reject(characters, { 'age': 36 });
* // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
*/
function reject(collection, callback, thisArg) {
callback = lodash.createCallback(callback, thisArg, 3);
return filter(collection, function(value, index, collection) {
return !callback(value, index, collection);
});
}
/**
* Retrieves a random element or `n` random elements from a collection.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to sample.
* @param {number} [n] The number of elements to sample.
* @param- {Object} [guard] Allows working with functions like `_.map`
* without using their `index` arguments as `n`.
* @returns {Array} Returns the random sample(s) of `collection`.
* @example
*
* _.sample([1, 2, 3, 4]);
* // => 2
*
* _.sample([1, 2, 3, 4], 2);
* // => [3, 1]
*/
function sample(collection, n, guard) {
if (collection && typeof collection.length != 'number') {
collection = values(collection);
} else if (support.unindexedChars && isString(collection)) {
collection = collection.split('');
}
if (n == null || guard) {
return collection ? collection[baseRandom(0, collection.length - 1)] : undefined;
}
var result = shuffle(collection);
result.length = nativeMin(nativeMax(0, n), result.length);
return result;
}
/**
* Creates an array of shuffled values, using a version of the Fisher-Yates
* shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to shuffle.
* @returns {Array} Returns a new shuffled collection.
* @example
*
* _.shuffle([1, 2, 3, 4, 5, 6]);
* // => [4, 1, 6, 3, 5, 2]
*/
function shuffle(collection) {
var index = -1,
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
forEach(collection, function(value) {
var rand = baseRandom(0, ++index);
result[index] = result[rand];
result[rand] = value;
});
return result;
}
/**
* Gets the size of the `collection` by returning `collection.length` for arrays
* and array-like objects or the number of own enumerable properties for objects.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to inspect.
* @returns {number} Returns `collection.length` or number of own enumerable properties.
* @example
*
* _.size([1, 2]);
* // => 2
*
* _.size({ 'one': 1, 'two': 2, 'three': 3 });
* // => 3
*
* _.size('pebbles');
* // => 7
*/
function size(collection) {
var length = collection ? collection.length : 0;
return typeof length == 'number' ? length : keys(collection).length;
}
/**
* Checks if the callback returns a truey value for **any** element of a
* collection. The function returns as soon as it finds a passing value and
* does not iterate over the entire collection. The callback is bound to
* `thisArg` and invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias any
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {boolean} Returns `true` if any element passed the callback check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true }
* ];
*
* // using "_.pluck" callback shorthand
* _.some(characters, 'blocked');
* // => true
*
* // using "_.where" callback shorthand
* _.some(characters, { 'age': 1 });
* // => false
*/
function some(collection, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
if ((result = callback(collection[index], index, collection))) {
break;
}
}
} else {
baseEach(collection, function(value, index, collection) {
return !(result = callback(value, index, collection));
});
}
return !!result;
}
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection through the callback. This method
* performs a stable sort, that is, it will preserve the original sort order
* of equal elements. The callback is bound to `thisArg` and invoked with
* three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an array of property names is provided for `callback` the collection
* will be sorted by each property value.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Array|Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of sorted elements.
* @example
*
* _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
* // => [3, 1, 2]
*
* _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
* // => [3, 1, 2]
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 },
* { 'name': 'barney', 'age': 26 },
* { 'name': 'fred', 'age': 30 }
* ];
*
* // using "_.pluck" callback shorthand
* _.map(_.sortBy(characters, 'age'), _.values);
* // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]]
*
* // sorting by multiple properties
* _.map(_.sortBy(characters, ['name', 'age']), _.values);
* // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]]
*/
function sortBy(collection, callback, thisArg) {
var index = -1,
isArr = isArray(callback),
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
if (!isArr) {
callback = lodash.createCallback(callback, thisArg, 3);
}
forEach(collection, function(value, key, collection) {
var object = result[++index] = getObject();
if (isArr) {
object.criteria = map(callback, function(key) { return value[key]; });
} else {
(object.criteria = getArray())[0] = callback(value, key, collection);
}
object.index = index;
object.value = value;
});
length = result.length;
result.sort(compareAscending);
while (length--) {
var object = result[length];
result[length] = object.value;
if (!isArr) {
releaseArray(object.criteria);
}
releaseObject(object);
}
return result;
}
/**
* Converts the `collection` to an array.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to convert.
* @returns {Array} Returns the new converted array.
* @example
*
* (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
* // => [2, 3, 4]
*/
function toArray(collection) {
if (collection && typeof collection.length == 'number') {
return (support.unindexedChars && isString(collection))
? collection.split('')
: slice(collection);
}
return values(collection);
}
/**
* Performs a deep comparison of each element in a `collection` to the given
* `properties` object, returning an array of all elements that have equivalent
* property values.
*
* @static
* @memberOf _
* @type Function
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Object} props The object of property values to filter by.
* @returns {Array} Returns a new array of elements that have the given properties.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] },
* { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }
* ];
*
* _.where(characters, { 'age': 36 });
* // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }]
*
* _.where(characters, { 'pets': ['dino'] });
* // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }]
*/
var where = filter;
/*--------------------------------------------------------------------------*/
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are all falsey.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to compact.
* @returns {Array} Returns a new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result.push(value);
}
}
return result;
}
/**
* Creates an array excluding all values of the provided arrays using strict
* equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to process.
* @param {...Array} [values] The arrays of values to exclude.
* @returns {Array} Returns a new array of filtered values.
* @example
*
* _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
* // => [1, 3, 4]
*/
function difference(array) {
return baseDifference(array, baseFlatten(arguments, true, true, 1));
}
/**
* This method is like `_.find` except that it returns the index of the first
* element that passes the callback check, instead of the element itself.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true },
* { 'name': 'pebbles', 'age': 1, 'blocked': false }
* ];
*
* _.findIndex(characters, function(chr) {
* return chr.age < 20;
* });
* // => 2
*
* // using "_.where" callback shorthand
* _.findIndex(characters, { 'age': 36 });
* // => 0
*
* // using "_.pluck" callback shorthand
* _.findIndex(characters, 'blocked');
* // => 1
*/
function findIndex(array, callback, thisArg) {
var index = -1,
length = array ? array.length : 0;
callback = lodash.createCallback(callback, thisArg, 3);
while (++index < length) {
if (callback(array[index], index, array)) {
return index;
}
}
return -1;
}
/**
* This method is like `_.findIndex` except that it iterates over elements
* of a `collection` from right to left.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': true },
* { 'name': 'fred', 'age': 40, 'blocked': false },
* { 'name': 'pebbles', 'age': 1, 'blocked': true }
* ];
*
* _.findLastIndex(characters, function(chr) {
* return chr.age > 30;
* });
* // => 1
*
* // using "_.where" callback shorthand
* _.findLastIndex(characters, { 'age': 36 });
* // => 0
*
* // using "_.pluck" callback shorthand
* _.findLastIndex(characters, 'blocked');
* // => 2
*/
function findLastIndex(array, callback, thisArg) {
var length = array ? array.length : 0;
callback = lodash.createCallback(callback, thisArg, 3);
while (length--) {
if (callback(array[length], length, array)) {
return length;
}
}
return -1;
}
/**
* Gets the first element or first `n` elements of an array. If a callback
* is provided elements at the beginning of the array are returned as long
* as the callback returns truey. The callback is bound to `thisArg` and
* invoked with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias head, take
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|number|string} [callback] The function called
* per element or the number of elements to return. If a property name or
* object is provided it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the first element(s) of `array`.
* @example
*
* _.first([1, 2, 3]);
* // => 1
*
* _.first([1, 2, 3], 2);
* // => [1, 2]
*
* _.first([1, 2, 3], function(num) {
* return num < 3;
* });
* // => [1, 2]
*
* var characters = [
* { 'name': 'barney', 'blocked': true, 'employer': 'slate' },
* { 'name': 'fred', 'blocked': false, 'employer': 'slate' },
* { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
* ];
*
* // using "_.pluck" callback shorthand
* _.first(characters, 'blocked');
* // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }]
*
* // using "_.where" callback shorthand
* _.pluck(_.first(characters, { 'employer': 'slate' }), 'name');
* // => ['barney', 'fred']
*/
function first(array, callback, thisArg) {
var n = 0,
length = array ? array.length : 0;
if (typeof callback != 'number' && callback != null) {
var index = -1;
callback = lodash.createCallback(callback, thisArg, 3);
while (++index < length && callback(array[index], index, array)) {
n++;
}
} else {
n = callback;
if (n == null || thisArg) {
return array ? array[0] : undefined;
}
}
return slice(array, 0, nativeMin(nativeMax(0, n), length));
}
/**
* Flattens a nested array (the nesting can be to any depth). If `isShallow`
* is truey, the array will only be flattened a single level. If a callback
* is provided each element of the array is passed through the callback before
* flattening. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to flatten.
* @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new flattened array.
* @example
*
* _.flatten([1, [2], [3, [[4]]]]);
* // => [1, 2, 3, 4];
*
* _.flatten([1, [2], [3, [[4]]]], true);
* // => [1, 2, 3, [[4]]];
*
* var characters = [
* { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] },
* { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }
* ];
*
* // using "_.pluck" callback shorthand
* _.flatten(characters, 'pets');
* // => ['hoppy', 'baby puss', 'dino']
*/
function flatten(array, isShallow, callback, thisArg) {
// juggle arguments
if (typeof isShallow != 'boolean' && isShallow != null) {
thisArg = callback;
callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow;
isShallow = false;
}
if (callback != null) {
array = map(array, callback, thisArg);
}
return baseFlatten(array, isShallow);
}
/**
* Gets the index at which the first occurrence of `value` is found using
* strict equality for comparisons, i.e. `===`. If the array is already sorted
* providing `true` for `fromIndex` will run a faster binary search.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {boolean|number} [fromIndex=0] The index to search from or `true`
* to perform a binary search on a sorted array.
* @returns {number} Returns the index of the matched value or `-1`.
* @example
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2);
* // => 1
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 4
*
* _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
* // => 2
*/
function indexOf(array, value, fromIndex) {
if (typeof fromIndex == 'number') {
var length = array ? array.length : 0;
fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0);
} else if (fromIndex) {
var index = sortedIndex(array, value);
return array[index] === value ? index : -1;
}
return baseIndexOf(array, value, fromIndex);
}
/**
* Gets all but the last element or last `n` elements of an array. If a
* callback is provided elements at the end of the array are excluded from
* the result as long as the callback returns truey. The callback is bound
* to `thisArg` and invoked with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|number|string} [callback=1] The function called
* per element or the number of elements to exclude. If a property name or
* object is provided it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a slice of `array`.
* @example
*
* _.initial([1, 2, 3]);
* // => [1, 2]
*
* _.initial([1, 2, 3], 2);
* // => [1]
*
* _.initial([1, 2, 3], function(num) {
* return num > 1;
* });
* // => [1]
*
* var characters = [
* { 'name': 'barney', 'blocked': false, 'employer': 'slate' },
* { 'name': 'fred', 'blocked': true, 'employer': 'slate' },
* { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
* ];
*
* // using "_.pluck" callback shorthand
* _.initial(characters, 'blocked');
* // => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }]
*
* // using "_.where" callback shorthand
* _.pluck(_.initial(characters, { 'employer': 'na' }), 'name');
* // => ['barney', 'fred']
*/
function initial(array, callback, thisArg) {
var n = 0,
length = array ? array.length : 0;
if (typeof callback != 'number' && callback != null) {
var index = length;
callback = lodash.createCallback(callback, thisArg, 3);
while (index-- && callback(array[index], index, array)) {
n++;
}
} else {
n = (callback == null || thisArg) ? 1 : callback || n;
}
return slice(array, 0, nativeMin(nativeMax(0, length - n), length));
}
/**
* Creates an array of unique values present in all provided arrays using
* strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {...Array} [array] The arrays to inspect.
* @returns {Array} Returns an array of shared values.
* @example
*
* _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]);
* // => [1, 2]
*/
function intersection() {
var args = [],
argsIndex = -1,
argsLength = arguments.length,
caches = getArray(),
indexOf = getIndexOf(),
trustIndexOf = indexOf === baseIndexOf,
seen = getArray();
while (++argsIndex < argsLength) {
var value = arguments[argsIndex];
if (isArray(value) || isArguments(value)) {
args.push(value);
caches.push(trustIndexOf && value.length >= largeArraySize &&
createCache(argsIndex ? args[argsIndex] : seen));
}
}
var array = args[0],
index = -1,
length = array ? array.length : 0,
result = [];
outer:
while (++index < length) {
var cache = caches[0];
value = array[index];
if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) {
argsIndex = argsLength;
(cache || seen).push(value);
while (--argsIndex) {
cache = caches[argsIndex];
if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) {
continue outer;
}
}
result.push(value);
}
}
while (argsLength--) {
cache = caches[argsLength];
if (cache) {
releaseObject(cache);
}
}
releaseArray(caches);
releaseArray(seen);
return result;
}
/**
* Gets the last element or last `n` elements of an array. If a callback is
* provided elements at the end of the array are returned as long as the
* callback returns truey. The callback is bound to `thisArg` and invoked
* with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|number|string} [callback] The function called
* per element or the number of elements to return. If a property name or
* object is provided it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the last element(s) of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*
* _.last([1, 2, 3], 2);
* // => [2, 3]
*
* _.last([1, 2, 3], function(num) {
* return num > 1;
* });
* // => [2, 3]
*
* var characters = [
* { 'name': 'barney', 'blocked': false, 'employer': 'slate' },
* { 'name': 'fred', 'blocked': true, 'employer': 'slate' },
* { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
* ];
*
* // using "_.pluck" callback shorthand
* _.pluck(_.last(characters, 'blocked'), 'name');
* // => ['fred', 'pebbles']
*
* // using "_.where" callback shorthand
* _.last(characters, { 'employer': 'na' });
* // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
*/
function last(array, callback, thisArg) {
var n = 0,
length = array ? array.length : 0;
if (typeof callback != 'number' && callback != null) {
var index = length;
callback = lodash.createCallback(callback, thisArg, 3);
while (index-- && callback(array[index], index, array)) {
n++;
}
} else {
n = callback;
if (n == null || thisArg) {
return array ? array[length - 1] : undefined;
}
}
return slice(array, nativeMax(0, length - n));
}
/**
* Gets the index at which the last occurrence of `value` is found using strict
* equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
* as the offset from the end of the collection.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the matched value or `-1`.
* @example
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
* // => 4
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 1
*/
function lastIndexOf(array, value, fromIndex) {
var index = array ? array.length : 0;
if (typeof fromIndex == 'number') {
index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1;
}
while (index--) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* Removes all provided values from the given array using strict equality for
* comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to modify.
* @param {...*} [value] The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3, 1, 2, 3];
* _.pull(array, 2, 3);
* console.log(array);
* // => [1, 1]
*/
function pull(array) {
var args = arguments,
argsIndex = 0,
argsLength = args.length,
length = array ? array.length : 0;
while (++argsIndex < argsLength) {
var index = -1,
value = args[argsIndex];
while (++index < length) {
if (array[index] === value) {
splice.call(array, index--, 1);
length--;
}
}
}
return array;
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to but not including `end`. If `start` is less than `stop` a
* zero-length range is created unless a negative `step` is specified.
*
* @static
* @memberOf _
* @category Arrays
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns a new range array.
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/
function range(start, end, step) {
start = +start || 0;
step = typeof step == 'number' ? step : (+step || 1);
if (end == null) {
end = start;
start = 0;
}
// use `Array(length)` so engines like Chakra and V8 avoid slower modes
// http://youtu.be/XAqIpGU8ZZk#t=17m25s
var index = -1,
length = nativeMax(0, ceil((end - start) / (step || 1))),
result = Array(length);
while (++index < length) {
result[index] = start;
start += step;
}
return result;
}
/**
* Removes all elements from an array that the callback returns truey for
* and returns an array of removed elements. The callback is bound to `thisArg`
* and invoked with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to modify.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4, 5, 6];
* var evens = _.remove(array, function(num) { return num % 2 == 0; });
*
* console.log(array);
* // => [1, 3, 5]
*
* console.log(evens);
* // => [2, 4, 6]
*/
function remove(array, callback, thisArg) {
var index = -1,
length = array ? array.length : 0,
result = [];
callback = lodash.createCallback(callback, thisArg, 3);
while (++index < length) {
var value = array[index];
if (callback(value, index, array)) {
result.push(value);
splice.call(array, index--, 1);
length--;
}
}
return result;
}
/**
* The opposite of `_.initial` this method gets all but the first element or
* first `n` elements of an array. If a callback function is provided elements
* at the beginning of the array are excluded from the result as long as the
* callback returns truey. The callback is bound to `thisArg` and invoked
* with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias drop, tail
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|number|string} [callback=1] The function called
* per element or the number of elements to exclude. If a property name or
* object is provided it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a slice of `array`.
* @example
*
* _.rest([1, 2, 3]);
* // => [2, 3]
*
* _.rest([1, 2, 3], 2);
* // => [3]
*
* _.rest([1, 2, 3], function(num) {
* return num < 3;
* });
* // => [3]
*
* var characters = [
* { 'name': 'barney', 'blocked': true, 'employer': 'slate' },
* { 'name': 'fred', 'blocked': false, 'employer': 'slate' },
* { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
* ];
*
* // using "_.pluck" callback shorthand
* _.pluck(_.rest(characters, 'blocked'), 'name');
* // => ['fred', 'pebbles']
*
* // using "_.where" callback shorthand
* _.rest(characters, { 'employer': 'slate' });
* // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
*/
function rest(array, callback, thisArg) {
if (typeof callback != 'number' && callback != null) {
var n = 0,
index = -1,
length = array ? array.length : 0;
callback = lodash.createCallback(callback, thisArg, 3);
while (++index < length && callback(array[index], index, array)) {
n++;
}
} else {
n = (callback == null || thisArg) ? 1 : nativeMax(0, callback);
}
return slice(array, n);
}
/**
* Uses a binary search to determine the smallest index at which a value
* should be inserted into a given sorted array in order to maintain the sort
* order of the array. If a callback is provided it will be executed for
* `value` and each element of `array` to compute their sort ranking. The
* callback is bound to `thisArg` and invoked with one argument; (value).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to inspect.
* @param {*} value The value to evaluate.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedIndex([20, 30, 50], 40);
* // => 2
*
* // using "_.pluck" callback shorthand
* _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
* // => 2
*
* var dict = {
* 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
* };
*
* _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
* return dict.wordToNumber[word];
* });
* // => 2
*
* _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
* return this.wordToNumber[word];
* }, dict);
* // => 2
*/
function sortedIndex(array, value, callback, thisArg) {
var low = 0,
high = array ? array.length : low;
// explicitly reference `identity` for better inlining in Firefox
callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity;
value = callback(value);
while (low < high) {
var mid = (low + high) >>> 1;
(callback(array[mid]) < value)
? low = mid + 1
: high = mid;
}
return low;
}
/**
* Creates an array of unique values, in order, of the provided arrays using
* strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {...Array} [array] The arrays to inspect.
* @returns {Array} Returns an array of combined values.
* @example
*
* _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]);
* // => [1, 2, 3, 5, 4]
*/
function union() {
return baseUniq(baseFlatten(arguments, true, true));
}
/**
* Creates a duplicate-value-free version of an array using strict equality
* for comparisons, i.e. `===`. If the array is sorted, providing
* `true` for `isSorted` will use a faster algorithm. If a callback is provided
* each element of `array` is passed through the callback before uniqueness
* is computed. The callback is bound to `thisArg` and invoked with three
* arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias unique
* @category Arrays
* @param {Array} array The array to process.
* @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a duplicate-value-free array.
* @example
*
* _.uniq([1, 2, 1, 3, 1]);
* // => [1, 2, 3]
*
* _.uniq([1, 1, 2, 2, 3], true);
* // => [1, 2, 3]
*
* _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); });
* // => ['A', 'b', 'C']
*
* _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);
* // => [1, 2.5, 3]
*
* // using "_.pluck" callback shorthand
* _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
function uniq(array, isSorted, callback, thisArg) {
// juggle arguments
if (typeof isSorted != 'boolean' && isSorted != null) {
thisArg = callback;
callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted;
isSorted = false;
}
if (callback != null) {
callback = lodash.createCallback(callback, thisArg, 3);
}
return baseUniq(array, isSorted, callback);
}
/**
* Creates an array excluding all provided values using strict equality for
* comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to filter.
* @param {...*} [value] The values to exclude.
* @returns {Array} Returns a new array of filtered values.
* @example
*
* _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
* // => [2, 3, 4]
*/
function without(array) {
return baseDifference(array, slice(arguments, 1));
}
/**
* Creates an array that is the symmetric difference of the provided arrays.
* See http://en.wikipedia.org/wiki/Symmetric_difference.
*
* @static
* @memberOf _
* @category Arrays
* @param {...Array} [array] The arrays to inspect.
* @returns {Array} Returns an array of values.
* @example
*
* _.xor([1, 2, 3], [5, 2, 1, 4]);
* // => [3, 5, 4]
*
* _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]);
* // => [1, 4, 5]
*/
function xor() {
var index = -1,
length = arguments.length;
while (++index < length) {
var array = arguments[index];
if (isArray(array) || isArguments(array)) {
var result = result
? baseUniq(baseDifference(result, array).concat(baseDifference(array, result)))
: array;
}
}
return result || [];
}
/**
* Creates an array of grouped elements, the first of which contains the first
* elements of the given arrays, the second of which contains the second
* elements of the given arrays, and so on.
*
* @static
* @memberOf _
* @alias unzip
* @category Arrays
* @param {...Array} [array] Arrays to process.
* @returns {Array} Returns a new array of grouped elements.
* @example
*
* _.zip(['fred', 'barney'], [30, 40], [true, false]);
* // => [['fred', 30, true], ['barney', 40, false]]
*/
function zip() {
var array = arguments.length > 1 ? arguments : arguments[0],
index = -1,
length = array ? max(pluck(array, 'length')) : 0,
result = Array(length < 0 ? 0 : length);
while (++index < length) {
result[index] = pluck(array, index);
}
return result;
}
/**
* Creates an object composed from arrays of `keys` and `values`. Provide
* either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`
* or two arrays, one of `keys` and one of corresponding `values`.
*
* @static
* @memberOf _
* @alias object
* @category Arrays
* @param {Array} keys The array of keys.
* @param {Array} [values=[]] The array of values.
* @returns {Object} Returns an object composed of the given keys and
* corresponding values.
* @example
*
* _.zipObject(['fred', 'barney'], [30, 40]);
* // => { 'fred': 30, 'barney': 40 }
*/
function zipObject(keys, values) {
var index = -1,
length = keys ? keys.length : 0,
result = {};
if (!values && length && !isArray(keys[0])) {
values = [];
}
while (++index < length) {
var key = keys[index];
if (values) {
result[key] = values[index];
} else if (key) {
result[key[0]] = key[1];
}
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Creates a function that executes `func`, with the `this` binding and
* arguments of the created function, only after being called `n` times.
*
* @static
* @memberOf _
* @category Functions
* @param {number} n The number of times the function must be called before
* `func` is executed.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var saves = ['profile', 'settings'];
*
* var done = _.after(saves.length, function() {
* console.log('Done saving!');
* });
*
* _.forEach(saves, function(type) {
* asyncSave({ 'type': type, 'complete': done });
* });
* // => logs 'Done saving!', after all saves have completed
*/
function after(n, func) {
if (!isFunction(func)) {
throw new TypeError;
}
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
/**
* Creates a function that, when called, invokes `func` with the `this`
* binding of `thisArg` and prepends any additional `bind` arguments to those
* provided to the bound function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to bind.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {...*} [arg] Arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var func = function(greeting) {
* return greeting + ' ' + this.name;
* };
*
* func = _.bind(func, { 'name': 'fred' }, 'hi');
* func();
* // => 'hi fred'
*/
function bind(func, thisArg) {
return arguments.length > 2
? createWrapper(func, 17, slice(arguments, 2), null, thisArg)
: createWrapper(func, 1, null, null, thisArg);
}
/**
* Binds methods of an object to the object itself, overwriting the existing
* method. Method names may be specified as individual arguments or as arrays
* of method names. If no method names are provided all the function properties
* of `object` will be bound.
*
* @static
* @memberOf _
* @category Functions
* @param {Object} object The object to bind and assign the bound methods to.
* @param {...string} [methodName] The object method names to
* bind, specified as individual method names or arrays of method names.
* @returns {Object} Returns `object`.
* @example
*
* var view = {
* 'label': 'docs',
* 'onClick': function() { console.log('clicked ' + this.label); }
* };
*
* _.bindAll(view);
* jQuery('#docs').on('click', view.onClick);
* // => logs 'clicked docs', when the button is clicked
*/
function bindAll(object) {
var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object),
index = -1,
length = funcs.length;
while (++index < length) {
var key = funcs[index];
object[key] = createWrapper(object[key], 1, null, null, object);
}
return object;
}
/**
* Creates a function that, when called, invokes the method at `object[key]`
* and prepends any additional `bindKey` arguments to those provided to the bound
* function. This method differs from `_.bind` by allowing bound functions to
* reference methods that will be redefined or don't yet exist.
* See http://michaux.ca/articles/lazy-function-definition-pattern.
*
* @static
* @memberOf _
* @category Functions
* @param {Object} object The object the method belongs to.
* @param {string} key The key of the method.
* @param {...*} [arg] Arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var object = {
* 'name': 'fred',
* 'greet': function(greeting) {
* return greeting + ' ' + this.name;
* }
* };
*
* var func = _.bindKey(object, 'greet', 'hi');
* func();
* // => 'hi fred'
*
* object.greet = function(greeting) {
* return greeting + 'ya ' + this.name + '!';
* };
*
* func();
* // => 'hiya fred!'
*/
function bindKey(object, key) {
return arguments.length > 2
? createWrapper(key, 19, slice(arguments, 2), null, object)
: createWrapper(key, 3, null, null, object);
}
/**
* Creates a function that is the composition of the provided functions,
* where each function consumes the return value of the function that follows.
* For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
* Each function is executed with the `this` binding of the composed function.
*
* @static
* @memberOf _
* @category Functions
* @param {...Function} [func] Functions to compose.
* @returns {Function} Returns the new composed function.
* @example
*
* var realNameMap = {
* 'pebbles': 'penelope'
* };
*
* var format = function(name) {
* name = realNameMap[name.toLowerCase()] || name;
* return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
* };
*
* var greet = function(formatted) {
* return 'Hiya ' + formatted + '!';
* };
*
* var welcome = _.compose(greet, format);
* welcome('pebbles');
* // => 'Hiya Penelope!'
*/
function compose() {
var funcs = arguments,
length = funcs.length;
while (length--) {
if (!isFunction(funcs[length])) {
throw new TypeError;
}
}
return function() {
var args = arguments,
length = funcs.length;
while (length--) {
args = [funcs[length].apply(this, args)];
}
return args[0];
};
}
/**
* Creates a function which accepts one or more arguments of `func` that when
* invoked either executes `func` returning its result, if all `func` arguments
* have been provided, or returns a function that accepts one or more of the
* remaining `func` arguments, and so on. The arity of `func` can be specified
* if `func.length` is not sufficient.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @returns {Function} Returns the new curried function.
* @example
*
* var curried = _.curry(function(a, b, c) {
* console.log(a + b + c);
* });
*
* curried(1)(2)(3);
* // => 6
*
* curried(1, 2)(3);
* // => 6
*
* curried(1, 2, 3);
* // => 6
*/
function curry(func, arity) {
arity = typeof arity == 'number' ? arity : (+arity || func.length);
return createWrapper(func, 4, null, null, null, arity);
}
/**
* Creates a function that will delay the execution of `func` until after
* `wait` milliseconds have elapsed since the last time it was invoked.
* Provide an options object to indicate that `func` should be invoked on
* the leading and/or trailing edge of the `wait` timeout. Subsequent calls
* to the debounced function will return the result of the last `func` call.
*
* Note: If `leading` and `trailing` options are `true` `func` will be called
* on the trailing edge of the timeout only if the the debounced function is
* invoked more than once during the `wait` timeout.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to debounce.
* @param {number} wait The number of milliseconds to delay.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout.
* @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called.
* @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // avoid costly calculations while the window size is in flux
* var lazyLayout = _.debounce(calculateLayout, 150);
* jQuery(window).on('resize', lazyLayout);
*
* // execute `sendMail` when the click event is fired, debouncing subsequent calls
* jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* });
*
* // ensure `batchLog` is executed once after 1 second of debounced calls
* var source = new EventSource('/stream');
* source.addEventListener('message', _.debounce(batchLog, 250, {
* 'maxWait': 1000
* }, false);
*/
function debounce(func, wait, options) {
var args,
maxTimeoutId,
result,
stamp,
thisArg,
timeoutId,
trailingCall,
lastCalled = 0,
maxWait = false,
trailing = true;
if (!isFunction(func)) {
throw new TypeError;
}
wait = nativeMax(0, wait) || 0;
if (options === true) {
var leading = true;
trailing = false;
} else if (isObject(options)) {
leading = options.leading;
maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);
trailing = 'trailing' in options ? options.trailing : trailing;
}
var delayed = function() {
var remaining = wait - (now() - stamp);
if (remaining <= 0) {
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
var isCalled = trailingCall;
maxTimeoutId = timeoutId = trailingCall = undefined;
if (isCalled) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
}
} else {
timeoutId = setTimeout(delayed, remaining);
}
};
var maxDelayed = function() {
if (timeoutId) {
clearTimeout(timeoutId);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
if (trailing || (maxWait !== wait)) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
}
};
return function() {
args = arguments;
stamp = now();
thisArg = this;
trailingCall = trailing && (timeoutId || !leading);
if (maxWait === false) {
var leadingCall = leading && !timeoutId;
} else {
if (!maxTimeoutId && !leading) {
lastCalled = stamp;
}
var remaining = maxWait - (stamp - lastCalled),
isCalled = remaining <= 0;
if (isCalled) {
if (maxTimeoutId) {
maxTimeoutId = clearTimeout(maxTimeoutId);
}
lastCalled = stamp;
result = func.apply(thisArg, args);
}
else if (!maxTimeoutId) {
maxTimeoutId = setTimeout(maxDelayed, remaining);
}
}
if (isCalled && timeoutId) {
timeoutId = clearTimeout(timeoutId);
}
else if (!timeoutId && wait !== maxWait) {
timeoutId = setTimeout(delayed, wait);
}
if (leadingCall) {
isCalled = true;
result = func.apply(thisArg, args);
}
if (isCalled && !timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
return result;
};
}
/**
* Defers executing the `func` function until the current call stack has cleared.
* Additional arguments will be provided to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to defer.
* @param {...*} [arg] Arguments to invoke the function with.
* @returns {number} Returns the timer id.
* @example
*
* _.defer(function(text) { console.log(text); }, 'deferred');
* // logs 'deferred' after one or more milliseconds
*/
function defer(func) {
if (!isFunction(func)) {
throw new TypeError;
}
var args = slice(arguments, 1);
return setTimeout(function() { func.apply(undefined, args); }, 1);
}
/**
* Executes the `func` function after `wait` milliseconds. Additional arguments
* will be provided to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay execution.
* @param {...*} [arg] Arguments to invoke the function with.
* @returns {number} Returns the timer id.
* @example
*
* _.delay(function(text) { console.log(text); }, 1000, 'later');
* // => logs 'later' after one second
*/
function delay(func, wait) {
if (!isFunction(func)) {
throw new TypeError;
}
var args = slice(arguments, 2);
return setTimeout(function() { func.apply(undefined, args); }, wait);
}
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided it will be used to determine the cache key for storing the result
* based on the arguments provided to the memoized function. By default, the
* first argument provided to the memoized function is used as the cache key.
* The `func` is executed with the `this` binding of the memoized function.
* The result cache is exposed as the `cache` property on the memoized function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] A function used to resolve the cache key.
* @returns {Function} Returns the new memoizing function.
* @example
*
* var fibonacci = _.memoize(function(n) {
* return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
* });
*
* fibonacci(9)
* // => 34
*
* var data = {
* 'fred': { 'name': 'fred', 'age': 40 },
* 'pebbles': { 'name': 'pebbles', 'age': 1 }
* };
*
* // modifying the result cache
* var get = _.memoize(function(name) { return data[name]; }, _.identity);
* get('pebbles');
* // => { 'name': 'pebbles', 'age': 1 }
*
* get.cache.pebbles.name = 'penelope';
* get('pebbles');
* // => { 'name': 'penelope', 'age': 1 }
*/
function memoize(func, resolver) {
if (!isFunction(func)) {
throw new TypeError;
}
var memoized = function() {
var cache = memoized.cache,
key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0];
return hasOwnProperty.call(cache, key)
? cache[key]
: (cache[key] = func.apply(this, arguments));
}
memoized.cache = {};
return memoized;
}
/**
* Creates a function that is restricted to execute `func` once. Repeat calls to
* the function will return the value of the first call. The `func` is executed
* with the `this` binding of the created function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // `initialize` executes `createApplication` once
*/
function once(func) {
var ran,
result;
if (!isFunction(func)) {
throw new TypeError;
}
return function() {
if (ran) {
return result;
}
ran = true;
result = func.apply(this, arguments);
// clear the `func` variable so the function may be garbage collected
func = null;
return result;
};
}
/**
* Creates a function that, when called, invokes `func` with any additional
* `partial` arguments prepended to those provided to the new function. This
* method is similar to `_.bind` except it does **not** alter the `this` binding.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [arg] Arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var greet = function(greeting, name) { return greeting + ' ' + name; };
* var hi = _.partial(greet, 'hi');
* hi('fred');
* // => 'hi fred'
*/
function partial(func) {
return createWrapper(func, 16, slice(arguments, 1));
}
/**
* This method is like `_.partial` except that `partial` arguments are
* appended to those provided to the new function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [arg] Arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var defaultsDeep = _.partialRight(_.merge, _.defaults);
*
* var options = {
* 'variable': 'data',
* 'imports': { 'jq': $ }
* };
*
* defaultsDeep(options, _.templateSettings);
*
* options.variable
* // => 'data'
*
* options.imports
* // => { '_': _, 'jq': $ }
*/
function partialRight(func) {
return createWrapper(func, 32, null, slice(arguments, 1));
}
/**
* Creates a function that, when executed, will only call the `func` function
* at most once per every `wait` milliseconds. Provide an options object to
* indicate that `func` should be invoked on the leading and/or trailing edge
* of the `wait` timeout. Subsequent calls to the throttled function will
* return the result of the last `func` call.
*
* Note: If `leading` and `trailing` options are `true` `func` will be called
* on the trailing edge of the timeout only if the the throttled function is
* invoked more than once during the `wait` timeout.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to throttle.
* @param {number} wait The number of milliseconds to throttle executions to.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout.
* @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // avoid excessively updating the position while scrolling
* var throttled = _.throttle(updatePosition, 100);
* jQuery(window).on('scroll', throttled);
*
* // execute `renewToken` when the click event is fired, but not more than once every 5 minutes
* jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
* 'trailing': false
* }));
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (!isFunction(func)) {
throw new TypeError;
}
if (options === false) {
leading = false;
} else if (isObject(options)) {
leading = 'leading' in options ? options.leading : leading;
trailing = 'trailing' in options ? options.trailing : trailing;
}
debounceOptions.leading = leading;
debounceOptions.maxWait = wait;
debounceOptions.trailing = trailing;
return debounce(func, wait, debounceOptions);
}
/**
* Creates a function that provides `value` to the wrapper function as its
* first argument. Additional arguments provided to the function are appended
* to those provided to the wrapper function. The wrapper is executed with
* the `this` binding of the created function.
*
* @static
* @memberOf _
* @category Functions
* @param {*} value The value to wrap.
* @param {Function} wrapper The wrapper function.
* @returns {Function} Returns the new function.
* @example
*
* var p = _.wrap(_.escape, function(func, text) {
* return '<p>' + func(text) + '</p>';
* });
*
* p('Fred, Wilma, & Pebbles');
* // => '<p>Fred, Wilma, & Pebbles</p>'
*/
function wrap(value, wrapper) {
return createWrapper(wrapper, 16, [value]);
}
/*--------------------------------------------------------------------------*/
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @category Utilities
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new function.
* @example
*
* var object = { 'name': 'fred' };
* var getter = _.constant(object);
* getter() === object;
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
/**
* Produces a callback bound to an optional `thisArg`. If `func` is a property
* name the created callback will return the property value for a given element.
* If `func` is an object the created callback will return `true` for elements
* that contain the equivalent object properties, otherwise it will return `false`.
*
* @static
* @memberOf _
* @category Utilities
* @param {*} [func=identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of the created callback.
* @param {number} [argCount] The number of arguments the callback accepts.
* @returns {Function} Returns a callback function.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* // wrap to create custom callback shorthands
* _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
* var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
* return !match ? func(callback, thisArg) : function(object) {
* return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
* };
* });
*
* _.filter(characters, 'age__gt38');
* // => [{ 'name': 'fred', 'age': 40 }]
*/
function createCallback(func, thisArg, argCount) {
var type = typeof func;
if (func == null || type == 'function') {
return baseCreateCallback(func, thisArg, argCount);
}
// handle "_.pluck" style callback shorthands
if (type != 'object') {
return property(func);
}
var props = keys(func),
key = props[0],
a = func[key];
// handle "_.where" style callback shorthands
if (props.length == 1 && a === a && !isObject(a)) {
// fast path the common case of providing an object with a single
// property containing a primitive value
return function(object) {
var b = object[key];
return a === b && (a !== 0 || (1 / a == 1 / b));
};
}
return function(object) {
var length = props.length,
result = false;
while (length--) {
if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) {
break;
}
}
return result;
};
}
/**
* Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their
* corresponding HTML entities.
*
* @static
* @memberOf _
* @category Utilities
* @param {string} string The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escape('Fred, Wilma, & Pebbles');
* // => 'Fred, Wilma, & Pebbles'
*/
function escape(string) {
return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar);
}
/**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utilities
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'name': 'fred' };
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
/**
* Adds function properties of a source object to the destination object.
* If `object` is a function methods will be added to its prototype as well.
*
* @static
* @memberOf _
* @category Utilities
* @param {Function|Object} [object=lodash] object The destination object.
* @param {Object} source The object of functions to add.
* @param {Object} [options] The options object.
* @param {boolean} [options.chain=true] Specify whether the functions added are chainable.
* @example
*
* function capitalize(string) {
* return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
* }
*
* _.mixin({ 'capitalize': capitalize });
* _.capitalize('fred');
* // => 'Fred'
*
* _('fred').capitalize().value();
* // => 'Fred'
*
* _.mixin({ 'capitalize': capitalize }, { 'chain': false });
* _('fred').capitalize();
* // => 'Fred'
*/
function mixin(object, source, options) {
var chain = true,
methodNames = source && functions(source);
if (!source || (!options && !methodNames.length)) {
if (options == null) {
options = source;
}
ctor = lodashWrapper;
source = object;
object = lodash;
methodNames = functions(source);
}
if (options === false) {
chain = false;
} else if (isObject(options) && 'chain' in options) {
chain = options.chain;
}
var ctor = object,
isFunc = isFunction(ctor);
forEach(methodNames, function(methodName) {
var func = object[methodName] = source[methodName];
if (isFunc) {
ctor.prototype[methodName] = function() {
var chainAll = this.__chain__,
value = this.__wrapped__,
args = [value];
push.apply(args, arguments);
var result = func.apply(object, args);
if (chain || chainAll) {
if (value === result && isObject(result)) {
return this;
}
result = new ctor(result);
result.__chain__ = chainAll;
}
return result;
};
}
});
}
/**
* Reverts the '_' variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @memberOf _
* @category Utilities
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/
function noConflict() {
context._ = oldDash;
return this;
}
/**
* A no-operation function.
*
* @static
* @memberOf _
* @category Utilities
* @example
*
* var object = { 'name': 'fred' };
* _.noop(object) === undefined;
* // => true
*/
function noop() {
// no operation performed
}
/**
* Gets the number of milliseconds that have elapsed since the Unix epoch
* (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @category Utilities
* @example
*
* var stamp = _.now();
* _.defer(function() { console.log(_.now() - stamp); });
* // => logs the number of milliseconds it took for the deferred function to be called
*/
var now = isNative(now = Date.now) && now || function() {
return new Date().getTime();
};
/**
* Converts the given value into an integer of the specified radix.
* If `radix` is `undefined` or `0` a `radix` of `10` is used unless the
* `value` is a hexadecimal, in which case a `radix` of `16` is used.
*
* Note: This method avoids differences in native ES3 and ES5 `parseInt`
* implementations. See http://es5.github.io/#E.
*
* @static
* @memberOf _
* @category Utilities
* @param {string} value The value to parse.
* @param {number} [radix] The radix used to interpret the value to parse.
* @returns {number} Returns the new integer value.
* @example
*
* _.parseInt('08');
* // => 8
*/
var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) {
// Firefox < 21 and Opera < 15 follow the ES3 specified implementation of `parseInt`
return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0);
};
/**
* Creates a "_.pluck" style function, which returns the `key` value of a
* given object.
*
* @static
* @memberOf _
* @category Utilities
* @param {string} key The name of the property to retrieve.
* @returns {Function} Returns the new function.
* @example
*
* var characters = [
* { 'name': 'fred', 'age': 40 },
* { 'name': 'barney', 'age': 36 }
* ];
*
* var getName = _.property('name');
*
* _.map(characters, getName);
* // => ['barney', 'fred']
*
* _.sortBy(characters, getName);
* // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]
*/
function property(key) {
return function(object) {
return object[key];
};
}
/**
* Produces a random number between `min` and `max` (inclusive). If only one
* argument is provided a number between `0` and the given number will be
* returned. If `floating` is truey or either `min` or `max` are floats a
* floating-point number will be returned instead of an integer.
*
* @static
* @memberOf _
* @category Utilities
* @param {number} [min=0] The minimum possible value.
* @param {number} [max=1] The maximum possible value.
* @param {boolean} [floating=false] Specify returning a floating-point number.
* @returns {number} Returns a random number.
* @example
*
* _.random(0, 5);
* // => an integer between 0 and 5
*
* _.random(5);
* // => also an integer between 0 and 5
*
* _.random(5, true);
* // => a floating-point number between 0 and 5
*
* _.random(1.2, 5.2);
* // => a floating-point number between 1.2 and 5.2
*/
function random(min, max, floating) {
var noMin = min == null,
noMax = max == null;
if (floating == null) {
if (typeof min == 'boolean' && noMax) {
floating = min;
min = 1;
}
else if (!noMax && typeof max == 'boolean') {
floating = max;
noMax = true;
}
}
if (noMin && noMax) {
max = 1;
}
min = +min || 0;
if (noMax) {
max = min;
min = 0;
} else {
max = +max || 0;
}
if (floating || min % 1 || max % 1) {
var rand = nativeRandom();
return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max);
}
return baseRandom(min, max);
}
/**
* Resolves the value of property `key` on `object`. If `key` is a function
* it will be invoked with the `this` binding of `object` and its result returned,
* else the property value is returned. If `object` is falsey then `undefined`
* is returned.
*
* @static
* @memberOf _
* @category Utilities
* @param {Object} object The object to inspect.
* @param {string} key The name of the property to resolve.
* @returns {*} Returns the resolved value.
* @example
*
* var object = {
* 'cheese': 'crumpets',
* 'stuff': function() {
* return 'nonsense';
* }
* };
*
* _.result(object, 'cheese');
* // => 'crumpets'
*
* _.result(object, 'stuff');
* // => 'nonsense'
*/
function result(object, key) {
if (object) {
var value = object[key];
return isFunction(value) ? object[key]() : value;
}
}
/**
* A micro-templating method that handles arbitrary delimiters, preserves
* whitespace, and correctly escapes quotes within interpolated code.
*
* Note: In the development build, `_.template` utilizes sourceURLs for easier
* debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
*
* For more information on precompiling templates see:
* http://lodash.com/custom-builds
*
* For more information on Chrome extension sandboxes see:
* http://developer.chrome.com/stable/extensions/sandboxingEval.html
*
* @static
* @memberOf _
* @category Utilities
* @param {string} text The template text.
* @param {Object} data The data object used to populate the text.
* @param {Object} [options] The options object.
* @param {RegExp} [options.escape] The "escape" delimiter.
* @param {RegExp} [options.evaluate] The "evaluate" delimiter.
* @param {Object} [options.imports] An object to import into the template as local variables.
* @param {RegExp} [options.interpolate] The "interpolate" delimiter.
* @param {string} [sourceURL] The sourceURL of the template's compiled source.
* @param {string} [variable] The data object variable name.
* @returns {Function|string} Returns a compiled function when no `data` object
* is given, else it returns the interpolated text.
* @example
*
* // using the "interpolate" delimiter to create a compiled template
* var compiled = _.template('hello <%= name %>');
* compiled({ 'name': 'fred' });
* // => 'hello fred'
*
* // using the "escape" delimiter to escape HTML in data property values
* _.template('<b><%- value %></b>', { 'value': '<script>' });
* // => '<b><script></b>'
*
* // using the "evaluate" delimiter to generate HTML
* var list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';
* _.template(list, { 'people': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // using the ES6 delimiter as an alternative to the default "interpolate" delimiter
* _.template('hello ${ name }', { 'name': 'pebbles' });
* // => 'hello pebbles'
*
* // using the internal `print` function in "evaluate" delimiters
* _.template('<% print("hello " + name); %>!', { 'name': 'barney' });
* // => 'hello barney!'
*
* // using a custom template delimiters
* _.templateSettings = {
* 'interpolate': /{{([\s\S]+?)}}/g
* };
*
* _.template('hello {{ name }}!', { 'name': 'mustache' });
* // => 'hello mustache!'
*
* // using the `imports` option to import jQuery
* var list = '<% jq.each(people, function(name) { %><li><%- name %></li><% }); %>';
* _.template(list, { 'people': ['fred', 'barney'] }, { 'imports': { 'jq': jQuery } });
* // => '<li>fred</li><li>barney</li>'
*
* // using the `sourceURL` option to specify a custom sourceURL for the template
* var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
* // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
*
* // using the `variable` option to ensure a with-statement isn't used in the compiled template
* var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' });
* compiled.source;
* // => function(data) {
* var __t, __p = '', __e = _.escape;
* __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!';
* return __p;
* }
*
* // using the `source` property to inline compiled templates for meaningful
* // line numbers in error messages and a stack trace
* fs.writeFileSync(path.join(cwd, 'jst.js'), '\
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
*/
function template(text, data, options) {
// based on Mark Resig's `tmpl` implementation
// http://eMark.org/blog/javascript-micro-templating/
// and Laura Doktorova's doT.js
// https://github.com/olado/doT
var settings = lodash.templateSettings;
text = String(text || '');
// avoid missing dependencies when `iteratorTemplate` is not defined
options = defaults({}, options, settings);
var imports = defaults({}, options.imports, settings.imports),
importsKeys = keys(imports),
importsValues = values(imports);
var isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// compile the regexp to match each delimiter
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// escape characters that cannot be included in string literals
source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// replace delimiters with snippets
if (escapeValue) {
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// the JS engine embedded in Adobe products requires returning the `match`
// string in order to produce the correct `offset` value
return match;
});
source += "';\n";
// if `variable` is not specified, wrap a with-statement around the generated
// code to add the data object to the top of the scope chain
var variable = options.variable,
hasVariable = variable;
if (!hasVariable) {
variable = 'obj';
source = 'with (' + variable + ') {\n' + source + '\n}\n';
}
// cleanup code by stripping empty strings
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// frame code as the function body
source = 'function(' + variable + ') {\n' +
(hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') +
"var __t, __p = '', __e = _.escape" +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
// Use a sourceURL for easier debugging.
// http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
var sourceURL = '\n/*\n//# sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/';
try {
var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues);
} catch(e) {
e.source = source;
throw e;
}
if (data) {
return result(data);
}
// provide the compiled function's source by its `toString` method, in
// supported environments, or the `source` property as a convenience for
// inlining compiled templates during the build process
result.source = source;
return result;
}
/**
* Executes the callback `n` times, returning an array of the results
* of each callback execution. The callback is bound to `thisArg` and invoked
* with one argument; (index).
*
* @static
* @memberOf _
* @category Utilities
* @param {number} n The number of times to execute the callback.
* @param {Function} callback The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns an array of the results of each `callback` execution.
* @example
*
* var diceRolls = _.times(3, _.partial(_.random, 1, 6));
* // => [3, 6, 4]
*
* _.times(3, function(n) { mage.castSpell(n); });
* // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
*
* _.times(3, function(n) { this.cast(n); }, mage);
* // => also calls `mage.castSpell(n)` three times
*/
function times(n, callback, thisArg) {
n = (n = +n) > -1 ? n : 0;
var index = -1,
result = Array(n);
callback = baseCreateCallback(callback, thisArg, 1);
while (++index < n) {
result[index] = callback(index);
}
return result;
}
/**
* The inverse of `_.escape` this method converts the HTML entities
* `&`, `<`, `>`, `"`, and `'` in `string` to their
* corresponding characters.
*
* @static
* @memberOf _
* @category Utilities
* @param {string} string The string to unescape.
* @returns {string} Returns the unescaped string.
* @example
*
* _.unescape('Fred, Barney & Pebbles');
* // => 'Fred, Barney & Pebbles'
*/
function unescape(string) {
return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar);
}
/**
* Generates a unique ID. If `prefix` is provided the ID will be appended to it.
*
* @static
* @memberOf _
* @category Utilities
* @param {string} [prefix] The value to prefix the ID with.
* @returns {string} Returns the unique ID.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*
* _.uniqueId();
* // => '105'
*/
function uniqueId(prefix) {
var id = ++idCounter;
return String(prefix == null ? '' : prefix) + id;
}
/*--------------------------------------------------------------------------*/
/**
* Creates a `lodash` object that wraps the given value with explicit
* method chaining enabled.
*
* @static
* @memberOf _
* @category Chaining
* @param {*} value The value to wrap.
* @returns {Object} Returns the wrapper object.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 },
* { 'name': 'pebbles', 'age': 1 }
* ];
*
* var youngest = _.chain(characters)
* .sortBy('age')
* .map(function(chr) { return chr.name + ' is ' + chr.age; })
* .first()
* .value();
* // => 'pebbles is 1'
*/
function chain(value) {
value = new lodashWrapper(value);
value.__chain__ = true;
return value;
}
/**
* Invokes `interceptor` with the `value` as the first argument and then
* returns `value`. The purpose of this method is to "tap into" a method
* chain in order to perform operations on intermediate results within
* the chain.
*
* @static
* @memberOf _
* @category Chaining
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns `value`.
* @example
*
* _([1, 2, 3, 4])
* .tap(function(array) { array.pop(); })
* .reverse()
* .value();
* // => [3, 2, 1]
*/
function tap(value, interceptor) {
interceptor(value);
return value;
}
/**
* Enables explicit method chaining on the wrapper object.
*
* @name chain
* @memberOf _
* @category Chaining
* @returns {*} Returns the wrapper object.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* // without explicit chaining
* _(characters).first();
* // => { 'name': 'barney', 'age': 36 }
*
* // with explicit chaining
* _(characters).chain()
* .first()
* .pick('age')
* .value();
* // => { 'age': 36 }
*/
function wrapperChain() {
this.__chain__ = true;
return this;
}
/**
* Produces the `toString` result of the wrapped value.
*
* @name toString
* @memberOf _
* @category Chaining
* @returns {string} Returns the string result.
* @example
*
* _([1, 2, 3]).toString();
* // => '1,2,3'
*/
function wrapperToString() {
return String(this.__wrapped__);
}
/**
* Extracts the wrapped value.
*
* @name valueOf
* @memberOf _
* @alias value
* @category Chaining
* @returns {*} Returns the wrapped value.
* @example
*
* _([1, 2, 3]).valueOf();
* // => [1, 2, 3]
*/
function wrapperValueOf() {
return this.__wrapped__;
}
/*--------------------------------------------------------------------------*/
// add functions that return wrapped values when chaining
lodash.after = after;
lodash.assign = assign;
lodash.at = at;
lodash.bind = bind;
lodash.bindAll = bindAll;
lodash.bindKey = bindKey;
lodash.chain = chain;
lodash.compact = compact;
lodash.compose = compose;
lodash.constant = constant;
lodash.countBy = countBy;
lodash.create = create;
lodash.createCallback = createCallback;
lodash.curry = curry;
lodash.debounce = debounce;
lodash.defaults = defaults;
lodash.defer = defer;
lodash.delay = delay;
lodash.difference = difference;
lodash.filter = filter;
lodash.flatten = flatten;
lodash.forEach = forEach;
lodash.forEachRight = forEachRight;
lodash.forIn = forIn;
lodash.forInRight = forInRight;
lodash.forOwn = forOwn;
lodash.forOwnRight = forOwnRight;
lodash.functions = functions;
lodash.groupBy = groupBy;
lodash.indexBy = indexBy;
lodash.initial = initial;
lodash.intersection = intersection;
lodash.invert = invert;
lodash.invoke = invoke;
lodash.keys = keys;
lodash.map = map;
lodash.mapValues = mapValues;
lodash.max = max;
lodash.memoize = memoize;
lodash.merge = merge;
lodash.min = min;
lodash.omit = omit;
lodash.once = once;
lodash.pairs = pairs;
lodash.partial = partial;
lodash.partialRight = partialRight;
lodash.pick = pick;
lodash.pluck = pluck;
lodash.property = property;
lodash.pull = pull;
lodash.range = range;
lodash.reject = reject;
lodash.remove = remove;
lodash.rest = rest;
lodash.shuffle = shuffle;
lodash.sortBy = sortBy;
lodash.tap = tap;
lodash.throttle = throttle;
lodash.times = times;
lodash.toArray = toArray;
lodash.transform = transform;
lodash.union = union;
lodash.uniq = uniq;
lodash.values = values;
lodash.where = where;
lodash.without = without;
lodash.wrap = wrap;
lodash.xor = xor;
lodash.zip = zip;
lodash.zipObject = zipObject;
// add aliases
lodash.collect = map;
lodash.drop = rest;
lodash.each = forEach;
lodash.eachRight = forEachRight;
lodash.extend = assign;
lodash.methods = functions;
lodash.object = zipObject;
lodash.select = filter;
lodash.tail = rest;
lodash.unique = uniq;
lodash.unzip = zip;
// add functions to `lodash.prototype`
mixin(lodash);
/*--------------------------------------------------------------------------*/
// add functions that return unwrapped values when chaining
lodash.clone = clone;
lodash.cloneDeep = cloneDeep;
lodash.contains = contains;
lodash.escape = escape;
lodash.every = every;
lodash.find = find;
lodash.findIndex = findIndex;
lodash.findKey = findKey;
lodash.findLast = findLast;
lodash.findLastIndex = findLastIndex;
lodash.findLastKey = findLastKey;
lodash.has = has;
lodash.identity = identity;
lodash.indexOf = indexOf;
lodash.isArguments = isArguments;
lodash.isArray = isArray;
lodash.isBoolean = isBoolean;
lodash.isDate = isDate;
lodash.isElement = isElement;
lodash.isEmpty = isEmpty;
lodash.isEqual = isEqual;
lodash.isFinite = isFinite;
lodash.isFunction = isFunction;
lodash.isNaN = isNaN;
lodash.isNull = isNull;
lodash.isNumber = isNumber;
lodash.isObject = isObject;
lodash.isPlainObject = isPlainObject;
lodash.isRegExp = isRegExp;
lodash.isString = isString;
lodash.isUndefined = isUndefined;
lodash.lastIndexOf = lastIndexOf;
lodash.mixin = mixin;
lodash.noConflict = noConflict;
lodash.noop = noop;
lodash.now = now;
lodash.parseInt = parseInt;
lodash.random = random;
lodash.reduce = reduce;
lodash.reduceRight = reduceRight;
lodash.result = result;
lodash.runInContext = runInContext;
lodash.size = size;
lodash.some = some;
lodash.sortedIndex = sortedIndex;
lodash.template = template;
lodash.unescape = unescape;
lodash.uniqueId = uniqueId;
// add aliases
lodash.all = every;
lodash.any = some;
lodash.detect = find;
lodash.findWhere = find;
lodash.foldl = reduce;
lodash.foldr = reduceRight;
lodash.include = contains;
lodash.inject = reduce;
mixin(function() {
var source = {}
forOwn(lodash, function(func, methodName) {
if (!lodash.prototype[methodName]) {
source[methodName] = func;
}
});
return source;
}(), false);
/*--------------------------------------------------------------------------*/
// add functions capable of returning wrapped and unwrapped values when chaining
lodash.first = first;
lodash.last = last;
lodash.sample = sample;
// add aliases
lodash.take = first;
lodash.head = first;
forOwn(lodash, function(func, methodName) {
var callbackable = methodName !== 'sample';
if (!lodash.prototype[methodName]) {
lodash.prototype[methodName]= function(n, guard) {
var chainAll = this.__chain__,
result = func(this.__wrapped__, n, guard);
return !chainAll && (n == null || (guard && !(callbackable && typeof n == 'function')))
? result
: new lodashWrapper(result, chainAll);
};
}
});
/*--------------------------------------------------------------------------*/
/**
* The semantic version number.
*
* @static
* @memberOf _
* @type string
*/
lodash.VERSION = '2.4.1';
// add "Chaining" functions to the wrapper
lodash.prototype.chain = wrapperChain;
lodash.prototype.toString = wrapperToString;
lodash.prototype.value = wrapperValueOf;
lodash.prototype.valueOf = wrapperValueOf;
// add `Array` functions that return unwrapped values
baseEach(['join', 'pop', 'shift'], function(methodName) {
var func = arrayRef[methodName];
lodash.prototype[methodName] = function() {
var chainAll = this.__chain__,
result = func.apply(this.__wrapped__, arguments);
return chainAll
? new lodashWrapper(result, chainAll)
: result;
};
});
// add `Array` functions that return the existing wrapped value
baseEach(['push', 'reverse', 'sort', 'unshift'], function(methodName) {
var func = arrayRef[methodName];
lodash.prototype[methodName] = function() {
func.apply(this.__wrapped__, arguments);
return this;
};
});
// add `Array` functions that return new wrapped values
baseEach(['concat', 'slice', 'splice'], function(methodName) {
var func = arrayRef[methodName];
lodash.prototype[methodName] = function() {
return new lodashWrapper(func.apply(this.__wrapped__, arguments), this.__chain__);
};
});
// avoid array-like object bugs with `Array#shift` and `Array#splice`
// in IE < 9, Firefox < 10, Narwhal, and RingoJS
if (!support.spliceObjects) {
baseEach(['pop', 'shift', 'splice'], function(methodName) {
var func = arrayRef[methodName],
isSplice = methodName == 'splice';
lodash.prototype[methodName] = function() {
var chainAll = this.__chain__,
value = this.__wrapped__,
result = func.apply(value, arguments);
if (value.length === 0) {
delete value[0];
}
return (chainAll || isSplice)
? new lodashWrapper(result, chainAll)
: result;
};
});
}
return lodash;
}
/*--------------------------------------------------------------------------*/
// expose Lo-Dash
var _ = runInContext();
// some AMD build optimizers like r.js check for condition patterns like the following:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// Expose Lo-Dash to the global object even when an AMD loader is present in
// case Lo-Dash is loaded with a RequireJS shim config.
// See http://requirejs.org/docs/api.html#config-shim
root._ = _;
// define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module
define(function() {
return _;
});
}
// check for `exports` after `define` in case a build optimizer adds an `exports` object
else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = _)._ = _;
}
// in Narwhal or Rhino -require
else {
freeExports._ = _;
}
}
else {
// in a browser or Rhino
root._ = _;
}
}.call(this));
| MarkySparky/teuchters | node_modules/gruntfile-gtx/node_modules/load-grunt-tasks/node_modules/multimatch/node_modules/lodash/dist/lodash.compat.js | JavaScript | mit | 244,097 |
var powerSaveBlocker;
powerSaveBlocker = process.atomBinding('power_save_blocker').powerSaveBlocker;
module.exports = powerSaveBlocker;
| simongregory/electron | lib/browser/api/power-save-blocker.js | JavaScript | mit | 138 |
const fs = require(`fs`)
const fetchData = require(`../fetch`)
// Fetch data from our sample site and save it to disk.
const typePrefix = `wordpress__`
const refactoredEntityTypes = {
post: `${typePrefix}POST`,
page: `${typePrefix}PAGE`,
tag: `${typePrefix}TAG`,
category: `${typePrefix}CATEGORY`,
}
fetchData({
_verbose: false,
_siteURL: `http://dev-gatbsyjswp.pantheonsite.io`,
baseUrl: `dev-gatbsyjswp.pantheonsite.io`,
_useACF: true,
_hostingWPCOM: false,
_perPage: 100,
typePrefix,
refactoredEntityTypes,
}).then(data => {
fs.writeFileSync(
`${__dirname}/../__tests__/data.json`,
JSON.stringify(data, null, 4)
)
})
| danielfarrell/gatsby | packages/gatsby-source-wordpress/src/scripts/download-test-data.js | JavaScript | mit | 659 |
requirejs.config({
"paths": {
"jquery": "https://code.jquery.com/jquery-1.11.3.min",
"moment": "../../moment",
"daterangepicker": "../../daterangepicker"
}
});
requirejs(['jquery', 'moment', 'daterangepicker'] , function ($, moment) {
$(document).ready(function() {
$('#config-text').keyup(function() {
eval($(this).val());
});
$('.configurator input, .configurator select').change(function() {
updateConfig();
});
$('.demo i').click(function() {
$(this).parent().find('input').click();
});
$('#startDate').daterangepicker({
singleDatePicker: true,
startDate: moment().subtract(6, 'days')
});
$('#endDate').daterangepicker({
singleDatePicker: true,
startDate: moment()
});
updateConfig();
function updateConfig() {
var options = {};
if ($('#singleDatePicker').is(':checked'))
options.singleDatePicker = true;
if ($('#showDropdowns').is(':checked'))
options.showDropdowns = true;
if ($('#showWeekNumbers').is(':checked'))
options.showWeekNumbers = true;
if ($('#showISOWeekNumbers').is(':checked'))
options.showISOWeekNumbers = true;
if ($('#timePicker').is(':checked'))
options.timePicker = true;
if ($('#timePicker24Hour').is(':checked'))
options.timePicker24Hour = true;
if ($('#timePickerIncrement').val().length && $('#timePickerIncrement').val() != 1)
options.timePickerIncrement = parseInt($('#timePickerIncrement').val(), 10);
if ($('#timePickerSeconds').is(':checked'))
options.timePickerSeconds = true;
if ($('#autoApply').is(':checked'))
options.autoApply = true;
if ($('#dateLimit').is(':checked'))
options.dateLimit = { days: 7 };
if ($('#ranges').is(':checked')) {
options.ranges = {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
};
}
if ($('#locale').is(':checked')) {
options.locale = {
format: 'MM/DD/YYYY HH:mm',
separator: ' - ',
applyLabel: 'Apply',
cancelLabel: 'Cancel',
fromLabel: 'From',
toLabel: 'To',
customRangeLabel: 'Custom',
daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr','Sa'],
monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
firstDay: 1
};
}
if (!$('#linkedCalendars').is(':checked'))
options.linkedCalendars = false;
if (!$('#autoUpdateInput').is(':checked'))
options.autoUpdateInput = false;
if ($('#alwaysShowCalendars').is(':checked'))
options.alwaysShowCalendars = true;
if ($('#parentEl').val().length)
options.parentEl = $('#parentEl').val();
if ($('#startDate').val().length)
options.startDate = $('#startDate').val();
if ($('#endDate').val().length)
options.endDate = $('#endDate').val();
if ($('#minDate').val().length)
options.minDate = $('#minDate').val();
if ($('#maxDate').val().length)
options.maxDate = $('#maxDate').val();
if ($('#opens').val().length && $('#opens').val() != 'right')
options.opens = $('#opens').val();
if ($('#drops').val().length && $('#drops').val() != 'down')
options.drops = $('#drops').val();
if ($('#buttonClasses').val().length && $('#buttonClasses').val() != 'btn btn-sm')
options.buttonClasses = $('#buttonClasses').val();
if ($('#applyClass').val().length && $('#applyClass').val() != 'btn-success')
options.applyClass = $('#applyClass').val();
if ($('#cancelClass').val().length && $('#cancelClass').val() != 'btn-default')
options.cancelClass = $('#cancelClass').val();
$('#config-text').val("$('#demo').daterangepicker(" + JSON.stringify(options, null, ' ') + ", function(start, end, label) {\n console.log(\"New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')\");\n});");
$('#config-demo').daterangepicker(options, function(start, end, label) { console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')'); });
}
});
});
| asiboro/asiboro.github.io | plugins/daterangepicker/example/amd/main.js | JavaScript | mit | 4,777 |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'justify', 'en', {
block: 'Justify',
center: 'Center',
left: 'Align Left',
right: 'Align Right'
} );
| baem1000/fredagskul | wp-content/upgrade/wck-custom-fields-and-custom-post-types-creator.1.2.2-TZwCX7/wck-custom-fields-and-custom-post-types-creator/wordpress-creation-kit-api/assets/js/ckeditor/plugins/justify/lang/en.js | JavaScript | gpl-2.0 | 287 |
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.lang} object for the
* Dutch language.
*/
/**#@+
@type String
@example
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKEDITOR.lang[ 'nl' ] = {
// ARIA description.
editor: 'Tekstverwerker',
editorPanel: 'Tekstverwerker beheerpaneel',
// Common messages and labels.
common: {
// Screenreader titles. Please note that screenreaders are not always capable
// of reading non-English words. So be careful while translating it.
editorHelp: 'Druk ALT 0 voor hulp',
browseServer: 'Bladeren op server',
url: 'URL',
protocol: 'Protocol',
upload: 'Upload',
uploadSubmit: 'Naar server verzenden',
image: 'Afbeelding',
flash: 'Flash',
form: 'Formulier',
checkbox: 'Selectievinkje',
radio: 'Keuzerondje',
textField: 'Tekstveld',
textarea: 'Tekstvak',
hiddenField: 'Verborgen veld',
button: 'Knop',
select: 'Selectieveld',
imageButton: 'Afbeeldingsknop',
notSet: '<niet ingevuld>',
id: 'Id',
name: 'Naam',
langDir: 'Schrijfrichting',
langDirLtr: 'Links naar rechts (LTR)',
langDirRtl: 'Rechts naar links (RTL)',
langCode: 'Taalcode',
longDescr: 'Lange URL-omschrijving',
cssClass: 'Stylesheet-klassen',
advisoryTitle: 'Adviserende titel',
cssStyle: 'Stijl',
ok: 'OK',
cancel: 'Annuleren',
close: 'Sluiten',
preview: 'Voorbeeld',
resize: 'Sleep om te herschalen',
generalTab: 'Algemeen',
advancedTab: 'Geavanceerd',
validateNumberFailed: 'Deze waarde is geen geldig getal.',
confirmNewPage: 'Alle aangebrachte wijzigingen gaan verloren. Weet u zeker dat u een nieuwe pagina wilt openen?',
confirmCancel: 'Enkele opties zijn gewijzigd. Weet u zeker dat u dit dialoogvenster wilt sluiten?',
options: 'Opties',
target: 'Doelvenster',
targetNew: 'Nieuw venster (_blank)',
targetTop: 'Hele venster (_top)',
targetSelf: 'Zelfde venster (_self)',
targetParent: 'Origineel venster (_parent)',
langDirLTR: 'Links naar rechts (LTR)',
langDirRTL: 'Rechts naar links (RTL)',
styles: 'Stijl',
cssClasses: 'Stylesheet-klassen',
width: 'Breedte',
height: 'Hoogte',
align: 'Uitlijning',
alignLeft: 'Links',
alignRight: 'Rechts',
alignCenter: 'Centreren',
alignJustify: 'Uitvullen',
alignTop: 'Boven',
alignMiddle: 'Midden',
alignBottom: 'Onder',
alignNone: 'Geen',
invalidValue : 'Ongeldige waarde.',
invalidHeight: 'De hoogte moet een getal zijn.',
invalidWidth: 'De breedte moet een getal zijn.',
invalidCssLength: 'Waarde in veld "%1" moet een positief nummer zijn, met of zonder een geldige CSS meeteenheid (px, %, in, cm, mm, em, ex, pt of pc).',
invalidHtmlLength: 'Waarde in veld "%1" moet een positief nummer zijn, met of zonder een geldige HTML meeteenheid (px of %).',
invalidInlineStyle: 'Waarde voor de online stijl moet bestaan uit een of meerdere tupels met het formaat "naam : waarde", gescheiden door puntkomma\'s.',
cssLengthTooltip: 'Geef een nummer in voor een waarde in pixels of geef een nummer in met een geldige CSS eenheid (px, %, in, cm, mm, em, ex, pt, of pc).',
// Put the voice-only part of the label in the span.
unavailable: '%1<span class="cke_accessibility">, niet beschikbaar</span>'
}
};
| SeeyaSia/www | web/libraries/ckeditor/lang/nl.js | JavaScript | gpl-2.0 | 3,386 |
/* -*- 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/. */
/*
*
* Date: 12 Feb 2002
* SUMMARY: Don't crash on invalid regexp literals / \\/ /
*
* See http://bugzilla.mozilla.org/show_bug.cgi?id=122076
* The function checkURL() below sometimes caused a compile-time error:
*
* SyntaxError: unterminated parenthetical (:
*
* However, sometimes it would cause a crash instead. The presence of
* other functions below is merely fodder to help provoke the crash.
* The constant |STRESS| is number of times we'll try to crash on this.
*
*/
//-----------------------------------------------------------------------------
var BUGNUMBER = 122076;
var summary = "Don't crash on invalid regexp literals / \\/ /";
var STRESS = 10;
var sEval = '';
printBugNumber(BUGNUMBER);
printStatus(summary);
sEval += 'function checkDate()'
sEval += '{'
sEval += 'return (this.value.search(/^[012]?\d\/[0123]?\d\/[0]\d$/) != -1);'
sEval += '}'
sEval += 'function checkDNSName()'
sEval += '{'
sEval += ' return (this.value.search(/^([\w\-]+\.)+([\w\-]{2,3})$/) != -1);'
sEval += '}'
sEval += 'function checkEmail()'
sEval += '{'
sEval += ' return (this.value.search(/^([\w\-]+\.)*[\w\-]+@([\w\-]+\.)+([\w\-]{2,3})$/) != -1);'
sEval += '}'
sEval += 'function checkHostOrIP()'
sEval += '{'
sEval += ' if (this.value.search(/^([\w\-]+\.)+([\w\-]{2,3})$/) == -1)'
sEval += ' return (this.value.search(/^[1-2]?\d{1,2}\.[1-2]?\d{1,2}\.[1-2]?\d{1,2}\.[1-2]?\d{1,2}$/) != -1);'
sEval += ' else'
sEval += ' return true;'
sEval += '}'
sEval += 'function checkIPAddress()'
sEval += '{'
sEval += ' return (this.value.search(/^[1-2]?\d{1,2}\.[1-2]?\d{1,2}\.[1-2]?\d{1,2}\.[1-2]?\d{1,2}$/) != -1);'
sEval += '}'
sEval += 'function checkURL()'
sEval += '{'
sEval += ' return (this.value.search(/^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,4}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\/\*\$+@&#;`~=%!]*)(\.\w{2,})?)*\/?)$/) != -1);'
sEval += '}'
for (var i=0; i<STRESS; i++)
{
try
{
eval(sEval);
}
catch(e)
{
}
}
reportCompare('No Crash', 'No Crash', '');
| SlateScience/MozillaJS | js/src/tests/ecma_3/RegExp/regress-122076.js | JavaScript | mpl-2.0 | 2,299 |
/* -*- 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/. */
/**
File Name: 15.9.3.1.js
ECMA Section: 15.9.3.1 new Date (year, month, date, hours, minutes, seconds, ms)
Description: The [[Prototype]] property of the newly constructed
object is set to the original Date prototype object,
the one that is the initial value of Date.prototype.
The [[Class]] property of the newly constructed object
is set as follows:
1. Call ToNumber(year)
2. Call ToNumber(month)
3. Call ToNumber(date)
4. Call ToNumber(hours)
5. Call ToNumber(minutes)
6. Call ToNumber(seconds)
7. Call ToNumber(ms)
8. If Result(1) is NaN and 0 <= ToInteger(Result(1)) <=
99, Result(8) is 1900+ToInteger(Result(1)); otherwise,
Result(8) is Result(1)
9. Compute MakeDay(Result(8), Result(2), Result(3)
10. Compute MakeTime(Result(4), Result(5), Result(6),
Result(7)
11. Compute MakeDate(Result(9), Result(10))
12. Set the [[Value]] property of the newly constructed
object to TimeClip(UTC(Result(11))).
This tests the returned value of a newly constructed
Date object.
Author: christine@netscape.com
Date: 7 july 1997
*/
var SECTION = "15.9.3.1";
var VERSION = "ECMA_1";
startTest();
var TITLE = "new Date( year, month, date, hours, minutes, seconds, ms )";
var TIME = 0;
var UTC_YEAR = 1;
var UTC_MONTH = 2;
var UTC_DATE = 3;
var UTC_DAY = 4;
var UTC_HOURS = 5;
var UTC_MINUTES = 6;
var UTC_SECONDS = 7;
var UTC_MS = 8;
var YEAR = 9;
var MONTH = 10;
var DATE = 11;
var DAY = 12;
var HOURS = 13;
var MINUTES = 14;
var SECONDS = 15;
var MS = 16;
writeHeaderToLog( SECTION + " "+ TITLE);
// all the "ResultArrays" below are hard-coded to Pacific Standard Time values -
// Dates around 2000
addNewTestCase( new Date( 1999,11,31,15,59,59,999),
"new Date( 1999,11,31,15,59,59,999)",
[TIME_2000-1,1999,11,31,5,23,59,59,999,1999,11,31,5,15,59,59,999] );
addNewTestCase( new Date( 1999,11,31,16,0,0,0),
"new Date( 1999,11,31,16,0,0,0)",
[TIME_2000,2000,0,1,6,0,0,0,0,1999,11,31,5, 16,0,0,0] );
addNewTestCase( new Date( 1999,11,31,23,59,59,999),
"new Date( 1999,11,31,23,59,59,999)",
[TIME_2000-PST_ADJUST-1,2000,0,1,6,7,59,59,999,1999,11,31,5,23,59,59,999] );
addNewTestCase( new Date( 2000,0,1,0,0,0,0),
"new Date( 2000,0,1,0,0,0,0)",
[TIME_2000-PST_ADJUST,2000,0,1,6,8,0,0,0,2000,0,1,6,0,0,0,0] );
addNewTestCase( new Date( 2000,0,1,0,0,0,1),
"new Date( 2000,0,1,0,0,0,1)",
[TIME_2000-PST_ADJUST+1,2000,0,1,6,8,0,0,1,2000,0,1,6,0,0,0,1] );
test();
function addNewTestCase( DateCase, DateString, ResultArray ) {
//adjust hard-coded ResultArray for tester's timezone instead of PST
adjustResultArray(ResultArray);
new TestCase( SECTION, DateString+".getTime()", ResultArray[TIME], DateCase.getTime() );
new TestCase( SECTION, DateString+".valueOf()", ResultArray[TIME], DateCase.valueOf() );
new TestCase( SECTION, DateString+".getUTCFullYear()", ResultArray[UTC_YEAR], DateCase.getUTCFullYear() );
new TestCase( SECTION, DateString+".getUTCMonth()", ResultArray[UTC_MONTH], DateCase.getUTCMonth() );
new TestCase( SECTION, DateString+".getUTCDate()", ResultArray[UTC_DATE], DateCase.getUTCDate() );
new TestCase( SECTION, DateString+".getUTCDay()", ResultArray[UTC_DAY], DateCase.getUTCDay() );
new TestCase( SECTION, DateString+".getUTCHours()", ResultArray[UTC_HOURS], DateCase.getUTCHours() );
new TestCase( SECTION, DateString+".getUTCMinutes()", ResultArray[UTC_MINUTES],DateCase.getUTCMinutes() );
new TestCase( SECTION, DateString+".getUTCSeconds()", ResultArray[UTC_SECONDS],DateCase.getUTCSeconds() );
new TestCase( SECTION, DateString+".getUTCMilliseconds()", ResultArray[UTC_MS], DateCase.getUTCMilliseconds() );
new TestCase( SECTION, DateString+".getFullYear()", ResultArray[YEAR], DateCase.getFullYear() );
new TestCase( SECTION, DateString+".getMonth()", ResultArray[MONTH], DateCase.getMonth() );
new TestCase( SECTION, DateString+".getDate()", ResultArray[DATE], DateCase.getDate() );
new TestCase( SECTION, DateString+".getDay()", ResultArray[DAY], DateCase.getDay() );
new TestCase( SECTION, DateString+".getHours()", ResultArray[HOURS], DateCase.getHours() );
new TestCase( SECTION, DateString+".getMinutes()", ResultArray[MINUTES], DateCase.getMinutes() );
new TestCase( SECTION, DateString+".getSeconds()", ResultArray[SECONDS], DateCase.getSeconds() );
new TestCase( SECTION, DateString+".getMilliseconds()", ResultArray[MS], DateCase.getMilliseconds() );
}
| JasonGross/mozjs | js/src/tests/ecma/Date/15.9.3.1-2.js | JavaScript | mpl-2.0 | 5,053 |
'use strict';
const stripIndent = require('strip-indent');
const indentString = require('indent-string');
module.exports = (str, count, indent) => indentString(stripIndent(str), count || 0, indent);
| BigBoss424/portfolio | v7/development/node_modules/redent/index.js | JavaScript | apache-2.0 | 200 |
//// [constructorReturnsInvalidType.ts]
class X {
constructor() {
return 1;
}
foo() { }
}
var x = new X();
//// [constructorReturnsInvalidType.js]
var X = (function () {
function X() {
return 1;
}
X.prototype.foo = function () {
};
return X;
})();
var x = new X();
| RReverser/TSX | tests/baselines/reference/constructorReturnsInvalidType.js | JavaScript | apache-2.0 | 330 |
dojo.provide("tests._base.Deferred");
var delay = function(ms){
var d = new dojo.Deferred();
ms = ms || 20;
setTimeout(function(){
d.progress(0.5);
},ms/2);
setTimeout(function(){
d.resolve();
},ms);
return d.promise;
};
doh.register("tests._base.Deferred",
[
function callback(t){
var nd = new dojo.Deferred();
var cnt = 0;
nd.addCallback(function(res){
doh.debug("debug from dojo.Deferred callback");
return res;
});
nd.addCallback(function(res){
// t.debug("val:", res);
cnt+=res;
return cnt;
});
nd.callback(5);
// t.debug("cnt:", cnt);
t.assertEqual(cnt, 5);
},
function callback_extra_args(t){
var nd = new dojo.Deferred();
var cnt = 0;
nd.addCallback(dojo.global, function(base, res){ cnt+=base; cnt+=res; return cnt; }, 30);
nd.callback(5);
t.assertEqual(cnt, 35);
},
function errback(t){
var nd = new dojo.Deferred();
var cnt = 0;
nd.addErrback(function(val){
return ++cnt;
});
nd.errback();
t.assertEqual(cnt, 1);
},
function callbackTwice(t){
var nd = new dojo.Deferred();
var cnt = 0;
nd.addCallback(function(res){
return ++cnt;
});
nd.callback();
t.assertEqual(cnt, 1);
var thrown = false;
try{
nd.callback();
}catch(e){
thrown = true;
}
t.assertTrue(thrown);
},
function addBoth(t){
var nd = new dojo.Deferred();
var cnt = 0;
nd.addBoth(function(res){
return ++cnt;
});
nd.callback();
t.assertEqual(cnt, 1);
// nd.callback();
// t.debug(cnt);
// t.assertEqual(cnt, 1);
},
function callbackNested(t){
var nd = new dojo.Deferred();
var nestedReturn = "yellow";
nd.addCallback(function(res){
nd.addCallback(function(res2){
nestedReturn = res2;
});
return "blue";
});
nd.callback("red");
t.assertEqual("blue", nestedReturn);
},
function simpleThen(t){
var td = new doh.Deferred();
delay().then(function(){
td.callback(true);
});
return td;
},
function thenChaining(t){
var td = new doh.Deferred();
var p = delay();
var p2 = p.then(function(){
return 1;
});
p3 = p2.then(function(){
return 2;
});
p3.then(function(){
p2.then(function(v){
t.assertEqual(v, 1);
p3.then(function(v){
t.assertEqual(v, 2);
td.callback(true);
});
});
});
return td;
},
function simpleWhen(t){
var td = new doh.Deferred();
dojo.when(delay(), function(){
td.callback(true);
});
return td;
},
function progress(t){
var td = new doh.Deferred();
var percentDone;
dojo.when(delay(), function(){
t.is(percentDone, 0.5);
td.callback(true);
},function(){},
function(completed){
percentDone = completed;
});
return td;
},
function errorHandler(t){
var def = new dojo.Deferred();
var handledError;
dojo.config.deferredOnError = function(e){
handledError = e;
};
def.reject(new Error("test"));
t.t(handledError instanceof Error);
},
function cancelThenDerivative(t){
var def = new dojo.Deferred();
var def2 = def.then();
try{
def2.cancel();
t.t(true); // Didn't throw an error
}catch(e){
t.t(false);
}
},
function cancelPromiseValue(t){
var cancelledDef;
var def = new dojo.Deferred(function(_def){ cancelledDef = _def; });
def.promise.cancel();
t.is(def, cancelledDef);
},
function errorResult(t){
var def = new dojo.Deferred();
var result = new Error("rejected");
def.reject(result);
t.is(def.fired, 1);
t.is(def.results[1], result);
},
function globalLeak(t){
var def = new dojo.Deferred();
def.then(function(){ return def; });
def.resolve(true);
t.is(dojo.global.results, undefined, "results is leaking into global");
t.is(dojo.global.fired, undefined, "fired is leaking into global");
},
function backAndForthProcess(t){
var def = new dojo.Deferred();
var retval = "fail";
def.addErrback(function(){
return "ignore error and throw this good string";
}).addCallback(function(){
throw new Error("error1");
}).addErrback(function(){
return "ignore second error and make it good again";
}).addCallback(function(){
retval = "succeed";
});
def.errback("");
t.assertEqual("succeed", retval);
},
function backAndForthProcessThen(t){
var def = new dojo.Deferred;
var retval = "fail";
def.then(null, function(){
return "ignore error and throw this good string";
}).then(function(){
throw "error1";
}).then(null, function(){
return "ignore second error and make it good again";
}).then(function(){
retval = "succeed";
});
def.reject("");
t.assertEqual("succeed", retval);
},
function returnErrorObject(t){
var def = new dojo.Deferred();
var retval = "fail";
def.addCallback(function(){
return new Error("returning an error should work same as throwing");
}).addErrback(function(){
retval = "succeed";
});
def.callback();
t.assertEqual("succeed", retval);
},
function returnErrorObjectThen(t){
var def = new dojo.Deferred();
var retval = "fail";
def.then(function(){
return new Error("returning an error should NOT work same as throwing");
}).then(function(){
retval = "succeed";
});
def.resolve();
t.assertEqual("succeed", retval);
},
function errbackWithPromise(t){
var def = new dojo.Deferred();
var retval;
def.addCallbacks(function(){}, function(err){
return err;
});
def.promise.then(
function(){ retval = "fail"; },
function(){ retval = "succeed"; });
def.errback(new Error);
t.assertEqual("succeed", retval);
}
]
);
| sulistionoadi/belajar-springmvc-dojo | training-web/src/main/webapp/js/dojotoolkit/dojo/tests/_base/Deferred.js | JavaScript | apache-2.0 | 5,706 |
/*
* Copyright 2012-2015 MarkLogic Corporation
*
* 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.
*/
define([
'json!./contributor.json',
'json!./question.json',
'json!./searchResponse.json',
'json!./searchResult.json',
'json!./ssSearchInstance.json',
'json!./tagsResult.json'
], function (
contributor,
question,
searchResponse,
searchResult,
ssSearchInstance,
tagsResult
) {
return {
searchResult: searchResult,
searchResponse: searchResponse,
contributor: contributor,
ssSearchInstance: ssSearchInstance,
question: question,
tagsResult: tagsResult
};
});
| marklogic/marklogic-samplestack | browser/src/mocks/index.js | JavaScript | apache-2.0 | 1,133 |
describe('[Regression](GH-1424)', function () {
it('Should raise click event on a button after "enter" key is pressed', function () {
return runTests('testcafe-fixtures/index-test.js', 'Press enter');
});
});
| georgiy-abbasov/testcafe-phoenix | test/functional/fixtures/regression/gh-1424/test.js | JavaScript | mit | 225 |
/*!
* Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/*!
* Ext JS Library 3.3.0
* Copyright(c) 2006-2010 Ext JS, Inc.
* licensing@extjs.com
* http://www.extjs.com/license
*/
Ext.ns('Ext.ux.grid');
Ext.ux.grid.LockingGridView = Ext.extend(Ext.grid.GridView, {
lockText : 'Lock',
unlockText : 'Unlock',
rowBorderWidth : 1,
lockedBorderWidth : 1,
/*
* This option ensures that height between the rows is synchronized
* between the locked and unlocked sides. This option only needs to be used
* when the row heights aren't predictable.
*/
syncHeights: false,
initTemplates : function(){
var ts = this.templates || {};
if (!ts.masterTpl) {
ts.masterTpl = new Ext.Template(
'<div class="x-grid3" hidefocus="true">',
'<div class="x-grid3-locked">',
'<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset" style="{lstyle}">{lockedHeader}</div></div><div class="x-clear"></div></div>',
'<div class="x-grid3-scroller"><div class="x-grid3-body" style="{lstyle}">{lockedBody}</div><div class="x-grid3-scroll-spacer"></div></div>',
'</div>',
'<div class="x-grid3-viewport x-grid3-unlocked">',
'<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset" style="{ostyle}">{header}</div></div><div class="x-clear"></div></div>',
'<div class="x-grid3-scroller"><div class="x-grid3-body" style="{bstyle}">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>',
'</div>',
'<div class="x-grid3-resize-marker"> </div>',
'<div class="x-grid3-resize-proxy"> </div>',
'</div>'
);
}
this.templates = ts;
Ext.ux.grid.LockingGridView.superclass.initTemplates.call(this);
},
getEditorParent : function(ed){
return this.el.dom;
},
initElements : function(){
var el = Ext.get(this.grid.getGridEl().dom.firstChild),
lockedWrap = el.child('div.x-grid3-locked'),
lockedHd = lockedWrap.child('div.x-grid3-header'),
lockedScroller = lockedWrap.child('div.x-grid3-scroller'),
mainWrap = el.child('div.x-grid3-viewport'),
mainHd = mainWrap.child('div.x-grid3-header'),
scroller = mainWrap.child('div.x-grid3-scroller');
if (this.grid.hideHeaders) {
lockedHd.setDisplayed(false);
mainHd.setDisplayed(false);
}
if(this.forceFit){
scroller.setStyle('overflow-x', 'hidden');
}
Ext.apply(this, {
el : el,
mainWrap: mainWrap,
mainHd : mainHd,
innerHd : mainHd.dom.firstChild,
scroller: scroller,
mainBody: scroller.child('div.x-grid3-body'),
focusEl : scroller.child('a'),
resizeMarker: el.child('div.x-grid3-resize-marker'),
resizeProxy : el.child('div.x-grid3-resize-proxy'),
lockedWrap: lockedWrap,
lockedHd: lockedHd,
lockedScroller: lockedScroller,
lockedBody: lockedScroller.child('div.x-grid3-body'),
lockedInnerHd: lockedHd.child('div.x-grid3-header-inner', true)
});
this.focusEl.swallowEvent('click', true);
},
getLockedRows : function(){
return this.hasRows() ? this.lockedBody.dom.childNodes : [];
},
getLockedRow : function(row){
return this.getLockedRows()[row];
},
getCell : function(row, col){
var lockedLen = this.cm.getLockedCount();
if(col < lockedLen){
return this.getLockedRow(row).getElementsByTagName('td')[col];
}
return Ext.ux.grid.LockingGridView.superclass.getCell.call(this, row, col - lockedLen);
},
getHeaderCell : function(index){
var lockedLen = this.cm.getLockedCount();
if(index < lockedLen){
return this.lockedHd.dom.getElementsByTagName('td')[index];
}
return Ext.ux.grid.LockingGridView.superclass.getHeaderCell.call(this, index - lockedLen);
},
addRowClass : function(row, cls){
var lockedRow = this.getLockedRow(row);
if(lockedRow){
this.fly(lockedRow).addClass(cls);
}
Ext.ux.grid.LockingGridView.superclass.addRowClass.call(this, row, cls);
},
removeRowClass : function(row, cls){
var lockedRow = this.getLockedRow(row);
if(lockedRow){
this.fly(lockedRow).removeClass(cls);
}
Ext.ux.grid.LockingGridView.superclass.removeRowClass.call(this, row, cls);
},
removeRow : function(row) {
Ext.removeNode(this.getLockedRow(row));
Ext.ux.grid.LockingGridView.superclass.removeRow.call(this, row);
},
removeRows : function(firstRow, lastRow){
var lockedBody = this.lockedBody.dom,
rowIndex = firstRow;
for(; rowIndex <= lastRow; rowIndex++){
Ext.removeNode(lockedBody.childNodes[firstRow]);
}
Ext.ux.grid.LockingGridView.superclass.removeRows.call(this, firstRow, lastRow);
},
syncScroll : function(e){
this.lockedScroller.dom.scrollTop = this.scroller.dom.scrollTop;
Ext.ux.grid.LockingGridView.superclass.syncScroll.call(this, e);
},
updateSortIcon : function(col, dir){
var sortClasses = this.sortClasses,
lockedHeaders = this.lockedHd.select('td').removeClass(sortClasses),
headers = this.mainHd.select('td').removeClass(sortClasses),
lockedLen = this.cm.getLockedCount(),
cls = sortClasses[dir == 'DESC' ? 1 : 0];
if(col < lockedLen){
lockedHeaders.item(col).addClass(cls);
}else{
headers.item(col - lockedLen).addClass(cls);
}
},
updateAllColumnWidths : function(){
var tw = this.getTotalWidth(),
clen = this.cm.getColumnCount(),
lw = this.getLockedWidth(),
llen = this.cm.getLockedCount(),
ws = [], len, i;
this.updateLockedWidth();
for(i = 0; i < clen; i++){
ws[i] = this.getColumnWidth(i);
var hd = this.getHeaderCell(i);
hd.style.width = ws[i];
}
var lns = this.getLockedRows(), ns = this.getRows(), row, trow, j;
for(i = 0, len = ns.length; i < len; i++){
row = lns[i];
row.style.width = lw;
if(row.firstChild){
row.firstChild.style.width = lw;
trow = row.firstChild.rows[0];
for (j = 0; j < llen; j++) {
trow.childNodes[j].style.width = ws[j];
}
}
row = ns[i];
row.style.width = tw;
if(row.firstChild){
row.firstChild.style.width = tw;
trow = row.firstChild.rows[0];
for (j = llen; j < clen; j++) {
trow.childNodes[j - llen].style.width = ws[j];
}
}
}
this.onAllColumnWidthsUpdated(ws, tw);
this.syncHeaderHeight();
},
updateColumnWidth : function(col, width){
var w = this.getColumnWidth(col),
llen = this.cm.getLockedCount(),
ns, rw, c, row;
this.updateLockedWidth();
if(col < llen){
ns = this.getLockedRows();
rw = this.getLockedWidth();
c = col;
}else{
ns = this.getRows();
rw = this.getTotalWidth();
c = col - llen;
}
var hd = this.getHeaderCell(col);
hd.style.width = w;
for(var i = 0, len = ns.length; i < len; i++){
row = ns[i];
row.style.width = rw;
if(row.firstChild){
row.firstChild.style.width = rw;
row.firstChild.rows[0].childNodes[c].style.width = w;
}
}
this.onColumnWidthUpdated(col, w, this.getTotalWidth());
this.syncHeaderHeight();
},
updateColumnHidden : function(col, hidden){
var llen = this.cm.getLockedCount(),
ns, rw, c, row,
display = hidden ? 'none' : '';
this.updateLockedWidth();
if(col < llen){
ns = this.getLockedRows();
rw = this.getLockedWidth();
c = col;
}else{
ns = this.getRows();
rw = this.getTotalWidth();
c = col - llen;
}
var hd = this.getHeaderCell(col);
hd.style.display = display;
for(var i = 0, len = ns.length; i < len; i++){
row = ns[i];
row.style.width = rw;
if(row.firstChild){
row.firstChild.style.width = rw;
row.firstChild.rows[0].childNodes[c].style.display = display;
}
}
this.onColumnHiddenUpdated(col, hidden, this.getTotalWidth());
delete this.lastViewWidth;
this.layout();
},
doRender : function(cs, rs, ds, startRow, colCount, stripe){
var ts = this.templates, ct = ts.cell, rt = ts.row, last = colCount-1,
tstyle = 'width:'+this.getTotalWidth()+';',
lstyle = 'width:'+this.getLockedWidth()+';',
buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r;
for(var j = 0, len = rs.length; j < len; j++){
r = rs[j]; cb = []; lcb = [];
var rowIndex = (j+startRow);
for(var i = 0; i < colCount; i++){
c = cs[i];
p.id = c.id;
p.css = (i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '')) +
(this.cm.config[i].cellCls ? ' ' + this.cm.config[i].cellCls : '');
p.attr = p.cellAttr = '';
p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
p.style = c.style;
if(Ext.isEmpty(p.value)){
p.value = ' ';
}
if(this.markDirty && r.dirty && Ext.isDefined(r.modified[c.name])){
p.css += ' x-grid3-dirty-cell';
}
if(c.locked){
lcb[lcb.length] = ct.apply(p);
}else{
cb[cb.length] = ct.apply(p);
}
}
var alt = [];
if(stripe && ((rowIndex+1) % 2 === 0)){
alt[0] = 'x-grid3-row-alt';
}
if(r.dirty){
alt[1] = ' x-grid3-dirty-row';
}
rp.cols = colCount;
if(this.getRowClass){
alt[2] = this.getRowClass(r, rowIndex, rp, ds);
}
rp.alt = alt.join(' ');
rp.cells = cb.join('');
rp.tstyle = tstyle;
buf[buf.length] = rt.apply(rp);
rp.cells = lcb.join('');
rp.tstyle = lstyle;
lbuf[lbuf.length] = rt.apply(rp);
}
return [buf.join(''), lbuf.join('')];
},
processRows : function(startRow, skipStripe){
if(!this.ds || this.ds.getCount() < 1){
return;
}
var rows = this.getRows(),
lrows = this.getLockedRows(),
row, lrow;
skipStripe = skipStripe || !this.grid.stripeRows;
startRow = startRow || 0;
for(var i = 0, len = rows.length; i < len; ++i){
row = rows[i];
lrow = lrows[i];
row.rowIndex = i;
lrow.rowIndex = i;
if(!skipStripe){
row.className = row.className.replace(this.rowClsRe, ' ');
lrow.className = lrow.className.replace(this.rowClsRe, ' ');
if ((i + 1) % 2 === 0){
row.className += ' x-grid3-row-alt';
lrow.className += ' x-grid3-row-alt';
}
}
this.syncRowHeights(row, lrow);
}
if(startRow === 0){
Ext.fly(rows[0]).addClass(this.firstRowCls);
Ext.fly(lrows[0]).addClass(this.firstRowCls);
}
Ext.fly(rows[rows.length - 1]).addClass(this.lastRowCls);
Ext.fly(lrows[lrows.length - 1]).addClass(this.lastRowCls);
},
syncRowHeights: function(row1, row2){
if(this.syncHeights){
var el1 = Ext.get(row1),
el2 = Ext.get(row2),
h1 = el1.getHeight(),
h2 = el2.getHeight();
if(h1 > h2){
el2.setHeight(h1);
}else if(h2 > h1){
el1.setHeight(h2);
}
}
},
afterRender : function(){
if(!this.ds || !this.cm){
return;
}
var bd = this.renderRows() || [' ', ' '];
this.mainBody.dom.innerHTML = bd[0];
this.lockedBody.dom.innerHTML = bd[1];
this.processRows(0, true);
if(this.deferEmptyText !== true){
this.applyEmptyText();
}
this.grid.fireEvent('viewready', this.grid);
},
renderUI : function(){
var templates = this.templates,
header = this.renderHeaders(),
body = templates.body.apply({rows:' '});
return templates.masterTpl.apply({
body : body,
header: header[0],
ostyle: 'width:' + this.getOffsetWidth() + ';',
bstyle: 'width:' + this.getTotalWidth() + ';',
lockedBody: body,
lockedHeader: header[1],
lstyle: 'width:'+this.getLockedWidth()+';'
});
},
afterRenderUI: function(){
var g = this.grid;
this.initElements();
Ext.fly(this.innerHd).on('click', this.handleHdDown, this);
Ext.fly(this.lockedInnerHd).on('click', this.handleHdDown, this);
this.mainHd.on({
scope: this,
mouseover: this.handleHdOver,
mouseout: this.handleHdOut,
mousemove: this.handleHdMove
});
this.lockedHd.on({
scope: this,
mouseover: this.handleHdOver,
mouseout: this.handleHdOut,
mousemove: this.handleHdMove
});
this.scroller.on('scroll', this.syncScroll, this);
if(g.enableColumnResize !== false){
this.splitZone = new Ext.grid.GridView.SplitDragZone(g, this.mainHd.dom);
this.splitZone.setOuterHandleElId(Ext.id(this.lockedHd.dom));
this.splitZone.setOuterHandleElId(Ext.id(this.mainHd.dom));
}
if(g.enableColumnMove){
this.columnDrag = new Ext.grid.GridView.ColumnDragZone(g, this.innerHd);
this.columnDrag.setOuterHandleElId(Ext.id(this.lockedInnerHd));
this.columnDrag.setOuterHandleElId(Ext.id(this.innerHd));
this.columnDrop = new Ext.grid.HeaderDropZone(g, this.mainHd.dom);
}
if(g.enableHdMenu !== false){
this.hmenu = new Ext.menu.Menu({id: g.id + '-hctx'});
this.hmenu.add(
{itemId: 'asc', text: this.sortAscText, cls: 'xg-hmenu-sort-asc'},
{itemId: 'desc', text: this.sortDescText, cls: 'xg-hmenu-sort-desc'}
);
if(this.grid.enableColLock !== false){
this.hmenu.add('-',
{itemId: 'lock', text: this.lockText, cls: 'xg-hmenu-lock'},
{itemId: 'unlock', text: this.unlockText, cls: 'xg-hmenu-unlock'}
);
}
if(g.enableColumnHide !== false){
this.colMenu = new Ext.menu.Menu({id:g.id + '-hcols-menu'});
this.colMenu.on({
scope: this,
beforeshow: this.beforeColMenuShow,
itemclick: this.handleHdMenuClick
});
this.hmenu.add('-', {
itemId:'columns',
hideOnClick: false,
text: this.columnsText,
menu: this.colMenu,
iconCls: 'x-cols-icon'
});
}
this.hmenu.on('itemclick', this.handleHdMenuClick, this);
}
if(g.trackMouseOver){
this.mainBody.on({
scope: this,
mouseover: this.onRowOver,
mouseout: this.onRowOut
});
this.lockedBody.on({
scope: this,
mouseover: this.onRowOver,
mouseout: this.onRowOut
});
}
if(g.enableDragDrop || g.enableDrag){
this.dragZone = new Ext.grid.GridDragZone(g, {
ddGroup : g.ddGroup || 'GridDD'
});
}
this.updateHeaderSortState();
},
layout : function(){
if(!this.mainBody){
return;
}
var g = this.grid;
var c = g.getGridEl();
var csize = c.getSize(true);
var vw = csize.width;
if(!g.hideHeaders && (vw < 20 || csize.height < 20)){
return;
}
this.syncHeaderHeight();
if(g.autoHeight){
this.scroller.dom.style.overflow = 'visible';
this.lockedScroller.dom.style.overflow = 'visible';
if(Ext.isWebKit){
this.scroller.dom.style.position = 'static';
this.lockedScroller.dom.style.position = 'static';
}
}else{
this.el.setSize(csize.width, csize.height);
var hdHeight = this.mainHd.getHeight();
var vh = csize.height - (hdHeight);
}
this.updateLockedWidth();
if(this.forceFit){
if(this.lastViewWidth != vw){
this.fitColumns(false, false);
this.lastViewWidth = vw;
}
}else {
this.autoExpand();
this.syncHeaderScroll();
}
this.onLayout(vw, vh);
},
getOffsetWidth : function() {
return (this.cm.getTotalWidth() - this.cm.getTotalLockedWidth() + this.getScrollOffset()) + 'px';
},
renderHeaders : function(){
var cm = this.cm,
ts = this.templates,
ct = ts.hcell,
cb = [], lcb = [],
p = {},
len = cm.getColumnCount(),
last = len - 1;
for(var i = 0; i < len; i++){
p.id = cm.getColumnId(i);
p.value = cm.getColumnHeader(i) || '';
p.style = this.getColumnStyle(i, true);
p.tooltip = this.getColumnTooltip(i);
p.css = (i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '')) +
(cm.config[i].headerCls ? ' ' + cm.config[i].headerCls : '');
if(cm.config[i].align == 'right'){
p.istyle = 'padding-right:16px';
} else {
delete p.istyle;
}
if(cm.isLocked(i)){
lcb[lcb.length] = ct.apply(p);
}else{
cb[cb.length] = ct.apply(p);
}
}
return [ts.header.apply({cells: cb.join(''), tstyle:'width:'+this.getTotalWidth()+';'}),
ts.header.apply({cells: lcb.join(''), tstyle:'width:'+this.getLockedWidth()+';'})];
},
updateHeaders : function(){
var hd = this.renderHeaders();
this.innerHd.firstChild.innerHTML = hd[0];
this.innerHd.firstChild.style.width = this.getOffsetWidth();
this.innerHd.firstChild.firstChild.style.width = this.getTotalWidth();
this.lockedInnerHd.firstChild.innerHTML = hd[1];
var lw = this.getLockedWidth();
this.lockedInnerHd.firstChild.style.width = lw;
this.lockedInnerHd.firstChild.firstChild.style.width = lw;
},
getResolvedXY : function(resolved){
if(!resolved){
return null;
}
var c = resolved.cell, r = resolved.row;
return c ? Ext.fly(c).getXY() : [this.scroller.getX(), Ext.fly(r).getY()];
},
syncFocusEl : function(row, col, hscroll){
Ext.ux.grid.LockingGridView.superclass.syncFocusEl.call(this, row, col, col < this.cm.getLockedCount() ? false : hscroll);
},
ensureVisible : function(row, col, hscroll){
return Ext.ux.grid.LockingGridView.superclass.ensureVisible.call(this, row, col, col < this.cm.getLockedCount() ? false : hscroll);
},
insertRows : function(dm, firstRow, lastRow, isUpdate){
var last = dm.getCount() - 1;
if(!isUpdate && firstRow === 0 && lastRow >= last){
this.refresh();
}else{
if(!isUpdate){
this.fireEvent('beforerowsinserted', this, firstRow, lastRow);
}
var html = this.renderRows(firstRow, lastRow),
before = this.getRow(firstRow);
if(before){
if(firstRow === 0){
this.removeRowClass(0, this.firstRowCls);
}
Ext.DomHelper.insertHtml('beforeBegin', before, html[0]);
before = this.getLockedRow(firstRow);
Ext.DomHelper.insertHtml('beforeBegin', before, html[1]);
}else{
this.removeRowClass(last - 1, this.lastRowCls);
Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html[0]);
Ext.DomHelper.insertHtml('beforeEnd', this.lockedBody.dom, html[1]);
}
if(!isUpdate){
this.fireEvent('rowsinserted', this, firstRow, lastRow);
this.processRows(firstRow);
}else if(firstRow === 0 || firstRow >= last){
this.addRowClass(firstRow, firstRow === 0 ? this.firstRowCls : this.lastRowCls);
}
}
this.syncFocusEl(firstRow);
},
getColumnStyle : function(col, isHeader){
var style = !isHeader ? this.cm.config[col].cellStyle || this.cm.config[col].css || '' : this.cm.config[col].headerStyle || '';
style += 'width:'+this.getColumnWidth(col)+';';
if(this.cm.isHidden(col)){
style += 'display:none;';
}
var align = this.cm.config[col].align;
if(align){
style += 'text-align:'+align+';';
}
return style;
},
getLockedWidth : function() {
return this.cm.getTotalLockedWidth() + 'px';
},
getTotalWidth : function() {
return (this.cm.getTotalWidth() - this.cm.getTotalLockedWidth()) + 'px';
},
getColumnData : function(){
var cs = [], cm = this.cm, colCount = cm.getColumnCount();
for(var i = 0; i < colCount; i++){
var name = cm.getDataIndex(i);
cs[i] = {
name : (!Ext.isDefined(name) ? this.ds.fields.get(i).name : name),
renderer : cm.getRenderer(i),
id : cm.getColumnId(i),
style : this.getColumnStyle(i),
locked : cm.isLocked(i)
};
}
return cs;
},
renderBody : function(){
var markup = this.renderRows() || [' ', ' '];
return [this.templates.body.apply({rows: markup[0]}), this.templates.body.apply({rows: markup[1]})];
},
refreshRow: function(record){
var store = this.ds,
colCount = this.cm.getColumnCount(),
columns = this.getColumnData(),
last = colCount - 1,
cls = ['x-grid3-row'],
rowParams = {
tstyle: String.format("width: {0};", this.getTotalWidth())
},
lockedRowParams = {
tstyle: String.format("width: {0};", this.getLockedWidth())
},
colBuffer = [],
lockedColBuffer = [],
cellTpl = this.templates.cell,
rowIndex,
row,
lockedRow,
column,
meta,
css,
i;
if (Ext.isNumber(record)) {
rowIndex = record;
record = store.getAt(rowIndex);
} else {
rowIndex = store.indexOf(record);
}
if (!record || rowIndex < 0) {
return;
}
for (i = 0; i < colCount; i++) {
column = columns[i];
if (i == 0) {
css = 'x-grid3-cell-first';
} else {
css = (i == last) ? 'x-grid3-cell-last ' : '';
}
meta = {
id: column.id,
style: column.style,
css: css,
attr: "",
cellAttr: ""
};
meta.value = column.renderer.call(column.scope, record.data[column.name], meta, record, rowIndex, i, store);
if (Ext.isEmpty(meta.value)) {
meta.value = ' ';
}
if (this.markDirty && record.dirty && typeof record.modified[column.name] != 'undefined') {
meta.css += ' x-grid3-dirty-cell';
}
if (column.locked) {
lockedColBuffer[i] = cellTpl.apply(meta);
} else {
colBuffer[i] = cellTpl.apply(meta);
}
}
row = this.getRow(rowIndex);
row.className = '';
lockedRow = this.getLockedRow(rowIndex);
lockedRow.className = '';
if (this.grid.stripeRows && ((rowIndex + 1) % 2 === 0)) {
cls.push('x-grid3-row-alt');
}
if (this.getRowClass) {
rowParams.cols = colCount;
cls.push(this.getRowClass(record, rowIndex, rowParams, store));
}
// Unlocked rows
this.fly(row).addClass(cls).setStyle(rowParams.tstyle);
rowParams.cells = colBuffer.join("");
row.innerHTML = this.templates.rowInner.apply(rowParams);
// Locked rows
this.fly(lockedRow).addClass(cls).setStyle(lockedRowParams.tstyle);
lockedRowParams.cells = lockedColBuffer.join("");
lockedRow.innerHTML = this.templates.rowInner.apply(lockedRowParams);
lockedRow.rowIndex = rowIndex;
this.syncRowHeights(row, lockedRow);
this.fireEvent('rowupdated', this, rowIndex, record);
},
refresh : function(headersToo){
this.fireEvent('beforerefresh', this);
this.grid.stopEditing(true);
var result = this.renderBody();
this.mainBody.update(result[0]).setWidth(this.getTotalWidth());
this.lockedBody.update(result[1]).setWidth(this.getLockedWidth());
if(headersToo === true){
this.updateHeaders();
this.updateHeaderSortState();
}
this.processRows(0, true);
this.layout();
this.applyEmptyText();
this.fireEvent('refresh', this);
},
onDenyColumnLock : function(){
},
initData : function(ds, cm){
if(this.cm){
this.cm.un('columnlockchange', this.onColumnLock, this);
}
Ext.ux.grid.LockingGridView.superclass.initData.call(this, ds, cm);
if(this.cm){
this.cm.on('columnlockchange', this.onColumnLock, this);
}
},
onColumnLock : function(){
this.refresh(true);
},
handleHdMenuClick : function(item){
var index = this.hdCtxIndex,
cm = this.cm,
id = item.getItemId(),
llen = cm.getLockedCount();
switch(id){
case 'lock':
if(cm.getColumnCount(true) <= llen + 1){
this.onDenyColumnLock();
return undefined;
}
cm.setLocked(index, true);
if(llen != index){
cm.moveColumn(index, llen);
this.grid.fireEvent('columnmove', index, llen);
}
break;
case 'unlock':
if(llen - 1 != index){
cm.setLocked(index, false, true);
cm.moveColumn(index, llen - 1);
this.grid.fireEvent('columnmove', index, llen - 1);
}else{
cm.setLocked(index, false);
}
break;
default:
return Ext.ux.grid.LockingGridView.superclass.handleHdMenuClick.call(this, item);
}
return true;
},
handleHdDown : function(e, t){
Ext.ux.grid.LockingGridView.superclass.handleHdDown.call(this, e, t);
if(this.grid.enableColLock !== false){
if(Ext.fly(t).hasClass('x-grid3-hd-btn')){
var hd = this.findHeaderCell(t),
index = this.getCellIndex(hd),
ms = this.hmenu.items, cm = this.cm;
ms.get('lock').setDisabled(cm.isLocked(index));
ms.get('unlock').setDisabled(!cm.isLocked(index));
}
}
},
syncHeaderHeight: function(){
var hrow = Ext.fly(this.innerHd).child('tr', true),
lhrow = Ext.fly(this.lockedInnerHd).child('tr', true);
hrow.style.height = 'auto';
lhrow.style.height = 'auto';
var hd = hrow.offsetHeight,
lhd = lhrow.offsetHeight,
height = Math.max(lhd, hd) + 'px';
hrow.style.height = height;
lhrow.style.height = height;
},
updateLockedWidth: function(){
var lw = this.cm.getTotalLockedWidth(),
tw = this.cm.getTotalWidth() - lw,
csize = this.grid.getGridEl().getSize(true),
lp = Ext.isBorderBox ? 0 : this.lockedBorderWidth,
rp = Ext.isBorderBox ? 0 : this.rowBorderWidth,
vw = (csize.width - lw - lp - rp) + 'px',
so = this.getScrollOffset();
if(!this.grid.autoHeight){
var vh = (csize.height - this.mainHd.getHeight()) + 'px';
this.lockedScroller.dom.style.height = vh;
this.scroller.dom.style.height = vh;
}
this.lockedWrap.dom.style.width = (lw + rp) + 'px';
this.scroller.dom.style.width = vw;
this.mainWrap.dom.style.left = (lw + lp + rp) + 'px';
if(this.innerHd){
this.lockedInnerHd.firstChild.style.width = lw + 'px';
this.lockedInnerHd.firstChild.firstChild.style.width = lw + 'px';
this.innerHd.style.width = vw;
this.innerHd.firstChild.style.width = (tw + rp + so) + 'px';
this.innerHd.firstChild.firstChild.style.width = tw + 'px';
}
if(this.mainBody){
this.lockedBody.dom.style.width = (lw + rp) + 'px';
this.mainBody.dom.style.width = (tw + rp) + 'px';
}
}
});
Ext.ux.grid.LockingColumnModel = Ext.extend(Ext.grid.ColumnModel, {
/**
* Returns true if the given column index is currently locked
* @param {Number} colIndex The column index
* @return {Boolean} True if the column is locked
*/
isLocked : function(colIndex){
return this.config[colIndex].locked === true;
},
/**
* Locks or unlocks a given column
* @param {Number} colIndex The column index
* @param {Boolean} value True to lock, false to unlock
* @param {Boolean} suppressEvent Pass false to cause the columnlockchange event not to fire
*/
setLocked : function(colIndex, value, suppressEvent){
if (this.isLocked(colIndex) == value) {
return;
}
this.config[colIndex].locked = value;
if (!suppressEvent) {
this.fireEvent('columnlockchange', this, colIndex, value);
}
},
/**
* Returns the total width of all locked columns
* @return {Number} The width of all locked columns
*/
getTotalLockedWidth : function(){
var totalWidth = 0;
for (var i = 0, len = this.config.length; i < len; i++) {
if (this.isLocked(i) && !this.isHidden(i)) {
totalWidth += this.getColumnWidth(i);
}
}
return totalWidth;
},
/**
* Returns the total number of locked columns
* @return {Number} The number of locked columns
*/
getLockedCount : function() {
var len = this.config.length;
for (var i = 0; i < len; i++) {
if (!this.isLocked(i)) {
return i;
}
}
//if we get to this point all of the columns are locked so we return the total
return len;
},
/**
* Moves a column from one position to another
* @param {Number} oldIndex The current column index
* @param {Number} newIndex The destination column index
*/
moveColumn : function(oldIndex, newIndex){
var oldLocked = this.isLocked(oldIndex),
newLocked = this.isLocked(newIndex);
if (oldIndex < newIndex && oldLocked && !newLocked) {
this.setLocked(oldIndex, false, true);
} else if (oldIndex > newIndex && !oldLocked && newLocked) {
this.setLocked(oldIndex, true, true);
}
Ext.ux.grid.LockingColumnModel.superclass.moveColumn.apply(this, arguments);
}
}); | limscoder/js-file-browser | src/extjs/examples/ux/LockingGridView.js | JavaScript | mit | 33,643 |
import Ember from "ember";
const { Route } = Ember;
const set = Ember.set;
export default Route.extend({
setupController() {
this.controllerFor('mixinStack').set('model', []);
let port = this.get('port');
port.on('objectInspector:updateObject', this, this.updateObject);
port.on('objectInspector:updateProperty', this, this.updateProperty);
port.on('objectInspector:updateErrors', this, this.updateErrors);
port.on('objectInspector:droppedObject', this, this.droppedObject);
port.on('deprecation:count', this, this.setDeprecationCount);
port.send('deprecation:getCount');
},
deactivate() {
let port = this.get('port');
port.off('objectInspector:updateObject', this, this.updateObject);
port.off('objectInspector:updateProperty', this, this.updateProperty);
port.off('objectInspector:updateErrors', this, this.updateErrors);
port.off('objectInspector:droppedObject', this, this.droppedObject);
port.off('deprecation:count', this, this.setDeprecationCount);
},
updateObject(options) {
const details = options.details,
name = options.name,
property = options.property,
objectId = options.objectId,
errors = options.errors;
Ember.NativeArray.apply(details);
details.forEach(arrayize);
let controller = this.get('controller');
if (options.parentObject) {
controller.pushMixinDetails(name, property, objectId, details);
} else {
controller.activateMixinDetails(name, objectId, details, errors);
}
this.send('expandInspector');
},
setDeprecationCount(message) {
this.controller.set('deprecationCount', message.count);
},
updateProperty(options) {
const detail = this.controllerFor('mixinDetails').get('model.mixins').objectAt(options.mixinIndex);
const property = Ember.get(detail, 'properties').findProperty('name', options.property);
set(property, 'value', options.value);
},
updateErrors(options) {
const mixinDetails = this.controllerFor('mixinDetails');
if (mixinDetails.get('model.objectId') === options.objectId) {
mixinDetails.set('model.errors', options.errors);
}
},
droppedObject(message) {
let controller = this.get('controller');
controller.droppedObject(message.objectId);
},
actions: {
expandInspector() {
this.set("controller.inspectorExpanded", true);
},
toggleInspector() {
this.toggleProperty("controller.inspectorExpanded");
},
inspectObject(objectId) {
if (objectId) {
this.get('port').send('objectInspector:inspectById', { objectId: objectId });
}
},
setIsDragging(isDragging) {
this.set('controller.isDragging', isDragging);
},
refreshPage() {
// If the adapter defined a `reloadTab` method, it means
// they prefer to handle the reload themselves
if (typeof this.get('adapter').reloadTab === 'function') {
this.get('adapter').reloadTab();
} else {
// inject ember_debug as quickly as possible in chrome
// so that promises created on dom ready are caught
this.get('port').send('general:refresh');
this.get('adapter').willReload();
}
}
}
});
function arrayize(mixin) {
Ember.NativeArray.apply(mixin.properties);
}
| jryans/ember-inspector | app/routes/application.js | JavaScript | mit | 3,292 |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.Inferno = global.Inferno || {})));
}(this, (function (exports) { 'use strict';
var NO_OP = '$NO_OP';
var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.';
// This should be boolean and not reference to window.document
var isBrowser = !!(typeof window !== 'undefined' && window.document);
// this is MUCH faster than .constructor === Array and instanceof Array
// in Node 7 and the later versions of V8, slower in older versions though
var isArray = Array.isArray;
function isStringOrNumber(o) {
var type = typeof o;
return type === 'string' || type === 'number';
}
function isNullOrUndef(o) {
return isUndefined(o) || isNull(o);
}
function isInvalid(o) {
return isNull(o) || o === false || isTrue(o) || isUndefined(o);
}
function isFunction(o) {
return typeof o === 'function';
}
function isString(o) {
return typeof o === 'string';
}
function isNumber(o) {
return typeof o === 'number';
}
function isNull(o) {
return o === null;
}
function isTrue(o) {
return o === true;
}
function isUndefined(o) {
return o === void 0;
}
function isDefined(o) {
return o !== void 0;
}
function isObject(o) {
return typeof o === 'object';
}
function throwError(message) {
if (!message) {
message = ERROR_MSG;
}
throw new Error(("Inferno Error: " + message));
}
function warning(message) {
// tslint:disable-next-line:no-console
console.error(message);
}
function combineFrom(first, second) {
var out = {};
if (first) {
for (var key in first) {
out[key] = first[key];
}
}
if (second) {
for (var key$1 in second) {
out[key$1] = second[key$1];
}
}
return out;
}
function getTagName(input) {
var tagName;
if (isArray(input)) {
var arrayText = input.length > 3 ? input.slice(0, 3).toString() + ',...' : input.toString();
tagName = 'Array(' + arrayText + ')';
}
else if (isStringOrNumber(input)) {
tagName = 'Text(' + input + ')';
}
else if (isInvalid(input)) {
tagName = 'InvalidVNode(' + input + ')';
}
else {
var flags = input.flags;
if (flags & 481 /* Element */) {
tagName = "<" + (input.type) + (input.className ? ' class="' + input.className + '"' : '') + ">";
}
else if (flags & 16 /* Text */) {
tagName = "Text(" + (input.children) + ")";
}
else if (flags & 1024 /* Portal */) {
tagName = "Portal*";
}
else {
var type = input.type;
// Fallback for IE
var componentName = type.name || type.displayName || type.constructor.name || (type.toString().match(/^function\s*([^\s(]+)/) || [])[1];
tagName = "<" + componentName + " />";
}
}
return '>> ' + tagName + '\n';
}
function DEV_ValidateKeys(vNodeTree, vNode, forceKeyed) {
var foundKeys = [];
for (var i = 0, len = vNodeTree.length; i < len; i++) {
var childNode = vNodeTree[i];
if (isArray(childNode)) {
return 'Encountered ARRAY in mount, array must be flattened, or normalize used. Location: \n' + getTagName(childNode);
}
if (isInvalid(childNode)) {
if (forceKeyed) {
return 'Encountered invalid node when preparing to keyed algorithm. Location: \n' + getTagName(childNode);
}
else if (foundKeys.length !== 0) {
return 'Encountered invalid node with mixed keys. Location: \n' + getTagName(childNode);
}
continue;
}
if (typeof childNode === 'object') {
childNode.isValidated = true;
}
var key = childNode.key;
if (!isNullOrUndef(key) && !isStringOrNumber(key)) {
return 'Encountered child vNode where key property is not string or number. Location: \n' + getTagName(childNode);
}
var children = childNode.children;
var childFlags = childNode.childFlags;
if (!isInvalid(children)) {
var val = (void 0);
if (childFlags & 12 /* MultipleChildren */) {
val = DEV_ValidateKeys(children, childNode, childNode.childFlags & 8 /* HasKeyedChildren */);
}
else if (childFlags === 2 /* HasVNodeChildren */) {
val = DEV_ValidateKeys([children], childNode, childNode.childFlags & 8 /* HasKeyedChildren */);
}
if (val) {
val += getTagName(childNode);
return val;
}
}
if (forceKeyed && isNullOrUndef(key)) {
return ('Encountered child without key during keyed algorithm. If this error points to Array make sure children is flat list. Location: \n' +
getTagName(childNode));
}
else if (!forceKeyed && isNullOrUndef(key)) {
if (foundKeys.length !== 0) {
return 'Encountered children with key missing. Location: \n' + getTagName(childNode);
}
continue;
}
if (foundKeys.indexOf(key) > -1) {
return 'Encountered two children with same key: {' + key + '}. Location: \n' + getTagName(childNode);
}
foundKeys.push(key);
}
}
function validateVNodeElementChildren(vNode) {
{
if (vNode.childFlags & 1 /* HasInvalidChildren */) {
return;
}
if (vNode.flags & 64 /* InputElement */) {
throwError("input elements can't have children.");
}
if (vNode.flags & 128 /* TextareaElement */) {
throwError("textarea elements can't have children.");
}
if (vNode.flags & 481 /* Element */) {
var voidTypes = ['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'];
var tag = vNode.type.toLowerCase();
if (tag === 'media') {
throwError("media elements can't have children.");
}
var idx = voidTypes.indexOf(tag);
if (idx !== -1) {
throwError(((voidTypes[idx]) + " elements can't have children."));
}
}
}
}
function validateKeys(vNode) {
{
// Checks if there is any key missing or duplicate keys
if (vNode.isValidated === false && vNode.children && vNode.flags & 481 /* Element */) {
var error = DEV_ValidateKeys(Array.isArray(vNode.children) ? vNode.children : [vNode.children], vNode, (vNode.childFlags & 8 /* HasKeyedChildren */) > 0);
if (error) {
throwError(error + getTagName(vNode));
}
}
vNode.isValidated = true;
}
}
var keyPrefix = '$';
function getVNode(childFlags, children, className, flags, key, props, ref, type) {
{
return {
childFlags: childFlags,
children: children,
className: className,
dom: null,
flags: flags,
isValidated: false,
key: key === void 0 ? null : key,
parentVNode: null,
props: props === void 0 ? null : props,
ref: ref === void 0 ? null : ref,
type: type
};
}
return {
childFlags: childFlags,
children: children,
className: className,
dom: null,
flags: flags,
key: key === void 0 ? null : key,
parentVNode: null,
props: props === void 0 ? null : props,
ref: ref === void 0 ? null : ref,
type: type
};
}
function createVNode(flags, type, className, children, childFlags, props, key, ref) {
{
if (flags & 14 /* Component */) {
throwError('Creating Component vNodes using createVNode is not allowed. Use Inferno.createComponentVNode method.');
}
}
var childFlag = childFlags === void 0 ? 1 /* HasInvalidChildren */ : childFlags;
var vNode = getVNode(childFlag, children, className, flags, key, props, ref, type);
var optsVNode = options.createVNode;
if (typeof optsVNode === 'function') {
optsVNode(vNode);
}
if (childFlag === 0 /* UnknownChildren */) {
normalizeChildren(vNode, vNode.children);
}
{
validateVNodeElementChildren(vNode);
}
return vNode;
}
function createComponentVNode(flags, type, props, key, ref) {
{
if (flags & 1 /* HtmlElement */) {
throwError('Creating element vNodes using createComponentVNode is not allowed. Use Inferno.createVNode method.');
}
}
if ((flags & 2 /* ComponentUnknown */) > 0) {
flags = isDefined(type.prototype) && isFunction(type.prototype.render) ? 4 /* ComponentClass */ : 8 /* ComponentFunction */;
}
// set default props
var defaultProps = type.defaultProps;
if (!isNullOrUndef(defaultProps)) {
if (!props) {
props = {}; // Props can be referenced and modified at application level so always create new object
}
for (var prop in defaultProps) {
if (isUndefined(props[prop])) {
props[prop] = defaultProps[prop];
}
}
}
if ((flags & 8 /* ComponentFunction */) > 0) {
var defaultHooks = type.defaultHooks;
if (!isNullOrUndef(defaultHooks)) {
if (!ref) {
// As ref cannot be referenced from application level, we can use the same refs object
ref = defaultHooks;
}
else {
for (var prop$1 in defaultHooks) {
if (isUndefined(ref[prop$1])) {
ref[prop$1] = defaultHooks[prop$1];
}
}
}
}
}
var vNode = getVNode(1 /* HasInvalidChildren */, null, null, flags, key, props, ref, type);
var optsVNode = options.createVNode;
if (isFunction(optsVNode)) {
optsVNode(vNode);
}
return vNode;
}
function createTextVNode(text, key) {
return getVNode(1 /* HasInvalidChildren */, isNullOrUndef(text) ? '' : text, null, 16 /* Text */, key, null, null, null);
}
function normalizeProps(vNode) {
var props = vNode.props;
if (props) {
var flags = vNode.flags;
if (flags & 481 /* Element */) {
if (isDefined(props.children) && isNullOrUndef(vNode.children)) {
normalizeChildren(vNode, props.children);
}
if (isDefined(props.className)) {
vNode.className = props.className || null;
props.className = undefined;
}
}
if (isDefined(props.key)) {
vNode.key = props.key;
props.key = undefined;
}
if (isDefined(props.ref)) {
if (flags & 8 /* ComponentFunction */) {
vNode.ref = combineFrom(vNode.ref, props.ref);
}
else {
vNode.ref = props.ref;
}
props.ref = undefined;
}
}
return vNode;
}
function directClone(vNodeToClone) {
var newVNode;
var flags = vNodeToClone.flags;
if (flags & 14 /* Component */) {
var props;
var propsToClone = vNodeToClone.props;
if (!isNull(propsToClone)) {
props = {};
for (var key in propsToClone) {
props[key] = propsToClone[key];
}
}
newVNode = createComponentVNode(flags, vNodeToClone.type, props, vNodeToClone.key, vNodeToClone.ref);
}
else if (flags & 481 /* Element */) {
var children = vNodeToClone.children;
newVNode = createVNode(flags, vNodeToClone.type, vNodeToClone.className, children, 0 /* UnknownChildren */, vNodeToClone.props, vNodeToClone.key, vNodeToClone.ref);
}
else if (flags & 16 /* Text */) {
newVNode = createTextVNode(vNodeToClone.children, vNodeToClone.key);
}
else if (flags & 1024 /* Portal */) {
newVNode = vNodeToClone;
}
return newVNode;
}
function createVoidVNode() {
return createTextVNode('', null);
}
function _normalizeVNodes(nodes, result, index, currentKey) {
for (var len = nodes.length; index < len; index++) {
var n = nodes[index];
if (!isInvalid(n)) {
var newKey = currentKey + keyPrefix + index;
if (isArray(n)) {
_normalizeVNodes(n, result, 0, newKey);
}
else {
if (isStringOrNumber(n)) {
n = createTextVNode(n, newKey);
}
else {
var oldKey = n.key;
var isPrefixedKey = isString(oldKey) && oldKey[0] === keyPrefix;
if (!isNull(n.dom) || isPrefixedKey) {
n = directClone(n);
}
if (isNull(oldKey) || isPrefixedKey) {
n.key = newKey;
}
else {
n.key = currentKey + oldKey;
}
}
result.push(n);
}
}
}
}
function getFlagsForElementVnode(type) {
if (type === 'svg') {
return 32 /* SvgElement */;
}
if (type === 'input') {
return 64 /* InputElement */;
}
if (type === 'select') {
return 256 /* SelectElement */;
}
if (type === 'textarea') {
return 128 /* TextareaElement */;
}
return 1 /* HtmlElement */;
}
function normalizeChildren(vNode, children) {
var newChildren;
var newChildFlags = 1 /* HasInvalidChildren */;
// Don't change children to match strict equal (===) true in patching
if (isInvalid(children)) {
newChildren = children;
}
else if (isString(children)) {
newChildFlags = 2 /* HasVNodeChildren */;
newChildren = createTextVNode(children);
}
else if (isNumber(children)) {
newChildFlags = 2 /* HasVNodeChildren */;
newChildren = createTextVNode(children + '');
}
else if (isArray(children)) {
var len = children.length;
if (len === 0) {
newChildren = null;
newChildFlags = 1 /* HasInvalidChildren */;
}
else {
// we assign $ which basically means we've flagged this array for future note
// if it comes back again, we need to clone it, as people are using it
// in an immutable way
// tslint:disable-next-line
if (Object.isFrozen(children) || children['$'] === true) {
children = children.slice();
}
newChildFlags = 8 /* HasKeyedChildren */;
for (var i = 0; i < len; i++) {
var n = children[i];
if (isInvalid(n) || isArray(n)) {
newChildren = newChildren || children.slice(0, i);
_normalizeVNodes(children, newChildren, i, '');
break;
}
else if (isStringOrNumber(n)) {
newChildren = newChildren || children.slice(0, i);
newChildren.push(createTextVNode(n, keyPrefix + i));
}
else {
var key = n.key;
var isNullDom = isNull(n.dom);
var isNullKey = isNull(key);
var isPrefixed = !isNullKey && key[0] === keyPrefix;
if (!isNullDom || isNullKey || isPrefixed) {
newChildren = newChildren || children.slice(0, i);
if (!isNullDom || isPrefixed) {
n = directClone(n);
}
if (isNullKey || isPrefixed) {
n.key = keyPrefix + i;
}
newChildren.push(n);
}
else if (newChildren) {
newChildren.push(n);
}
}
}
newChildren = newChildren || children;
newChildren.$ = true;
}
}
else {
newChildren = children;
if (!isNull(children.dom)) {
newChildren = directClone(children);
}
newChildFlags = 2 /* HasVNodeChildren */;
}
vNode.children = newChildren;
vNode.childFlags = newChildFlags;
{
validateVNodeElementChildren(vNode);
}
return vNode;
}
var options = {
afterMount: null,
afterRender: null,
afterUpdate: null,
beforeRender: null,
beforeUnmount: null,
createVNode: null,
roots: []
};
/**
* Links given data to event as first parameter
* @param {*} data data to be linked, it will be available in function as first parameter
* @param {Function} event Function to be called when event occurs
* @returns {{data: *, event: Function}}
*/
function linkEvent(data, event) {
if (isFunction(event)) {
return { data: data, event: event };
}
return null; // Return null when event is invalid, to avoid creating unnecessary event handlers
}
var xlinkNS = 'http://www.w3.org/1999/xlink';
var xmlNS = 'http://www.w3.org/XML/1998/namespace';
var svgNS = 'http://www.w3.org/2000/svg';
var namespaces = {
'xlink:actuate': xlinkNS,
'xlink:arcrole': xlinkNS,
'xlink:href': xlinkNS,
'xlink:role': xlinkNS,
'xlink:show': xlinkNS,
'xlink:title': xlinkNS,
'xlink:type': xlinkNS,
'xml:base': xmlNS,
'xml:lang': xmlNS,
'xml:space': xmlNS
};
// We need EMPTY_OBJ defined in one place.
// Its used for comparison so we cant inline it into shared
var EMPTY_OBJ = {};
var LIFECYCLE = [];
{
Object.freeze(EMPTY_OBJ);
}
function appendChild(parentDom, dom) {
parentDom.appendChild(dom);
}
function insertOrAppend(parentDom, newNode, nextNode) {
if (isNullOrUndef(nextNode)) {
appendChild(parentDom, newNode);
}
else {
parentDom.insertBefore(newNode, nextNode);
}
}
function documentCreateElement(tag, isSVG) {
if (isSVG === true) {
return document.createElementNS(svgNS, tag);
}
return document.createElement(tag);
}
function replaceChild(parentDom, newDom, lastDom) {
parentDom.replaceChild(newDom, lastDom);
}
function removeChild(parentDom, dom) {
parentDom.removeChild(dom);
}
function callAll(arrayFn) {
var listener;
while ((listener = arrayFn.shift()) !== undefined) {
listener();
}
}
var attachedEventCounts = {};
var attachedEvents = {};
function handleEvent(name, nextEvent, dom) {
var eventsLeft = attachedEventCounts[name];
var eventsObject = dom.$EV;
if (nextEvent) {
if (!eventsLeft) {
attachedEvents[name] = attachEventToDocument(name);
attachedEventCounts[name] = 0;
}
if (!eventsObject) {
eventsObject = dom.$EV = {};
}
if (!eventsObject[name]) {
attachedEventCounts[name]++;
}
eventsObject[name] = nextEvent;
}
else if (eventsObject && eventsObject[name]) {
attachedEventCounts[name]--;
if (eventsLeft === 1) {
document.removeEventListener(normalizeEventName(name), attachedEvents[name]);
attachedEvents[name] = null;
}
eventsObject[name] = nextEvent;
}
}
function dispatchEvents(event, target, isClick, name, eventData) {
var dom = target;
while (!isNull(dom)) {
// Html Nodes can be nested fe: span inside button in that scenario browser does not handle disabled attribute on parent,
// because the event listener is on document.body
// Don't process clicks on disabled elements
if (isClick && dom.disabled) {
return;
}
var eventsObject = dom.$EV;
if (eventsObject) {
var currentEvent = eventsObject[name];
if (currentEvent) {
// linkEvent object
eventData.dom = dom;
if (currentEvent.event) {
currentEvent.event(currentEvent.data, event);
}
else {
currentEvent(event);
}
if (event.cancelBubble) {
return;
}
}
}
dom = dom.parentNode;
}
}
function normalizeEventName(name) {
return name.substr(2).toLowerCase();
}
function stopPropagation() {
this.cancelBubble = true;
this.stopImmediatePropagation();
}
function attachEventToDocument(name) {
var docEvent = function (event) {
var type = event.type;
var isClick = type === 'click' || type === 'dblclick';
if (isClick && event.button !== 0) {
// Firefox incorrectly triggers click event for mid/right mouse buttons.
// This bug has been active for 12 years.
// https://bugzilla.mozilla.org/show_bug.cgi?id=184051
event.preventDefault();
event.stopPropagation();
return false;
}
event.stopPropagation = stopPropagation;
// Event data needs to be object to save reference to currentTarget getter
var eventData = {
dom: document
};
try {
Object.defineProperty(event, 'currentTarget', {
configurable: true,
get: function get() {
return eventData.dom;
}
});
}
catch (e) {
/* safari7 and phantomJS will crash */
}
dispatchEvents(event, event.target, isClick, name, eventData);
};
document.addEventListener(normalizeEventName(name), docEvent);
return docEvent;
}
function isSameInnerHTML(dom, innerHTML) {
var tempdom = document.createElement('i');
tempdom.innerHTML = innerHTML;
return tempdom.innerHTML === dom.innerHTML;
}
function isSamePropsInnerHTML(dom, props) {
return Boolean(props && props.dangerouslySetInnerHTML && props.dangerouslySetInnerHTML.__html && isSameInnerHTML(dom, props.dangerouslySetInnerHTML.__html));
}
function triggerEventListener(props, methodName, e) {
if (props[methodName]) {
var listener = props[methodName];
if (listener.event) {
listener.event(listener.data, e);
}
else {
listener(e);
}
}
else {
var nativeListenerName = methodName.toLowerCase();
if (props[nativeListenerName]) {
props[nativeListenerName](e);
}
}
}
function createWrappedFunction(methodName, applyValue) {
var fnMethod = function (e) {
e.stopPropagation();
var vNode = this.$V;
// If vNode is gone by the time event fires, no-op
if (!vNode) {
return;
}
var props = vNode.props || EMPTY_OBJ;
var dom = vNode.dom;
if (isString(methodName)) {
triggerEventListener(props, methodName, e);
}
else {
for (var i = 0; i < methodName.length; i++) {
triggerEventListener(props, methodName[i], e);
}
}
if (isFunction(applyValue)) {
var newVNode = this.$V;
var newProps = newVNode.props || EMPTY_OBJ;
applyValue(newProps, dom, false, newVNode);
}
};
Object.defineProperty(fnMethod, 'wrapped', {
configurable: false,
enumerable: false,
value: true,
writable: false
});
return fnMethod;
}
function isCheckedType(type) {
return type === 'checkbox' || type === 'radio';
}
var onTextInputChange = createWrappedFunction('onInput', applyValueInput);
var wrappedOnChange = createWrappedFunction(['onClick', 'onChange'], applyValueInput);
/* tslint:disable-next-line:no-empty */
function emptywrapper(event) {
event.stopPropagation();
}
emptywrapper.wrapped = true;
function inputEvents(dom, nextPropsOrEmpty) {
if (isCheckedType(nextPropsOrEmpty.type)) {
dom.onchange = wrappedOnChange;
dom.onclick = emptywrapper;
}
else {
dom.oninput = onTextInputChange;
}
}
function applyValueInput(nextPropsOrEmpty, dom) {
var type = nextPropsOrEmpty.type;
var value = nextPropsOrEmpty.value;
var checked = nextPropsOrEmpty.checked;
var multiple = nextPropsOrEmpty.multiple;
var defaultValue = nextPropsOrEmpty.defaultValue;
var hasValue = !isNullOrUndef(value);
if (type && type !== dom.type) {
dom.setAttribute('type', type);
}
if (!isNullOrUndef(multiple) && multiple !== dom.multiple) {
dom.multiple = multiple;
}
if (!isNullOrUndef(defaultValue) && !hasValue) {
dom.defaultValue = defaultValue + '';
}
if (isCheckedType(type)) {
if (hasValue) {
dom.value = value;
}
if (!isNullOrUndef(checked)) {
dom.checked = checked;
}
}
else {
if (hasValue && dom.value !== value) {
dom.defaultValue = value;
dom.value = value;
}
else if (!isNullOrUndef(checked)) {
dom.checked = checked;
}
}
}
function updateChildOptionGroup(vNode, value) {
var type = vNode.type;
if (type === 'optgroup') {
var children = vNode.children;
var childFlags = vNode.childFlags;
if (childFlags & 12 /* MultipleChildren */) {
for (var i = 0, len = children.length; i < len; i++) {
updateChildOption(children[i], value);
}
}
else if (childFlags === 2 /* HasVNodeChildren */) {
updateChildOption(children, value);
}
}
else {
updateChildOption(vNode, value);
}
}
function updateChildOption(vNode, value) {
var props = vNode.props || EMPTY_OBJ;
var dom = vNode.dom;
// we do this as multiple may have changed
dom.value = props.value;
if ((isArray(value) && value.indexOf(props.value) !== -1) || props.value === value) {
dom.selected = true;
}
else if (!isNullOrUndef(value) || !isNullOrUndef(props.selected)) {
dom.selected = props.selected || false;
}
}
var onSelectChange = createWrappedFunction('onChange', applyValueSelect);
function selectEvents(dom) {
dom.onchange = onSelectChange;
}
function applyValueSelect(nextPropsOrEmpty, dom, mounting, vNode) {
var multiplePropInBoolean = Boolean(nextPropsOrEmpty.multiple);
if (!isNullOrUndef(nextPropsOrEmpty.multiple) && multiplePropInBoolean !== dom.multiple) {
dom.multiple = multiplePropInBoolean;
}
var childFlags = vNode.childFlags;
if ((childFlags & 1 /* HasInvalidChildren */) === 0) {
var children = vNode.children;
var value = nextPropsOrEmpty.value;
if (mounting && isNullOrUndef(value)) {
value = nextPropsOrEmpty.defaultValue;
}
if (childFlags & 12 /* MultipleChildren */) {
for (var i = 0, len = children.length; i < len; i++) {
updateChildOptionGroup(children[i], value);
}
}
else if (childFlags === 2 /* HasVNodeChildren */) {
updateChildOptionGroup(children, value);
}
}
}
var onTextareaInputChange = createWrappedFunction('onInput', applyValueTextArea);
var wrappedOnChange$1 = createWrappedFunction('onChange');
function textAreaEvents(dom, nextPropsOrEmpty) {
dom.oninput = onTextareaInputChange;
if (nextPropsOrEmpty.onChange) {
dom.onchange = wrappedOnChange$1;
}
}
function applyValueTextArea(nextPropsOrEmpty, dom, mounting) {
var value = nextPropsOrEmpty.value;
var domValue = dom.value;
if (isNullOrUndef(value)) {
if (mounting) {
var defaultValue = nextPropsOrEmpty.defaultValue;
if (!isNullOrUndef(defaultValue) && defaultValue !== domValue) {
dom.defaultValue = defaultValue;
dom.value = defaultValue;
}
}
}
else if (domValue !== value) {
/* There is value so keep it controlled */
dom.defaultValue = value;
dom.value = value;
}
}
/**
* There is currently no support for switching same input between controlled and nonControlled
* If that ever becomes a real issue, then re design controlled elements
* Currently user must choose either controlled or non-controlled and stick with that
*/
function processElement(flags, vNode, dom, nextPropsOrEmpty, mounting, isControlled) {
if (flags & 64 /* InputElement */) {
applyValueInput(nextPropsOrEmpty, dom);
}
else if (flags & 256 /* SelectElement */) {
applyValueSelect(nextPropsOrEmpty, dom, mounting, vNode);
}
else if (flags & 128 /* TextareaElement */) {
applyValueTextArea(nextPropsOrEmpty, dom, mounting);
}
if (isControlled) {
dom.$V = vNode;
}
}
function addFormElementEventHandlers(flags, dom, nextPropsOrEmpty) {
if (flags & 64 /* InputElement */) {
inputEvents(dom, nextPropsOrEmpty);
}
else if (flags & 256 /* SelectElement */) {
selectEvents(dom);
}
else if (flags & 128 /* TextareaElement */) {
textAreaEvents(dom, nextPropsOrEmpty);
}
}
function isControlledFormElement(nextPropsOrEmpty) {
return nextPropsOrEmpty.type && isCheckedType(nextPropsOrEmpty.type) ? !isNullOrUndef(nextPropsOrEmpty.checked) : !isNullOrUndef(nextPropsOrEmpty.value);
}
function remove(vNode, parentDom) {
unmount(vNode);
if (!isNull(parentDom)) {
removeChild(parentDom, vNode.dom);
// Let carbage collector free memory
vNode.dom = null;
}
}
function unmount(vNode) {
var flags = vNode.flags;
if (flags & 481 /* Element */) {
var ref = vNode.ref;
var props = vNode.props;
if (isFunction(ref)) {
ref(null);
}
var children = vNode.children;
var childFlags = vNode.childFlags;
if (childFlags & 12 /* MultipleChildren */) {
unmountAllChildren(children);
}
else if (childFlags === 2 /* HasVNodeChildren */) {
unmount(children);
}
if (!isNull(props)) {
for (var name in props) {
switch (name) {
case 'onClick':
case 'onDblClick':
case 'onFocusIn':
case 'onFocusOut':
case 'onKeyDown':
case 'onKeyPress':
case 'onKeyUp':
case 'onMouseDown':
case 'onMouseMove':
case 'onMouseUp':
case 'onSubmit':
case 'onTouchEnd':
case 'onTouchMove':
case 'onTouchStart':
handleEvent(name, null, vNode.dom);
break;
default:
break;
}
}
}
}
else if (flags & 14 /* Component */) {
var instance = vNode.children;
var ref$1 = vNode.ref;
if (flags & 4 /* ComponentClass */) {
if (isFunction(options.beforeUnmount)) {
options.beforeUnmount(vNode);
}
if (isFunction(instance.componentWillUnmount)) {
instance.componentWillUnmount();
}
if (isFunction(ref$1)) {
ref$1(null);
}
instance.$UN = true;
unmount(instance.$LI);
}
else {
if (!isNullOrUndef(ref$1) && isFunction(ref$1.onComponentWillUnmount)) {
ref$1.onComponentWillUnmount(vNode.dom, vNode.props || EMPTY_OBJ);
}
unmount(instance);
}
}
else if (flags & 1024 /* Portal */) {
var children$1 = vNode.children;
if (!isNull(children$1) && isObject(children$1)) {
remove(children$1, vNode.type);
}
}
}
function unmountAllChildren(children) {
for (var i = 0, len = children.length; i < len; i++) {
unmount(children[i]);
}
}
function removeAllChildren(dom, children) {
unmountAllChildren(children);
dom.textContent = '';
}
function createLinkEvent(linkEvent, nextValue) {
return function (e) {
linkEvent(nextValue.data, e);
};
}
function patchEvent(name, lastValue, nextValue, dom) {
var nameLowerCase = name.toLowerCase();
if (!isFunction(nextValue) && !isNullOrUndef(nextValue)) {
var linkEvent = nextValue.event;
if (linkEvent && isFunction(linkEvent)) {
dom[nameLowerCase] = createLinkEvent(linkEvent, nextValue);
}
else {
// Development warning
{
throwError(("an event on a VNode \"" + name + "\". was not a function or a valid linkEvent."));
}
}
}
else {
var domEvent = dom[nameLowerCase];
// if the function is wrapped, that means it's been controlled by a wrapper
if (!domEvent || !domEvent.wrapped) {
dom[nameLowerCase] = nextValue;
}
}
}
function getNumberStyleValue(style, value) {
switch (style) {
case 'animationIterationCount':
case 'borderImageOutset':
case 'borderImageSlice':
case 'borderImageWidth':
case 'boxFlex':
case 'boxFlexGroup':
case 'boxOrdinalGroup':
case 'columnCount':
case 'fillOpacity':
case 'flex':
case 'flexGrow':
case 'flexNegative':
case 'flexOrder':
case 'flexPositive':
case 'flexShrink':
case 'floodOpacity':
case 'fontWeight':
case 'gridColumn':
case 'gridRow':
case 'lineClamp':
case 'lineHeight':
case 'opacity':
case 'order':
case 'orphans':
case 'stopOpacity':
case 'strokeDasharray':
case 'strokeDashoffset':
case 'strokeMiterlimit':
case 'strokeOpacity':
case 'strokeWidth':
case 'tabSize':
case 'widows':
case 'zIndex':
case 'zoom':
return value;
default:
return value + 'px';
}
}
// We are assuming here that we come from patchProp routine
// -nextAttrValue cannot be null or undefined
function patchStyle(lastAttrValue, nextAttrValue, dom) {
var domStyle = dom.style;
var style;
var value;
if (isString(nextAttrValue)) {
domStyle.cssText = nextAttrValue;
return;
}
if (!isNullOrUndef(lastAttrValue) && !isString(lastAttrValue)) {
for (style in nextAttrValue) {
// do not add a hasOwnProperty check here, it affects performance
value = nextAttrValue[style];
if (value !== lastAttrValue[style]) {
domStyle[style] = isNumber(value) ? getNumberStyleValue(style, value) : value;
}
}
for (style in lastAttrValue) {
if (isNullOrUndef(nextAttrValue[style])) {
domStyle[style] = '';
}
}
}
else {
for (style in nextAttrValue) {
value = nextAttrValue[style];
domStyle[style] = isNumber(value) ? getNumberStyleValue(style, value) : value;
}
}
}
function patchProp(prop, lastValue, nextValue, dom, isSVG, hasControlledValue, lastVNode) {
switch (prop) {
case 'onClick':
case 'onDblClick':
case 'onFocusIn':
case 'onFocusOut':
case 'onKeyDown':
case 'onKeyPress':
case 'onKeyUp':
case 'onMouseDown':
case 'onMouseMove':
case 'onMouseUp':
case 'onSubmit':
case 'onTouchEnd':
case 'onTouchMove':
case 'onTouchStart':
handleEvent(prop, nextValue, dom);
break;
case 'children':
case 'childrenType':
case 'className':
case 'defaultValue':
case 'key':
case 'multiple':
case 'ref':
return;
case 'allowfullscreen':
case 'autoFocus':
case 'autoplay':
case 'capture':
case 'checked':
case 'controls':
case 'default':
case 'disabled':
case 'hidden':
case 'indeterminate':
case 'loop':
case 'muted':
case 'novalidate':
case 'open':
case 'readOnly':
case 'required':
case 'reversed':
case 'scoped':
case 'seamless':
case 'selected':
prop = prop === 'autoFocus' ? prop.toLowerCase() : prop;
dom[prop] = !!nextValue;
break;
case 'defaultChecked':
case 'value':
case 'volume':
if (hasControlledValue && prop === 'value') {
return;
}
var value = isNullOrUndef(nextValue) ? '' : nextValue;
if (dom[prop] !== value) {
dom[prop] = value;
}
break;
case 'dangerouslySetInnerHTML':
var lastHtml = (lastValue && lastValue.__html) || '';
var nextHtml = (nextValue && nextValue.__html) || '';
if (lastHtml !== nextHtml) {
if (!isNullOrUndef(nextHtml) && !isSameInnerHTML(dom, nextHtml)) {
if (!isNull(lastVNode)) {
if (lastVNode.childFlags & 12 /* MultipleChildren */) {
unmountAllChildren(lastVNode.children);
}
else if (lastVNode.childFlags === 2 /* HasVNodeChildren */) {
unmount(lastVNode.children);
}
lastVNode.children = null;
lastVNode.childFlags = 1 /* HasInvalidChildren */;
}
dom.innerHTML = nextHtml;
}
}
break;
default:
if (prop[0] === 'o' && prop[1] === 'n') {
patchEvent(prop, lastValue, nextValue, dom);
}
else if (isNullOrUndef(nextValue)) {
dom.removeAttribute(prop);
}
else if (prop === 'style') {
patchStyle(lastValue, nextValue, dom);
}
else if (isSVG && namespaces[prop]) {
// We optimize for NS being boolean. Its 99.9% time false
// If we end up in this path we can read property again
dom.setAttributeNS(namespaces[prop], prop, nextValue);
}
else {
dom.setAttribute(prop, nextValue);
}
break;
}
}
function mountProps(vNode, flags, props, dom, isSVG) {
var hasControlledValue = false;
var isFormElement = (flags & 448 /* FormElement */) > 0;
if (isFormElement) {
hasControlledValue = isControlledFormElement(props);
if (hasControlledValue) {
addFormElementEventHandlers(flags, dom, props);
}
}
for (var prop in props) {
// do not add a hasOwnProperty check here, it affects performance
patchProp(prop, null, props[prop], dom, isSVG, hasControlledValue, null);
}
if (isFormElement) {
processElement(flags, vNode, dom, props, true, hasControlledValue);
}
}
function createClassComponentInstance(vNode, Component, props, context) {
var instance = new Component(props, context);
vNode.children = instance;
instance.$V = vNode;
instance.$BS = false;
instance.context = context;
if (instance.props === EMPTY_OBJ) {
instance.props = props;
}
instance.$UN = false;
if (isFunction(instance.componentWillMount)) {
instance.$BR = true;
instance.componentWillMount();
if (instance.$PSS) {
var state = instance.state;
var pending = instance.$PS;
if (isNull(state)) {
instance.state = pending;
}
else {
for (var key in pending) {
state[key] = pending[key];
}
}
instance.$PSS = false;
instance.$PS = null;
}
instance.$BR = false;
}
if (isFunction(options.beforeRender)) {
options.beforeRender(instance);
}
var input = handleComponentInput(instance.render(props, instance.state, context), vNode);
var childContext;
if (isFunction(instance.getChildContext)) {
childContext = instance.getChildContext();
}
if (isNullOrUndef(childContext)) {
instance.$CX = context;
}
else {
instance.$CX = combineFrom(context, childContext);
}
if (isFunction(options.afterRender)) {
options.afterRender(instance);
}
instance.$LI = input;
return instance;
}
function handleComponentInput(input, componentVNode) {
// Development validation
{
if (isArray(input)) {
throwError('a valid Inferno VNode (or null) must be returned from a component render. You may have returned an array or an invalid object.');
}
}
if (isInvalid(input)) {
input = createVoidVNode();
}
else if (isStringOrNumber(input)) {
input = createTextVNode(input, null);
}
else {
if (input.dom) {
input = directClone(input);
}
if (input.flags & 14 /* Component */) {
// if we have an input that is also a component, we run into a tricky situation
// where the root vNode needs to always have the correct DOM entry
// we can optimise this in the future, but this gets us out of a lot of issues
input.parentVNode = componentVNode;
}
}
return input;
}
function mount(vNode, parentDom, lifecycle, context, isSVG) {
var flags = vNode.flags;
if (flags & 481 /* Element */) {
return mountElement(vNode, parentDom, lifecycle, context, isSVG);
}
if (flags & 14 /* Component */) {
return mountComponent(vNode, parentDom, lifecycle, context, isSVG, (flags & 4 /* ComponentClass */) > 0);
}
if (flags & 512 /* Void */ || flags & 16 /* Text */) {
return mountText(vNode, parentDom);
}
if (flags & 1024 /* Portal */) {
mount(vNode.children, vNode.type, lifecycle, context, false);
return (vNode.dom = mountText(createVoidVNode(), parentDom));
}
// Development validation, in production we don't need to throw because it crashes anyway
{
if (typeof vNode === 'object') {
throwError(("mount() received an object that's not a valid VNode, you should stringify it first, fix createVNode flags or call normalizeChildren. Object: \"" + (JSON.stringify(vNode)) + "\"."));
}
else {
throwError(("mount() expects a valid VNode, instead it received an object with the type \"" + (typeof vNode) + "\"."));
}
}
}
function mountText(vNode, parentDom) {
var dom = (vNode.dom = document.createTextNode(vNode.children));
if (!isNull(parentDom)) {
appendChild(parentDom, dom);
}
return dom;
}
function mountElement(vNode, parentDom, lifecycle, context, isSVG) {
var flags = vNode.flags;
var children = vNode.children;
var props = vNode.props;
var className = vNode.className;
var ref = vNode.ref;
var childFlags = vNode.childFlags;
isSVG = isSVG || (flags & 32 /* SvgElement */) > 0;
var dom = documentCreateElement(vNode.type, isSVG);
vNode.dom = dom;
if (!isNullOrUndef(className) && className !== '') {
if (isSVG) {
dom.setAttribute('class', className);
}
else {
dom.className = className;
}
}
{
validateKeys(vNode);
}
if (!isNull(parentDom)) {
appendChild(parentDom, dom);
}
if ((childFlags & 1 /* HasInvalidChildren */) === 0) {
var childrenIsSVG = isSVG === true && vNode.type !== 'foreignObject';
if (childFlags === 2 /* HasVNodeChildren */) {
mount(children, dom, lifecycle, context, childrenIsSVG);
}
else if (childFlags & 12 /* MultipleChildren */) {
mountArrayChildren(children, dom, lifecycle, context, childrenIsSVG);
}
}
if (!isNull(props)) {
mountProps(vNode, flags, props, dom, isSVG);
}
{
if (isString(ref)) {
throwError('string "refs" are not supported in Inferno 1.0. Use callback "refs" instead.');
}
}
if (isFunction(ref)) {
mountRef(dom, ref, lifecycle);
}
return dom;
}
function mountArrayChildren(children, dom, lifecycle, context, isSVG) {
for (var i = 0, len = children.length; i < len; i++) {
var child = children[i];
if (!isNull(child.dom)) {
children[i] = child = directClone(child);
}
mount(child, dom, lifecycle, context, isSVG);
}
}
function mountComponent(vNode, parentDom, lifecycle, context, isSVG, isClass) {
var dom;
var type = vNode.type;
var props = vNode.props || EMPTY_OBJ;
var ref = vNode.ref;
if (isClass) {
var instance = createClassComponentInstance(vNode, type, props, context);
vNode.dom = dom = mount(instance.$LI, null, lifecycle, instance.$CX, isSVG);
mountClassComponentCallbacks(vNode, ref, instance, lifecycle);
instance.$UPD = false;
}
else {
var input = handleComponentInput(type(props, context), vNode);
vNode.children = input;
vNode.dom = dom = mount(input, null, lifecycle, context, isSVG);
mountFunctionalComponentCallbacks(props, ref, dom, lifecycle);
}
if (!isNull(parentDom)) {
appendChild(parentDom, dom);
}
return dom;
}
function createClassMountCallback(instance, hasAfterMount, afterMount, vNode, hasDidMount) {
return function () {
instance.$UPD = true;
if (hasAfterMount) {
afterMount(vNode);
}
if (hasDidMount) {
instance.componentDidMount();
}
instance.$UPD = false;
};
}
function mountClassComponentCallbacks(vNode, ref, instance, lifecycle) {
if (isFunction(ref)) {
ref(instance);
}
else {
{
if (isStringOrNumber(ref)) {
throwError('string "refs" are not supported in Inferno 1.0. Use callback "refs" instead.');
}
else if (!isNullOrUndef(ref) && isObject(ref) && vNode.flags & 4 /* ComponentClass */) {
throwError('functional component lifecycle events are not supported on ES2015 class components.');
}
}
}
var hasDidMount = isFunction(instance.componentDidMount);
var afterMount = options.afterMount;
var hasAfterMount = isFunction(afterMount);
if (hasDidMount || hasAfterMount) {
lifecycle.push(createClassMountCallback(instance, hasAfterMount, afterMount, vNode, hasDidMount));
}
}
// Create did mount callback lazily to avoid creating function context if not needed
function createOnMountCallback(ref, dom, props) {
return function () { return ref.onComponentDidMount(dom, props); };
}
function mountFunctionalComponentCallbacks(props, ref, dom, lifecycle) {
if (!isNullOrUndef(ref)) {
if (isFunction(ref.onComponentWillMount)) {
ref.onComponentWillMount(props);
}
if (isFunction(ref.onComponentDidMount)) {
lifecycle.push(createOnMountCallback(ref, dom, props));
}
}
}
function mountRef(dom, value, lifecycle) {
lifecycle.push(function () { return value(dom); });
}
function hydrateComponent(vNode, dom, lifecycle, context, isSVG, isClass) {
var type = vNode.type;
var ref = vNode.ref;
var props = vNode.props || EMPTY_OBJ;
if (isClass) {
var instance = createClassComponentInstance(vNode, type, props, context);
var input = instance.$LI;
hydrateVNode(input, dom, lifecycle, instance.$CX, isSVG);
vNode.dom = input.dom;
mountClassComponentCallbacks(vNode, ref, instance, lifecycle);
instance.$UPD = false; // Mount finished allow going sync
}
else {
var input$1 = handleComponentInput(type(props, context), vNode);
hydrateVNode(input$1, dom, lifecycle, context, isSVG);
vNode.children = input$1;
vNode.dom = input$1.dom;
mountFunctionalComponentCallbacks(props, ref, dom, lifecycle);
}
}
function hydrateElement(vNode, dom, lifecycle, context, isSVG) {
var children = vNode.children;
var props = vNode.props;
var className = vNode.className;
var flags = vNode.flags;
var ref = vNode.ref;
isSVG = isSVG || (flags & 32 /* SvgElement */) > 0;
if (dom.nodeType !== 1 || dom.tagName.toLowerCase() !== vNode.type) {
{
warning("Inferno hydration: Server-side markup doesn't match client-side markup or Initial render target is not empty");
}
var newDom = mountElement(vNode, null, lifecycle, context, isSVG);
vNode.dom = newDom;
replaceChild(dom.parentNode, newDom, dom);
}
else {
vNode.dom = dom;
var childNode = dom.firstChild;
var childFlags = vNode.childFlags;
if ((childFlags & 1 /* HasInvalidChildren */) === 0) {
var nextSibling = null;
while (childNode) {
nextSibling = childNode.nextSibling;
if (childNode.nodeType === 8) {
if (childNode.data === '!') {
dom.replaceChild(document.createTextNode(''), childNode);
}
else {
dom.removeChild(childNode);
}
}
childNode = nextSibling;
}
childNode = dom.firstChild;
if (childFlags === 2 /* HasVNodeChildren */) {
if (isNull(childNode)) {
mount(children, dom, lifecycle, context, isSVG);
}
else {
nextSibling = childNode.nextSibling;
hydrateVNode(children, childNode, lifecycle, context, isSVG);
childNode = nextSibling;
}
}
else if (childFlags & 12 /* MultipleChildren */) {
for (var i = 0, len = children.length; i < len; i++) {
var child = children[i];
if (isNull(childNode)) {
mount(child, dom, lifecycle, context, isSVG);
}
else {
nextSibling = childNode.nextSibling;
hydrateVNode(child, childNode, lifecycle, context, isSVG);
childNode = nextSibling;
}
}
}
// clear any other DOM nodes, there should be only a single entry for the root
while (childNode) {
nextSibling = childNode.nextSibling;
dom.removeChild(childNode);
childNode = nextSibling;
}
}
else if (!isNull(dom.firstChild) && !isSamePropsInnerHTML(dom, props)) {
dom.textContent = ''; // dom has content, but VNode has no children remove everything from DOM
if (flags & 448 /* FormElement */) {
// If element is form element, we need to clear defaultValue also
dom.defaultValue = '';
}
}
if (!isNull(props)) {
mountProps(vNode, flags, props, dom, isSVG);
}
if (isNullOrUndef(className)) {
if (dom.className !== '') {
dom.removeAttribute('class');
}
}
else if (isSVG) {
dom.setAttribute('class', className);
}
else {
dom.className = className;
}
if (isFunction(ref)) {
mountRef(dom, ref, lifecycle);
}
else {
{
if (isString(ref)) {
throwError('string "refs" are not supported in Inferno 1.0. Use callback "refs" instead.');
}
}
}
}
}
function hydrateText(vNode, dom) {
if (dom.nodeType !== 3) {
var newDom = mountText(vNode, null);
vNode.dom = newDom;
replaceChild(dom.parentNode, newDom, dom);
}
else {
var text = vNode.children;
if (dom.nodeValue !== text) {
dom.nodeValue = text;
}
vNode.dom = dom;
}
}
function hydrateVNode(vNode, dom, lifecycle, context, isSVG) {
var flags = vNode.flags;
if (flags & 14 /* Component */) {
hydrateComponent(vNode, dom, lifecycle, context, isSVG, (flags & 4 /* ComponentClass */) > 0);
}
else if (flags & 481 /* Element */) {
hydrateElement(vNode, dom, lifecycle, context, isSVG);
}
else if (flags & 16 /* Text */) {
hydrateText(vNode, dom);
}
else if (flags & 512 /* Void */) {
vNode.dom = dom;
}
else {
{
throwError(("hydrate() expects a valid VNode, instead it received an object with the type \"" + (typeof vNode) + "\"."));
}
throwError();
}
}
function hydrate(input, parentDom, callback) {
var dom = parentDom.firstChild;
if (!isNull(dom)) {
if (!isInvalid(input)) {
hydrateVNode(input, dom, LIFECYCLE, EMPTY_OBJ, false);
}
dom = parentDom.firstChild;
// clear any other DOM nodes, there should be only a single entry for the root
while ((dom = dom.nextSibling)) {
parentDom.removeChild(dom);
}
}
if (LIFECYCLE.length > 0) {
callAll(LIFECYCLE);
}
if (!parentDom.$V) {
options.roots.push(parentDom);
}
parentDom.$V = input;
if (isFunction(callback)) {
callback();
}
}
function replaceWithNewNode(lastNode, nextNode, parentDom, lifecycle, context, isSVG) {
unmount(lastNode);
replaceChild(parentDom, mount(nextNode, null, lifecycle, context, isSVG), lastNode.dom);
}
function patch(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG) {
if (lastVNode !== nextVNode) {
var nextFlags = nextVNode.flags | 0;
if (lastVNode.flags !== nextFlags || nextFlags & 2048 /* ReCreate */) {
replaceWithNewNode(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG);
}
else if (nextFlags & 481 /* Element */) {
patchElement(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG);
}
else if (nextFlags & 14 /* Component */) {
patchComponent(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, (nextFlags & 4 /* ComponentClass */) > 0);
}
else if (nextFlags & 16 /* Text */) {
patchText(lastVNode, nextVNode, parentDom);
}
else if (nextFlags & 512 /* Void */) {
nextVNode.dom = lastVNode.dom;
}
else {
// Portal
patchPortal(lastVNode, nextVNode, lifecycle, context);
}
}
}
function patchPortal(lastVNode, nextVNode, lifecycle, context) {
var lastContainer = lastVNode.type;
var nextContainer = nextVNode.type;
var nextChildren = nextVNode.children;
patchChildren(lastVNode.childFlags, nextVNode.childFlags, lastVNode.children, nextChildren, lastContainer, lifecycle, context, false);
nextVNode.dom = lastVNode.dom;
if (lastContainer !== nextContainer && !isInvalid(nextChildren)) {
var node = nextChildren.dom;
lastContainer.removeChild(node);
nextContainer.appendChild(node);
}
}
function patchElement(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG) {
var nextTag = nextVNode.type;
if (lastVNode.type !== nextTag) {
replaceWithNewNode(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG);
}
else {
var dom = lastVNode.dom;
var nextFlags = nextVNode.flags;
var lastProps = lastVNode.props;
var nextProps = nextVNode.props;
var isFormElement = false;
var hasControlledValue = false;
var nextPropsOrEmpty;
nextVNode.dom = dom;
isSVG = isSVG || (nextFlags & 32 /* SvgElement */) > 0;
// inlined patchProps -- starts --
if (lastProps !== nextProps) {
var lastPropsOrEmpty = lastProps || EMPTY_OBJ;
nextPropsOrEmpty = nextProps || EMPTY_OBJ;
if (nextPropsOrEmpty !== EMPTY_OBJ) {
isFormElement = (nextFlags & 448 /* FormElement */) > 0;
if (isFormElement) {
hasControlledValue = isControlledFormElement(nextPropsOrEmpty);
}
for (var prop in nextPropsOrEmpty) {
var lastValue = lastPropsOrEmpty[prop];
var nextValue = nextPropsOrEmpty[prop];
if (lastValue !== nextValue) {
patchProp(prop, lastValue, nextValue, dom, isSVG, hasControlledValue, lastVNode);
}
}
}
if (lastPropsOrEmpty !== EMPTY_OBJ) {
for (var prop$1 in lastPropsOrEmpty) {
// do not add a hasOwnProperty check here, it affects performance
if (!nextPropsOrEmpty.hasOwnProperty(prop$1) && !isNullOrUndef(lastPropsOrEmpty[prop$1])) {
patchProp(prop$1, lastPropsOrEmpty[prop$1], null, dom, isSVG, hasControlledValue, lastVNode);
}
}
}
}
var lastChildren = lastVNode.children;
var nextChildren = nextVNode.children;
var nextRef = nextVNode.ref;
var lastClassName = lastVNode.className;
var nextClassName = nextVNode.className;
if (lastChildren !== nextChildren) {
{
validateKeys(nextVNode);
}
patchChildren(lastVNode.childFlags, nextVNode.childFlags, lastChildren, nextChildren, dom, lifecycle, context, isSVG && nextTag !== 'foreignObject');
}
if (isFormElement) {
processElement(nextFlags, nextVNode, dom, nextPropsOrEmpty, false, hasControlledValue);
}
// inlined patchProps -- ends --
if (lastClassName !== nextClassName) {
if (isNullOrUndef(nextClassName)) {
dom.removeAttribute('class');
}
else if (isSVG) {
dom.setAttribute('class', nextClassName);
}
else {
dom.className = nextClassName;
}
}
if (isFunction(nextRef) && lastVNode.ref !== nextRef) {
mountRef(dom, nextRef, lifecycle);
}
else {
{
if (isString(nextRef)) {
throwError('string "refs" are not supported in Inferno 1.0. Use callback "refs" instead.');
}
}
}
}
}
function patchChildren(lastChildFlags, nextChildFlags, lastChildren, nextChildren, parentDOM, lifecycle, context, isSVG) {
switch (lastChildFlags) {
case 2 /* HasVNodeChildren */:
switch (nextChildFlags) {
case 2 /* HasVNodeChildren */:
patch(lastChildren, nextChildren, parentDOM, lifecycle, context, isSVG);
break;
case 1 /* HasInvalidChildren */:
remove(lastChildren, parentDOM);
break;
default:
remove(lastChildren, parentDOM);
mountArrayChildren(nextChildren, parentDOM, lifecycle, context, isSVG);
break;
}
break;
case 1 /* HasInvalidChildren */:
switch (nextChildFlags) {
case 2 /* HasVNodeChildren */:
mount(nextChildren, parentDOM, lifecycle, context, isSVG);
break;
case 1 /* HasInvalidChildren */:
break;
default:
mountArrayChildren(nextChildren, parentDOM, lifecycle, context, isSVG);
break;
}
break;
default:
if (nextChildFlags & 12 /* MultipleChildren */) {
var lastLength = lastChildren.length;
var nextLength = nextChildren.length;
// Fast path's for both algorithms
if (lastLength === 0) {
if (nextLength > 0) {
mountArrayChildren(nextChildren, parentDOM, lifecycle, context, isSVG);
}
}
else if (nextLength === 0) {
removeAllChildren(parentDOM, lastChildren);
}
else if (nextChildFlags === 8 /* HasKeyedChildren */ && lastChildFlags === 8 /* HasKeyedChildren */) {
patchKeyedChildren(lastChildren, nextChildren, parentDOM, lifecycle, context, isSVG, lastLength, nextLength);
}
else {
patchNonKeyedChildren(lastChildren, nextChildren, parentDOM, lifecycle, context, isSVG, lastLength, nextLength);
}
}
else if (nextChildFlags === 1 /* HasInvalidChildren */) {
removeAllChildren(parentDOM, lastChildren);
}
else {
removeAllChildren(parentDOM, lastChildren);
mount(nextChildren, parentDOM, lifecycle, context, isSVG);
}
break;
}
}
function updateClassComponent(instance, nextState, nextVNode, nextProps, parentDom, lifecycle, context, isSVG, force, fromSetState) {
var lastState = instance.state;
var lastProps = instance.props;
nextVNode.children = instance;
var lastInput = instance.$LI;
var renderOutput;
if (instance.$UN) {
{
throwError('Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.');
}
return;
}
if (lastProps !== nextProps || nextProps === EMPTY_OBJ) {
if (!fromSetState && isFunction(instance.componentWillReceiveProps)) {
instance.$BR = true;
instance.componentWillReceiveProps(nextProps, context);
// If instance component was removed during its own update do nothing...
if (instance.$UN) {
return;
}
instance.$BR = false;
}
if (instance.$PSS) {
nextState = combineFrom(nextState, instance.$PS);
instance.$PSS = false;
instance.$PS = null;
}
}
/* Update if scu is not defined, or it returns truthy value or force */
var hasSCU = isFunction(instance.shouldComponentUpdate);
if (force || !hasSCU || (hasSCU && instance.shouldComponentUpdate(nextProps, nextState, context))) {
if (isFunction(instance.componentWillUpdate)) {
instance.$BS = true;
instance.componentWillUpdate(nextProps, nextState, context);
instance.$BS = false;
}
instance.props = nextProps;
instance.state = nextState;
instance.context = context;
if (isFunction(options.beforeRender)) {
options.beforeRender(instance);
}
renderOutput = instance.render(nextProps, nextState, context);
if (isFunction(options.afterRender)) {
options.afterRender(instance);
}
var didUpdate = renderOutput !== NO_OP;
var childContext;
if (isFunction(instance.getChildContext)) {
childContext = instance.getChildContext();
}
if (isNullOrUndef(childContext)) {
childContext = context;
}
else {
childContext = combineFrom(context, childContext);
}
instance.$CX = childContext;
if (didUpdate) {
var nextInput = (instance.$LI = handleComponentInput(renderOutput, nextVNode));
patch(lastInput, nextInput, parentDom, lifecycle, childContext, isSVG);
if (isFunction(instance.componentDidUpdate)) {
instance.componentDidUpdate(lastProps, lastState);
}
if (isFunction(options.afterUpdate)) {
options.afterUpdate(nextVNode);
}
}
}
else {
instance.props = nextProps;
instance.state = nextState;
instance.context = context;
}
nextVNode.dom = instance.$LI.dom;
}
function patchComponent(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, isClass) {
var nextType = nextVNode.type;
var lastKey = lastVNode.key;
var nextKey = nextVNode.key;
if (lastVNode.type !== nextType || lastKey !== nextKey) {
replaceWithNewNode(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG);
}
else {
var nextProps = nextVNode.props || EMPTY_OBJ;
if (isClass) {
var instance = lastVNode.children;
instance.$UPD = true;
updateClassComponent(instance, instance.state, nextVNode, nextProps, parentDom, lifecycle, context, isSVG, false, false);
instance.$V = nextVNode;
instance.$UPD = false;
}
else {
var shouldUpdate = true;
var lastProps = lastVNode.props;
var nextHooks = nextVNode.ref;
var nextHooksDefined = !isNullOrUndef(nextHooks);
var lastInput = lastVNode.children;
nextVNode.dom = lastVNode.dom;
nextVNode.children = lastInput;
if (nextHooksDefined && isFunction(nextHooks.onComponentShouldUpdate)) {
shouldUpdate = nextHooks.onComponentShouldUpdate(lastProps, nextProps);
}
if (shouldUpdate !== false) {
if (nextHooksDefined && isFunction(nextHooks.onComponentWillUpdate)) {
nextHooks.onComponentWillUpdate(lastProps, nextProps);
}
var nextInput = nextType(nextProps, context);
if (nextInput !== NO_OP) {
nextInput = handleComponentInput(nextInput, nextVNode);
patch(lastInput, nextInput, parentDom, lifecycle, context, isSVG);
nextVNode.children = nextInput;
nextVNode.dom = nextInput.dom;
if (nextHooksDefined && isFunction(nextHooks.onComponentDidUpdate)) {
nextHooks.onComponentDidUpdate(lastProps, nextProps);
}
}
}
else if (lastInput.flags & 14 /* Component */) {
lastInput.parentVNode = nextVNode;
}
}
}
}
function patchText(lastVNode, nextVNode, parentDom) {
var nextText = nextVNode.children;
var textNode = parentDom.firstChild;
var dom;
// Guard against external change on DOM node.
if (isNull(textNode)) {
parentDom.textContent = nextText;
dom = parentDom.firstChild;
}
else {
dom = lastVNode.dom;
if (nextText !== lastVNode.children) {
dom.nodeValue = nextText;
}
}
nextVNode.dom = dom;
}
function patchNonKeyedChildren(lastChildren, nextChildren, dom, lifecycle, context, isSVG, lastChildrenLength, nextChildrenLength) {
var commonLength = lastChildrenLength > nextChildrenLength ? nextChildrenLength : lastChildrenLength;
var i = 0;
for (; i < commonLength; i++) {
var nextChild = nextChildren[i];
if (nextChild.dom) {
nextChild = nextChildren[i] = directClone(nextChild);
}
patch(lastChildren[i], nextChild, dom, lifecycle, context, isSVG);
}
if (lastChildrenLength < nextChildrenLength) {
for (i = commonLength; i < nextChildrenLength; i++) {
var nextChild$1 = nextChildren[i];
if (nextChild$1.dom) {
nextChild$1 = nextChildren[i] = directClone(nextChild$1);
}
mount(nextChild$1, dom, lifecycle, context, isSVG);
}
}
else if (lastChildrenLength > nextChildrenLength) {
for (i = commonLength; i < lastChildrenLength; i++) {
remove(lastChildren[i], dom);
}
}
}
function patchKeyedChildren(a, b, dom, lifecycle, context, isSVG, aLength, bLength) {
var aEnd = aLength - 1;
var bEnd = bLength - 1;
var aStart = 0;
var bStart = 0;
var i;
var j;
var aNode;
var bNode;
var nextNode;
var nextPos;
var node;
var aStartNode = a[aStart];
var bStartNode = b[bStart];
var aEndNode = a[aEnd];
var bEndNode = b[bEnd];
if (bStartNode.dom) {
b[bStart] = bStartNode = directClone(bStartNode);
}
if (bEndNode.dom) {
b[bEnd] = bEndNode = directClone(bEndNode);
}
// Step 1
// tslint:disable-next-line
outer: {
// Sync nodes with the same key at the beginning.
while (aStartNode.key === bStartNode.key) {
patch(aStartNode, bStartNode, dom, lifecycle, context, isSVG);
aStart++;
bStart++;
if (aStart > aEnd || bStart > bEnd) {
break outer;
}
aStartNode = a[aStart];
bStartNode = b[bStart];
if (bStartNode.dom) {
b[bStart] = bStartNode = directClone(bStartNode);
}
}
// Sync nodes with the same key at the end.
while (aEndNode.key === bEndNode.key) {
patch(aEndNode, bEndNode, dom, lifecycle, context, isSVG);
aEnd--;
bEnd--;
if (aStart > aEnd || bStart > bEnd) {
break outer;
}
aEndNode = a[aEnd];
bEndNode = b[bEnd];
if (bEndNode.dom) {
b[bEnd] = bEndNode = directClone(bEndNode);
}
}
}
if (aStart > aEnd) {
if (bStart <= bEnd) {
nextPos = bEnd + 1;
nextNode = nextPos < bLength ? b[nextPos].dom : null;
while (bStart <= bEnd) {
node = b[bStart];
if (node.dom) {
b[bStart] = node = directClone(node);
}
bStart++;
insertOrAppend(dom, mount(node, null, lifecycle, context, isSVG), nextNode);
}
}
}
else if (bStart > bEnd) {
while (aStart <= aEnd) {
remove(a[aStart++], dom);
}
}
else {
var aLeft = aEnd - aStart + 1;
var bLeft = bEnd - bStart + 1;
var sources = new Array(bLeft);
for (i = 0; i < bLeft; i++) {
sources[i] = -1;
}
var moved = false;
var pos = 0;
var patched = 0;
// When sizes are small, just loop them through
if (bLeft <= 4 || aLeft * bLeft <= 16) {
for (i = aStart; i <= aEnd; i++) {
aNode = a[i];
if (patched < bLeft) {
for (j = bStart; j <= bEnd; j++) {
bNode = b[j];
if (aNode.key === bNode.key) {
sources[j - bStart] = i;
if (pos > j) {
moved = true;
}
else {
pos = j;
}
if (bNode.dom) {
b[j] = bNode = directClone(bNode);
}
patch(aNode, bNode, dom, lifecycle, context, isSVG);
patched++;
a[i] = null;
break;
}
}
}
}
}
else {
var keyIndex = {};
// Map keys by their index in array
for (i = bStart; i <= bEnd; i++) {
keyIndex[b[i].key] = i;
}
// Try to patch same keys
for (i = aStart; i <= aEnd; i++) {
aNode = a[i];
if (patched < bLeft) {
j = keyIndex[aNode.key];
if (isDefined(j)) {
bNode = b[j];
sources[j - bStart] = i;
if (pos > j) {
moved = true;
}
else {
pos = j;
}
if (bNode.dom) {
b[j] = bNode = directClone(bNode);
}
patch(aNode, bNode, dom, lifecycle, context, isSVG);
patched++;
a[i] = null;
}
}
}
}
// fast-path: if nothing patched remove all old and add all new
if (aLeft === aLength && patched === 0) {
removeAllChildren(dom, a);
mountArrayChildren(b, dom, lifecycle, context, isSVG);
}
else {
i = aLeft - patched;
while (i > 0) {
aNode = a[aStart++];
if (!isNull(aNode)) {
remove(aNode, dom);
i--;
}
}
if (moved) {
var seq = lis_algorithm(sources);
j = seq.length - 1;
for (i = bLeft - 1; i >= 0; i--) {
if (sources[i] === -1) {
pos = i + bStart;
node = b[pos];
if (node.dom) {
b[pos] = node = directClone(node);
}
nextPos = pos + 1;
insertOrAppend(dom, mount(node, null, lifecycle, context, isSVG), nextPos < bLength ? b[nextPos].dom : null);
}
else if (j < 0 || i !== seq[j]) {
pos = i + bStart;
node = b[pos];
nextPos = pos + 1;
insertOrAppend(dom, node.dom, nextPos < bLength ? b[nextPos].dom : null);
}
else {
j--;
}
}
}
else if (patched !== bLeft) {
// when patched count doesn't match b length we need to insert those new ones
// loop backwards so we can use insertBefore
for (i = bLeft - 1; i >= 0; i--) {
if (sources[i] === -1) {
pos = i + bStart;
node = b[pos];
if (node.dom) {
b[pos] = node = directClone(node);
}
nextPos = pos + 1;
insertOrAppend(dom, mount(node, null, lifecycle, context, isSVG), nextPos < bLength ? b[nextPos].dom : null);
}
}
}
}
}
}
// // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
function lis_algorithm(arr) {
var p = arr.slice();
var result = [0];
var i;
var j;
var u;
var v;
var c;
var len = arr.length;
for (i = 0; i < len; i++) {
var arrI = arr[i];
if (arrI !== -1) {
j = result[result.length - 1];
if (arr[j] < arrI) {
p[i] = j;
result.push(i);
continue;
}
u = 0;
v = result.length - 1;
while (u < v) {
c = ((u + v) / 2) | 0;
if (arr[result[c]] < arrI) {
u = c + 1;
}
else {
v = c;
}
}
if (arrI < arr[result[u]]) {
if (u > 0) {
p[i] = result[u - 1];
}
result[u] = i;
}
}
}
u = result.length;
v = result[u - 1];
while (u-- > 0) {
result[u] = v;
v = p[v];
}
return result;
}
var roots = options.roots;
{
if (isBrowser && document.body === null) {
warning('Inferno warning: you cannot initialize inferno without "document.body". Wait on "DOMContentLoaded" event, add script to bottom of body, or use async/defer attributes on script tag.');
}
}
var documentBody = isBrowser ? document.body : null;
function render(input, parentDom, callback) {
// Development warning
{
if (documentBody === parentDom) {
throwError('you cannot render() to the "document.body". Use an empty element as a container instead.');
}
}
if (input === NO_OP) {
return;
}
var rootLen = roots.length;
var rootInput;
var index;
for (index = 0; index < rootLen; index++) {
if (roots[index] === parentDom) {
rootInput = parentDom.$V;
break;
}
}
if (isUndefined(rootInput)) {
if (!isInvalid(input)) {
if (input.dom) {
input = directClone(input);
}
if (isNull(parentDom.firstChild)) {
mount(input, parentDom, LIFECYCLE, EMPTY_OBJ, false);
parentDom.$V = input;
roots.push(parentDom);
}
else {
hydrate(input, parentDom);
}
rootInput = input;
}
}
else {
if (isNullOrUndef(input)) {
remove(rootInput, parentDom);
roots.splice(index, 1);
}
else {
if (input.dom) {
input = directClone(input);
}
patch(rootInput, input, parentDom, LIFECYCLE, EMPTY_OBJ, false);
rootInput = parentDom.$V = input;
}
}
if (LIFECYCLE.length > 0) {
callAll(LIFECYCLE);
}
if (isFunction(callback)) {
callback();
}
if (rootInput && rootInput.flags & 14 /* Component */) {
return rootInput.children;
}
}
function createRenderer(parentDom) {
return function renderer(lastInput, nextInput) {
if (!parentDom) {
parentDom = lastInput;
}
render(nextInput, parentDom);
};
}
function createPortal(children, container) {
return createVNode(1024 /* Portal */, container, null, children, 0 /* UnknownChildren */, null, isInvalid(children) ? null : children.key, null);
}
var resolvedPromise = typeof Promise === 'undefined' ? null : Promise.resolve();
var fallbackMethod = typeof requestAnimationFrame === 'undefined' ? setTimeout : requestAnimationFrame;
function nextTick(fn) {
if (resolvedPromise) {
return resolvedPromise.then(fn);
}
return fallbackMethod(fn);
}
function queueStateChanges(component, newState, callback) {
if (isFunction(newState)) {
newState = newState(component.state, component.props, component.context);
}
var pending = component.$PS;
if (isNullOrUndef(pending)) {
component.$PS = newState;
}
else {
for (var stateKey in newState) {
pending[stateKey] = newState[stateKey];
}
}
if (!component.$PSS && !component.$BR) {
if (!component.$UPD) {
component.$PSS = true;
component.$UPD = true;
applyState(component, false, callback);
component.$UPD = false;
}
else {
// Async
var queue = component.$QU;
if (isNull(queue)) {
queue = component.$QU = [];
nextTick(promiseCallback(component, queue));
}
if (isFunction(callback)) {
queue.push(callback);
}
}
}
else {
component.$PSS = true;
if (component.$BR && isFunction(callback)) {
LIFECYCLE.push(callback.bind(component));
}
}
}
function promiseCallback(component, queue) {
return function () {
component.$QU = null;
component.$UPD = true;
applyState(component, false, function () {
for (var i = 0, len = queue.length; i < len; i++) {
queue[i].call(component);
}
});
component.$UPD = false;
};
}
function applyState(component, force, callback) {
if (component.$UN) {
return;
}
if (force || !component.$BR) {
component.$PSS = false;
var pendingState = component.$PS;
var prevState = component.state;
var nextState = combineFrom(prevState, pendingState);
var props = component.props;
var context = component.context;
component.$PS = null;
var vNode = component.$V;
var lastInput = component.$LI;
var parentDom = lastInput.dom && lastInput.dom.parentNode;
updateClassComponent(component, nextState, vNode, props, parentDom, LIFECYCLE, context, (vNode.flags & 32 /* SvgElement */) > 0, force, true);
if (component.$UN) {
return;
}
if ((component.$LI.flags & 1024 /* Portal */) === 0) {
var dom = component.$LI.dom;
while (!isNull((vNode = vNode.parentVNode))) {
if ((vNode.flags & 14 /* Component */) > 0) {
vNode.dom = dom;
}
}
}
if (LIFECYCLE.length > 0) {
callAll(LIFECYCLE);
}
}
else {
component.state = component.$PS;
component.$PS = null;
}
if (isFunction(callback)) {
callback.call(component);
}
}
var Component = function Component(props, context) {
this.state = null;
// Internal properties
this.$BR = false; // BLOCK RENDER
this.$BS = true; // BLOCK STATE
this.$PSS = false; // PENDING SET STATE
this.$PS = null; // PENDING STATE (PARTIAL or FULL)
this.$LI = null; // LAST INPUT
this.$V = null; // VNODE
this.$UN = false; // UNMOUNTED
this.$CX = null; // CHILDCONTEXT
this.$UPD = true; // UPDATING
this.$QU = null; // QUEUE
/** @type {object} */
this.props = props || EMPTY_OBJ;
/** @type {object} */
this.context = context || EMPTY_OBJ; // context should not be mutable
};
Component.prototype.forceUpdate = function forceUpdate (callback) {
if (this.$UN) {
return;
}
applyState(this, true, callback);
};
Component.prototype.setState = function setState (newState, callback) {
if (this.$UN) {
return;
}
if (!this.$BS) {
queueStateChanges(this, newState, callback);
}
else {
// Development warning
{
throwError('cannot update state via setState() in componentWillUpdate() or constructor.');
}
return;
}
};
// tslint:disable-next-line:no-empty
Component.prototype.render = function render (nextProps, nextState, nextContext) { };
// Public
Component.defaultProps = null;
{
/* tslint:disable-next-line:no-empty */
var testFunc = function testFn() { };
if ((testFunc.name || testFunc.toString()).indexOf('testFn') === -1) {
warning("It looks like you're using a minified copy of the development build " +
'of Inferno. When deploying Inferno apps to production, make sure to use ' +
'the production build which skips development warnings and is faster. ' +
'See http://infernojs.org for more details.');
}
}
var version = "4.0.8";
exports.Component = Component;
exports.EMPTY_OBJ = EMPTY_OBJ;
exports.NO_OP = NO_OP;
exports.createComponentVNode = createComponentVNode;
exports.createPortal = createPortal;
exports.createRenderer = createRenderer;
exports.createTextVNode = createTextVNode;
exports.createVNode = createVNode;
exports.directClone = directClone;
exports.getFlagsForElementVnode = getFlagsForElementVnode;
exports.getNumberStyleValue = getNumberStyleValue;
exports.hydrate = hydrate;
exports.linkEvent = linkEvent;
exports.normalizeProps = normalizeProps;
exports.options = options;
exports.render = render;
exports.version = version;
Object.defineProperty(exports, '__esModule', { value: true });
})));
| jonobr1/cdnjs | ajax/libs/inferno/4.0.8/inferno.js | JavaScript | mit | 96,955 |
// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
/**
* @license @product.name@ JS v@product.version@ (@product.date@)
*
* (c) 2009-2014 Torstein Honsi
*
* License: www.highcharts.com/license
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) {
module.exports = root.document ?
factory(root) :
function (w) {
return factory(w);
};
} else {
root.Highcharts = factory();
}
}(typeof window !== 'undefined' ? window : this, function (w) {
| frank12268/codis | cmd/fe/assets/node_modules/highcharts/js/parts/Intro.js | JavaScript | mit | 554 |
Behaviour.register({
'#backButton': function(button) {
button.onclick = function() {
if (isNaN(memberId) || memberId <= 0) {
self.location = pathPrefix + "/searchLoanGroups";
} else {
self.location = pathPrefix + "/memberLoanGroups?memberId=" + memberId;
}
}
}
}); | diriger/solcyc | web/pages/loanGroups/viewLoanGroup.js | JavaScript | gpl-2.0 | 287 |
/* global describe, beforeEach, it */
import { expect } from "chai";
import { shouldOpenInNewTab } from "./utils";
describe("app/lib/utils:shouldOpenInNewTab", () => {
let mockClickEvent;
beforeEach(() => {
mockClickEvent = {
ctrlKey: false,
metaKey: false,
type: "click",
button: 0
};
});
it("should default to false", () => {
expect(shouldOpenInNewTab(mockClickEvent)).to.be.false;
});
it("should return true when ctrl-clicked", () => {
mockClickEvent.ctrlKey = true;
expect(shouldOpenInNewTab(mockClickEvent)).to.be.true;
});
it("should return true when cmd-clicked", () => {
mockClickEvent.metaKey = true;
expect(shouldOpenInNewTab(mockClickEvent)).to.be.true;
});
it("should return false for non-click events", () => {
mockClickEvent.type = "keypress";
expect(shouldOpenInNewTab(mockClickEvent)).to.be.false;
});
it("should return true for middle clicks", () => {
mockClickEvent.button = 1;
expect(shouldOpenInNewTab(mockClickEvent)).to.be.true;
});
it("should return false for right clicks", () => {
mockClickEvent.button = 2;
expect(shouldOpenInNewTab(mockClickEvent)).to.be.false;
});
});
| mozilla/idea-town | frontend/src/app/lib/tests.js | JavaScript | mpl-2.0 | 1,211 |
/* */
"format amd";
/*! jQuery UI - v1.11.4 - 2015-03-13
* http://jqueryui.com
* Copyright jQuery Foundation and other contributors; Licensed MIT */
(function(e){"function"==typeof define&&define.amd?define(["../datepicker"],e):e(jQuery.datepicker)})(function(e){return e.regional.kk={closeText:"Жабу",prevText:"<Алдыңғы",nextText:"Келесі>",currentText:"Бүгін",monthNames:["Қаңтар","Ақпан","Наурыз","Сәуір","Мамыр","Маусым","Шілде","Тамыз","Қыркүйек","Қазан","Қараша","Желтоқсан"],monthNamesShort:["Қаң","Ақп","Нау","Сәу","Мам","Мау","Шіл","Там","Қыр","Қаз","Қар","Жел"],dayNames:["Жексенбі","Дүйсенбі","Сейсенбі","Сәрсенбі","Бейсенбі","Жұма","Сенбі"],dayNamesShort:["жкс","дсн","ссн","срс","бсн","жма","снб"],dayNamesMin:["Жк","Дс","Сс","Ср","Бс","Жм","Сн"],weekHeader:"Не",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.setDefaults(e.regional.kk),e.regional.kk}); | IsmailM/sequenceserver | public/vendor/github/components/jqueryui@1.11.4/ui/minified/i18n/datepicker-kk.min.js | JavaScript | agpl-3.0 | 1,125 |
/**
* @license
* Copyright 2015 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.
*
* Credits:
* Original version of this file was derived from
* https://github.com/ampproject/amphtml/blob/master/test/functional/test-srcset.js
*/
goog.provide('parse_srcset.ParseSrcsetTest');
goog.require('parse_srcset.parseSrcset');
/**
* A strict comparison between two values.
* Note: Unfortunately assert.strictEqual has some drawbacks, including that
* it truncates the provided arguments (and it's not configurable) and
* with the Closure compiler, it requires a message argument to which
* we'd always have to pass undefined. Too messy, so we roll our own.
* @param {T} expected
* @param {T} saw
* @template T
*/
function assertStrictEqual(expected, saw) {
assert.ok(expected === saw, 'expected: ' + expected + ' saw: ' + saw);
}
/**
* Test parseSrcset and assert results are as expected.
* @param {string} s
* @param {!Array<!parse_srcset.SrcsetSourceDef>} expected
*/
function test(s, expected) {
const result = parse_srcset.parseSrcset(s);
assertStrictEqual(result.srcsetImages.length, expected.length);
for (let i = 0; i < expected.length; i++) {
const r = result.srcsetImages[i];
const e = expected[i];
assertStrictEqual(r.url, e.url);
assertStrictEqual(r.widthOrPixelDensity, e.widthOrPixelDensity);
}
expect(result.success).toBe(true);
}
describe('Srcset parseSrcset', () => {
it('should accept single source', () => {
test('image', [
{url: 'image', widthOrPixelDensity: '1x'},
]);
});
it('should accept single source with width/pixel-density', () => {
test('image 100w', [
{url: 'image', widthOrPixelDensity: '100w'},
]);
test('image 2x', [
{url: 'image', widthOrPixelDensity: '2x'},
]);
});
it('should accept whitespace around url', () => {
test(' \t\n image \n\t\t ', [
{url: 'image', widthOrPixelDensity: '1x'},
]);
});
it('should ignore empty source', () => {
test(' \n image \n, ', [
{url: 'image', widthOrPixelDensity: '1x'},
]);
test(' , \n image \n, ', [
{url: 'image', widthOrPixelDensity: '1x'},
]);
});
it('should accept multiple sources', () => {
test('image1 2x, image2, image3 3x, image4 4x', [
{url: 'image1', widthOrPixelDensity: '2x'},
{url: 'image2', widthOrPixelDensity: '1x'},
{url: 'image3', widthOrPixelDensity: '3x'},
{url: 'image4', widthOrPixelDensity: '4x'},
]);
test(' \n image 2x \n\t, image2 \n ', [
{url: 'image', widthOrPixelDensity: '2x'},
{url: 'image2', widthOrPixelDensity: '1x'},
]);
});
it('should not accept multiple sources with duplicate width', () => {
const result = parse_srcset.parseSrcset(
'image1 10w, image2 100w, image3 1000w, image4 10w');
expect(result.success).toBe(false);
});
it('should accept width-based sources', () => {
test(' \n image-100 100w\n, image 10w', [
{url: 'image-100', widthOrPixelDensity: '100w'},
{url: 'image', widthOrPixelDensity: '10w'},
]);
});
it('should accept dpr-based sources', () => {
test(' \n image-x1.5 1.5x\n , image', [
{url: 'image-x1.5', widthOrPixelDensity: '1.5x'},
{url: 'image', widthOrPixelDensity: '1x'},
]);
});
it('should accept commas in URLs', () => {
test(' \n image,1 100w\n , \n image,2 50w \n', [
{url: 'image,1', widthOrPixelDensity: '100w'},
{url: 'image,2', widthOrPixelDensity: '50w'},
]);
test(' \n image,100w 100w\n , \n image,20w 50w \n', [
{url: 'image,100w', widthOrPixelDensity: '100w'},
{url: 'image,20w', widthOrPixelDensity: '50w'},
]);
test(' \n image,2 2x\n , \n image,1', [
{url: 'image,2', widthOrPixelDensity: '2x'},
{url: 'image,1', widthOrPixelDensity: '1x'},
]);
test(' \n image,2x 2x\n , \n image,1x', [
{url: 'image,2x', widthOrPixelDensity: '2x'},
{url: 'image,1x', widthOrPixelDensity: '1x'},
]);
test(' \n image,2 , \n image,1 2x\n', [
{url: 'image,2', widthOrPixelDensity: '1x'},
{url: 'image,1', widthOrPixelDensity: '2x'},
]);
test(' \n image,1x , \n image,2x 2x\n', [
{url: 'image,1x', widthOrPixelDensity: '1x'},
{url: 'image,2x', widthOrPixelDensity: '2x'},
]);
test(' \n image,1 \n ', [
{url: 'image,1', widthOrPixelDensity: '1x'},
]);
test(' \n image,1x \n ', [
{url: 'image,1x', widthOrPixelDensity: '1x'},
]);
});
it('should accept leading and trailing commas and commas in url', () => {
// Leading and trailing commas are OK, as are commas in side URLs.
// This example only looks a little strange because the ParseSourceSet
// function does not further validate the URL.
test(',image1,100w,image2,50w,', [
{url: 'image1,100w,image2,50w', widthOrPixelDensity: '1x'},
]);
// This is a more typical-looking example, with leading and trailing commas.
test(',example.com/,/,/,/,50w,', [
{url: 'example.com/,/,/,/,50w', widthOrPixelDensity: '1x'},
]);
});
it('should accept no-whitespace', () => {
test('image 100w,image 50w', [
{url: 'image', widthOrPixelDensity: '100w'},
{url: 'image', widthOrPixelDensity: '50w'},
]);
test('image,1 100w,image,2 50w', [
{url: 'image,1', widthOrPixelDensity: '100w'},
{url: 'image,2', widthOrPixelDensity: '50w'},
]);
test('image,1 2x,image,2', [
{url: 'image,1', widthOrPixelDensity: '2x'},
{url: 'image,2', widthOrPixelDensity: '1x'},
]);
test('image,2 2x', [
{url: 'image,2', widthOrPixelDensity: '2x'},
]);
test('image,1', [
{url: 'image,1', widthOrPixelDensity: '1x'},
]);
});
it('should accept other special chars in URLs', () => {
test(' \n http://im-a+ge;1?&2#3 100w\n , \n image;2 50w \n', [
{url: 'http://im-a+ge;1?&2#3', widthOrPixelDensity: '100w'},
{url: 'image;2', widthOrPixelDensity: '50w'},
]);
});
it('should accept false cognitives in URLs', () => {
test(' \n image,100w 100w\n , \n image,20x 50w \n', [
{url: 'image,100w', widthOrPixelDensity: '100w'},
{url: 'image,20x', widthOrPixelDensity: '50w'},
]);
test(' \n image,1x 2x\n , \n image,2x', [
{url: 'image,1x', widthOrPixelDensity: '2x'},
{url: 'image,2x', widthOrPixelDensity: '1x'},
]);
test(' \n image,1x \n ', [
{url: 'image,1x', widthOrPixelDensity: '1x'},
]);
test(' \n image,1w \n ', [
{url: 'image,1w', widthOrPixelDensity: '1x'},
]);
});
it('should parse misc examples', () => {
test('image-1x.png 1x, image-2x.png 2x, image-3x.png 3x, image-4x.png 4x', [
{url: 'image-1x.png', widthOrPixelDensity: '1x'},
{url: 'image-2x.png', widthOrPixelDensity: '2x'},
{url: 'image-3x.png', widthOrPixelDensity: '3x'},
{url: 'image-4x.png', widthOrPixelDensity: '4x'},
]);
test('image,one.png', [
{url: 'image,one.png', widthOrPixelDensity: '1x'},
]);
});
it('should reject urls with spaces', () => {
let result = parse_srcset.parseSrcset('image 1x png 1x');
expect(result.success).toBe(false);
result = parse_srcset.parseSrcset('image 1x png 1x, image-2x.png 2x');
expect(result.success).toBe(false);
});
it('should reject width or pixel density with negatives', () => {
let result = parse_srcset.parseSrcset('image.png -1x');
expect(result.success).toBe(false);
result = parse_srcset.parseSrcset('image.png 1x, image2.png -2x');
expect(result.success).toBe(false);
result = parse_srcset.parseSrcset('image.png -480w');
expect(result.success).toBe(false);
result = parse_srcset.parseSrcset('image.png 1x, image2.png -100w');
expect(result.success).toBe(false);
});
it('should reject empty srcsets', () => {
let result = parse_srcset.parseSrcset('');
expect(result.success).toBe(false);
result = parse_srcset.parseSrcset(' \n\t\f\r');
expect(result.success).toBe(false);
});
it('should reject invalid text after valid srcsets', () => {
const result = parse_srcset.parseSrcset('image1, image2, ,,,');
expect(result.success).toBe(false);
});
it('should reject no comma between sources', () => {
const result = parse_srcset.parseSrcset('image1 100w image2 50w');
expect(result.success).toBe(false);
});
});
| luciancrasovan/amphtml | validator/engine/parse-srcset_test.js | JavaScript | apache-2.0 | 8,950 |
var KeyVault = require('azure-keyvault');
var util = require('util');
var Crypto = require('crypto');
var AuthenticationContext = require('adal-node').AuthenticationContext;
var clientId = '<to-be-filled>';
var clientSecret = '<to-be-filled>';
var vaultUri = '<to-be-filled>';
// Authenticator - retrieves the access token
var authenticator = function (challenge, callback) {
// Create a new authentication context.
var context = new AuthenticationContext(challenge.authorization);
// Use the context to acquire an authentication token.
return context.acquireTokenWithClientCredentials(challenge.resource, clientId, clientSecret, function (err, tokenResponse) {
if (err) throw err;
// Calculate the value to be set in the request's Authorization header and resume the call.
var authorizationValue = tokenResponse.tokenType + ' ' + tokenResponse.accessToken;
return callback(null, authorizationValue);
});
};
var credentials = new KeyVault.KeyVaultCredentials(authenticator);
var client = new KeyVault.KeyVaultClient(credentials);
var attributes = { expires: new Date('2050-02-02T08:00:00.000Z'), notBefore: new Date('2016-01-01T08:00:00.000Z') };
var keyOperations = ['encrypt', 'decrypt', 'sign', 'verify', 'wrapKey', 'unwrapKey'];
//Create a key
client.createKey(vaultUri, 'mykey', 'RSA', { keyOps: keyOperations, keyAttributes: attributes }, function(err, keyBundle) {
if (err) throw err;
console.log('\n\nkey ', keyBundle.key.kid, ' is created.\n', util.inspect(keyBundle, { depth: null }));
// Retrieve the key
client.getKey(keyBundle.key.kid, function(getErr, getKeyBundle) {
if (getErr) throw getErr;
console.log('\n\nkey ', getKeyBundle.key.kid, ' is retrieved.\n');
// Encrypt a plain text
var encryptionContent = new Buffer('This message is to be encrypted...');
client.encrypt(keyBundle.key.kid, 'RSA-OAEP', encryptionContent, function (encryptErr, cipherText) {
if (encryptErr) throw encryptErr;
console.log('\n\nText is encrypted: ', cipherText.result);
// Decrypt a cipher text
client.decrypt(keyBundle.key.kid, 'RSA-OAEP', cipherText.result, function (decryptErr, plainText) {
if (decryptErr) throw decryptErr;
console.log('\n\nThe encrypted cipher text is decrypted to: ', plainText.result);
});
});
// Sign a digest value
var hash = Crypto.createHash('sha256');
var digest = hash.update(new Buffer('sign me')).digest();
client.sign(keyBundle.key.kid, 'RS256', digest, function (signErr, signature) {
if (signErr) throw signErr;
console.log('The signature for digest ', digest, ' is: ', signature.result);
// Verify a signature
client.verify(keyBundle.key.kid, 'RS256', digest, signature.result, function (verifyErr, verification) {
if (verifyErr) throw verifyErr;
console.log('The verification', verification.value === true? 'succeeded':'failed');
});
});
});
// Update the key with new tags
client.updateKey(keyBundle.key.kid, {tags: {'tag1': 'this is tag1', 'tag2': 'this is tag2'}}, function (getErr, updatedKeyBundle) {
if (getErr) throw getErr;
console.log('\n\nkey ', updatedKeyBundle.key.kid, ' is updated.\n', util.inspect(updatedKeyBundle, { depth: null }));
});
// List all versions of the key
var parsedId = KeyVault.parseKeyIdentifier(keyBundle.key.kid);
client.getKeyVersions(parsedId.vault, parsedId.name, function (getVersionsErr, result) {
if (getVersionsErr) throw getVersionsErr;
var loop = function (nextLink) {
if (nextLink !== null && nextLink !== undefined) {
client.getKeyVersionsNext(nextLink, function (err, res) {
console.log(res);
loop(res.nextLink);
});
}
};
console.log(result);
loop(result.nextLink);
});
});
//Create a secret
client.setSecret(vaultUri, 'mysecret', 'my password', { contentType: 'test secret', secretAttributes: attributes }, function (err, secretBundle) {
if (err) throw err;
console.log('\n\nSecret ', secretBundle.id, ' is created.\n', util.inspect(secretBundle, { depth: null }));
// Retrieve the secret
client.getSecret(secretBundle.id, function (getErr, getSecretBundle) {
if (getErr) throw getErr;
console.log('\n\nSecret ', getSecretBundle.id, ' is retrieved.\n');
});
// List all secrets
var parsedId = KeyVault.parseSecretIdentifier(secretBundle.id);
client.getSecrets(parsedId.vault, parsedId.name, function (err, result) {
if (err) throw err;
var loop = function (nextLink) {
if (nextLink !== null && nextLink !== undefined) {
client.getSecretsNext(nextLink, function (err, res) {
console.log(res);
loop(res.nextLink);
});
}
};
console.log(result);
loop(result.nextLink);
});
});
var certificatePolicy = {
keyProperties : {
exportable: true,
reuseKey : false,
keySize : 2048,
keyType : 'RSA'
},
secretProperties : {
contentType : 'application/x-pkcs12'
},
issuerParameters : {
name : 'Self'
},
x509CertificateProperties : {
subject : 'CN=*.microsoft.com',
subjectAlternativeNames : ['onedrive.microsoft.com', 'xbox.microsoft.com'],
validityInMonths : 24
}
};
var intervalTime = 5000;
//Create a certificate
client.createCertificate(vaultUri, 'mycertificate', { certificatePolicy: certificatePolicy }, function (err, certificateOperation) {
if (err) throw err;
console.log('\n\nCertificate', certificateOperation.id, 'is being created.\n', util.inspect(certificateOperation, { depth: null }));
// Poll the certificate status until it is created
var interval = setInterval(function getCertStatus() {
var parsedId = KeyVault.parseCertificateOperationIdentifier(certificateOperation.id);
client.getCertificateOperation(parsedId.vault, parsedId.name, function (err, pendingCertificate) {
if (err) throw err;
if (pendingCertificate.status.toUpperCase() === 'completed'.toUpperCase()) {
clearInterval(interval);
console.log('\n\nCertificate', pendingCertificate.target, 'is created.\n', util.inspect(pendingCertificate, { depth: null }));
var parsedCertId = KeyVault.parseCertificateIdentifier(pendingCertificate.target);
//Delete the created certificate
client.deleteCertificate(parsedCertId.vault, parsedCertId.name, function (delErr, deleteResp) {
console.log('\n\nCertificate', pendingCertificate.target, 'is deleted.\n');
});
}
else if (pendingCertificate.status.toUpperCase() === 'InProgress'.toUpperCase()) {
console.log('\n\nCertificate', certificateOperation.id, 'is being created.\n', util.inspect(pendingCertificate, { depth: null }));
}
});
}, intervalTime);
}); | begoldsm/azure-sdk-for-node | lib/services/keyVault/sample.js | JavaScript | apache-2.0 | 6,910 |
//>>built
define("dojox/form/nls/el/Uploader",{label:"\u0395\u03c0\u03b9\u03bb\u03bf\u03b3\u03ae \u03b1\u03c1\u03c7\u03b5\u03af\u03c9\u03bd..."}); | aconyteds/Esri-Ozone-Map-Widget | vendor/js/esri/arcgis_js_api/library/3.12/3.12compact/dojox/form/nls/el/Uploader.js | JavaScript | apache-2.0 | 146 |
const JsonReporter = require('./mocha-custom-json-reporter');
const mocha = require('mocha');
const MochaDotsReporter = require('./mocha-dots-reporter');
const MochaJUnitReporter = require('mocha-junit-reporter');
const {Base} = mocha.reporters;
/**
* @param {*} runner
* @param {*} options
* @return {MochaDotsReporter}
*/
function ciReporter(runner, options) {
Base.call(this, runner, options);
this._mochaDotsReporter = new MochaDotsReporter(runner);
this._jsonReporter = new JsonReporter(runner);
this._mochaJunitReporter = new MochaJUnitReporter(runner, options);
// TODO(#28387) clean up this typing.
return /** @type {*} */ (this);
}
ciReporter.prototype.__proto__ = Base.prototype;
module.exports = ciReporter;
| Gregable/amphtml | build-system/tasks/e2e/mocha-ci-reporter.js | JavaScript | apache-2.0 | 737 |
// Copyright 2014 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.
/**
* @fileoverview An UI component to authenciate to Chrome. The component hosts
* IdP web pages in a webview. A client who is interested in monitoring
* authentication events should pass a listener object of type
* cr.login.GaiaAuthHost.Listener as defined in this file. After initialization,
* call {@code load} to start the authentication flow.
*/
cr.define('cr.login', function() {
'use strict';
// TODO(rogerta): should use gaia URL from GaiaUrls::gaia_url() instead
// of hardcoding the prod URL here. As is, this does not work with staging
// environments.
var IDP_ORIGIN = 'https://accounts.google.com/';
var IDP_PATH = 'ServiceLogin?skipvpage=true&sarp=1&rm=hide';
var CONTINUE_URL =
'chrome-extension://mfffpogegjflfpflabcdkioaeobkgjik/success.html';
var SIGN_IN_HEADER = 'google-accounts-signin';
var EMBEDDED_FORM_HEADER = 'google-accounts-embedded';
var SAML_HEADER = 'google-accounts-saml';
var LOCATION_HEADER = 'location';
/**
* The source URL parameter for the constrained signin flow.
*/
var CONSTRAINED_FLOW_SOURCE = 'chrome';
/**
* Enum for the authorization mode, must match AuthMode defined in
* chrome/browser/ui/webui/inline_login_ui.cc.
* @enum {number}
*/
var AuthMode = {
DEFAULT: 0,
OFFLINE: 1,
DESKTOP: 2
};
/**
* Enum for the authorization type.
* @enum {number}
*/
var AuthFlow = {
DEFAULT: 0,
SAML: 1
};
/**
* Initializes the authenticator component.
* @param {webview|string} webview The webview element or its ID to host IdP
* web pages.
* @constructor
*/
function Authenticator(webview) {
this.webview_ = typeof webview == 'string' ? $(webview) : webview;
assert(this.webview_);
this.email_ = null;
this.password_ = null;
this.gaiaId_ = null,
this.sessionIndex_ = null;
this.chooseWhatToSync_ = false;
this.skipForNow_ = false;
this.authFlow_ = AuthFlow.DEFAULT;
this.loaded_ = false;
this.idpOrigin_ = null;
this.continueUrl_ = null;
this.continueUrlWithoutParams_ = null;
this.initialFrameUrl_ = null;
this.reloadUrl_ = null;
this.trusted_ = true;
}
// TODO(guohui,xiyuan): no need to inherit EventTarget once we deprecate the
// old event-based signin flow.
Authenticator.prototype = Object.create(cr.EventTarget.prototype);
/**
* Loads the authenticator component with the given parameters.
* @param {AuthMode} authMode Authorization mode.
* @param {Object} data Parameters for the authorization flow.
*/
Authenticator.prototype.load = function(authMode, data) {
this.idpOrigin_ = data.gaiaUrl || IDP_ORIGIN;
this.continueUrl_ = data.continueUrl || CONTINUE_URL;
this.continueUrlWithoutParams_ =
this.continueUrl_.substring(0, this.continueUrl_.indexOf('?')) ||
this.continueUrl_;
this.isConstrainedWindow_ = data.constrained == '1';
this.initialFrameUrl_ = this.constructInitialFrameUrl_(data);
this.reloadUrl_ = data.frameUrl || this.initialFrameUrl_;
this.authFlow_ = AuthFlow.DEFAULT;
this.webview_.src = this.reloadUrl_;
this.webview_.addEventListener(
'newwindow', this.onNewWindow_.bind(this));
this.webview_.addEventListener(
'loadstop', this.onLoadStop_.bind(this));
this.webview_.request.onCompleted.addListener(
this.onRequestCompleted_.bind(this),
{urls: ['*://*/*', this.continueUrlWithoutParams_ + '*'],
types: ['main_frame']},
['responseHeaders']);
this.webview_.request.onHeadersReceived.addListener(
this.onHeadersReceived_.bind(this),
{urls: [this.idpOrigin_ + '*'], types: ['main_frame']},
['responseHeaders']);
window.addEventListener(
'message', this.onMessageFromWebview_.bind(this), false);
window.addEventListener(
'focus', this.onFocus_.bind(this), false);
window.addEventListener(
'popstate', this.onPopState_.bind(this), false);
};
/**
* Reloads the authenticator component.
*/
Authenticator.prototype.reload = function() {
this.webview_.src = this.reloadUrl_;
this.authFlow_ = AuthFlow.DEFAULT;
};
Authenticator.prototype.constructInitialFrameUrl_ = function(data) {
var url = this.idpOrigin_ + (data.gaiaPath || IDP_PATH);
url = appendParam(url, 'continue', this.continueUrl_);
url = appendParam(url, 'service', data.service);
if (data.hl)
url = appendParam(url, 'hl', data.hl);
if (data.email)
url = appendParam(url, 'Email', data.email);
if (this.isConstrainedWindow_)
url = appendParam(url, 'source', CONSTRAINED_FLOW_SOURCE);
return url;
};
/**
* Invoked when a main frame request in the webview has completed.
* @private
*/
Authenticator.prototype.onRequestCompleted_ = function(details) {
var currentUrl = details.url;
if (currentUrl.lastIndexOf(this.continueUrlWithoutParams_, 0) == 0) {
if (currentUrl.indexOf('ntp=1') >= 0)
this.skipForNow_ = true;
this.onAuthCompleted_();
return;
}
if (currentUrl.indexOf('https') != 0)
this.trusted_ = false;
if (this.isConstrainedWindow_) {
var isEmbeddedPage = false;
if (this.idpOrigin_ && currentUrl.lastIndexOf(this.idpOrigin_) == 0) {
var headers = details.responseHeaders;
for (var i = 0; headers && i < headers.length; ++i) {
if (headers[i].name.toLowerCase() == EMBEDDED_FORM_HEADER) {
isEmbeddedPage = true;
break;
}
}
}
if (!isEmbeddedPage) {
this.dispatchEvent(new CustomEvent('resize', {detail: currentUrl}));
return;
}
}
this.updateHistoryState_(currentUrl);
// Posts a message to IdP pages to initiate communication.
if (currentUrl.lastIndexOf(this.idpOrigin_) == 0)
this.webview_.contentWindow.postMessage({}, currentUrl);
};
/**
* Manually updates the history. Invoked upon completion of a webview
* navigation.
* @param {string} url Request URL.
* @private
*/
Authenticator.prototype.updateHistoryState_ = function(url) {
if (history.state && history.state.url != url)
history.pushState({url: url}, '');
else
history.replaceState({url: url});
};
/**
* Invoked when the sign-in page takes focus.
* @param {object} e The focus event being triggered.
* @private
*/
Authenticator.prototype.onFocus_ = function(e) {
this.webview_.focus();
};
/**
* Invoked when the history state is changed.
* @param {object} e The popstate event being triggered.
* @private
*/
Authenticator.prototype.onPopState_ = function(e) {
var state = e.state;
if (state && state.url)
this.webview_.src = state.url;
};
/**
* Invoked when headers are received in the main frame of the webview. It
* 1) reads the authenticated user info from a signin header,
* 2) signals the start of a saml flow upon receiving a saml header.
* @return {!Object} Modified request headers.
* @private
*/
Authenticator.prototype.onHeadersReceived_ = function(details) {
var headers = details.responseHeaders;
for (var i = 0; headers && i < headers.length; ++i) {
var header = headers[i];
var headerName = header.name.toLowerCase();
if (headerName == SIGN_IN_HEADER) {
var headerValues = header.value.toLowerCase().split(',');
var signinDetails = {};
headerValues.forEach(function(e) {
var pair = e.split('=');
signinDetails[pair[0].trim()] = pair[1].trim();
});
// Removes "" around.
var email = signinDetails['email'].slice(1, -1);
if (this.email_ != email) {
this.email_ = email;
// Clears the scraped password if the email has changed.
this.password_ = null;
}
this.gaiaId_ = signinDetails['obfuscatedid'].slice(1, -1);
this.sessionIndex_ = signinDetails['sessionindex'];
} else if (headerName == SAML_HEADER) {
this.authFlow_ = AuthFlow.SAML;
} else if (headerName == LOCATION_HEADER) {
// If the "choose what to sync" checkbox was clicked, then the continue
// URL will contain a source=3 field.
var location = decodeURIComponent(header.value);
this.chooseWhatToSync_ = !!location.match(/(\?|&)source=3($|&)/);
}
}
};
/**
* Invoked when an HTML5 message is received from the webview element.
* @param {object} e Payload of the received HTML5 message.
* @private
*/
Authenticator.prototype.onMessageFromWebview_ = function(e) {
// The event origin does not have a trailing slash.
if (e.origin != this.idpOrigin_.substring(0, this.idpOrigin_ - 1)) {
return;
}
var msg = e.data;
if (msg.method == 'attemptLogin') {
this.email_ = msg.email;
this.password_ = msg.password;
this.chooseWhatToSync_ = msg.chooseWhatToSync;
}
};
/**
* Invoked to process authentication completion.
* @private
*/
Authenticator.prototype.onAuthCompleted_ = function() {
if (!this.email_ && !this.skipForNow_) {
this.webview_.src = this.initialFrameUrl_;
return;
}
this.dispatchEvent(
new CustomEvent('authCompleted',
{detail: {email: this.email_,
gaiaId: this.gaiaId_,
password: this.password_,
usingSAML: this.authFlow_ == AuthFlow.SAML,
chooseWhatToSync: this.chooseWhatToSync_,
skipForNow: this.skipForNow_,
sessionIndex: this.sessionIndex_ || '',
trusted: this.trusted_}}));
};
/**
* Invoked when the webview attempts to open a new window.
* @private
*/
Authenticator.prototype.onNewWindow_ = function(e) {
this.dispatchEvent(new CustomEvent('newWindow', {detail: e}));
};
/**
* Invoked when the webview finishes loading a page.
* @private
*/
Authenticator.prototype.onLoadStop_ = function(e) {
if (!this.loaded_) {
this.loaded_ = true;
this.webview_.focus();
this.dispatchEvent(new Event('ready'));
}
};
Authenticator.AuthFlow = AuthFlow;
Authenticator.AuthMode = AuthMode;
return {
// TODO(guohui, xiyuan): Rename GaiaAuthHost to Authenticator once the old
// iframe-based flow is deprecated.
GaiaAuthHost: Authenticator
};
});
| mxOBS/deb-pkg_trusty_chromium-browser | chrome/browser/resources/gaia_auth_host/authenticator.js | JavaScript | bsd-3-clause | 10,746 |
Event.addBehavior({
'body:click' : function(event) {
if (event.shiftKey && event.altKey) {
Dryml.click(event)
Event.stop(event)
}
}
})
var Dryml = {
menu: null,
event: null,
click: function(event) {
Dryml.event = event
Dryml.showSourceMenu(event.target)
},
showSourceMenu: function(element) {
var stack = Dryml.getSrcInfoStack(element)
Dryml.showMenu(stack)
},
getSrcInfoStack: function(element) {
var stack = $A()
while(element != document.documentElement) {
var el = Dryml.findPrecedingDrymlInfo(element)
if (el == null) {
element = element.parentNode
} else {
element = el
var info = Dryml.getDrymlInfo(element)
stack.push(info)
}
}
return stack
},
findPrecedingDrymlInfo: function(element) {
var ignoreCount = 0
var el = element
while (el = el.previousSibling) {
if (Dryml.isDrymlInfo(el)) {
if (ignoreCount > 0)
ignoreCount -= 1;
else
return el
} else if (Dryml.isDrymlInfoClose(el)) {
ignoreCount += 1
}
}
return null
},
getDrymlInfo: function(el) {
var parts = el.nodeValue.sub(/^\[DRYML\|/, "").sub(/\[$/, "").split("|")
return { kind: parts[0], tag: parts[1], line: parts[2], file: parts[3] }
},
isDrymlInfo: function(el) {
return el.nodeType == Node.COMMENT_NODE && el.nodeValue.match(/^\[DRYML/)
},
isDrymlInfoClose: function(el) {
return el.nodeType == Node.COMMENT_NODE && el.nodeValue == "]DRYML]"
},
showMenu: function(stack) {
Dryml.removeMenu()
var style = $style({id: "dryml-menu-style"},
"#dryml-src-menu { position: fixed; margin: 10px; padding: 10px; background: black; color: white; border: 1px solid white; }\n",
"#dryml-src-menu a { color: white; text-decoration: none; border: none; }\n",
"#dryml-src-menu td { padding: 2px 7px; }\n",
"#dryml-src-menu a:hover { background: black; color: white; text-decoration: none; border: none; }\n")
$$("head")[0].appendChild(style)
var items = stack.map(Dryml.makeMenuItem)
var closer = $a({href:"#"}, "[close]")
closer.onclick = Dryml.removeMenu
Dryml.menu = $div({id: "dryml-src-menu",
style: "position: fixed; margin: 10px; padding: 10px; background: black; color: #cfc; border: 1px solid white;"
},
closer,
$table(items))
document.body.appendChild(Dryml.menu)
Dryml.menu.style.top = "20px"//Dryml.event.clientY + "px"
Dryml.menu.style.left = "20px"//Dryml.event.clientX + "px"
},
editSourceFile: function(path, line) {
new Ajax.Request("/dryml/edit_source?file=" + path + "&line=" + line)
},
makeMenuItem: function(item) {
var text
switch (item.kind) {
case "call":
text = "<" + item.tag + ">"
break
case "param":
text = "<" + item.tag + ":>"
break
case "replace":
text = "<" + item.tag + ": replace>"
break
case "def":
text = "<def " + item.tag + ">"
break
}
var a = $a({href:"#"}, text)
a.onclick = function() { Dryml.editSourceFile(item.file, item.line); return false }
var filename = item.file.sub("vendor/plugins", "").sub("app/views", "").sub(/^\/+/, "").sub(".dryml", "")
return $tr($td({"class": "file"}, filename), $td(a))
},
removeMenu: function() {
if (Dryml.menu) {
$("dryml-menu-style").remove()
Dryml.menu.remove()
Dryml.menu = null
}
}
}
| lak/puppetshow | vendor/plugins/hobo/generators/hobo/templates/dryml-support.js | JavaScript | bsd-3-clause | 4,121 |
// Copyright 2014 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.
import {assert, assertInstanceof, assertNotReached} from 'chrome://resources/js/assert.m.js';
import {dispatchSimpleEvent} from 'chrome://resources/js/cr.m.js';
import {List} from 'chrome://resources/js/cr/ui/list.m.js';
import {ListItem} from 'chrome://resources/js/cr/ui/list_item.m.js';
import {ListSelectionModel} from 'chrome://resources/js/cr/ui/list_selection_model.m.js';
import {ListSingleSelectionModel} from 'chrome://resources/js/cr/ui/list_single_selection_model.m.js';
import {queryRequiredElement} from 'chrome://resources/js/util.m.js';
import {DialogType} from '../../../common/js/dialog_type.js';
import {util} from '../../../common/js/util.js';
import {FileListModel} from '../file_list_model.js';
import {ListThumbnailLoader} from '../list_thumbnail_loader.js';
import {FileGrid} from './file_grid.js';
import {FileTable} from './file_table.js';
class TextSearchState {
constructor() {
/** @public {string} */
this.text = '';
/** @public {!Date} */
this.date = new Date();
}
}
/**
* List container for the file table and the grid view.
*/
export class ListContainer {
/**
* @param {!HTMLElement} element Element of the container.
* @param {!FileTable} table File table.
* @param {!FileGrid} grid File grid.
* @param {DialogType} type The type of the main dialog.
*/
constructor(element, table, grid, type) {
/**
* The container element of the file list.
* @type {!HTMLElement}
* @const
*/
this.element = element;
/**
* The file table.
* @type {!FileTable}
* @const
*/
this.table = table;
/**
* The file grid.
* @type {!FileGrid}
* @const
*/
this.grid = grid;
/**
* Current file list.
* @type {ListContainer.ListType}
*/
this.currentListType = ListContainer.ListType.UNINITIALIZED;
/**
* The input element to rename entry.
* @type {!HTMLInputElement}
* @const
*/
this.renameInput =
assertInstanceof(document.createElement('input'), HTMLInputElement);
this.renameInput.className = 'rename entry-name';
/**
* Spinner on file list which is shown while loading.
* @type {!HTMLElement}
* @const
*/
this.spinner =
queryRequiredElement('files-spinner.loading-indicator', element);
/**
* @type {FileListModel}
*/
this.dataModel = null;
/**
* @type {ListThumbnailLoader}
*/
this.listThumbnailLoader = null;
/**
* @type {ListSelectionModel|ListSingleSelectionModel}
*/
this.selectionModel = null;
/**
* Data model which is used as a placefolder in inactive file list.
* @type {FileListModel}
*/
this.emptyDataModel = null;
/**
* Selection model which is used as a placefolder in inactive file list.
* @type {!ListSelectionModel}
* @const
* @private
*/
this.emptySelectionModel_ = new ListSelectionModel();
/**
* @type {!TextSearchState}
* @const
*/
this.textSearchState = new TextSearchState();
/**
* Whtehter to allow or cancel a context menu event.
* @type {boolean}
* @private
*/
this.allowContextMenuByTouch_ = false;
// Overriding the default role 'list' to 'listbox' for better accessibility
// on ChromeOS.
this.table.list.setAttribute('role', 'listbox');
this.table.list.id = 'file-list';
this.grid.setAttribute('role', 'listbox');
this.grid.id = 'file-list';
this.element.addEventListener('keydown', this.onKeyDown_.bind(this));
this.element.addEventListener('keypress', this.onKeyPress_.bind(this));
this.element.addEventListener('mousemove', this.onMouseMove_.bind(this));
this.element.addEventListener(
'contextmenu', this.onContextMenu_.bind(this), /* useCapture */ true);
// Disables context menu by long-tap when at least one file/folder is
// selected, while still enabling two-finger tap.
this.element.addEventListener('touchstart', function(e) {
if (e.touches.length > 1) {
this.allowContextMenuByTouch_ = true;
}
}.bind(this), {passive: true});
this.element.addEventListener('touchend', function(e) {
if (e.touches.length == 0) {
// contextmenu event will be sent right after touchend.
setTimeout(function() {
this.allowContextMenuByTouch_ = false;
}.bind(this));
}
}.bind(this));
this.element.addEventListener('contextmenu', function(e) {
// Block context menu triggered by touch event unless it is right after
// multi-touch, or we are currently selecting a file.
if (this.currentList.selectedItem && !this.allowContextMenuByTouch_ &&
e.sourceCapabilities && e.sourceCapabilities.firesTouchEvents) {
e.stopPropagation();
}
}.bind(this), true);
// Ensure the list and grid are marked ARIA single select for save as.
if (type === DialogType.SELECT_SAVEAS_FILE) {
const list = table.querySelector('#file-list');
list.setAttribute('aria-multiselectable', 'false');
grid.setAttribute('aria-multiselectable', 'false');
}
}
/**
* @return {!FileTable|!FileGrid}
*/
get currentView() {
switch (this.currentListType) {
case ListContainer.ListType.DETAIL:
return this.table;
case ListContainer.ListType.THUMBNAIL:
return this.grid;
}
assertNotReached();
}
/**
* @return {!List}
*/
get currentList() {
switch (this.currentListType) {
case ListContainer.ListType.DETAIL:
return this.table.list;
case ListContainer.ListType.THUMBNAIL:
return this.grid;
}
assertNotReached();
}
/**
* Notifies beginning of batch update to the UI.
*/
startBatchUpdates() {
this.table.startBatchUpdates();
this.grid.startBatchUpdates();
}
/**
* Notifies end of batch update to the UI.
*/
endBatchUpdates() {
this.table.endBatchUpdates();
this.grid.endBatchUpdates();
}
/**
* Sets the current list type.
* @param {ListContainer.ListType} listType New list type.
*/
setCurrentListType(listType) {
assert(this.dataModel);
assert(this.selectionModel);
this.startBatchUpdates();
this.currentListType = listType;
this.element.classList.toggle(
'list-view', listType === ListContainer.ListType.DETAIL);
this.element.classList.toggle(
'thumbnail-view', listType === ListContainer.ListType.THUMBNAIL);
// TODO(dzvorygin): style.display and dataModel setting order shouldn't
// cause any UI bugs. Currently, the only right way is first to set display
// style and only then set dataModel.
// Always sharing the data model between the detail/thumb views confuses
// them. Instead we maintain this bogus data model, and hook it up to the
// view that is not in use.
switch (listType) {
case ListContainer.ListType.DETAIL:
this.table.dataModel = this.dataModel;
this.table.setListThumbnailLoader(this.listThumbnailLoader);
this.table.selectionModel = this.selectionModel;
this.table.hidden = false;
this.grid.hidden = true;
this.grid.selectionModel = this.emptySelectionModel_;
this.grid.setListThumbnailLoader(null);
this.grid.dataModel = this.emptyDataModel;
break;
case ListContainer.ListType.THUMBNAIL:
this.grid.dataModel = this.dataModel;
this.grid.setListThumbnailLoader(this.listThumbnailLoader);
this.grid.selectionModel = this.selectionModel;
this.grid.hidden = false;
this.table.hidden = true;
this.table.selectionModel = this.emptySelectionModel_;
this.table.setListThumbnailLoader(null);
this.table.dataModel = this.emptyDataModel;
break;
default:
assertNotReached();
break;
}
this.endBatchUpdates();
}
/**
* Clears hover highlighting in the list container until next mouse move.
*/
clearHover() {
this.element.classList.add('nohover');
}
/**
* Finds list item element from the ancestor node.
* @param {!HTMLElement} node
* @return {ListItem}
*/
findListItemForNode(node) {
const item = this.currentList.getListItemAncestor(node);
// TODO(serya): list should check that.
return item && this.currentList.isItem(item) ?
assertInstanceof(item, ListItem) :
null;
}
/**
* Focuses the active file list in the list container.
*/
focus() {
switch (this.currentListType) {
case ListContainer.ListType.DETAIL:
this.table.list.focus();
break;
case ListContainer.ListType.THUMBNAIL:
this.grid.focus();
break;
default:
assertNotReached();
break;
}
}
/**
* Check if our context menu has any items that can be activated
* @return {boolean} True if the menu has action item. Otherwise, false.
* @private
*/
contextMenuHasActions_() {
const menu = document.querySelector('#file-context-menu');
const menuItems = menu.querySelectorAll('cr-menu-item, hr');
for (const item of menuItems) {
if (!item.hasAttribute('hidden') && !item.hasAttribute('disabled') &&
(window.getComputedStyle(item).display != 'none')) {
return true;
}
}
return false;
}
/**
* Contextmenu event handler to prevent change of focus on long-tapping the
* header of the file list.
* @param {!Event} e Menu event.
* @private
*/
onContextMenu_(e) {
if (!this.allowContextMenuByTouch_ && e.sourceCapabilities &&
e.sourceCapabilities.firesTouchEvents) {
this.focus();
}
}
/**
* KeyDown event handler for the div#list-container element.
* @param {!Event} event Key event.
* @private
*/
onKeyDown_(event) {
// Ignore keydown handler in the rename input box.
if (event.srcElement.tagName == 'INPUT') {
event.stopImmediatePropagation();
return;
}
switch (event.key) {
case 'Home':
case 'End':
case 'ArrowUp':
case 'ArrowDown':
case 'ArrowLeft':
case 'ArrowRight':
// When navigating with keyboard we hide the distracting mouse hover
// highlighting until the user moves the mouse again.
this.clearHover();
break;
}
}
/**
* KeyPress event handler for the div#list-container element.
* @param {!Event} event Key event.
* @private
*/
onKeyPress_(event) {
// Ignore keypress handler in the rename input box.
if (event.srcElement.tagName == 'INPUT' || event.ctrlKey || event.metaKey ||
event.altKey) {
event.stopImmediatePropagation();
return;
}
const now = new Date();
const character = String.fromCharCode(event.charCode).toLowerCase();
const text =
now - this.textSearchState.date > 1000 ? '' : this.textSearchState.text;
this.textSearchState.text = text + character;
this.textSearchState.date = now;
if (this.textSearchState.text) {
dispatchSimpleEvent(this.element, ListContainer.EventType.TEXT_SEARCH);
}
}
/**
* Mousemove event handler for the div#list-container element.
* @param {Event} event Mouse event.
* @private
*/
onMouseMove_(event) {
// The user grabbed the mouse, restore the hover highlighting.
this.element.classList.remove('nohover');
}
}
/**
* @enum {string}
* @const
*/
ListContainer.EventType = {
TEXT_SEARCH: 'textsearch'
};
/**
* @enum {string}
* @const
*/
ListContainer.ListType = {
UNINITIALIZED: 'uninitialized',
DETAIL: 'detail',
THUMBNAIL: 'thumb'
};
/**
* Keep the order of this in sync with FileManagerListType in
* tools/metrics/histograms/enums.xml.
* The array indices will be recorded in UMA as enum values. The index for each
* root type should never be renumbered nor reused in this array.
*
* @type {Array<ListContainer.ListType>}
* @const
*/
ListContainer.ListTypesForUMA = Object.freeze([
ListContainer.ListType.UNINITIALIZED,
ListContainer.ListType.DETAIL,
ListContainer.ListType.THUMBNAIL,
]);
console.assert(
Object.keys(ListContainer.ListType).length ===
ListContainer.ListTypesForUMA.length,
'Members in ListTypesForUMA do not match those in ListType.');
| scheib/chromium | ui/file_manager/file_manager/foreground/js/ui/list_container.js | JavaScript | bsd-3-clause | 12,504 |
const debug = require('ghost-ignition').debug('api:v2:utils:serializers:output:actions');
const mapper = require('./utils/mapper');
module.exports = {
browse(models, apiConfig, frame) {
debug('browse');
frame.response = {
actions: models.data.map(model => mapper.mapAction(model, frame)),
meta: models.meta
};
}
};
| dingotiles/ghost-for-cloudfoundry | versions/3.3.0/core/server/api/v2/utils/serializers/output/actions.js | JavaScript | mit | 373 |
var fnObj = {};
var ACTIONS = axboot.actionExtend(fnObj, {
PAGE_SEARCH: function (caller, act, data) {
axboot.ajax({
type: "GET",
url: ["samples", "parent"],
data: caller.searchView.getData(),
callback: function (res) {
caller.gridView01.setData(res);
},
options: {
// axboot.ajax 함수에 2번째 인자는 필수가 아닙니다. ajax의 옵션을 전달하고자 할때 사용합니다.
onError: function (err) {
console.log(err);
}
}
});
return false;
},
PAGE_SAVE: function (caller, act, data) {
var saveList = [].concat(caller.gridView01.getData("modified"));
saveList = saveList.concat(caller.gridView01.getData("deleted"));
axboot.ajax({
type: "PUT",
url: ["samples", "parent"],
data: JSON.stringify(saveList),
callback: function (res) {
ACTIONS.dispatch(ACTIONS.PAGE_SEARCH);
axToast.push("저장 되었습니다");
}
});
},
ITEM_CLICK: function (caller, act, data) {
},
ITEM_ADD: function (caller, act, data) {
caller.gridView01.addRow();
},
ITEM_DEL: function (caller, act, data) {
caller.gridView01.delRow("selected");
}
});
// fnObj 기본 함수 스타트와 리사이즈
fnObj.pageStart = function () {
this.pageButtonView.initView();
this.searchView.initView();
this.gridView01.initView();
ACTIONS.dispatch(ACTIONS.PAGE_SEARCH);
};
fnObj.pageResize = function () {
};
fnObj.pageButtonView = axboot.viewExtend({
initView: function () {
axboot.buttonClick(this, "data-page-btn", {
"search": function () {
ACTIONS.dispatch(ACTIONS.PAGE_SEARCH);
},
"save": function () {
ACTIONS.dispatch(ACTIONS.PAGE_SAVE);
},
"excel": function () {
}
});
}
});
//== view 시작
/**
* searchView
*/
fnObj.searchView = axboot.viewExtend(axboot.searchView, {
initView: function () {
this.target = $(document["searchView0"]);
this.target.attr("onsubmit", "return ACTIONS.dispatch(ACTIONS.PAGE_SEARCH);");
this.filter = $("#filter");
},
getData: function () {
return {
pageNumber: this.pageNumber,
pageSize: this.pageSize,
filter: this.filter.val()
}
}
});
/**
* gridView
*/
fnObj.gridView01 = axboot.viewExtend(axboot.gridView, {
initView: function () {
var _this = this;
this.target = axboot.gridBuilder({
showRowSelector: true,
frozenColumnIndex: 0,
multipleSelect: true,
target: $('[data-ax5grid="grid-view-01"]'),
columns: [
{key: "key", label: "KEY", width: 160, align: "left", editor: "text"},
{key: "value", label: "VALUE", width: 350, align: "left", editor: "text"},
{key: "etc1", label: "ETC1", width: 100, align: "center", editor: "text"},
{key: "etc2", label: "ETC2", width: 100, align: "center", editor: "text"},
{key: "etc3", label: "ETC3", width: 100, align: "center", editor: "text"},
{key: "etc4", label: "ETC4", width: 100, align: "center", editor: "text"}
],
body: {
onClick: function () {
this.self.select(this.dindex, {selectedClear: true});
}
}
});
axboot.buttonClick(this, "data-grid-view-01-btn", {
"add": function () {
ACTIONS.dispatch(ACTIONS.ITEM_ADD);
},
"delete": function () {
ACTIONS.dispatch(ACTIONS.ITEM_DEL);
}
});
},
getData: function (_type) {
var list = [];
var _list = this.target.getList(_type);
if (_type == "modified" || _type == "deleted") {
list = ax5.util.filter(_list, function () {
delete this.deleted;
return this.key;
});
} else {
list = _list;
}
return list;
},
addRow: function () {
this.target.addRow({__created__: true}, "last");
}
}); | axboot/ax-boot-framework | ax-boot-initialzr/src/main/resources/templates/webapp/assets/js/view/login.js | JavaScript | mit | 4,420 |
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require_tree . | spring-peepers-2014/Red-Jaguars | dbcoverflow/app/assets/javascripts/application.js | JavaScript | mit | 640 |
jQuery(document).ready(function($){
// Use only one frame for all upload fields
var frame = new Array(), media = wp.media;
// add image field
function dtGetImageHtml( data ) {
var template = wp.media.template('dt-post-gallery-item');
return template(data);
}
function fetch_selection( ids, options ) {
if ( typeof ids == 'undefined' || ids.length <= 0 ) return;
var id_array = ids,
args = {orderby: "post__in", order: "ASC", type: "image", perPage: -1, post__in: id_array},
attachments = wp.media.query( args ),
selection = new wp.media.model.Selection( attachments.models,
{
props: attachments.props.toJSON(),
multiple: true
});
if ( options.state == 'gallery-library' && !isNaN( parseInt(id_array[0],10)) && id_array.length ) {
options.state = 'gallery-edit';
}
return selection;
}
$( 'body' ).on( 'click', '.rwmb-image-advanced-upload-mk2', function( e ) {
e.preventDefault();
var $uploadButton = $( this ),
options = {
frame: 'post',
state: 'gallery-library',
button: 'Add image',
class: 'media-frame rwmb-media-frame rwmb-media-frame-mk2'
},
$imageList = $uploadButton.siblings( '.rwmb-images' ),
maxFileUploads = $imageList.data( 'max_file_uploads' ),
msg = 'You may only upload ' + maxFileUploads + ' file',
frame_key = _.random(0, 999999999999999999),
$images = $imageList.find('.rwmb-delete-file'),
ids = new Array();
if ( 1 == maxFileUploads ) {
options.frame = 'select';
options.state = 'library';
}
if ( maxFileUploads > 1 )
msg += 's';
for (var i=0; i<$images.length; i++ ) {
ids[i] = jQuery($images[i]).attr('data-attachment_id');
}
var prefill = fetch_selection( ids, options );
// If the media frame already exists, reopen it.
if ( frame[frame_key] )
{
frame[frame_key].open();
return;
}
// Create the media frame.
frame[frame_key] = wp.media(
{
frame: options.frame,
state: options.state,
library: { type: 'image' },
button: { text: options.button },
className: options['class'],
selection: prefill
});
// Remove all attached 'select' and 'update' events
frame[frame_key].off( 'update select' );
// Handle selection
frame[frame_key].on( 'update select', function(e) {
// Get selections
var uploaded = $imageList.children().length,
selLength, ids = [];
// for gallery
if(typeof e !== 'undefined') {
selection = e;
// for sigle image
} else {
selection = frame[frame_key].state().get('selection');
}
selection = selection.toJSON();
selLength = selection.length;
for ( var i=0; i<selLength; i++ ) {
ids[i] = selection[i].id;
}
if ( maxFileUploads > 0 && ( uploaded + selLength ) > maxFileUploads ) {
if ( uploaded < maxFileUploads )
selection = selection.slice( 0, maxFileUploads - uploaded );
alert( msg );
}
// Attach attachment to field and get HTML
var data = {
action : 'rwmb_attach_media',
post_id : $( '#post_ID' ).val(),
field_id : $imageList.data( 'field_id' ),
attachments_ids : ids,
_ajax_nonce : $uploadButton.data( 'attach_media_nonce' )
};
$.post( ajaxurl, data, function( r ) {
var r = wpAjax.parseAjaxResponse( r, 'ajax-response' );
if ( r.errors ) {
alert( r.responses[0].errors[0].message );
} else {
var tplData = { editTitle: 'Edit', deleteTitle: 'Delete' },
html = '';
for ( var i=0; i<selLength; i++ ) {
var item = selection[i];
html += dtGetImageHtml( jQuery.extend( tplData, {
imgID : item.id,
imgSrc : item.sizes.thumbnail && item.sizes.thumbnail.url ? item.sizes.thumbnail.url : item.url,
editHref: item.editLink
} ) );
}
$imageList.children().remove();
$imageList.removeClass( 'hidden' ).prepend( html );
}
// Hide files button if reach max file uploads
if ( maxFileUploads && $imageList.children().length >= maxFileUploads ) {
$uploadButton.addClass( 'hidden' );
}
}, 'xml' );
} );
// Finally, open the modal
frame[frame_key].open();
} );
}); | julia26/puppy | wp-content/themes/puppy/inc/extensions/custom-meta-boxes/js/media.js | JavaScript | gpl-2.0 | 4,285 |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'maximize', 'cs', {
maximize: 'Maximalizovat',
minimize: 'Minimalizovat'
} );
| nttuyen/task | task-management/src/main/resources/org/exoplatform/task/management/assets/ckeditorCustom/plugins/maximize/lang/cs.js | JavaScript | lgpl-3.0 | 260 |
// vim: set ts=4 sw=4 tw=99 et:
function testUKeyUObject(a, key1, key2, key3) {
a.a = function () { return this.d; }
a.b = function () { return this.e; }
a.c = function() { return this.f; }
a.d = 20;
a.e = "hi";
a.f = 500;
delete a["b"];
Object.defineProperty(a, "b", { get: function () { return function () { return this.e; } } });
assertEq(a[key1](), 20);
assertEq(a[key2](), "hi");
assertEq(a[key3](), 500);
}
for (var i = 0; i < 5; i++)
testUKeyUObject({}, "a", "b", "c");
| glycerine/vj | src/js-1.8.5/js/src/jit-test/tests/jaeger/testPropCallElem2.js | JavaScript | apache-2.0 | 529 |
define({ root:
//begin v1.x content
{
"months-format-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"
],
"quarters-standAlone-narrow": [
"1",
"2",
"3",
"4"
],
"dateFormatItem-yQQQ": "y QQQ",
"dateFormatItem-yMEd": "EEE, y-M-d",
"dateFormatItem-MMMEd": "E MMM d",
"eraNarrow": [
"AH"
],
"dateTimeFormats-appendItem-Day-Of-Week": "{0} {1}",
"dateFormat-long": "y MMMM d",
"months-format-wide": [
"Muharram",
"Safar",
"Rabiʻ I",
"Rabiʻ II",
"Jumada I",
"Jumada II",
"Rajab",
"Shaʻban",
"Ramadan",
"Shawwal",
"Dhuʻl-Qiʻdah",
"Dhuʻl-Hijjah"
],
"dateTimeFormat-medium": "{1} {0}",
"dateFormatItem-EEEd": "d EEE",
"dayPeriods-format-wide-pm": "PM",
"dateFormat-full": "EEEE, y MMMM dd",
"dateFormatItem-Md": "M-d",
"dayPeriods-format-abbr-am": "AM",
"dateTimeFormats-appendItem-Second": "{0} ({2}: {1})",
"dateFormatItem-yM": "y-M",
"months-standAlone-wide": [
"Muharram",
"Safar",
"Rabiʻ I",
"Rabiʻ II",
"Jumada I",
"Jumada II",
"Rajab",
"Shaʻban",
"Ramadan",
"Shawwal",
"Dhuʻl-Qiʻdah",
"Dhuʻl-Hijjah"
],
"timeFormat-short": "HH:mm",
"quarters-format-wide": [
"Q1",
"Q2",
"Q3",
"Q4"
],
"timeFormat-long": "HH:mm:ss z",
"dateFormatItem-yMMM": "y MMM",
"dateFormatItem-yQ": "y Q",
"dateTimeFormats-appendItem-Era": "{0} {1}",
"months-format-abbr": [
"Muh.",
"Saf.",
"Rab. I",
"Rab. II",
"Jum. I",
"Jum. II",
"Raj.",
"Sha.",
"Ram.",
"Shaw.",
"Dhuʻl-Q.",
"Dhuʻl-H."
],
"timeFormat-full": "HH:mm:ss zzzz",
"dateTimeFormats-appendItem-Week": "{0} ({2}: {1})",
"dateFormatItem-H": "HH",
"months-standAlone-abbr": [
"Muh.",
"Saf.",
"Rab. I",
"Rab. II",
"Jum. I",
"Jum. II",
"Raj.",
"Sha.",
"Ram.",
"Shaw.",
"Dhuʻl-Q.",
"Dhuʻl-H."
],
"quarters-format-abbr": [
"Q1",
"Q2",
"Q3",
"Q4"
],
"quarters-standAlone-wide": [
"Q1",
"Q2",
"Q3",
"Q4"
],
"dateFormatItem-M": "L",
"days-standAlone-wide": [
"1",
"2",
"3",
"4",
"5",
"6",
"7"
],
"timeFormat-medium": "HH:mm:ss",
"dateFormatItem-Hm": "HH:mm",
"quarters-standAlone-abbr": [
"Q1",
"Q2",
"Q3",
"Q4"
],
"eraAbbr": [
"AH"
],
"days-standAlone-abbr": [
"1",
"2",
"3",
"4",
"5",
"6",
"7"
],
"dateFormatItem-d": "d",
"dateFormatItem-ms": "mm:ss",
"quarters-format-narrow": [
"1",
"2",
"3",
"4"
],
"dateFormatItem-h": "h a",
"dateTimeFormat-long": "{1} {0}",
"dayPeriods-format-narrow-am": "AM",
"dateFormatItem-MMMd": "MMM d",
"dateFormatItem-MEd": "E, M-d",
"dateTimeFormat-full": "{1} {0}",
"days-format-wide": [
"1",
"2",
"3",
"4",
"5",
"6",
"7"
],
"dateTimeFormats-appendItem-Day": "{0} ({2}: {1})",
"dateFormatItem-y": "y",
"months-standAlone-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"
],
"dateFormatItem-hm": "h:mm a",
"dateTimeFormats-appendItem-Year": "{0} {1}",
"dateTimeFormats-appendItem-Hour": "{0} ({2}: {1})",
"dayPeriods-format-abbr-pm": "PM",
"days-format-abbr": [
"1",
"2",
"3",
"4",
"5",
"6",
"7"
],
"eraNames": [
"AH"
],
"days-format-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7"
],
"days-standAlone-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7"
],
"dateFormatItem-MMM": "LLL",
"dateTimeFormats-appendItem-Quarter": "{0} ({2}: {1})",
"dayPeriods-format-wide-am": "AM",
"dateTimeFormats-appendItem-Month": "{0} ({2}: {1})",
"dateTimeFormats-appendItem-Minute": "{0} ({2}: {1})",
"dateFormat-short": "yyyy-MM-dd",
"dateFormatItem-yMMMEd": "EEE, y MMM d",
"dateTimeFormats-appendItem-Timezone": "{0} {1}",
"dateFormat-medium": "y MMM d",
"dayPeriods-format-narrow-pm": "PM",
"dateTimeFormat-short": "{1} {0}",
"dateFormatItem-Hms": "HH:mm:ss",
"dateFormatItem-hms": "h:mm:ss a"
}
//end v1.x content
,
"ar": true,
"da": true,
"de": true,
"en": true,
"en-gb": true,
"es": true,
"fi": true,
"fr": true,
"he": true,
"hu": true,
"it": true,
"nb": true,
"nl": true,
"pl": true,
"pt": true,
"pt-pt": true,
"ru": true,
"sv": true,
"th": true,
"tr": true,
"zh": true,
"zh-hant": true
}); | sulistionoadi/belajar-springmvc-dojo | training-web/src/main/webapp/js/dojotoolkit/dojo/cldr/nls/islamic.js | JavaScript | apache-2.0 | 4,186 |
// DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py.
// OffscreenCanvas test in a worker:2d.composite.solid.xor
// Description:
// Note:
importScripts("/resources/testharness.js");
importScripts("/html/canvas/resources/canvas-tests.js");
var t = async_test("");
var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
throw reason;
});
t.step(function() {
var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');
ctx.fillStyle = 'rgba(0, 255, 255, 1.0)';
ctx.fillRect(0, 0, 100, 50);
ctx.globalCompositeOperation = 'xor';
ctx.fillStyle = 'rgba(255, 255, 0, 1.0)';
ctx.fillRect(0, 0, 100, 50);
_assertPixelApprox(offscreenCanvas, 50,25, 0,0,0,0, "50,25", "0,0,0,0", 5);
t.done();
});
done();
| scheib/chromium | third_party/blink/web_tests/external/wpt/html/canvas/offscreen/compositing/2d.composite.solid.xor.worker.js | JavaScript | bsd-3-clause | 783 |
import React, {Component, PropTypes} from 'react'
import style from './style.js'
import ErrorStackParser from 'error-stack-parser'
import assign from 'object-assign'
import {isFilenameAbsolute, makeUrl, makeLinkText} from './lib'
export default class RedBox extends Component {
static propTypes = {
error: PropTypes.instanceOf(Error).isRequired,
filename: PropTypes.string,
editorScheme: PropTypes.string,
useLines: PropTypes.bool,
useColumns: PropTypes.bool
}
static displayName = 'RedBox'
static defaultProps = {
useLines: true,
useColumns: true
}
render () {
const {error, filename, editorScheme, useLines, useColumns} = this.props
const {redbox, message, stack, frame, file, linkToFile} = assign({}, style, this.props.style)
const frames = ErrorStackParser.parse(error).map((f, index) => {
let text
let url
if (index === 0 && filename && !isFilenameAbsolute(f.fileName)) {
url = makeUrl(filename, editorScheme)
text = makeLinkText(filename)
} else {
let lines = useLines ? f.lineNumber : null
let columns = useColumns ? f.columnNumber : null
url = makeUrl(f.fileName, editorScheme, lines, columns)
text = makeLinkText(f.fileName, lines, columns)
}
return (
<div style={frame} key={index}>
<div>{f.functionName}</div>
<div style={file}>
<a href={url} style={linkToFile}>{text}</a>
</div>
</div>
)
})
return (
<div style={redbox}>
<div style={message}>{error.name}: {error.message}</div>
<div style={stack}>{frames}</div>
</div>
)
}
}
| PixnBits/redbox-react | src/index.js | JavaScript | mit | 1,683 |
/**
* Themes: Velonic Admin theme
*
**/
! function($) {
"use strict";
/**
Sidebar Module
*/
var SideBar = function() {
this.$body = $("body"),
this.$sideBar = $('aside.left-panel'),
this.$navbarToggle = $(".navbar-toggle"),
this.$navbarItem = $("aside.left-panel nav.navigation > ul > li:has(ul) > a")
};
//initilizing
SideBar.prototype.init = function() {
//on toggle side menu bar
var $this = this;
$(document).on('click', '.navbar-toggle', function () {
$this.$sideBar.toggleClass('collapsed');
});
//on menu item clicking
this.$navbarItem.click(function () {
if ($this.$sideBar.hasClass('collapsed') == false || $(window).width() < 768) {
$("aside.left-panel nav.navigation > ul > li > ul").slideUp(300);
$("aside.left-panel nav.navigation > ul > li").removeClass('active');
if (!$(this).next().is(":visible")) {
$(this).next().slideToggle(300, function () {
$("aside.left-panel:not(.collapsed)").getNiceScroll().resize();
});
$(this).closest('li').addClass('active');
}
return false;
}
});
//adding nicescroll to sidebar
if ($.isFunction($.fn.niceScroll)) {
$("aside.left-panel:not(.collapsed)").niceScroll({
cursorcolor: '#8e909a',
cursorborder: '0px solid #fff',
cursoropacitymax: '0.5',
cursorborderradius: '0px'
});
}
},
//exposing the sidebar module
$.SideBar = new SideBar, $.SideBar.Constructor = SideBar
}(window.jQuery),
//portlets
function($) {
"use strict";
/**
Portlet Widget
*/
var Portlet = function() {
this.$body = $("body"),
this.$portletIdentifier = ".portlet",
this.$portletCloser = '.portlet a[data-toggle="remove"]',
this.$portletRefresher = '.portlet a[data-toggle="reload"]'
};
//on init
Portlet.prototype.init = function() {
// Panel closest
var $this = this;
$(document).on("click",this.$portletCloser, function (ev) {
ev.preventDefault();
var $portlet = $(this).closest($this.$portletIdentifier);
var $portlet_parent = $portlet.parent();
$portlet.remove();
if ($portlet_parent.children().length == 0) {
$portlet_parent.remove();
}
});
// Panel Reload
$(document).on("click",this.$portletRefresher, function (ev) {
ev.preventDefault();
var $portlet = $(this).closest($this.$portletIdentifier);
// This is just a simulation, nothing is going to be reloaded
$portlet.append('<div class="panel-disabled"><div class="loader-1"></div></div>');
var $pd = $portlet.find('.panel-disabled');
setTimeout(function () {
$pd.fadeOut('fast', function () {
$pd.remove();
});
}, 500 + 300 * (Math.random() * 5));
});
},
//
$.Portlet = new Portlet, $.Portlet.Constructor = Portlet
}(window.jQuery),
//main app module
function($) {
"use strict";
var VelonicApp = function() {
this.VERSION = "1.0.0",
this.AUTHOR = "Coderthemes",
this.SUPPORT = "coderthemes@gmail.com",
this.pageScrollElement = "html, body",
this.$body = $("body")
};
//initializing tooltip
VelonicApp.prototype.initTooltipPlugin = function() {
$.fn.tooltip && $('[data-toggle="tooltip"]').tooltip()
},
//initializing popover
VelonicApp.prototype.initPopoverPlugin = function() {
$.fn.popover && $('[data-toggle="popover"]').popover()
},
//initializing nicescroll
VelonicApp.prototype.initNiceScrollPlugin = function() {
//You can change the color of scroll bar here
$.fn.niceScroll && $(".nicescroll").niceScroll({ cursorcolor: '#9d9ea5', cursorborderradius: '0px'});
},
//initializing knob
VelonicApp.prototype.initKnob = function() {
if ($(".knob").length > 0) {
$(".knob").knob();
}
},
//initilizing
VelonicApp.prototype.init = function() {
this.initTooltipPlugin(),
this.initPopoverPlugin(),
this.initNiceScrollPlugin(),
this.initKnob(),
//creating side bar
$.SideBar.init(),
//creating portles
$.Portlet.init();
},
$.VelonicApp = new VelonicApp, $.VelonicApp.Constructor = VelonicApp
}(window.jQuery),
//initializing main application module
function($) {
"use strict";
$.VelonicApp.init()
}(window.jQuery);
/* ==============================================
7.WOW plugin triggers animate.css on scroll
=============================================== */
var wow = new WOW(
{
boxClass: 'wow', // animated element css class (default is wow)
animateClass: 'animated', // animation css class (default is animated)
offset: 50, // distance to the element when triggering the animation (default is 0)
mobile: false // trigger animations on mobile devices (true is default)
}
);
wow.init();
| proyectobufete/ProyectoBufete | web/asst/js/jquery.app.js | JavaScript | mit | 5,422 |
"use strict";
var Client = require("./../lib/index");
var testAuth = require("./../testAuth.json");
var github = new Client({
debug: true
});
github.authenticate({
type: "oauth",
token: testAuth["token"]
});
github.repos.createFile({
owner: "kaizensoze",
repo: "misc-scripts",
path: "blah.txt",
message: "blah blah",
content: "YmxlZXAgYmxvb3A="
}, function(err, res) {
console.log(err, res);
});
| juanfrank2/dotfiles | vscode.symlink/extensions/Shan.code-settings-sync-2.8.2/node_modules/github/examples/createFile.js | JavaScript | mit | 436 |
define("ace/snippets/sass",["require","exports","module"], function(require, exports, module) {
"use strict";
exports.snippetText = "";
exports.scope = "sass";
});
(function() {
window.require(["ace/snippets/sass"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
| NPellet/jsGraph | web/site/js/ace-builds/src/snippets/sass.js | JavaScript | mit | 497 |
/*
* Keeps track of items being created or deleted in a list
* - emits events about changes when .poll is called
* - events are: delete, create
*
* Usage:
*
* var tracker = changeTracker.create(updateItems, items);
*
* - updateItems is a function to fetch the current state of the items you want
* to watch. It should return a list of objects with a unique 'name'.
*
* - items is the current list, as given by running updateItems now
*
* tracker.on("create", createListener);
* tracker.on("delete", deleteListener);
* tracker.poll();
*
* When calling poll, updateItems is called, the result is compared to the old
* list, and events are emitted.
*
*/
var EventEmitter = require("events").EventEmitter;
var when = require("when");
function create(updateItems, items) {
var instance = Object.create(this);
instance.updateItems = updateItems;
instance.items = items;
return instance;
}
function eq(item1) {
return function (item2) { return item1.name === item2.name; };
}
function notIn(coll) {
return function (item) { return !coll.some(eq(item)); };
}
function poll() {
var d = when.defer();
this.updateItems(function (err, after) {
if (err) { return d.reject(err); }
var before = this.items;
var created = after.filter(notIn(before));
var deleted = before.filter(notIn(after));
created.forEach(this.emit.bind(this, "create"));
deleted.forEach(this.emit.bind(this, "delete"));
this.items = after;
d.resolve();
}.bind(this));
return d.promise;
}
module.exports = new EventEmitter();
module.exports.create = create;
module.exports.poll = poll;
| zenners/angular-contacts | node_modules/firebase/node_modules/faye-websocket/node_modules/websocket-driver/node_modules/websocket-extensions/node_modules/jstest/node_modules/karma/node_modules/sinon/node_modules/samsam/node_modules/buster/node_modules_old/buster-autotest/node_modules/fs-watch-tree/lib/change-tracker.js | JavaScript | mit | 1,697 |
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.dom.comment} class, which represents
* a DOM comment node.
*/
/**
* Represents a DOM comment node.
*
* var nativeNode = document.createComment( 'Example' );
* var comment = new CKEDITOR.dom.comment( nativeNode );
*
* var comment = new CKEDITOR.dom.comment( 'Example' );
*
* @class
* @extends CKEDITOR.dom.node
* @constructor Creates a comment class instance.
* @param {Object/String} comment A native DOM comment node or a string containing
* the text to use to create a new comment node.
* @param {CKEDITOR.dom.document} [ownerDocument] The document that will contain
* the node in case of new node creation. Defaults to the current document.
*/
CKEDITOR.dom.comment = function( comment, ownerDocument ) {
if ( typeof comment == 'string' )
comment = ( ownerDocument ? ownerDocument.$ : document ).createComment( comment );
CKEDITOR.dom.domObject.call( this, comment );
};
CKEDITOR.dom.comment.prototype = new CKEDITOR.dom.node();
CKEDITOR.tools.extend( CKEDITOR.dom.comment.prototype, {
/**
* The node type. This is a constant value set to {@link CKEDITOR#NODE_COMMENT}.
*
* @readonly
* @property {Number} [=CKEDITOR.NODE_COMMENT]
*/
type: CKEDITOR.NODE_COMMENT,
/**
* Gets the outer HTML of this comment.
*
* @returns {String} The HTML `<!-- comment value -->`.
*/
getOuterHtml: function() {
return '<!--' + this.$.nodeValue + '-->';
}
} );
| SeeyaSia/www | web/libraries/ckeditor/core/dom/comment.js | JavaScript | gpl-2.0 | 1,608 |
/*
* jQuery mmenu {ADDON} add-on
* mmenu.frebsite.nl
*
* Copyright (c) Fred Heusschen
*/
(function( $ ) {
var _PLUGIN_ = 'mmenu',
_ADDON_ = '{ADDON}';
$[ _PLUGIN_ ].addons[ _ADDON_ ] = {
// setup: fired once per menu
setup: function()
{
var that = this,
opts = this.opts[ _ADDON_ ],
conf = this.conf[ _ADDON_ ];
glbl = $[ _PLUGIN_ ].glbl;
// Extend shorthand options
if ( typeof opts != 'object' )
{
opts = {};
}
opts = this.opts[ _ADDON_ ] = $.extend( true, {}, $[ _PLUGIN_ ].defaults[ _ADDON_ ], opts );
// Extend shorthand configuration
if ( typeof conf != 'object' )
{
conf = {};
}
conf = this.conf[ _ADDON_ ] = $.extend( true, {}, $[ _PLUGIN_ ].configuration[ _ADDON_ ], conf );
// Add methods to api
// this._api = $.merge( this._api, [ 'fn1', 'fn2' ] );
// Bind functions to update
// this.bind( 'update', function() {} );
// this.bind( 'initPanels', function() {} );
// this.bind( 'initPage', function() {} );
},
// add: fired once per page load
add: function()
{
_c = $[ _PLUGIN_ ]._c;
_d = $[ _PLUGIN_ ]._d;
_e = $[ _PLUGIN_ ]._e;
// ...Add classnames, data and events
},
// clickAnchor: prevents default behavior when clicking an anchor
clickAnchor: function( $a, inMenu )
{
// if ( $a.is( '.CLASSNAME' ) )
// {
// return true;
// }
// return false;
}
};
// Default options and configuration
$[ _PLUGIN_ ].defaults[ _ADDON_ ] = {
// ...
};
$[ _PLUGIN_ ].configuration.classNames[ _ADDON_ ] = {
// ...
};
var _c, _d, _e, glbl;
})( jQuery ); | 474846718/taxi_website | taxi/jQuery.mmenu-master/src/jquery,mmenu.addon-template.js | JavaScript | gpl-3.0 | 1,605 |
/* -*- 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 = '15.9.5.30-1.js';
/**
File Name: 15.9.5.30-1.js
ECMA Section: 15.9.5.30 Date.prototype.setHours(hour [, min [, sec [, ms ]]] )
Description:
If min is not specified, this behaves as if min were specified with the
value getMinutes( ). If sec is not specified, this behaves as if sec were
specified with the value getSeconds ( ). If ms is not specified, this
behaves as if ms were specified with the value getMilliseconds( ).
1. Let t be the result of LocalTime(this time value).
2. Call ToNumber(hour).
3. If min is not specified, compute MinFromTime(t); otherwise, call
ToNumber(min).
4. If sec is not specified, compute SecFromTime(t); otherwise, call
ToNumber(sec).
5. If ms is not specified, compute msFromTime(t); otherwise, call
ToNumber(ms).
6. Compute MakeTime(Result(2), Result(3), Result(4), Result(5)).
7. Compute UTC(MakeDate(Day(t), Result(6))).
8. Set the [[Value]] property of the this value to TimeClip(Result(7)).
9. Return the value of the [[Value]] property of the this value.
Author: christine@netscape.com
Date: 12 november 1997
*/
var SECTION = "15.9.5.30-1";
var VERSION = "ECMA_1";
startTest();
writeHeaderToLog( SECTION + " Date.prototype.setHours( hour [, min, sec, ms] )");
addNewTestCase( 0,0,0,0,void 0,
"TDATE = new Date(0);(TDATE).setHours(0);TDATE" );
addNewTestCase( 28800000, 23, 59, 999,void 0,
"TDATE = new Date(28800000);(TDATE).setHours(23,59,999);TDATE" );
addNewTestCase( 28800000, 999, 999, void 0, void 0,
"TDATE = new Date(28800000);(TDATE).setHours(999,999);TDATE" );
addNewTestCase( 28800000,999,0, void 0, void 0,
"TDATE = new Date(28800000);(TDATE).setHours(999);TDATE" );
addNewTestCase( 28800000,-8, void 0, void 0, void 0,
"TDATE = new Date(28800000);(TDATE).setHours(-8);TDATE" );
addNewTestCase( 946684800000,8760, void 0, void 0, void 0,
"TDATE = new Date(946684800000);(TDATE).setHours(8760);TDATE" );
addNewTestCase( TIME_2000 - msPerDay, 23, 59, 59, 999,
"d = new Date( " + (TIME_2000-msPerDay) +"); d.setHours(23,59,59,999)" );
addNewTestCase( TIME_2000 - msPerDay, 23, 59, 59, 1000,
"d = new Date( " + (TIME_2000-msPerDay) +"); d.setHours(23,59,59,1000)" );
test();
function addNewTestCase( time, hours, min, sec, ms, DateString) {
var UTCDate = UTCDateFromTime( SetHours( time, hours, min, sec, ms ));
var LocalDate = LocalDateFromTime( SetHours( time, hours, min, sec, ms ));
var DateCase = new Date( time );
if ( min == void 0 ) {
DateCase.setHours( hours );
} else {
if ( sec == void 0 ) {
DateCase.setHours( hours, min );
} else {
if ( ms == void 0 ) {
DateCase.setHours( hours, min, sec );
} else {
DateCase.setHours( hours, min, sec, ms );
}
}
}
new TestCase( SECTION, DateString+".getTime()", UTCDate.value, DateCase.getTime() );
new TestCase( SECTION, DateString+".valueOf()", UTCDate.value, DateCase.valueOf() );
new TestCase( SECTION, DateString+".getUTCFullYear()", UTCDate.year, DateCase.getUTCFullYear() );
new TestCase( SECTION, DateString+".getUTCMonth()", UTCDate.month, DateCase.getUTCMonth() );
new TestCase( SECTION, DateString+".getUTCDate()", UTCDate.date, DateCase.getUTCDate() );
new TestCase( SECTION, DateString+".getUTCDay()", UTCDate.day, DateCase.getUTCDay() );
new TestCase( SECTION, DateString+".getUTCHours()", UTCDate.hours, DateCase.getUTCHours() );
new TestCase( SECTION, DateString+".getUTCMinutes()", UTCDate.minutes,DateCase.getUTCMinutes() );
new TestCase( SECTION, DateString+".getUTCSeconds()", UTCDate.seconds,DateCase.getUTCSeconds() );
new TestCase( SECTION, DateString+".getUTCMilliseconds()", UTCDate.ms, DateCase.getUTCMilliseconds() );
new TestCase( SECTION, DateString+".getFullYear()", LocalDate.year, DateCase.getFullYear() );
new TestCase( SECTION, DateString+".getMonth()", LocalDate.month, DateCase.getMonth() );
new TestCase( SECTION, DateString+".getDate()", LocalDate.date, DateCase.getDate() );
new TestCase( SECTION, DateString+".getDay()", LocalDate.day, DateCase.getDay() );
new TestCase( SECTION, DateString+".getHours()", LocalDate.hours, DateCase.getHours() );
new TestCase( SECTION, DateString+".getMinutes()", LocalDate.minutes, DateCase.getMinutes() );
new TestCase( SECTION, DateString+".getSeconds()", LocalDate.seconds, DateCase.getSeconds() );
new TestCase( SECTION, DateString+".getMilliseconds()", LocalDate.ms, DateCase.getMilliseconds() );
DateCase.toString = Object.prototype.toString;
new TestCase( SECTION,
DateString+".toString=Object.prototype.toString;"+DateString+".toString()",
"[object Date]",
DateCase.toString() );
}
function MyDate() {
this.year = 0;
this.month = 0;
this.date = 0;
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
this.ms = 0;
}
function LocalDateFromTime(t) {
t = LocalTime(t);
return ( MyDateFromTime(t) );
}
function UTCDateFromTime(t) {
return ( MyDateFromTime(t) );
}
function MyDateFromTime( t ) {
var d = new MyDate();
d.year = YearFromTime(t);
d.month = MonthFromTime(t);
d.date = DateFromTime(t);
d.hours = HourFromTime(t);
d.minutes = MinFromTime(t);
d.seconds = SecFromTime(t);
d.ms = msFromTime(t);
d.day = WeekDay( t );
d.time = MakeTime( d.hours, d.minutes, d.seconds, d.ms );
d.value = TimeClip( MakeDate( MakeDay( d.year, d.month, d.date ), d.time ) );
return (d);
}
function SetHours( t, hour, min, sec, ms ) {
var TIME = LocalTime(t);
var HOUR = Number(hour);
var MIN = ( min == void 0) ? MinFromTime(TIME) : Number(min);
var SEC = ( sec == void 0) ? SecFromTime(TIME) : Number(sec);
var MS = ( ms == void 0 ) ? msFromTime(TIME) : Number(ms);
var RESULT6 = MakeTime( HOUR,
MIN,
SEC,
MS );
var UTC_TIME = UTC( MakeDate(Day(TIME), RESULT6) );
return ( TimeClip(UTC_TIME) );
}
| sam/htmlunit-rhino-fork | testsrc/tests/ecma/Date/15.9.5.30-1.js | JavaScript | mpl-2.0 | 6,427 |
/* -*- 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/. */
var gTestfile = 'regress-474771.js';
//-----------------------------------------------------------------------------
var BUGNUMBER = 474771;
var summary = 'TM: do not halt execution with gczeal, prototype mangling, for..in';
var actual = '';
var expect = '';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
expect = 'PASS';
jit(true);
if (typeof gczeal != 'undefined')
{
gczeal(2);
}
Object.prototype.q = 3;
for each (let x in [6, 7]) { } print(actual = "PASS");
jit(false);
delete Object.prototype.q;
reportCompare(expect, actual, summary);
exitFunc ('test');
}
| ashwinrayaprolu1984/rhino | testsrc/tests/js1_7/regress/regress-474771.js | JavaScript | mpl-2.0 | 1,099 |
/* -*- 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/. */
var gTestfile = 'regress-373827-01.js';
//-----------------------------------------------------------------------------
var BUGNUMBER = 373827;
var summary = 'Do not assert: OBJ_GET_CLASS(cx, obj)->flags & JSCLASS_HAS_PRIVATE';
var actual = '';
var expect = '';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
let ([] = [{x: function(){}}]) { };
reportCompare(expect, actual, summary);
exitFunc ('test');
}
| tuchida/rhino | testsrc/tests/js1_7/regress/regress-373827-01.js | JavaScript | mpl-2.0 | 920 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* Empty string variable has a length property
*
* @path ch08/8.4/S8.4_A4.js
* @description Try read length property of empty string variable
*/
var __str = "";
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (__str.length !== 0) {
$ERROR('#1: var __str = ""; __str.length === 0. Actual: ' + (__str));
}
//
//////////////////////////////////////////////////////////////////////////////
| hippich/typescript | tests/Fidelity/test262/suite/ch08/8.4/S8.4_A4.js | JavaScript | apache-2.0 | 575 |
/*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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.
*/
define(['webida-lib/app-config'], function (appConfig) {
'use strict';
var template =
' <style> ' +
' #FileSelectionTreeInWidget<%id-postfix%> ' +
' { ' +
' width: 100%; ' +
' height: 100%; ' +
' } ' +
' .selDirSelectedExpanded' +
' { ' +
' background-image: url("' + appConfig.baseUrl + '/common/src/webida/' +
'widgets/dialogs/file-selection/icons/select_state_folderopen.png");' +
' background-position: 0, 0;' +
' background-repeat: no-repeat;' +
' width: 16px;' +
' height: 16px;' +
' }' +
' .selDirDeselectedExpanded' +
' { ' +
' background-image: url("' + appConfig.baseUrl + '/common/src/webida/' +
'widgets/dialogs/file-selection/icons/select_state_folderopen.png");' +
' background-position: -32px, 0;' +
' background-repeat: no-repeat;' +
' width: 16px;' +
' height: 16px;' +
' }' +
' .selDirPartialExpanded' +
' { ' +
' background-image: url("' + appConfig.baseUrl + '/common/src/webida/' +
'widgets/dialogs/file-selection/icons/select_state_folderopen.png");' +
' background-position: -16px, 0;' +
' background-repeat: no-repeat;' +
' width: 16px;' +
' height: 16px;' +
' }' +
' .selDirSelectedCollapsed' +
' { ' +
' background-image: url("' + appConfig.baseUrl + '/common/src/webida/' +
'widgets/dialogs/file-selection/icons/select_state_folder.png");' +
' background-position: 0, 0;' +
' background-repeat: no-repeat;' +
' width: 16px;' +
' height: 16px;' +
' }' +
' .selDirDeselectedCollapsed' +
' { ' +
' background-image: url("' + appConfig.baseUrl + '/common/src/webida/' +
'widgets/dialogs/file-selection/icons/select_state_folder.png");' +
' background-position: -32px, 0;' +
' background-repeat: no-repeat;' +
' width: 16px;' +
' height: 16px;' +
' }' +
' .selDirPartialCollapsed' +
' { ' +
' background-image: url("' + appConfig.baseUrl + '/common/src/webida/' +
'widgets/dialogs/file-selection/icons/select_state_folder.png");' +
' background-position: -16px, 0;' +
' background-repeat: no-repeat;' +
' width: 16px;' +
' height: 16px;' +
' }' +
' .selFileSelected' +
' { ' +
' background-image: url("' + appConfig.baseUrl + '/common/src/webida/' +
'widgets/dialogs/file-selection/icons/select_state_file.png");' +
' background-position: 0, 0;' +
' background-repeat: no-repeat;' +
' width: 16px;' +
' height: 16px;' +
' }' +
' .selFileDeselected' +
' { ' +
' background-image: url("' + appConfig.baseUrl + '/common/src/webida/' +
'widgets/dialogs/file-selection/icons/select_state_file.png");' +
' background-position: -16px, 0;' +
' background-repeat: no-repeat;' +
' width: 16px;' +
' height: 16px;' +
' }' +
' .fileIcon' +
' { background: url("' + appConfig.baseUrl + '/common/src/webida/' +
'widgets/dialogs/file-selection/icons/fileIcon.png") no-repeat; width: 16px; height: 16px; }' +
' </style> ' +
' <div class="dijitDialogPaneContentArea">' +
' <div id="FileSelectionTreeInWidget<%id-postfix%>"> </div>' +
' </div>';
return template;
});
| leechwin/webida-client | common/src/webida/widgets/fs-selector/dlg-content-template.js | JavaScript | apache-2.0 | 4,862 |
import ga from 'modules/googleAnalyticsAdapter.js';
var assert = require('assert');
describe('Ga', function () {
describe('enableAnalytics', function () {
var cpmDistribution = function(cpm) {
return cpm <= 1 ? '<= 1$' : '> 1$';
}
var config = { options: { trackerName: 'foo', enableDistribution: true, cpmDistribution: cpmDistribution } };
// enableAnalytics can only be called once
ga.enableAnalytics(config);
it('should accept a tracker name option and output prefixed send string', function () {
var output = ga.getTrackerSend();
assert.equal(output, 'foo.send');
});
it('should use the custom cpm distribution', function() {
assert.equal(ga.getCpmDistribution(0.5), '<= 1$');
assert.equal(ga.getCpmDistribution(1), '<= 1$');
assert.equal(ga.getCpmDistribution(2), '> 1$');
assert.equal(ga.getCpmDistribution(5.23), '> 1$');
});
});
});
| varashellov/Prebid.js | test/spec/modules/googleAnalyticsAdapter_spec.js | JavaScript | apache-2.0 | 928 |
// Run only by vendor node.
// In an ideal world this would be run in the same process/context of
// atom-shell but there are many hurdles atm, see
// https://github.com/atom/atom-shell/issues/533
// increase the libuv threadpool size to 1.5x the number of logical CPUs.
process.env.UV_THREADPOOL_SIZE = Math.ceil(Math.max(4, require('os').cpus().length * 1.5));
process.title = 'mapbox-studio';
if (process.platform === 'win32') {
// HOME is undefined on windows
process.env.HOME = process.env.USERPROFILE;
// NULL out PATH to avoid potential conflicting dlls
process.env.PATH = '';
}
var tm = require('./lib/tm');
var path = require('path');
var getport = require('getport');
var package_json = require('./package.json');
var server;
var config = require('minimist')(process.argv.slice(2));
config.shell = config.shell || false;
config.port = config.port || undefined;
config.test = config.test || false;
config.cwd = path.resolve(config.cwd || process.env.HOME);
var logger = require('fastlog')('', 'debug', '<${timestamp}>');
var usage = function usage() {
var str = [
''
, ' Usage: mbstudio [options]'
, ''
, ' where [options] is any of:'
, ' --version - Returns running version then exits'
, ' --port - Port to run on (default: ' + config.port + ')'
, ' --cwd - Working directory to run within (default: ' + config.cwd + ')'
// TODO - are these used?
, ' --shell - (default: ' + config.shell + ')'
, ' --test - (default: ' + config.test + ')'
, ''
, 'mbstudio@' + package_json.version + ' ' + path.resolve(__dirname, '..')
, 'node@' + process.versions.node
].join('\n')
return str
}
if (config.version) {
logger.debug(package_json.version);
process.exit(0);
}
if (config.help || config.h) {
logger.debug(usage());
process.exit(0);
}
if (!config.port) {
getport(3000, 3999, configure);
} else {
configure();
}
function configure(err, port) {
if (err) throw err;
config.port = config.port || port;
tm.config(config, listen);
}
function listen(err) {
if (err) throw err;
server = require('./lib/server');
if (config.shell) {
server.listen(tm.config().port, '127.0.0.1', finish);
} else {
server.listen(tm.config().port, finish);
}
}
function finish(err) {
if (err) throw err;
server.emit('ready');
logger.debug('Mapbox Studio @ http://localhost:'+tm.config().port+'/');
}
| tizzybec/mapbox-studio | index-server.js | JavaScript | bsd-3-clause | 2,464 |
export default {
plurals: [[/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status|bonus)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes']],
singular: [[/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status|bonus)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1']],
irregularPairs: [['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies']],
uncountable: ['equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police']
}; | DanielJRaine/employee-forms-auth | tmp/broccoli_persistent_filterbabel__babel_ember_inflector-output_path-TKPSAOYg.tmp/modules/ember-inflector/lib/system/inflections.js | JavaScript | mit | 1,613 |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function () {};
exports.default = foo;
exports.default = 42;
exports.default = {};
exports.default = [];
exports.default = foo;
exports.default = class {};
function foo() {}
class Foo {}
exports.default = Foo;
exports.default = foo;
exports.default = (function () {
return "foo";
})(); | mrtrizer/babel | packages/babel-plugin-transform-es2015-modules-commonjs/test/fixtures/interop/exports-default/expected.js | JavaScript | mit | 388 |
// Copyright 2009 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* Constructs a mapper that maps addresses into code entries.
*
* @constructor
*/
function CodeMap() {
/**
* Dynamic code entries. Used for JIT compiled code.
*/
this.dynamics_ = new SplayTree();
/**
* Name generator for entries having duplicate names.
*/
this.dynamicsNameGen_ = new CodeMap.NameGenerator();
/**
* Static code entries. Used for statically compiled code.
*/
this.statics_ = new SplayTree();
/**
* Libraries entries. Used for the whole static code libraries.
*/
this.libraries_ = new SplayTree();
/**
* Map of memory pages occupied with static code.
*/
this.pages_ = [];
};
/**
* The number of alignment bits in a page address.
*/
CodeMap.PAGE_ALIGNMENT = 12;
/**
* Page size in bytes.
*/
CodeMap.PAGE_SIZE =
1 << CodeMap.PAGE_ALIGNMENT;
/**
* Adds a dynamic (i.e. moveable and discardable) code entry.
*
* @param {number} start The starting address.
* @param {CodeMap.CodeEntry} codeEntry Code entry object.
*/
CodeMap.prototype.addCode = function(start, codeEntry) {
this.deleteAllCoveredNodes_(this.dynamics_, start, start + codeEntry.size);
this.dynamics_.insert(start, codeEntry);
};
/**
* Moves a dynamic code entry. Throws an exception if there is no dynamic
* code entry with the specified starting address.
*
* @param {number} from The starting address of the entry being moved.
* @param {number} to The destination address.
*/
CodeMap.prototype.moveCode = function(from, to) {
var removedNode = this.dynamics_.remove(from);
this.deleteAllCoveredNodes_(this.dynamics_, to, to + removedNode.value.size);
this.dynamics_.insert(to, removedNode.value);
};
/**
* Discards a dynamic code entry. Throws an exception if there is no dynamic
* code entry with the specified starting address.
*
* @param {number} start The starting address of the entry being deleted.
*/
CodeMap.prototype.deleteCode = function(start) {
var removedNode = this.dynamics_.remove(start);
};
/**
* Adds a library entry.
*
* @param {number} start The starting address.
* @param {CodeMap.CodeEntry} codeEntry Code entry object.
*/
CodeMap.prototype.addLibrary = function(
start, codeEntry) {
this.markPages_(start, start + codeEntry.size);
this.libraries_.insert(start, codeEntry);
};
/**
* Adds a static code entry.
*
* @param {number} start The starting address.
* @param {CodeMap.CodeEntry} codeEntry Code entry object.
*/
CodeMap.prototype.addStaticCode = function(
start, codeEntry) {
this.statics_.insert(start, codeEntry);
};
/**
* @private
*/
CodeMap.prototype.markPages_ = function(start, end) {
for (var addr = start; addr <= end;
addr += CodeMap.PAGE_SIZE) {
this.pages_[addr >>> CodeMap.PAGE_ALIGNMENT] = 1;
}
};
/**
* @private
*/
CodeMap.prototype.deleteAllCoveredNodes_ = function(tree, start, end) {
var to_delete = [];
var addr = end - 1;
while (addr >= start) {
var node = tree.findGreatestLessThan(addr);
if (!node) break;
var start2 = node.key, end2 = start2 + node.value.size;
if (start2 < end && start < end2) to_delete.push(start2);
addr = start2 - 1;
}
for (var i = 0, l = to_delete.length; i < l; ++i) tree.remove(to_delete[i]);
};
/**
* @private
*/
CodeMap.prototype.isAddressBelongsTo_ = function(addr, node) {
return addr >= node.key && addr < (node.key + node.value.size);
};
/**
* @private
*/
CodeMap.prototype.findInTree_ = function(tree, addr) {
var node = tree.findGreatestLessThan(addr);
return node && this.isAddressBelongsTo_(addr, node) ? node : null;
};
/**
* Finds a code entry that contains the specified address. Both static and
* dynamic code entries are considered. Returns the code entry and the offset
* within the entry.
*
* @param {number} addr Address.
*/
CodeMap.prototype.findAddress = function(addr) {
var pageAddr = addr >>> CodeMap.PAGE_ALIGNMENT;
if (pageAddr in this.pages_) {
// Static code entries can contain "holes" of unnamed code.
// In this case, the whole library is assigned to this address.
var result = this.findInTree_(this.statics_, addr);
if (!result) {
result = this.findInTree_(this.libraries_, addr);
if (!result) return null;
}
return { entry : result.value, offset : addr - result.key };
}
var min = this.dynamics_.findMin();
var max = this.dynamics_.findMax();
if (max != null && addr < (max.key + max.value.size) && addr >= min.key) {
var dynaEntry = this.findInTree_(this.dynamics_, addr);
if (dynaEntry == null) return null;
// Dedupe entry name.
var entry = dynaEntry.value;
if (!entry.nameUpdated_) {
entry.name = this.dynamicsNameGen_.getName(entry.name);
entry.nameUpdated_ = true;
}
return { entry : entry, offset : addr - dynaEntry.key };
}
return null;
};
/**
* Finds a code entry that contains the specified address. Both static and
* dynamic code entries are considered.
*
* @param {number} addr Address.
*/
CodeMap.prototype.findEntry = function(addr) {
var result = this.findAddress(addr);
return result ? result.entry : null;
};
/**
* Returns a dynamic code entry using its starting address.
*
* @param {number} addr Address.
*/
CodeMap.prototype.findDynamicEntryByStartAddress =
function(addr) {
var node = this.dynamics_.find(addr);
return node ? node.value : null;
};
/**
* Returns an array of all dynamic code entries.
*/
CodeMap.prototype.getAllDynamicEntries = function() {
return this.dynamics_.exportValues();
};
/**
* Returns an array of pairs of all dynamic code entries and their addresses.
*/
CodeMap.prototype.getAllDynamicEntriesWithAddresses = function() {
return this.dynamics_.exportKeysAndValues();
};
/**
* Returns an array of all static code entries.
*/
CodeMap.prototype.getAllStaticEntries = function() {
return this.statics_.exportValues();
};
/**
* Returns an array of pairs of all static code entries and their addresses.
*/
CodeMap.prototype.getAllStaticEntriesWithAddresses = function() {
return this.statics_.exportKeysAndValues();
};
/**
* Returns an array of all libraries entries.
*/
CodeMap.prototype.getAllLibrariesEntries = function() {
return this.libraries_.exportValues();
};
/**
* Creates a code entry object.
*
* @param {number} size Code entry size in bytes.
* @param {string} opt_name Code entry name.
* @param {string} opt_type Code entry type, e.g. SHARED_LIB, CPP.
* @constructor
*/
CodeMap.CodeEntry = function(size, opt_name, opt_type) {
this.size = size;
this.name = opt_name || '';
this.type = opt_type || '';
this.nameUpdated_ = false;
};
CodeMap.CodeEntry.prototype.getName = function() {
return this.name;
};
CodeMap.CodeEntry.prototype.toString = function() {
return this.name + ': ' + this.size.toString(16);
};
CodeMap.NameGenerator = function() {
this.knownNames_ = {};
};
CodeMap.NameGenerator.prototype.getName = function(name) {
if (!(name in this.knownNames_)) {
this.knownNames_[name] = 0;
return name;
}
var count = ++this.knownNames_[name];
return name + ' {' + count + '}';
};
| MTASZTAKI/ApertusVR | plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/deps/v8/tools/codemap.js | JavaScript | mit | 8,722 |
module.exports={A:{A:{"1":"J C UB","129":"G E B A"},B:{"1":"D X g H L"},C:{"2":"0 1 2 4 5 SB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s QB PB"},D:{"1":"0 1 4 5 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s EB BB TB CB"},E:{"1":"F I J C G E B A FB GB HB IB JB KB","2":"9 DB"},F:{"1":"H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r","2":"6 7 E A D LB MB NB OB RB y"},G:{"1":"3 G A AB VB WB XB YB ZB aB bB cB","2":"9"},H:{"2":"dB"},I:{"1":"2 3 F s eB fB gB hB iB jB"},J:{"1":"C B"},K:{"1":"K","2":"6 7 B A D y"},L:{"1":"8"},M:{"2":"t"},N:{"129":"B A"},O:{"1":"kB"},P:{"1":"F I"},Q:{"1":"lB"},R:{"1":"mB"}},B:7,C:"CSS zoom"};
| redq81/redq81.github.io | test/node_modules/caniuse-lite/data/features/css-zoom.js | JavaScript | mit | 760 |
import r from 'restructure';
import Entity from '../entity';
import StringRef from '../string-ref';
export default Entity({
id: r.uint32le,
name: StringRef,
});
| timkurvers/blizzardry | src/lib/dbc/entities/spam-messages.js | JavaScript | mit | 167 |
module.exports={A:{A:{"2":"I C G E A B SB"},B:{"1":"K","2":"D g q"},C:{"1":"0 1 2 e f J h i j k l m n o p u v w t y r W","2":"3 QB F H I C G E A B D g q K L M N O P Q R S T U V s X Y Z a b c d OB NB"},D:{"1":"0 1 2 6 9 k l m n o p u v w t y r W CB RB AB","2":"F H I C G E A B D g q K L M N O P Q R S T U V s X Y Z a b c d e f J h i j"},E:{"1":"E A GB HB IB","2":"7 F H I C G BB DB EB FB"},F:{"1":"X Y Z a b c d e f J h i j k l m n o p","2":"4 5 E B D K L M N O P Q R S T U V s JB KB LB MB PB z"},G:{"1":"XB YB ZB aB","2":"7 8 G x TB UB VB WB"},H:{"2":"bB"},I:{"1":"W","2":"3 F cB dB eB fB x gB hB"},J:{"2":"C A"},K:{"1":"J","2":"4 5 A B D z"},L:{"1":"6"},M:{"1":"r"},N:{"2":"A B"},O:{"2":"iB"},P:{"1":"H","2":"F"},Q:{"2":"jB"},R:{"1":"kB"}},B:1,C:"Element.closest()"};
| keeyanajones/Samples | streamingProject/twitch/bots/NodeJsChatBot/node_modules/caniuse-lite/data/features/element-closest.js | JavaScript | mit | 769 |
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define('element/locale/it', ['module', 'exports'], factory);
} else if (typeof exports !== "undefined") {
factory(module, exports);
} else {
var mod = {
exports: {}
};
factory(mod, mod.exports);
global.ELEMENT.lang = global.ELEMENT.lang || {};
global.ELEMENT.lang.it = mod.exports;
}
})(this, function (module, exports) {
'use strict';
exports.__esModule = true;
exports.default = {
el: {
colorpicker: {
confirm: 'OK',
clear: 'Pulisci'
},
datepicker: {
now: 'Ora',
today: 'Oggi',
cancel: 'Cancella',
clear: 'Pulisci',
confirm: 'OK',
selectDate: 'Seleziona data',
selectTime: 'Seleziona ora',
startDate: 'Data inizio',
startTime: 'Ora inizio',
endDate: 'Data fine',
endTime: 'Ora fine',
prevYear: 'Anno precedente',
nextYear: 'Anno successivo',
prevMonth: 'Mese precedente',
nextMonth: 'Mese successivo',
year: '',
month1: 'Gennaio',
month2: 'Febbraio',
month3: 'Marzo',
month4: 'Aprile',
month5: 'Maggio',
month6: 'Giugno',
month7: 'Luglio',
month8: 'Agosto',
month9: 'Settembre',
month10: 'Ottobre',
month11: 'Novembre',
month12: 'Dicembre',
// week: 'settimana',
weeks: {
sun: 'Dom',
mon: 'Lun',
tue: 'Mar',
wed: 'Mer',
thu: 'Gio',
fri: 'Ven',
sat: 'Sab'
},
months: {
jan: 'Gen',
feb: 'Feb',
mar: 'Mar',
apr: 'Apr',
may: 'Mag',
jun: 'Giu',
jul: 'Lug',
aug: 'Ago',
sep: 'Set',
oct: 'Ott',
nov: 'Nov',
dec: 'Dic'
}
},
select: {
loading: 'Caricamento',
noMatch: 'Nessuna corrispondenza',
noData: 'Nessun dato',
placeholder: 'Seleziona'
},
cascader: {
noMatch: 'Nessuna corrispondenza',
loading: 'Caricamento',
placeholder: 'Seleziona'
},
pagination: {
goto: 'Vai a',
pagesize: '/page',
total: 'Totale {total}',
pageClassifier: ''
},
messagebox: {
confirm: 'OK',
cancel: 'Cancella',
error: 'Input non valido'
},
upload: {
deleteTip: 'Premi cancella per rimuovere',
delete: 'Cancella',
preview: 'Anteprima',
continue: 'Continua'
},
table: {
emptyText: 'Nessun dato',
confirmFilter: 'Conferma',
resetFilter: 'Reset',
clearFilter: 'Tutti',
sumText: 'Somma'
},
tree: {
emptyText: 'Nessun dato'
},
transfer: {
noMatch: 'Nessuna corrispondenza',
noData: 'Nessun dato',
titles: ['Lista 1', 'Lista 2'],
filterPlaceholder: 'Inserisci filtro',
noCheckedFormat: '{total} elementi',
hasCheckedFormat: '{checked}/{total} selezionati'
},
image: {
error: 'FAILED' // to be translated
}
}
};
module.exports = exports['default'];
}); | sufuf3/cdnjs | ajax/libs/element-ui/2.8.2/locale/it.js | JavaScript | mit | 3,306 |
/* */
var $ = require('./$'),
$def = require('./$.def'),
invoke = require('./$.invoke'),
partial = require('./$.partial'),
navigator = $.g.navigator,
MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent);
function wrap(set) {
return MSIE ? function(fn, time) {
return set(invoke(partial, [].slice.call(arguments, 2), $.isFunction(fn) ? fn : Function(fn)), time);
} : set;
}
$def($def.G + $def.B + $def.F * MSIE, {
setTimeout: wrap($.g.setTimeout),
setInterval: wrap($.g.setInterval)
});
| megadreams/Aurelia | sample_application/jspm_packages/npm/core-js@0.9.18/modules/web.timers.js | JavaScript | cc0-1.0 | 525 |
(function() {
var instance = openerp;
openerp.web.search = {};
var QWeb = instance.web.qweb,
_t = instance.web._t,
_lt = instance.web._lt;
_.mixin({
sum: function (obj) { return _.reduce(obj, function (a, b) { return a + b; }, 0); }
});
/** @namespace */
var my = instance.web.search = {};
var B = Backbone;
my.FacetValue = B.Model.extend({
});
my.FacetValues = B.Collection.extend({
model: my.FacetValue
});
my.Facet = B.Model.extend({
initialize: function (attrs) {
var values = attrs.values;
delete attrs.values;
B.Model.prototype.initialize.apply(this, arguments);
this.values = new my.FacetValues(values || []);
this.values.on('add remove change reset', function (_, options) {
this.trigger('change', this, options);
}, this);
},
get: function (key) {
if (key !== 'values') {
return B.Model.prototype.get.call(this, key);
}
return this.values.toJSON();
},
set: function (key, value) {
if (key !== 'values') {
return B.Model.prototype.set.call(this, key, value);
}
this.values.reset(value);
},
toJSON: function () {
var out = {};
var attrs = this.attributes;
for(var att in attrs) {
if (!attrs.hasOwnProperty(att) || att === 'field') {
continue;
}
out[att] = attrs[att];
}
out.values = this.values.toJSON();
return out;
}
});
my.SearchQuery = B.Collection.extend({
model: my.Facet,
initialize: function () {
B.Collection.prototype.initialize.apply(
this, arguments);
this.on('change', function (facet) {
if(!facet.values.isEmpty()) { return; }
this.remove(facet, {silent: true});
}, this);
},
add: function (values, options) {
options = options || {};
if (!values) {
values = [];
} else if (!(values instanceof Array)) {
values = [values];
}
_(values).each(function (value) {
var model = this._prepareModel(value, options);
var previous = this.detect(function (facet) {
return facet.get('category') === model.get('category')
&& facet.get('field') === model.get('field');
});
if (previous) {
previous.values.add(model.get('values'), _.omit(options, 'at', 'merge'));
return;
}
B.Collection.prototype.add.call(this, model, options);
}, this);
// warning: in backbone 1.0+ add is supposed to return the added models,
// but here toggle may delegate to add and return its value directly.
// return value of neither seems actually used but should be tested
// before change, probably
return this;
},
toggle: function (value, options) {
options = options || {};
var facet = this.detect(function (facet) {
return facet.get('category') === value.category
&& facet.get('field') === value.field;
});
if (!facet) {
return this.add(value, options);
}
var changed = false;
_(value.values).each(function (val) {
var already_value = facet.values.detect(function (v) {
return v.get('value') === val.value
&& v.get('label') === val.label;
});
// toggle value
if (already_value) {
facet.values.remove(already_value, {silent: true});
} else {
facet.values.add(val, {silent: true});
}
changed = true;
});
// "Commit" changes to values array as a single call, so observers of
// change event don't get misled by intermediate incomplete toggling
// states
facet.trigger('change', facet);
return this;
}
});
function assert(condition, message) {
if(!condition) {
throw new Error(message);
}
}
my.InputView = instance.web.Widget.extend({
template: 'SearchView.InputView',
events: {
focus: function () { this.trigger('focused', this); },
blur: function () { this.$el.text(''); this.trigger('blurred', this); },
keydown: 'onKeydown',
paste: 'onPaste',
},
getSelection: function () {
this.el.normalize();
// get Text node
var root = this.el.childNodes[0];
if (!root || !root.textContent) {
// if input does not have a child node, or the child node is an
// empty string, then the selection can only be (0, 0)
return {start: 0, end: 0};
}
var range = window.getSelection().getRangeAt(0);
// In Firefox, depending on the way text is selected (drag, double- or
// triple-click) the range may start or end on the parent of the
// selected text node‽ Check for this condition and fixup the range
// note: apparently with C-a this can go even higher?
if (range.startContainer === this.el && range.startOffset === 0) {
range.setStart(root, 0);
}
if (range.endContainer === this.el && range.endOffset === 1) {
range.setEnd(root, root.length);
}
assert(range.startContainer === root,
"selection should be in the input view");
assert(range.endContainer === root,
"selection should be in the input view");
return {
start: range.startOffset,
end: range.endOffset
};
},
onKeydown: function (e) {
this.el.normalize();
var sel;
switch (e.which) {
// Do not insert newline, but let it bubble so searchview can use it
case $.ui.keyCode.ENTER:
e.preventDefault();
break;
// FIXME: may forget content if non-empty but caret at index 0, ok?
case $.ui.keyCode.BACKSPACE:
sel = this.getSelection();
if (sel.start === 0 && sel.start === sel.end) {
e.preventDefault();
var preceding = this.getParent().siblingSubview(this, -1);
if (preceding && (preceding instanceof my.FacetView)) {
preceding.model.destroy();
}
}
break;
// let left/right events propagate to view if caret is at input border
// and not a selection
case $.ui.keyCode.LEFT:
sel = this.getSelection();
if (sel.start !== 0 || sel.start !== sel.end) {
e.stopPropagation();
}
break;
case $.ui.keyCode.RIGHT:
sel = this.getSelection();
var len = this.$el.text().length;
if (sel.start !== len || sel.start !== sel.end) {
e.stopPropagation();
}
break;
}
},
setCursorAtEnd: function () {
this.el.normalize();
var sel = window.getSelection();
sel.removeAllRanges();
var range = document.createRange();
// in theory, range.selectNodeContents should work here. In practice,
// MSIE9 has issues from time to time, instead of selecting the inner
// text node it would select the reference node instead (e.g. in demo
// data, company news, copy across the "Company News" link + the title,
// from about half the link to half the text, paste in search box then
// hit the left arrow key, getSelection would blow up).
//
// Explicitly selecting only the inner text node (only child node
// since we've normalized the parent) avoids the issue
range.selectNode(this.el.childNodes[0]);
range.collapse(false);
sel.addRange(range);
},
onPaste: function () {
this.el.normalize();
// In MSIE and Webkit, it is possible to get various representations of
// the clipboard data at this point e.g.
// window.clipboardData.getData('Text') and
// event.clipboardData.getData('text/plain') to ensure we have a plain
// text representation of the object (and probably ensure the object is
// pastable as well, so nobody puts an image in the search view)
// (nb: since it's not possible to alter the content of the clipboard
// — at least in Webkit — to ensure only textual content is available,
// using this would require 1. getting the text data; 2. manually
// inserting the text data into the content; and 3. cancelling the
// paste event)
//
// But Firefox doesn't support the clipboard API (as of FF18)
// although it correctly triggers the paste event (Opera does not even
// do that) => implement lowest-denominator system where onPaste
// triggers a followup "cleanup" pass after the data has been pasted
setTimeout(function () {
// Read text content (ignore pasted HTML)
var data = this.$el.text();
if (!data)
return;
// paste raw text back in
this.$el.empty().text(data);
this.el.normalize();
// Set the cursor at the end of the text, so the cursor is not lost
// in some kind of error-spawning limbo.
this.setCursorAtEnd();
}.bind(this), 0);
}
});
my.FacetView = instance.web.Widget.extend({
template: 'SearchView.FacetView',
events: {
'focus': function () { this.trigger('focused', this); },
'blur': function () { this.trigger('blurred', this); },
'click': function (e) {
if ($(e.target).is('.oe_facet_remove')) {
this.model.destroy();
return false;
}
this.$el.focus();
e.stopPropagation();
},
'keydown': function (e) {
var keys = $.ui.keyCode;
switch (e.which) {
case keys.BACKSPACE:
case keys.DELETE:
this.model.destroy();
return false;
}
}
},
init: function (parent, model) {
this._super(parent);
this.model = model;
this.model.on('change', this.model_changed, this);
},
destroy: function () {
this.model.off('change', this.model_changed, this);
this._super();
},
start: function () {
var self = this;
var $e = this.$('> span:last-child');
return $.when(this._super()).then(function () {
return $.when.apply(null, self.model.values.map(function (value) {
return new my.FacetValueView(self, value).appendTo($e);
}));
});
},
model_changed: function () {
this.$el.text(this.$el.text() + '*');
}
});
my.FacetValueView = instance.web.Widget.extend({
template: 'SearchView.FacetView.Value',
init: function (parent, model) {
this._super(parent);
this.model = model;
this.model.on('change', this.model_changed, this);
},
destroy: function () {
this.model.off('change', this.model_changed, this);
this._super();
},
model_changed: function () {
this.$el.text(this.$el.text() + '*');
}
});
instance.web.SearchView = instance.web.Widget.extend(/** @lends instance.web.SearchView# */{
template: "SearchView",
events: {
// focus last input if view itself is clicked
'click': function (e) {
if (e.target === this.$('.oe_searchview_facets')[0]) {
this.$('.oe_searchview_input:last').focus();
}
},
// search button
'click button.oe_searchview_search': function (e) {
e.stopImmediatePropagation();
this.do_search();
},
'click .oe_searchview_clear': function (e) {
e.stopImmediatePropagation();
this.query.reset();
},
'click .oe_searchview_unfold_drawer': function (e) {
e.stopImmediatePropagation();
if (this.drawer)
this.drawer.toggle();
},
'keydown .oe_searchview_input, .oe_searchview_facet': function (e) {
switch(e.which) {
case $.ui.keyCode.LEFT:
this.focusPreceding(e.target);
e.preventDefault();
break;
case $.ui.keyCode.RIGHT:
if (!this.autocomplete.is_expandable()) {
this.focusFollowing(e.target);
}
e.preventDefault();
break;
}
},
'autocompleteopen': function () {
this.$el.autocomplete('widget').css('z-index', 9999);
},
},
/**
* @constructs instance.web.SearchView
* @extends instance.web.Widget
*
* @param parent
* @param dataset
* @param view_id
* @param defaults
* @param {Object} [options]
* @param {Boolean} [options.hidden=false] hide the search view
* @param {Boolean} [options.disable_custom_filters=false] do not load custom filters from ir.filters
*/
init: function(parent, dataset, view_id, defaults, options) {
this.options = _.defaults(options || {}, {
hidden: false,
disable_custom_filters: false,
});
this._super(parent);
this.dataset = dataset;
this.model = dataset.model;
this.view_id = view_id;
this.defaults = defaults || {};
this.has_defaults = !_.isEmpty(this.defaults);
this.headless = this.options.hidden && !this.has_defaults;
this.input_subviews = [];
this.view_manager = null;
this.$view_manager_header = null;
this.ready = $.Deferred();
this.drawer_ready = $.Deferred();
this.fields_view_get = $.Deferred();
this.drawer = new instance.web.SearchViewDrawer(parent, this);
},
start: function() {
var self = this;
var p = this._super();
this.$view_manager_header = this.$el.parents(".oe_view_manager_header").first();
this.setup_global_completion();
this.query = new my.SearchQuery()
.on('add change reset remove', this.proxy('do_search'))
.on('change', this.proxy('renderChangedFacets'))
.on('add reset remove', this.proxy('renderFacets'));
if (this.options.hidden) {
this.$el.hide();
}
if (this.headless) {
this.ready.resolve();
} else {
var load_view = instance.web.fields_view_get({
model: this.dataset._model,
view_id: this.view_id,
view_type: 'search',
context: this.dataset.get_context(),
});
this.alive($.when(load_view)).then(function (r) {
self.fields_view_get.resolve(r);
return self.search_view_loaded(r);
}).fail(function () {
self.ready.reject.apply(null, arguments);
});
}
var view_manager = this.getParent();
while (!(view_manager instanceof instance.web.ViewManager) &&
view_manager && view_manager.getParent) {
view_manager = view_manager.getParent();
}
if (view_manager) {
this.view_manager = view_manager;
view_manager.on('switch_mode', this, function (e) {
self.drawer.toggle(e === 'graph');
});
}
return $.when(p, this.ready);
},
set_drawer: function (drawer) {
this.drawer = drawer;
},
show: function () {
this.$el.show();
},
hide: function () {
this.$el.hide();
},
subviewForRoot: function (subview_root) {
return _(this.input_subviews).detect(function (subview) {
return subview.$el[0] === subview_root;
});
},
siblingSubview: function (subview, direction, wrap_around) {
var index = _(this.input_subviews).indexOf(subview) + direction;
if (wrap_around && index < 0) {
index = this.input_subviews.length - 1;
} else if (wrap_around && index >= this.input_subviews.length) {
index = 0;
}
return this.input_subviews[index];
},
focusPreceding: function (subview_root) {
return this.siblingSubview(
this.subviewForRoot(subview_root), -1, true)
.$el.focus();
},
focusFollowing: function (subview_root) {
return this.siblingSubview(
this.subviewForRoot(subview_root), +1, true)
.$el.focus();
},
/**
* Sets up search view's view-wide auto-completion widget
*/
setup_global_completion: function () {
var self = this;
this.autocomplete = new instance.web.search.AutoComplete(this, {
source: this.proxy('complete_global_search'),
select: this.proxy('select_completion'),
delay: 0,
get_search_string: function () {
return self.$('div.oe_searchview_input').text();
},
width: this.$el.width(),
});
this.autocomplete.appendTo(this.$el);
},
/**
* Provide auto-completion result for req.term (an array to `resp`)
*
* @param {Object} req request to complete
* @param {String} req.term searched term to complete
* @param {Function} resp response callback
*/
complete_global_search: function (req, resp) {
$.when.apply(null, _(this.drawer.inputs).chain()
.filter(function (input) { return input.visible(); })
.invoke('complete', req.term)
.value()).then(function () {
resp(_(arguments).chain()
.compact()
.flatten(true)
.value());
});
},
/**
* Action to perform in case of selection: create a facet (model)
* and add it to the search collection
*
* @param {Object} e selection event, preventDefault to avoid setting value on object
* @param {Object} ui selection information
* @param {Object} ui.item selected completion item
*/
select_completion: function (e, ui) {
e.preventDefault();
var input_index = _(this.input_subviews).indexOf(
this.subviewForRoot(
this.$('div.oe_searchview_input:focus')[0]));
this.query.add(ui.item.facet, {at: input_index / 2});
},
childFocused: function () {
this.$el.addClass('oe_focused');
},
childBlurred: function () {
var val = this.$el.val();
this.$el.val('');
this.$el.removeClass('oe_focused')
.trigger('blur');
this.autocomplete.close();
},
/**
* Call the renderFacets method with the correct arguments.
* This is due to the fact that change events are called with two arguments
* (model, options) while add, reset and remove events are called with
* (collection, model, options) as arguments
*/
renderChangedFacets: function (model, options) {
this.renderFacets(undefined, model, options);
},
/**
* @param {openerp.web.search.SearchQuery | undefined} Undefined if event is change
* @param {openerp.web.search.Facet}
* @param {Object} [options]
*/
renderFacets: function (collection, model, options) {
var self = this;
var started = [];
var $e = this.$('div.oe_searchview_facets');
_.invoke(this.input_subviews, 'destroy');
this.input_subviews = [];
var i = new my.InputView(this);
started.push(i.appendTo($e));
this.input_subviews.push(i);
this.query.each(function (facet) {
var f = new my.FacetView(this, facet);
started.push(f.appendTo($e));
self.input_subviews.push(f);
var i = new my.InputView(this);
started.push(i.appendTo($e));
self.input_subviews.push(i);
}, this);
_.each(this.input_subviews, function (childView) {
childView.on('focused', self, self.proxy('childFocused'));
childView.on('blurred', self, self.proxy('childBlurred'));
});
$.when.apply(null, started).then(function () {
if (options && options.focus_input === false) return;
var input_to_focus;
// options.at: facet inserted at given index, focus next input
// otherwise just focus last input
if (!options || typeof options.at !== 'number') {
input_to_focus = _.last(self.input_subviews);
} else {
input_to_focus = self.input_subviews[(options.at + 1) * 2];
}
input_to_focus.$el.focus();
});
},
search_view_loaded: function(data) {
var self = this;
this.fields_view = data;
if (data.type !== 'search' ||
data.arch.tag !== 'search') {
throw new Error(_.str.sprintf(
"Got non-search view after asking for a search view: type %s, arch root %s",
data.type, data.arch.tag));
}
return this.drawer_ready
.then(this.proxy('setup_default_query'))
.then(function () {
self.trigger("search_view_loaded", data);
self.ready.resolve();
});
},
setup_default_query: function () {
// Hacky implementation of CustomFilters#facet_for_defaults ensure
// CustomFilters will be ready (and CustomFilters#filters will be
// correctly filled) by the time this method executes.
var custom_filters = this.drawer.custom_filters.filters;
if (!this.options.disable_custom_filters && !_(custom_filters).isEmpty()) {
// Check for any is_default custom filter
var personal_filter = _(custom_filters).find(function (filter) {
return filter.user_id && filter.is_default;
});
if (personal_filter) {
this.drawer.custom_filters.toggle_filter(personal_filter, true);
return;
}
var global_filter = _(custom_filters).find(function (filter) {
return !filter.user_id && filter.is_default;
});
if (global_filter) {
this.drawer.custom_filters.toggle_filter(global_filter, true);
return;
}
}
// No custom filter, or no is_default custom filter, apply view defaults
this.query.reset(_(arguments).compact(), {preventSearch: true});
},
/**
* Extract search data from the view's facets.
*
* Result is an object with 4 (own) properties:
*
* errors
* An array of any error generated during data validation and
* extraction, contains the validation error objects
* domains
* Array of domains
* contexts
* Array of contexts
* groupbys
* Array of domains, in groupby order rather than view order
*
* @return {Object}
*/
build_search_data: function () {
var domains = [], contexts = [], groupbys = [], errors = [];
this.query.each(function (facet) {
var field = facet.get('field');
try {
var domain = field.get_domain(facet);
if (domain) {
domains.push(domain);
}
var context = field.get_context(facet);
if (context) {
contexts.push(context);
}
var group_by = field.get_groupby(facet);
if (group_by) {
groupbys.push.apply(groupbys, group_by);
}
} catch (e) {
if (e instanceof instance.web.search.Invalid) {
errors.push(e);
} else {
throw e;
}
}
});
return {
domains: domains,
contexts: contexts,
groupbys: groupbys,
errors: errors
};
},
/**
* Performs the search view collection of widget data.
*
* If the collection went well (all fields are valid), then triggers
* :js:func:`instance.web.SearchView.on_search`.
*
* If at least one field failed its validation, triggers
* :js:func:`instance.web.SearchView.on_invalid` instead.
*
* @param [_query]
* @param {Object} [options]
*/
do_search: function (_query, options) {
if (options && options.preventSearch) {
return;
}
var search = this.build_search_data();
if (!_.isEmpty(search.errors)) {
this.on_invalid(search.errors);
return;
}
this.trigger('search_data', search.domains, search.contexts, search.groupbys);
},
/**
* Triggered after the SearchView has collected all relevant domains and
* contexts.
*
* It is provided with an Array of domains and an Array of contexts, which
* may or may not be evaluated (each item can be either a valid domain or
* context, or a string to evaluate in order in the sequence)
*
* It is also passed an array of contexts used for group_by (they are in
* the correct order for group_by evaluation, which contexts may not be)
*
* @event
* @param {Array} domains an array of literal domains or domain references
* @param {Array} contexts an array of literal contexts or context refs
* @param {Array} groupbys ordered contexts which may or may not have group_by keys
*/
/**
* Triggered after a validation error in the SearchView fields.
*
* Error objects have three keys:
* * ``field`` is the name of the invalid field
* * ``value`` is the invalid value
* * ``message`` is the (in)validation message provided by the field
*
* @event
* @param {Array} errors a never-empty array of error objects
*/
on_invalid: function (errors) {
this.do_notify(_t("Invalid Search"), _t("triggered from search view"));
this.trigger('invalid_search', errors);
},
// The method appendTo is overwrited to be able to insert the drawer anywhere
appendTo: function ($searchview_parent, $searchview_drawer_node) {
var $searchview_drawer_node = $searchview_drawer_node || $searchview_parent;
return $.when(
this._super($searchview_parent),
this.drawer.appendTo($searchview_drawer_node)
);
},
destroy: function () {
this.drawer.destroy();
this.getParent().destroy.call(this);
}
});
instance.web.SearchViewDrawer = instance.web.Widget.extend({
template: "SearchViewDrawer",
init: function(parent, searchview) {
this._super(parent);
this.searchview = searchview;
this.searchview.set_drawer(this);
this.ready = searchview.drawer_ready;
this.controls = [];
this.inputs = [];
},
toggle: function (visibility) {
this.$el.toggle(visibility);
var $view_manager_body = this.$el.closest('.oe_view_manager_body');
if ($view_manager_body.length) {
$view_manager_body.scrollTop(0);
}
},
start: function() {
var self = this;
if (this.searchview.headless) return $.when(this._super(), this.searchview.ready);
var filters_ready = this.searchview.fields_view_get
.then(this.proxy('prepare_filters'));
return $.when(this._super(), filters_ready).then(function () {
var defaults = arguments[1][0];
self.ready.resolve.apply(null, defaults);
});
},
prepare_filters: function (data) {
this.make_widgets(
data['arch'].children,
data.fields);
this.add_common_inputs();
// build drawer
var in_drawer = this.select_for_drawer();
var $first_col = this.$(".col-md-7"),
$snd_col = this.$(".col-md-5");
var add_custom_filters = in_drawer[0].appendTo($first_col),
add_filters = in_drawer[1].appendTo($first_col),
add_rest = $.when.apply(null, _(in_drawer.slice(2)).invoke('appendTo', $snd_col)),
defaults_fetched = $.when.apply(null, _(this.inputs).invoke(
'facet_for_defaults', this.searchview.defaults));
return $.when(defaults_fetched, add_custom_filters, add_filters, add_rest);
},
/**
* Sets up thingie where all the mess is put?
*/
select_for_drawer: function () {
return _(this.inputs).filter(function (input) {
return input.in_drawer();
});
},
/**
* Builds a list of widget rows (each row is an array of widgets)
*
* @param {Array} items a list of nodes to convert to widgets
* @param {Object} fields a mapping of field names to (ORM) field attributes
* @param {Object} [group] group to put the new controls in
*/
make_widgets: function (items, fields, group) {
if (!group) {
group = new instance.web.search.Group(
this, 'q', {attrs: {string: _t("Filters")}});
}
var self = this;
var filters = [];
_.each(items, function (item) {
if (filters.length && item.tag !== 'filter') {
group.push(new instance.web.search.FilterGroup(filters, group));
filters = [];
}
switch (item.tag) {
case 'separator': case 'newline':
break;
case 'filter':
filters.push(new instance.web.search.Filter(item, group));
break;
case 'group':
self.add_separator();
self.make_widgets(item.children, fields,
new instance.web.search.Group(group, 'w', item));
self.add_separator();
break;
case 'field':
var field = this.make_field(
item, fields[item['attrs'].name], group);
group.push(field);
// filters
self.make_widgets(item.children, fields, group);
break;
}
}, this);
if (filters.length) {
group.push(new instance.web.search.FilterGroup(filters, this));
}
},
add_separator: function () {
if (!(_.last(this.inputs) instanceof instance.web.search.Separator))
new instance.web.search.Separator(this);
},
/**
* Creates a field for the provided field descriptor item (which comes
* from fields_view_get)
*
* @param {Object} item fields_view_get node for the field
* @param {Object} field fields_get result for the field
* @param {Object} [parent]
* @returns instance.web.search.Field
*/
make_field: function (item, field, parent) {
// M2O combined with selection widget is pointless and broken in search views,
// but has been used in the past for unsupported hacks -> ignore it
if (field.type === "many2one" && item.attrs.widget === "selection"){
item.attrs.widget = undefined;
}
var obj = instance.web.search.fields.get_any( [item.attrs.widget, field.type]);
if(obj) {
return new (obj) (item, field, parent || this);
} else {
console.group('Unknown field type ' + field.type);
console.error('View node', item);
console.info('View field', field);
console.info('In view', this);
console.groupEnd();
return null;
}
},
add_common_inputs: function() {
// add custom filters to this.inputs
this.custom_filters = new instance.web.search.CustomFilters(this);
// add Filters to this.inputs, need view.controls filled
(new instance.web.search.Filters(this));
(new instance.web.search.SaveFilter(this, this.custom_filters));
// add Advanced to this.inputs
(new instance.web.search.Advanced(this));
},
});
/**
* Registry of search fields, called by :js:class:`instance.web.SearchView` to
* find and instantiate its field widgets.
*/
instance.web.search.fields = new instance.web.Registry({
'char': 'instance.web.search.CharField',
'text': 'instance.web.search.CharField',
'html': 'instance.web.search.CharField',
'boolean': 'instance.web.search.BooleanField',
'integer': 'instance.web.search.IntegerField',
'id': 'instance.web.search.IntegerField',
'float': 'instance.web.search.FloatField',
'selection': 'instance.web.search.SelectionField',
'datetime': 'instance.web.search.DateTimeField',
'date': 'instance.web.search.DateField',
'many2one': 'instance.web.search.ManyToOneField',
'many2many': 'instance.web.search.CharField',
'one2many': 'instance.web.search.CharField'
});
instance.web.search.Invalid = instance.web.Class.extend( /** @lends instance.web.search.Invalid# */{
/**
* Exception thrown by search widgets when they hold invalid values,
* which they can not return when asked.
*
* @constructs instance.web.search.Invalid
* @extends instance.web.Class
*
* @param field the name of the field holding an invalid value
* @param value the invalid value
* @param message validation failure message
*/
init: function (field, value, message) {
this.field = field;
this.value = value;
this.message = message;
},
toString: function () {
return _.str.sprintf(
_t("Incorrect value for field %(fieldname)s: [%(value)s] is %(message)s"),
{fieldname: this.field, value: this.value, message: this.message}
);
}
});
instance.web.search.Widget = instance.web.Widget.extend( /** @lends instance.web.search.Widget# */{
template: null,
/**
* Root class of all search widgets
*
* @constructs instance.web.search.Widget
* @extends instance.web.Widget
*
* @param parent parent of this widget
*/
init: function (parent) {
this._super(parent);
var ancestor = parent;
do {
this.drawer = ancestor;
} while (!(ancestor instanceof instance.web.SearchViewDrawer)
&& (ancestor = (ancestor.getParent && ancestor.getParent())));
this.view = this.drawer.searchview || this.drawer;
}
});
instance.web.search.add_expand_listener = function($root) {
$root.find('a.searchview_group_string').click(function (e) {
$root.toggleClass('folded expanded');
e.stopPropagation();
e.preventDefault();
});
};
instance.web.search.Group = instance.web.search.Widget.extend({
init: function (parent, icon, node) {
this._super(parent);
var attrs = node.attrs;
this.modifiers = attrs.modifiers =
attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
this.attrs = attrs;
this.icon = icon;
this.name = attrs.string;
this.children = [];
this.drawer.controls.push(this);
},
push: function (input) {
this.children.push(input);
},
visible: function () {
return !this.modifiers.invisible;
},
});
instance.web.search.Input = instance.web.search.Widget.extend( /** @lends instance.web.search.Input# */{
_in_drawer: false,
/**
* @constructs instance.web.search.Input
* @extends instance.web.search.Widget
*
* @param parent
*/
init: function (parent) {
this._super(parent);
this.load_attrs({});
this.drawer.inputs.push(this);
},
/**
* Fetch auto-completion values for the widget.
*
* The completion values should be an array of objects with keys category,
* label, value prefixed with an object with keys type=section and label
*
* @param {String} value value to complete
* @returns {jQuery.Deferred<null|Array>}
*/
complete: function (value) {
return $.when(null);
},
/**
* Returns a Facet instance for the provided defaults if they apply to
* this widget, or null if they don't.
*
* This default implementation will try calling
* :js:func:`instance.web.search.Input#facet_for` if the widget's name
* matches the input key
*
* @param {Object} defaults
* @returns {jQuery.Deferred<null|Object>}
*/
facet_for_defaults: function (defaults) {
if (!this.attrs ||
!(this.attrs.name in defaults && defaults[this.attrs.name])) {
return $.when(null);
}
return this.facet_for(defaults[this.attrs.name]);
},
in_drawer: function () {
return !!this._in_drawer;
},
get_context: function () {
throw new Error(
"get_context not implemented for widget " + this.attrs.type);
},
get_groupby: function () {
throw new Error(
"get_groupby not implemented for widget " + this.attrs.type);
},
get_domain: function () {
throw new Error(
"get_domain not implemented for widget " + this.attrs.type);
},
load_attrs: function (attrs) {
attrs.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
this.attrs = attrs;
},
/**
* Returns whether the input is "visible". The default behavior is to
* query the ``modifiers.invisible`` flag on the input's description or
* view node.
*
* @returns {Boolean}
*/
visible: function () {
if (this.attrs.modifiers.invisible) {
return false;
}
var parent = this;
while ((parent = parent.getParent()) &&
( (parent instanceof instance.web.search.Group)
|| (parent instanceof instance.web.search.Input))) {
if (!parent.visible()) {
return false;
}
}
return true;
},
});
instance.web.search.FilterGroup = instance.web.search.Input.extend(/** @lends instance.web.search.FilterGroup# */{
template: 'SearchView.filters',
icon: 'q',
completion_label: _lt("Filter on: %s"),
/**
* Inclusive group of filters, creates a continuous "button" with clickable
* sections (the normal display for filters is to be a self-contained button)
*
* @constructs instance.web.search.FilterGroup
* @extends instance.web.search.Input
*
* @param {Array<instance.web.search.Filter>} filters elements of the group
* @param {instance.web.SearchView} parent parent in which the filters are contained
*/
init: function (filters, parent) {
// If all filters are group_by and we're not initializing a GroupbyGroup,
// create a GroupbyGroup instead of the current FilterGroup
if (!(this instanceof instance.web.search.GroupbyGroup) &&
_(filters).all(function (f) {
if (!f.attrs.context) { return false; }
var c = instance.web.pyeval.eval('context', f.attrs.context);
return !_.isEmpty(c.group_by);})) {
return new instance.web.search.GroupbyGroup(filters, parent);
}
this._super(parent);
this.filters = filters;
this.view.query.on('add remove change reset', this.proxy('search_change'));
},
start: function () {
this.$el.on('click', 'li', this.proxy('toggle_filter'));
return $.when(null);
},
/**
* Handles change of the search query: any of the group's filter which is
* in the search query should be visually checked in the drawer
*/
search_change: function () {
var self = this;
var $filters = this.$('> li').removeClass('badge');
var facet = this.view.query.find(_.bind(this.match_facet, this));
if (!facet) { return; }
facet.values.each(function (v) {
var i = _(self.filters).indexOf(v.get('value'));
if (i === -1) { return; }
$filters.filter(function () {
return Number($(this).data('index')) === i;
}).addClass('badge');
});
},
/**
* Matches the group to a facet, in order to find if the group is
* represented in the current search query
*/
match_facet: function (facet) {
return facet.get('field') === this;
},
make_facet: function (values) {
return {
category: _t("Filter"),
icon: this.icon,
values: values,
field: this
};
},
make_value: function (filter) {
return {
label: filter.attrs.string || filter.attrs.help || filter.attrs.name,
value: filter
};
},
facet_for_defaults: function (defaults) {
var self = this;
var fs = _(this.filters).chain()
.filter(function (f) {
return f.attrs && f.attrs.name && !!defaults[f.attrs.name];
}).map(function (f) {
return self.make_value(f);
}).value();
if (_.isEmpty(fs)) { return $.when(null); }
return $.when(this.make_facet(fs));
},
/**
* Fetches contexts for all enabled filters in the group
*
* @param {openerp.web.search.Facet} facet
* @return {*} combined contexts of the enabled filters in this group
*/
get_context: function (facet) {
var contexts = facet.values.chain()
.map(function (f) { return f.get('value').attrs.context; })
.without('{}')
.reject(_.isEmpty)
.value();
if (!contexts.length) { return; }
if (contexts.length === 1) { return contexts[0]; }
return _.extend(new instance.web.CompoundContext(), {
__contexts: contexts
});
},
/**
* Fetches group_by sequence for all enabled filters in the group
*
* @param {VS.model.SearchFacet} facet
* @return {Array} enabled filters in this group
*/
get_groupby: function (facet) {
return facet.values.chain()
.map(function (f) { return f.get('value').attrs.context; })
.without('{}')
.reject(_.isEmpty)
.value();
},
/**
* Handles domains-fetching for all the filters within it: groups them.
*
* @param {VS.model.SearchFacet} facet
* @return {*} combined domains of the enabled filters in this group
*/
get_domain: function (facet) {
var domains = facet.values.chain()
.map(function (f) { return f.get('value').attrs.domain; })
.without('[]')
.reject(_.isEmpty)
.value();
if (!domains.length) { return; }
if (domains.length === 1) { return domains[0]; }
for (var i=domains.length; --i;) {
domains.unshift(['|']);
}
return _.extend(new instance.web.CompoundDomain(), {
__domains: domains
});
},
toggle_filter: function (e) {
this.toggle(this.filters[Number($(e.target).data('index'))]);
},
toggle: function (filter) {
this.view.query.toggle(this.make_facet([this.make_value(filter)]));
},
complete: function (item) {
var self = this;
item = item.toLowerCase();
var facet_values = _(this.filters).chain()
.filter(function (filter) { return filter.visible(); })
.filter(function (filter) {
var at = {
string: filter.attrs.string || '',
help: filter.attrs.help || '',
name: filter.attrs.name || ''
};
var include = _.str.include;
return include(at.string.toLowerCase(), item)
|| include(at.help.toLowerCase(), item)
|| include(at.name.toLowerCase(), item);
})
.map(this.make_value)
.value();
if (_(facet_values).isEmpty()) { return $.when(null); }
return $.when(_.map(facet_values, function (facet_value) {
return {
label: _.str.sprintf(self.completion_label.toString(),
_.escape(facet_value.label)),
facet: self.make_facet([facet_value])
};
}));
}
});
instance.web.search.GroupbyGroup = instance.web.search.FilterGroup.extend({
icon: 'w',
completion_label: _lt("Group by: %s"),
init: function (filters, parent) {
this._super(filters, parent);
// Not flanders: facet unicity is handled through the
// (category, field) pair of facet attributes. This is all well and
// good for regular filter groups where a group matches a facet, but for
// groupby we want a single facet. So cheat: add an attribute on the
// view which proxies to the first GroupbyGroup, so it can be used
// for every GroupbyGroup and still provides the various methods needed
// by the search view. Use weirdo name to avoid risks of conflicts
if (!this.view._s_groupby) {
this.view._s_groupby = {
help: "See GroupbyGroup#init",
get_context: this.proxy('get_context'),
get_domain: this.proxy('get_domain'),
get_groupby: this.proxy('get_groupby')
};
}
},
match_facet: function (facet) {
return facet.get('field') === this.view._s_groupby;
},
make_facet: function (values) {
return {
category: _t("GroupBy"),
icon: this.icon,
values: values,
field: this.view._s_groupby
};
}
});
instance.web.search.Filter = instance.web.search.Input.extend(/** @lends instance.web.search.Filter# */{
template: 'SearchView.filter',
/**
* Implementation of the OpenERP filters (button with a context and/or
* a domain sent as-is to the search view)
*
* Filters are only attributes holder, the actual work (compositing
* domains and contexts, converting between facets and filters) is
* performed by the filter group.
*
* @constructs instance.web.search.Filter
* @extends instance.web.search.Input
*
* @param node
* @param parent
*/
init: function (node, parent) {
this._super(parent);
this.load_attrs(node.attrs);
},
facet_for: function () { return $.when(null); },
get_context: function () { },
get_domain: function () { },
});
instance.web.search.Separator = instance.web.search.Input.extend({
_in_drawer: false,
complete: function () {
return {is_separator: true};
}
});
instance.web.search.Field = instance.web.search.Input.extend( /** @lends instance.web.search.Field# */ {
template: 'SearchView.field',
default_operator: '=',
/**
* @constructs instance.web.search.Field
* @extends instance.web.search.Input
*
* @param view_section
* @param field
* @param parent
*/
init: function (view_section, field, parent) {
this._super(parent);
this.load_attrs(_.extend({}, field, view_section.attrs));
},
facet_for: function (value) {
return $.when({
field: this,
category: this.attrs.string || this.attrs.name,
values: [{label: String(value), value: value}]
});
},
value_from: function (facetValue) {
return facetValue.get('value');
},
get_context: function (facet) {
var self = this;
// A field needs a context to send when active
var context = this.attrs.context;
if (_.isEmpty(context) || !facet.values.length) {
return;
}
var contexts = facet.values.map(function (facetValue) {
return new instance.web.CompoundContext(context)
.set_eval_context({self: self.value_from(facetValue)});
});
if (contexts.length === 1) { return contexts[0]; }
return _.extend(new instance.web.CompoundContext(), {
__contexts: contexts
});
},
get_groupby: function () { },
/**
* Function creating the returned domain for the field, override this
* methods in children if you only need to customize the field's domain
* without more complex alterations or tests (and without the need to
* change override the handling of filter_domain)
*
* @param {String} name the field's name
* @param {String} operator the field's operator (either attribute-specified or default operator for the field
* @param {Number|String} facet parsed value for the field
* @returns {Array<Array>} domain to include in the resulting search
*/
make_domain: function (name, operator, facet) {
return [[name, operator, this.value_from(facet)]];
},
get_domain: function (facet) {
if (!facet.values.length) { return; }
var value_to_domain;
var self = this;
var domain = this.attrs['filter_domain'];
if (domain) {
value_to_domain = function (facetValue) {
return new instance.web.CompoundDomain(domain)
.set_eval_context({self: self.value_from(facetValue)});
};
} else {
value_to_domain = function (facetValue) {
return self.make_domain(
self.attrs.name,
self.attrs.operator || self.default_operator,
facetValue);
};
}
var domains = facet.values.map(value_to_domain);
if (domains.length === 1) { return domains[0]; }
for (var i = domains.length; --i;) {
domains.unshift(['|']);
}
return _.extend(new instance.web.CompoundDomain(), {
__domains: domains
});
}
});
/**
* Implementation of the ``char`` OpenERP field type:
*
* * Default operator is ``ilike`` rather than ``=``
*
* * The Javascript and the HTML values are identical (strings)
*
* @class
* @extends instance.web.search.Field
*/
instance.web.search.CharField = instance.web.search.Field.extend( /** @lends instance.web.search.CharField# */ {
default_operator: 'ilike',
complete: function (value) {
if (_.isEmpty(value)) { return $.when(null); }
var label = _.str.sprintf(_.str.escapeHTML(
_t("Search %(field)s for: %(value)s")), {
field: '<em>' + _.escape(this.attrs.string) + '</em>',
value: '<strong>' + _.escape(value) + '</strong>'});
return $.when([{
label: label,
facet: {
category: this.attrs.string,
field: this,
values: [{label: value, value: value}]
}
}]);
}
});
instance.web.search.NumberField = instance.web.search.Field.extend(/** @lends instance.web.search.NumberField# */{
complete: function (value) {
var val = this.parse(value);
if (isNaN(val)) { return $.when(); }
var label = _.str.sprintf(
_t("Search %(field)s for: %(value)s"), {
field: '<em>' + _.escape(this.attrs.string) + '</em>',
value: '<strong>' + _.escape(value) + '</strong>'});
return $.when([{
label: label,
facet: {
category: this.attrs.string,
field: this,
values: [{label: value, value: val}]
}
}]);
},
});
/**
* @class
* @extends instance.web.search.NumberField
*/
instance.web.search.IntegerField = instance.web.search.NumberField.extend(/** @lends instance.web.search.IntegerField# */{
error_message: _t("not a valid integer"),
parse: function (value) {
try {
return instance.web.parse_value(value, {'widget': 'integer'});
} catch (e) {
return NaN;
}
}
});
/**
* @class
* @extends instance.web.search.NumberField
*/
instance.web.search.FloatField = instance.web.search.NumberField.extend(/** @lends instance.web.search.FloatField# */{
error_message: _t("not a valid number"),
parse: function (value) {
try {
return instance.web.parse_value(value, {'widget': 'float'});
} catch (e) {
return NaN;
}
}
});
/**
* Utility function for m2o & selection fields taking a selection/name_get pair
* (value, name) and converting it to a Facet descriptor
*
* @param {instance.web.search.Field} field holder field
* @param {Array} pair pair value to convert
*/
function facet_from(field, pair) {
return {
field: field,
category: field['attrs'].string,
values: [{label: pair[1], value: pair[0]}]
};
}
/**
* @class
* @extends instance.web.search.Field
*/
instance.web.search.SelectionField = instance.web.search.Field.extend(/** @lends instance.web.search.SelectionField# */{
// This implementation is a basic <select> field, but it may have to be
// altered to be more in line with the GTK client, which uses a combo box
// (~ jquery.autocomplete):
// * If an option was selected in the list, behave as currently
// * If something which is not in the list was entered (via the text input),
// the default domain should become (`ilike` string_value) but **any
// ``context`` or ``filter_domain`` becomes falsy, idem if ``@operator``
// is specified. So at least get_domain needs to be quite a bit
// overridden (if there's no @value and there is no filter_domain and
// there is no @operator, return [[name, 'ilike', str_val]]
template: 'SearchView.field.selection',
init: function () {
this._super.apply(this, arguments);
// prepend empty option if there is no empty option in the selection list
this.prepend_empty = !_(this.attrs.selection).detect(function (item) {
return !item[1];
});
},
complete: function (needle) {
var self = this;
var results = _(this.attrs.selection).chain()
.filter(function (sel) {
var value = sel[0], label = sel[1];
if (!value) { return false; }
return label.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
})
.map(function (sel) {
return {
label: _.escape(sel[1]),
facet: facet_from(self, sel)
};
}).value();
if (_.isEmpty(results)) { return $.when(null); }
return $.when.call(null, [{
label: _.escape(this.attrs.string)
}].concat(results));
},
facet_for: function (value) {
var match = _(this.attrs.selection).detect(function (sel) {
return sel[0] === value;
});
if (!match) { return $.when(null); }
return $.when(facet_from(this, match));
}
});
instance.web.search.BooleanField = instance.web.search.SelectionField.extend(/** @lends instance.web.search.BooleanField# */{
/**
* @constructs instance.web.search.BooleanField
* @extends instance.web.search.BooleanField
*/
init: function () {
this._super.apply(this, arguments);
this.attrs.selection = [
[true, _t("Yes")],
[false, _t("No")]
];
}
});
/**
* @class
* @extends instance.web.search.DateField
*/
instance.web.search.DateField = instance.web.search.Field.extend(/** @lends instance.web.search.DateField# */{
value_from: function (facetValue) {
return instance.web.date_to_str(facetValue.get('value'));
},
complete: function (needle) {
var d = Date.parse(needle);
if (!d) { return $.when(null); }
var date_string = instance.web.format_value(d, this.attrs);
var label = _.str.sprintf(_.str.escapeHTML(
_t("Search %(field)s at: %(value)s")), {
field: '<em>' + _.escape(this.attrs.string) + '</em>',
value: '<strong>' + date_string + '</strong>'});
return $.when([{
label: label,
facet: {
category: this.attrs.string,
field: this,
values: [{label: date_string, value: d}]
}
}]);
}
});
/**
* Implementation of the ``datetime`` openerp field type:
*
* * Uses the same widget as the ``date`` field type (a simple date)
*
* * Builds a slighly more complex, it's a datetime range (includes time)
* spanning the whole day selected by the date widget
*
* @class
* @extends instance.web.DateField
*/
instance.web.search.DateTimeField = instance.web.search.DateField.extend(/** @lends instance.web.search.DateTimeField# */{
value_from: function (facetValue) {
return instance.web.datetime_to_str(facetValue.get('value'));
}
});
instance.web.search.ManyToOneField = instance.web.search.CharField.extend({
default_operator: {},
init: function (view_section, field, parent) {
this._super(view_section, field, parent);
this.model = new instance.web.Model(this.attrs.relation);
},
complete: function (value) {
if (_.isEmpty(value)) { return $.when(null); }
var label = _.str.sprintf(_.str.escapeHTML(
_t("Search %(field)s for: %(value)s")), {
field: '<em>' + _.escape(this.attrs.string) + '</em>',
value: '<strong>' + _.escape(value) + '</strong>'});
return $.when([{
label: label,
facet: {
category: this.attrs.string,
field: this,
values: [{label: value, value: value}]
},
expand: this.expand.bind(this),
}]);
},
expand: function (needle) {
var self = this;
// FIXME: "concurrent" searches (multiple requests, mis-ordered responses)
var context = instance.web.pyeval.eval(
'contexts', [this.view.dataset.get_context()]);
return this.model.call('name_search', [], {
name: needle,
args: instance.web.pyeval.eval(
'domains', this.attrs.domain ? [this.attrs.domain] : [], context),
limit: 8,
context: context
}).then(function (results) {
if (_.isEmpty(results)) { return null; }
return _(results).map(function (result) {
return {
label: _.escape(result[1]),
facet: facet_from(self, result)
};
});
});
},
facet_for: function (value) {
var self = this;
if (value instanceof Array) {
if (value.length === 2 && _.isString(value[1])) {
return $.when(facet_from(this, value));
}
assert(value.length <= 1,
_t("M2O search fields do not currently handle multiple default values"));
// there are many cases of {search_default_$m2ofield: [id]}, need
// to handle this as if it were a single value.
value = value[0];
}
return this.model.call('name_get', [value]).then(function (names) {
if (_(names).isEmpty()) { return null; }
return facet_from(self, names[0]);
});
},
value_from: function (facetValue) {
return facetValue.get('label');
},
make_domain: function (name, operator, facetValue) {
switch(operator){
case this.default_operator:
return [[name, '=', facetValue.get('value')]];
case 'child_of':
return [[name, 'child_of', facetValue.get('value')]];
}
return this._super(name, operator, facetValue);
},
get_context: function (facet) {
var values = facet.values;
if (_.isEmpty(this.attrs.context) && values.length === 1) {
var c = {};
c['default_' + this.attrs.name] = values.at(0).get('value');
return c;
}
return this._super(facet);
}
});
instance.web.search.CustomFilters = instance.web.search.Input.extend({
template: 'SearchView.Custom',
_in_drawer: true,
init: function () {
this.is_ready = $.Deferred();
this._super.apply(this,arguments);
},
start: function () {
var self = this;
this.model = new instance.web.Model('ir.filters');
this.filters = {};
this.$filters = {};
this.view.query
.on('remove', function (facet) {
if (!facet.get('is_custom_filter')) {
return;
}
self.clear_selection();
})
.on('reset', this.proxy('clear_selection'));
return this.model.call('get_filters', [this.view.model, this.get_action_id()])
.then(this.proxy('set_filters'))
.done(function () { self.is_ready.resolve(); })
.fail(function () { self.is_ready.reject.apply(self.is_ready, arguments); });
},
get_action_id: function(){
var action = instance.client.action_manager.inner_action;
if (action) return action.id;
},
/**
* Special implementation delaying defaults until CustomFilters is loaded
*/
facet_for_defaults: function () {
return this.is_ready;
},
/**
* Generates a mapping key (in the filters and $filter mappings) for the
* filter descriptor object provided (as returned by ``get_filters``).
*
* The mapping key is guaranteed to be unique for a given (user_id, name)
* pair.
*
* @param {Object} filter
* @param {String} filter.name
* @param {Number|Pair<Number, String>} [filter.user_id]
* @return {String} mapping key corresponding to the filter
*/
key_for: function (filter) {
var user_id = filter.user_id,
action_id = filter.action_id;
var uid = (user_id instanceof Array) ? user_id[0] : user_id;
var act_id = (action_id instanceof Array) ? action_id[0] : action_id;
return _.str.sprintf('(%s)(%s)%s', uid, act_id, filter.name);
},
/**
* Generates a :js:class:`~instance.web.search.Facet` descriptor from a
* filter descriptor
*
* @param {Object} filter
* @param {String} filter.name
* @param {Object} [filter.context]
* @param {Array} [filter.domain]
* @return {Object}
*/
facet_for: function (filter) {
return {
category: _t("Custom Filter"),
icon: 'M',
field: {
get_context: function () { return filter.context; },
get_groupby: function () { return [filter.context]; },
get_domain: function () { return filter.domain; }
},
_id: filter['id'],
is_custom_filter: true,
values: [{label: filter.name, value: null}]
};
},
clear_selection: function () {
this.$('span.badge').removeClass('badge');
},
append_filter: function (filter) {
var self = this;
var key = this.key_for(filter);
var warning = _t("This filter is global and will be removed for everybody if you continue.");
var $filter;
if (key in this.$filters) {
$filter = this.$filters[key];
} else {
var id = filter.id;
this.filters[key] = filter;
$filter = $('<li></li>')
.appendTo(this.$('.oe_searchview_custom_list'))
.toggleClass('oe_searchview_custom_default', filter.is_default)
.append(this.$filters[key] = $('<span>').text(filter.name));
this.$filters[key].addClass(filter.user_id ? 'oe_searchview_custom_private'
: 'oe_searchview_custom_public')
$('<a class="oe_searchview_custom_delete">x</a>')
.click(function (e) {
e.stopPropagation();
if (!(filter.user_id || confirm(warning))) {
return;
}
self.model.call('unlink', [id]).done(function () {
$filter.remove();
delete self.$filters[key];
delete self.filters[key];
if (_.isEmpty(self.filters)) {
self.hide();
}
});
})
.appendTo($filter);
}
this.$filters[key].unbind('click').click(function () {
self.toggle_filter(filter);
});
this.show();
},
toggle_filter: function (filter, preventSearch) {
var current = this.view.query.find(function (facet) {
return facet.get('_id') === filter.id;
});
if (current) {
this.view.query.remove(current);
this.$filters[this.key_for(filter)].removeClass('badge');
return;
}
this.view.query.reset([this.facet_for(filter)], {
preventSearch: preventSearch || false});
this.$filters[this.key_for(filter)].addClass('badge');
},
set_filters: function (filters) {
_(filters).map(_.bind(this.append_filter, this));
if (!filters.length) {
this.hide();
}
},
hide: function () {
this.$el.hide();
},
show: function () {
this.$el.show();
},
});
instance.web.search.SaveFilter = instance.web.search.Input.extend({
template: 'SearchView.SaveFilter',
_in_drawer: true,
init: function (parent, custom_filters) {
this._super(parent);
this.custom_filters = custom_filters;
},
start: function () {
var self = this;
this.model = new instance.web.Model('ir.filters');
this.$el.on('submit', 'form', this.proxy('save_current'));
this.$el.on('click', 'input[type=checkbox]', function() {
$(this).siblings('input[type=checkbox]').prop('checked', false);
});
this.$el.on('click', 'h4', function () {
self.$el.toggleClass('oe_opened');
});
},
save_current: function () {
var self = this;
var $name = this.$('input:first');
var private_filter = !this.$('#oe_searchview_custom_public').prop('checked');
var set_as_default = this.$('#oe_searchview_custom_default').prop('checked');
if (_.isEmpty($name.val())){
this.do_warn(_t("Error"), _t("Filter name is required."));
return false;
}
var search = this.view.build_search_data();
instance.web.pyeval.eval_domains_and_contexts({
domains: search.domains,
contexts: search.contexts,
group_by_seq: search.groupbys || []
}).done(function (results) {
if (!_.isEmpty(results.group_by)) {
results.context.group_by = results.group_by;
}
// Don't save user_context keys in the custom filter, otherwise end
// up with e.g. wrong uid or lang stored *and used in subsequent
// reqs*
var ctx = results.context;
_(_.keys(instance.session.user_context)).each(function (key) {
delete ctx[key];
});
var filter = {
name: $name.val(),
user_id: private_filter ? instance.session.uid : false,
model_id: self.view.model,
context: results.context,
domain: results.domain,
is_default: set_as_default,
action_id: self.custom_filters.get_action_id()
};
// FIXME: current context?
return self.model.call('create_or_replace', [filter]).done(function (id) {
filter.id = id;
if (self.custom_filters) {
self.custom_filters.append_filter(filter);
}
self.$el
.removeClass('oe_opened')
.find('form')[0].reset();
});
});
return false;
},
});
instance.web.search.Filters = instance.web.search.Input.extend({
template: 'SearchView.Filters',
_in_drawer: true,
start: function () {
var self = this;
var is_group = function (i) { return i instanceof instance.web.search.FilterGroup; };
var visible_filters = _(this.drawer.controls).chain().reject(function (group) {
return _(_(group.children).filter(is_group)).isEmpty()
|| group.modifiers.invisible;
});
var groups = visible_filters.map(function (group) {
var filters = _(group.children).filter(is_group);
return {
name: _.str.sprintf("<span class='oe_i'>%s</span> %s",
group.icon, group.name),
filters: filters,
length: _(filters).chain().map(function (i) {
return i.filters.length; }).sum().value()
};
}).value();
var $dl = $('<dl class="dl-horizontal">').appendTo(this.$el);
var rendered_lines = _.map(groups, function (group) {
$('<dt>').html(group.name).appendTo($dl);
var $dd = $('<dd>').appendTo($dl);
return $.when.apply(null, _(group.filters).invoke('appendTo', $dd));
});
return $.when.apply(this, rendered_lines);
},
});
instance.web.search.Advanced = instance.web.search.Input.extend({
template: 'SearchView.advanced',
_in_drawer: true,
start: function () {
var self = this;
this.$el
.on('keypress keydown keyup', function (e) { e.stopPropagation(); })
.on('click', 'h4', function () {
self.$el.toggleClass('oe_opened');
}).on('click', 'button.oe_add_condition', function () {
self.append_proposition();
}).on('submit', 'form', function (e) {
e.preventDefault();
self.commit_search();
});
return $.when(
this._super(),
new instance.web.Model(this.view.model).call('fields_get', {
context: this.view.dataset.context
}).done(function(data) {
self.fields = {
id: { string: 'ID', type: 'id' }
};
_.each(data, function(field_def, field_name) {
if (field_def.selectable !== false && field_name != 'id') {
self.fields[field_name] = field_def;
}
});
})).done(function () {
self.append_proposition();
});
},
append_proposition: function () {
var self = this;
return (new instance.web.search.ExtendedSearchProposition(this, this.fields))
.appendTo(this.$('ul')).done(function () {
self.$('button.oe_apply').prop('disabled', false);
});
},
remove_proposition: function (prop) {
// removing last proposition, disable apply button
if (this.getChildren().length <= 1) {
this.$('button.oe_apply').prop('disabled', true);
}
prop.destroy();
},
commit_search: function () {
// Get domain sections from all propositions
var children = this.getChildren();
var propositions = _.invoke(children, 'get_proposition');
var domain = _(propositions).pluck('value');
for (var i = domain.length; --i;) {
domain.unshift('|');
}
this.view.query.add({
category: _t("Advanced"),
values: propositions,
field: {
get_context: function () { },
get_domain: function () { return domain;},
get_groupby: function () { }
}
});
// remove all propositions
_.invoke(children, 'destroy');
// add new empty proposition
this.append_proposition();
// TODO: API on searchview
this.view.$el.removeClass('oe_searchview_open_drawer');
}
});
instance.web.search.ExtendedSearchProposition = instance.web.Widget.extend(/** @lends instance.web.search.ExtendedSearchProposition# */{
template: 'SearchView.extended_search.proposition',
events: {
'change .searchview_extended_prop_field': 'changed',
'change .searchview_extended_prop_op': 'operator_changed',
'click .searchview_extended_delete_prop': function (e) {
e.stopPropagation();
this.getParent().remove_proposition(this);
}
},
/**
* @constructs instance.web.search.ExtendedSearchProposition
* @extends instance.web.Widget
*
* @param parent
* @param fields
*/
init: function (parent, fields) {
this._super(parent);
this.fields = _(fields).chain()
.map(function(val, key) { return _.extend({}, val, {'name': key}); })
.filter(function (field) { return !field.deprecated && (field.store === void 0 || field.store || field.fnct_search); })
.sortBy(function(field) {return field.string;})
.value();
this.attrs = {_: _, fields: this.fields, selected: null};
this.value = null;
},
start: function () {
return this._super().done(this.proxy('changed'));
},
changed: function() {
var nval = this.$(".searchview_extended_prop_field").val();
if(this.attrs.selected === null || this.attrs.selected === undefined || nval != this.attrs.selected.name) {
this.select_field(_.detect(this.fields, function(x) {return x.name == nval;}));
}
},
operator_changed: function (e) {
var $value = this.$('.searchview_extended_prop_value');
switch ($(e.target).val()) {
case '∃':
case '∄':
$value.hide();
break;
default:
$value.show();
}
},
/**
* Selects the provided field object
*
* @param field a field descriptor object (as returned by fields_get, augmented by the field name)
*/
select_field: function(field) {
var self = this;
if(this.attrs.selected !== null && this.attrs.selected !== undefined) {
this.value.destroy();
this.value = null;
this.$('.searchview_extended_prop_op').html('');
}
this.attrs.selected = field;
if(field === null || field === undefined) {
return;
}
var type = field.type;
var Field = instance.web.search.custom_filters.get_object(type);
if(!Field) {
Field = instance.web.search.custom_filters.get_object("char");
}
this.value = new Field(this, field);
_.each(this.value.operators, function(operator) {
$('<option>', {value: operator.value})
.text(String(operator.text))
.appendTo(self.$('.searchview_extended_prop_op'));
});
var $value_loc = this.$('.searchview_extended_prop_value').show().empty();
this.value.appendTo($value_loc);
},
get_proposition: function() {
if (this.attrs.selected === null || this.attrs.selected === undefined)
return null;
var field = this.attrs.selected;
var op_select = this.$('.searchview_extended_prop_op')[0];
var operator = op_select.options[op_select.selectedIndex];
return {
label: this.value.get_label(field, operator),
value: this.value.get_domain(field, operator),
};
}
});
instance.web.search.ExtendedSearchProposition.Field = instance.web.Widget.extend({
init: function (parent, field) {
this._super(parent);
this.field = field;
},
get_label: function (field, operator) {
var format;
switch (operator.value) {
case '∃': case '∄': format = _t('%(field)s %(operator)s'); break;
default: format = _t('%(field)s %(operator)s "%(value)s"'); break;
}
return this.format_label(format, field, operator);
},
format_label: function (format, field, operator) {
return _.str.sprintf(format, {
field: field.string,
// According to spec, HTMLOptionElement#label should return
// HTMLOptionElement#text when not defined/empty, but it does
// not in older Webkit (between Safari 5.1.5 and Chrome 17) and
// Gecko (pre Firefox 7) browsers, so we need a manual fallback
// for those
operator: operator.label || operator.text,
value: this
});
},
get_domain: function (field, operator) {
switch (operator.value) {
case '∃': return this.make_domain(field.name, '!=', false);
case '∄': return this.make_domain(field.name, '=', false);
default: return this.make_domain(
field.name, operator.value, this.get_value());
}
},
make_domain: function (field, operator, value) {
return [field, operator, value];
},
/**
* Returns a human-readable version of the value, in case the "logical"
* and the "semantic" values of a field differ (as for selection fields,
* for instance).
*
* The default implementation simply returns the value itself.
*
* @return {String} human-readable version of the value
*/
toString: function () {
return this.get_value();
}
});
instance.web.search.ExtendedSearchProposition.Char = instance.web.search.ExtendedSearchProposition.Field.extend({
template: 'SearchView.extended_search.proposition.char',
operators: [
{value: "ilike", text: _lt("contains")},
{value: "not ilike", text: _lt("doesn't contain")},
{value: "=", text: _lt("is equal to")},
{value: "!=", text: _lt("is not equal to")},
{value: "∃", text: _lt("is set")},
{value: "∄", text: _lt("is not set")}
],
get_value: function() {
return this.$el.val();
}
});
instance.web.search.ExtendedSearchProposition.DateTime = instance.web.search.ExtendedSearchProposition.Field.extend({
template: 'SearchView.extended_search.proposition.empty',
operators: [
{value: "=", text: _lt("is equal to")},
{value: "!=", text: _lt("is not equal to")},
{value: ">", text: _lt("greater than")},
{value: "<", text: _lt("less than")},
{value: ">=", text: _lt("greater or equal than")},
{value: "<=", text: _lt("less or equal than")},
{value: "∃", text: _lt("is set")},
{value: "∄", text: _lt("is not set")}
],
/**
* Date widgets live in view_form which is not yet loaded when this is
* initialized -_-
*/
widget: function () { return instance.web.DateTimeWidget; },
get_value: function() {
return this.datewidget.get_value();
},
toString: function () {
return instance.web.format_value(this.get_value(), { type:"datetime" });
},
start: function() {
var ready = this._super();
this.datewidget = new (this.widget())(this);
this.datewidget.appendTo(this.$el);
return ready;
}
});
instance.web.search.ExtendedSearchProposition.Date = instance.web.search.ExtendedSearchProposition.DateTime.extend({
widget: function () { return instance.web.DateWidget; },
toString: function () {
return instance.web.format_value(this.get_value(), { type:"date" });
}
});
instance.web.search.ExtendedSearchProposition.Integer = instance.web.search.ExtendedSearchProposition.Field.extend({
template: 'SearchView.extended_search.proposition.integer',
operators: [
{value: "=", text: _lt("is equal to")},
{value: "!=", text: _lt("is not equal to")},
{value: ">", text: _lt("greater than")},
{value: "<", text: _lt("less than")},
{value: ">=", text: _lt("greater or equal than")},
{value: "<=", text: _lt("less or equal than")},
{value: "∃", text: _lt("is set")},
{value: "∄", text: _lt("is not set")}
],
toString: function () {
return this.$el.val();
},
get_value: function() {
try {
var val =this.$el.val();
return instance.web.parse_value(val === "" ? 0 : val, {'widget': 'integer'});
} catch (e) {
return "";
}
}
});
instance.web.search.ExtendedSearchProposition.Id = instance.web.search.ExtendedSearchProposition.Integer.extend({
operators: [{value: "=", text: _lt("is")}]
});
instance.web.search.ExtendedSearchProposition.Float = instance.web.search.ExtendedSearchProposition.Field.extend({
template: 'SearchView.extended_search.proposition.float',
operators: [
{value: "=", text: _lt("is equal to")},
{value: "!=", text: _lt("is not equal to")},
{value: ">", text: _lt("greater than")},
{value: "<", text: _lt("less than")},
{value: ">=", text: _lt("greater or equal than")},
{value: "<=", text: _lt("less or equal than")},
{value: "∃", text: _lt("is set")},
{value: "∄", text: _lt("is not set")}
],
toString: function () {
return this.$el.val();
},
get_value: function() {
try {
var val =this.$el.val();
return instance.web.parse_value(val === "" ? 0.0 : val, {'widget': 'float'});
} catch (e) {
return "";
}
}
});
instance.web.search.ExtendedSearchProposition.Selection = instance.web.search.ExtendedSearchProposition.Field.extend({
template: 'SearchView.extended_search.proposition.selection',
operators: [
{value: "=", text: _lt("is")},
{value: "!=", text: _lt("is not")},
{value: "∃", text: _lt("is set")},
{value: "∄", text: _lt("is not set")}
],
toString: function () {
var select = this.$el[0];
var option = select.options[select.selectedIndex];
return option.label || option.text;
},
get_value: function() {
return this.$el.val();
}
});
instance.web.search.ExtendedSearchProposition.Boolean = instance.web.search.ExtendedSearchProposition.Field.extend({
template: 'SearchView.extended_search.proposition.empty',
operators: [
{value: "=", text: _lt("is true")},
{value: "!=", text: _lt("is false")}
],
get_label: function (field, operator) {
return this.format_label(
_t('%(field)s %(operator)s'), field, operator);
},
get_value: function() {
return true;
}
});
instance.web.search.custom_filters = new instance.web.Registry({
'char': 'instance.web.search.ExtendedSearchProposition.Char',
'text': 'instance.web.search.ExtendedSearchProposition.Char',
'one2many': 'instance.web.search.ExtendedSearchProposition.Char',
'many2one': 'instance.web.search.ExtendedSearchProposition.Char',
'many2many': 'instance.web.search.ExtendedSearchProposition.Char',
'datetime': 'instance.web.search.ExtendedSearchProposition.DateTime',
'date': 'instance.web.search.ExtendedSearchProposition.Date',
'integer': 'instance.web.search.ExtendedSearchProposition.Integer',
'float': 'instance.web.search.ExtendedSearchProposition.Float',
'boolean': 'instance.web.search.ExtendedSearchProposition.Boolean',
'selection': 'instance.web.search.ExtendedSearchProposition.Selection',
'id': 'instance.web.search.ExtendedSearchProposition.Id'
});
instance.web.search.AutoComplete = instance.web.Widget.extend({
template: "SearchView.autocomplete",
// Parameters for autocomplete constructor:
//
// parent: this is used to detect keyboard events
//
// options.source: function ({term:query}, callback). This function will be called to
// obtain the search results corresponding to the query string. It is assumed that
// options.source will call callback with the results.
// options.delay: delay in millisecond before calling source. Useful if you don't want
// to make too many rpc calls
// options.select: function (ev, {item: {facet:facet}}). Autocomplete widget will call
// that function when a selection is made by the user
// options.get_search_string: function (). This function will be called by autocomplete
// to obtain the current search string.
init: function (parent, options) {
this._super(parent);
this.$input = parent.$el;
this.source = options.source;
this.delay = options.delay;
this.select = options.select,
this.get_search_string = options.get_search_string;
this.width = options.width || 400;
this.current_result = null;
this.searching = true;
this.search_string = null;
this.current_search = null;
},
start: function () {
var self = this;
this.$el.width(this.width);
this.$input.on('keyup', function (ev) {
if (ev.which === $.ui.keyCode.RIGHT) {
self.searching = true;
ev.preventDefault();
return;
}
if (!self.searching) {
self.searching = true;
return;
}
self.search_string = self.get_search_string();
if (self.search_string.length) {
var search_string = self.search_string;
setTimeout(function () { self.initiate_search(search_string);}, self.delay);
} else {
self.close();
}
});
this.$input.on('keydown', function (ev) {
switch (ev.which) {
case $.ui.keyCode.TAB:
case $.ui.keyCode.ENTER:
if (self.get_search_string().length) {
self.select_item(ev);
}
break;
case $.ui.keyCode.DOWN:
self.move('down');
self.searching = false;
ev.preventDefault();
break;
case $.ui.keyCode.UP:
self.move('up');
self.searching = false;
ev.preventDefault();
break;
case $.ui.keyCode.RIGHT:
self.searching = false;
var current = self.current_result
if (current && current.expand && !current.expanded) {
self.expand();
self.searching = true;
}
ev.preventDefault();
break;
case $.ui.keyCode.ESCAPE:
self.close();
self.searching = false;
break;
}
});
},
initiate_search: function (query) {
if (query === this.search_string && query !== this.current_search) {
this.search(query);
}
},
search: function (query) {
var self = this;
this.current_search = query;
this.source({term:query}, function (results) {
if (results.length) {
self.render_search_results(results);
self.focus_element(self.$('li:first-child'));
} else {
self.close();
}
});
},
render_search_results: function (results) {
var self = this;
var $list = this.$('ul');
$list.empty();
var render_separator = false;
results.forEach(function (result) {
if (result.is_separator) {
if (render_separator)
$list.append($('<li>').addClass('oe-separator'));
render_separator = false;
} else {
var $item = self.make_list_item(result).appendTo($list);
result.$el = $item;
render_separator = true;
}
});
this.show();
},
make_list_item: function (result) {
var self = this;
var $li = $('<li>')
.hover(function (ev) {self.focus_element($li);})
.mousedown(function (ev) {
if (ev.button === 0) { // left button
self.select(ev, {item: {facet: result.facet}});
self.close();
} else {
ev.preventDefault();
}
})
.data('result', result);
if (result.expand) {
var $expand = $('<span class="oe-expand">').text('▶').appendTo($li);
$expand.mousedown(function (ev) {
ev.preventDefault();
ev.stopPropagation();
if (result.expanded)
self.fold();
else
self.expand();
});
result.expanded = false;
}
if (result.indent) $li.addClass('oe-indent');
$li.append($('<span>').html(result.label));
return $li;
},
expand: function () {
var self = this;
this.current_result.expand(this.get_search_string()).then(function (results) {
(results || [{label: '(no result)'}]).reverse().forEach(function (result) {
result.indent = true;
var $li = self.make_list_item(result);
self.current_result.$el.after($li);
});
self.current_result.expanded = true;
self.current_result.$el.find('span.oe-expand').html('▼');
});
},
fold: function () {
var $next = this.current_result.$el.next();
while ($next.hasClass('oe-indent')) {
$next.remove();
$next = this.current_result.$el.next();
}
this.current_result.expanded = false;
this.current_result.$el.find('span.oe-expand').html('▶');
},
focus_element: function ($li) {
this.$('li').removeClass('oe-selection-focus');
$li.addClass('oe-selection-focus');
this.current_result = $li.data('result');
},
select_item: function (ev) {
if (this.current_result.facet) {
this.select(ev, {item: {facet: this.current_result.facet}});
this.close();
}
},
show: function () {
this.$el.show();
},
close: function () {
this.current_search = null;
this.search_string = null;
this.searching = true;
this.$el.hide();
},
move: function (direction) {
var $next;
if (direction === 'down') {
$next = this.$('li.oe-selection-focus').nextAll(':not(.oe-separator)').first();
if (!$next.length) $next = this.$('li:first-child');
} else {
$next = this.$('li.oe-selection-focus').prevAll(':not(.oe-separator)').first();
if (!$next.length) $next = this.$('li:not(.oe-separator)').last();
}
this.focus_element($next);
},
is_expandable: function () {
return !!this.$('.oe-selection-focus .oe-expand').length;
},
});
})();
// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
| fdvarela/odoo8 | addons/web/static/src/js/search.js | JavaScript | agpl-3.0 | 92,024 |
//{namespace name=backend/config/view/main}
/**
* 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 Base
* @subpackage Component
* @version $Id$
* @author shopware AG
*/
Ext.define('Shopware.apps.Base.view.element.Interval', {
extend:'Ext.form.field.ComboBox',
alias:[
'widget.base-element-interval'
],
queryMode: 'local',
forceSelection: false,
editable: true,
store: [
[0, '{s name=element/interval/empty_value}None (0 Sec.){/s}'],
[120, '{s name=element/interval/2_minutes}2 Minutes (120 Sec.){/s}'],
[300, '{s name=element/interval/5_minutes}5 Minutes (300 Sec.){/s}'],
[600, '{s name=element/interval/10_minutes}10 Minutes (600 Sec.){/s}'],
[900, '{s name=element/interval/15_minutes}15 Minutes (900 Sec.){/s}'],
[1800, '{s name=element/interval/30_minutes}30 Minutes (1800 Sec.){/s}'],
[3600, '{s name=element/interval/1_hour}1 Hour (3600 Sec.){/s}'],
[7200, '{s name=element/interval/2_hours}2 Hours (7200 Sec.){/s}'],
[14400, '{s name=element/interval/4_hours}4 Hours (14400 Sec.){/s}'],
[28800, '{s name=element/interval/8_hours}8 Hours (28800 Sec.){/s}'],
[43200, '{s name=element/interval/12_hours}12 Hours (43200 Sec.){/s}'],
[86400, '{s name=element/interval/1_day}1 Day (86400 Sec.){/s}'],
[172800, '{s name=element/interval/2_days}2 Days (172800 Sec.){/s}'],
[604800, '{s name=element/interval/1_week}1 Week (604800 Sec.){/s}']
],
initComponent:function () {
var me = this;
me.callParent(arguments);
}
});
| wlwwt/shopware | themes/Backend/ExtJs/backend/base/component/element/interval.js | JavaScript | agpl-3.0 | 2,522 |
define([
'domReady',
'jquery',
'underscore',
'gettext',
'common/js/components/views/feedback_notification',
'common/js/components/views/feedback_prompt',
'js/utils/date_utils',
'js/utils/module',
'js/utils/handle_iframe_binding',
'edx-ui-toolkit/js/dropdown-menu/dropdown-menu-view',
'jquery.ui',
'jquery.leanModal',
'jquery.form',
'jquery.smoothScroll'
],
function(
domReady,
$,
_,
gettext,
NotificationView,
PromptView,
DateUtils,
ModuleUtils,
IframeUtils,
DropdownMenuView
) {
'use strict';
var $body;
function smoothScrollLink(e) {
(e).preventDefault();
$.smoothScroll({
offset: -200,
easing: 'swing',
speed: 1000,
scrollElement: null,
scrollTarget: $(this).attr('href')
});
}
function hideNotification(e) {
(e).preventDefault();
$(this)
.closest('.wrapper-notification')
.removeClass('is-shown')
.addClass('is-hiding')
.attr('aria-hidden', 'true');
}
function hideAlert(e) {
(e).preventDefault();
$(this).closest('.wrapper-alert').removeClass('is-shown');
}
domReady(function() {
var dropdownMenuView;
$body = $('body');
$body.on('click', '.embeddable-xml-input', function() {
$(this).select();
});
$body.addClass('js');
// alerts/notifications - manual close
$('.action-alert-close, .alert.has-actions .nav-actions a').bind('click', hideAlert);
$('.action-notification-close').bind('click', hideNotification);
// nav - dropdown related
$body.click(function() {
$('.nav-dd .nav-item .wrapper-nav-sub').removeClass('is-shown');
$('.nav-dd .nav-item .title').removeClass('is-selected');
});
$('.nav-dd .nav-item, .filterable-column .nav-item').click(function(e) {
var $subnav = $(this).find('.wrapper-nav-sub'),
$title = $(this).find('.title');
if ($subnav.hasClass('is-shown')) {
$subnav.removeClass('is-shown');
$title.removeClass('is-selected');
} else {
$('.nav-dd .nav-item .title').removeClass('is-selected');
$('.nav-dd .nav-item .wrapper-nav-sub').removeClass('is-shown');
$title.addClass('is-selected');
$subnav.addClass('is-shown');
// if propagation is not stopped, the event will bubble up to the
// body element, which will close the dropdown.
e.stopPropagation();
}
});
// general link management - new window/tab
$('a[rel="external"]:not([title])')
.attr('title', gettext('This link will open in a new browser window/tab'));
$('a[rel="external"]').attr('target', '_blank');
// general link management - lean modal window
$('a[rel="modal"]').attr('title', gettext('This link will open in a modal window')).leanModal({
overlay: 0.50,
closeButton: '.action-modal-close'
});
$('.action-modal-close').click(function(e) {
(e).preventDefault();
});
// general link management - smooth scrolling page links
$('a[rel*="view"][href^="#"]').bind('click', smoothScrollLink);
IframeUtils.iframeBinding();
// disable ajax caching in IE so that backbone fetches work
if ($.browser.msie) {
$.ajaxSetup({cache: false});
}
// Initiate the edx tool kit dropdown menu
if ($('.js-header-user-menu').length) {
dropdownMenuView = new DropdownMenuView({
el: '.js-header-user-menu'
});
dropdownMenuView.postRender();
}
window.studioNavMenuActive = true;
});
}); // end require()
| BehavioralInsightsTeam/edx-platform | cms/static/js/base.js | JavaScript | agpl-3.0 | 4,363 |
'use strict';
var ArrayIterator = require('es6-iterator/array');
module.exports = function () { return new ArrayIterator(this, 'value'); };
| Ramanujakalyan/Inherit | ui/node_modules/gulp-minify-html/node_modules/minimize/node_modules/cli-color/node_modules/es5-ext/array/#/values/shim.js | JavaScript | unlicense | 145 |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch10/10.4/10.4.3/10.4.3-1-19gs.js
* @description Strict - checking 'this' from a global scope (indirect eval used within strict mode)
* @onlyStrict
*/
"use strict";
var my_eval = eval;
if (my_eval("this") !== fnGlobalObject()) {
throw "'this' had incorrect value!";
}
| hippich/typescript | tests/Fidelity/test262/suite/ch10/10.4/10.4.3/10.4.3-1-19gs.js | JavaScript | apache-2.0 | 679 |
(function () {
var print = (function () {
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var register = function (editor) {
editor.addCommand('mcePrint', function () {
editor.getWin().print();
});
};
var $_brqngvjljjgwecz3 = { register: register };
var register$1 = function (editor) {
editor.addButton('print', {
title: 'Print',
cmd: 'mcePrint'
});
editor.addMenuItem('print', {
text: 'Print',
cmd: 'mcePrint',
icon: 'print'
});
};
var $_3xztukjmjjgwecz4 = { register: register$1 };
global.add('print', function (editor) {
$_brqngvjljjgwecz3.register(editor);
$_3xztukjmjjgwecz4.register(editor);
editor.addShortcut('Meta+P', '', 'mcePrint');
});
function Plugin () {
}
return Plugin;
}());
})();
| glenrobson/SimpleAnnotationServer | src/main/webapp/mirador-2.6.1/plugins/print/plugin.js | JavaScript | apache-2.0 | 835 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var path_1 = require("path");
var virtual_file_utils_1 = require("./virtual-file-utils");
var HybridFileSystem = (function () {
function HybridFileSystem(fileCache) {
this.fileCache = fileCache;
this.filesStats = {};
this.directoryStats = {};
}
HybridFileSystem.prototype.setInputFileSystem = function (fs) {
this.inputFileSystem = fs;
};
HybridFileSystem.prototype.setOutputFileSystem = function (fs) {
this.outputFileSystem = fs;
};
HybridFileSystem.prototype.setWriteToDisk = function (write) {
this.writeToDisk = write;
};
HybridFileSystem.prototype.isSync = function () {
return this.inputFileSystem.isSync();
};
HybridFileSystem.prototype.stat = function (path, callback) {
// first check the fileStats
var fileStat = this.filesStats[path];
if (fileStat) {
return callback(null, fileStat);
}
// then check the directory stats
var directoryStat = this.directoryStats[path];
if (directoryStat) {
return callback(null, directoryStat);
}
// fallback to list
return this.inputFileSystem.stat(path, callback);
};
HybridFileSystem.prototype.readdir = function (path, callback) {
return this.inputFileSystem.readdir(path, callback);
};
HybridFileSystem.prototype.readJson = function (path, callback) {
return this.inputFileSystem.readJson(path, callback);
};
HybridFileSystem.prototype.readlink = function (path, callback) {
return this.inputFileSystem.readlink(path, function (err, response) {
callback(err, response);
});
};
HybridFileSystem.prototype.purge = function (pathsToPurge) {
if (this.fileCache) {
for (var _i = 0, pathsToPurge_1 = pathsToPurge; _i < pathsToPurge_1.length; _i++) {
var path = pathsToPurge_1[_i];
this.fileCache.remove(path);
}
}
};
HybridFileSystem.prototype.readFile = function (path, callback) {
var file = this.fileCache.get(path);
if (file) {
callback(null, new Buffer(file.content));
return;
}
return this.inputFileSystem.readFile(path, callback);
};
HybridFileSystem.prototype.addVirtualFile = function (filePath, fileContent) {
this.fileCache.set(filePath, { path: filePath, content: fileContent });
var fileStats = new virtual_file_utils_1.VirtualFileStats(filePath, fileContent);
this.filesStats[filePath] = fileStats;
var directoryPath = path_1.dirname(filePath);
var directoryStats = new virtual_file_utils_1.VirtualDirStats(directoryPath);
this.directoryStats[directoryPath] = directoryStats;
};
HybridFileSystem.prototype.getFileContent = function (filePath) {
var file = this.fileCache.get(filePath);
if (file) {
return file.content;
}
return null;
};
HybridFileSystem.prototype.getDirectoryStats = function (path) {
return this.directoryStats[path];
};
HybridFileSystem.prototype.getSubDirs = function (directoryPath) {
return Object.keys(this.directoryStats)
.filter(function (filePath) { return path_1.dirname(filePath) === directoryPath; })
.map(function (filePath) { return path_1.basename(directoryPath); });
};
HybridFileSystem.prototype.getFileNamesInDirectory = function (directoryPath) {
return Object.keys(this.filesStats).filter(function (filePath) { return path_1.dirname(filePath) === directoryPath; }).map(function (filePath) { return path_1.basename(filePath); });
};
HybridFileSystem.prototype.getAllFileStats = function () {
return this.filesStats;
};
HybridFileSystem.prototype.getAllDirStats = function () {
return this.directoryStats;
};
HybridFileSystem.prototype.mkdirp = function (filePath, callback) {
if (this.writeToDisk) {
return this.outputFileSystem.mkdirp(filePath, callback);
}
callback();
};
HybridFileSystem.prototype.mkdir = function (filePath, callback) {
if (this.writeToDisk) {
return this.outputFileSystem.mkdir(filePath, callback);
}
callback();
};
HybridFileSystem.prototype.rmdir = function (filePath, callback) {
if (this.writeToDisk) {
return this.outputFileSystem.rmdir(filePath, callback);
}
callback();
};
HybridFileSystem.prototype.unlink = function (filePath, callback) {
if (this.writeToDisk) {
return this.outputFileSystem.unlink(filePath, callback);
}
callback();
};
HybridFileSystem.prototype.join = function (dirPath, fileName) {
return path_1.join(dirPath, fileName);
};
HybridFileSystem.prototype.writeFile = function (filePath, fileContent, callback) {
var stringContent = fileContent.toString();
this.addVirtualFile(filePath, stringContent);
if (this.writeToDisk) {
return this.outputFileSystem.writeFile(filePath, fileContent, callback);
}
callback();
};
return HybridFileSystem;
}());
exports.HybridFileSystem = HybridFileSystem;
| vivadaniele/spid-ionic-sdk | node_modules/@ionic/app-scripts/dist/util/hybrid-file-system.js | JavaScript | bsd-3-clause | 5,396 |
module.exports = function() {
return {
modulePrefix: 'some-cool-app',
EmberENV: {
asdflkmawejf: ';jlnu3yr23'
},
APP: {
autoboot: false
}
};
};
| mike-north/ember-cli | tests/fixtures/brocfile-tests/custom-ember-env/config/environment.js | JavaScript | mit | 180 |
const COLORS_ON = {
RESET: '\x1B[39m',
ANSWER: '\x1B[36m', // NYAN
SUCCESS: '\x1B[32m', // GREEN
QUESTION: '\x1B[1m', // BOLD
question: function (str) {
return this.QUESTION + str + '\x1B[22m'
},
success: function (str) {
return this.SUCCESS + str + this.RESET
}
}
const COLORS_OFF = {
RESET: '',
ANSWER: '',
SUCCESS: '',
QUESTION: '',
question: function (str) {
return str
},
success: function (str) {
return str
}
}
exports.ON = COLORS_ON
exports.OFF = COLORS_OFF
| ChromeDevTools/devtools-node-modules | third_party/node_modules/karma/lib/init/color_schemes.js | JavaScript | apache-2.0 | 516 |
/**
* 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.
*/
/**
* Returns a Deferred struct, which holds a pending promise and its associated
* resolve and reject functions.
*
* This is preferred instead of creating a Promise instance to extract the
* resolve/reject functions yourself:
*
* ```
* // Avoid doing
* let resolve;
* const promise = new Promise(res => {
* resolve = res;
* });
*
* // Good
* const deferred = new Deferred();
* const { promise, resolve } = deferred;
* ```
*
* @template T
*/
export class Deferred {
/**
* Creates an instance of Deferred.
*/
constructor() {
let resolve, reject;
/**
* @const {!Promise<T>}
*/
this.promise = new /*OK*/Promise((res, rej) => {
resolve = res;
reject = rej;
});
/**
* @const {function(T=)}
*/
this.resolve = resolve;
/**
* @const {function(*=)}
*/
this.reject = reject;
}
}
/**
* Creates a promise resolved to the return value of fn.
* If fn sync throws, it will cause the promise to reject.
*
* @param {function():T} fn
* @return {!Promise<T>}
* @template T
*/
export function tryResolve(fn) {
return new Promise(resolve => {
resolve(fn());
});
}
/**
* Returns a promise which resolves if a threshold amount of the given promises
* resolve, and rejects otherwise.
* @param {!Array<!Promise>} promises The array of promises to test.
* @param {number} count The number of promises that must resolve for the
* returned promise to resolve.
* @return {!Promise} A promise that resolves if any of the given promises
* resolve, and which rejects otherwise.
*/
export function some(promises, count = 1) {
return new Promise((resolve, reject) => {
count = Math.max(count, 0);
const extra = promises.length - count;
if (extra < 0) {
reject(new Error('not enough promises to resolve'));
}
if (promises.length == 0) {
resolve([]);
}
const values = [];
const reasons = [];
const onFulfilled = value => {
if (values.length < count) {
values.push(value);
}
if (values.length == count) {
resolve(values);
}
};
const onRejected = reason => {
if (reasons.length <= extra) {
reasons.push(reason);
}
if (reasons.length > extra) {
reject(reasons);
}
};
for (let i = 0; i < promises.length; i++) {
Promise.resolve(promises[i]).then(onFulfilled, onRejected);
}
});
}
/**
* Resolves with the result of the last promise added.
* @implements {IThenable}
*/
export class LastAddedResolver {
/**
* @param {!Array<!Promise>=} opt_promises
*/
constructor(opt_promises) {
let resolve_, reject_;
/** @private @const {!Promise} */
this.promise_ = new Promise((resolve, reject) => {
resolve_ = resolve;
reject_ = reject;
});
/** @private */
this.resolve_ = resolve_;
/** @private */
this.reject_ = reject_;
/** @private */
this.count_ = 0;
if (opt_promises) {
for (let i = 0; i < opt_promises.length; i++) {
this.add(opt_promises[i]);
}
}
}
/**
* Add a promise to possibly be resolved.
* @param {!Promise} promise
* @return {!Promise}
*/
add(promise) {
const countAtAdd = ++this.count_;
Promise.resolve(promise).then(result => {
if (this.count_ === countAtAdd) {
this.resolve_(result);
}
}, error => {
// Don't follow behavior of Promise.all and Promise.race error so that
// this will only reject when most recently added promise fails.
if (this.count_ === countAtAdd) {
this.reject_(error);
}
});
return this.promise_;
}
/** @override */
then(opt_resolve, opt_reject) {
return this.promise_.then(opt_resolve, opt_reject);
}
}
| koshka/amphtml | src/utils/promise.js | JavaScript | apache-2.0 | 4,424 |
/**
* jQuery EasyUI 1.5.1
*
* Copyright (c) 2009-2016 www.jeasyui.com. All rights reserved.
*
* Licensed under the freeware license: http://www.jeasyui.com/license_freeware.php
* To use it on other terms please contact us: info@jeasyui.com
*
*/
(function($){
function _1(_2){
var _3=$.data(_2,"pagination");
var _4=_3.options;
var bb=_3.bb={};
var _5=$(_2).addClass("pagination").html("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tr></tr></table>");
var tr=_5.find("tr");
var aa=$.extend([],_4.layout);
if(!_4.showPageList){
_6(aa,"list");
}
if(!_4.showRefresh){
_6(aa,"refresh");
}
if(aa[0]=="sep"){
aa.shift();
}
if(aa[aa.length-1]=="sep"){
aa.pop();
}
for(var _7=0;_7<aa.length;_7++){
var _8=aa[_7];
if(_8=="list"){
var ps=$("<select class=\"pagination-page-list\"></select>");
ps.bind("change",function(){
_4.pageSize=parseInt($(this).val());
_4.onChangePageSize.call(_2,_4.pageSize);
_10(_2,_4.pageNumber);
});
for(var i=0;i<_4.pageList.length;i++){
$("<option></option>").text(_4.pageList[i]).appendTo(ps);
}
$("<td></td>").append(ps).appendTo(tr);
}else{
if(_8=="sep"){
$("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr);
}else{
if(_8=="first"){
bb.first=_9("first");
}else{
if(_8=="prev"){
bb.prev=_9("prev");
}else{
if(_8=="next"){
bb.next=_9("next");
}else{
if(_8=="last"){
bb.last=_9("last");
}else{
if(_8=="manual"){
$("<span style=\"padding-left:6px;\"></span>").html(_4.beforePageText).appendTo(tr).wrap("<td></td>");
bb.num=$("<input class=\"pagination-num\" type=\"text\" value=\"1\" size=\"2\">").appendTo(tr).wrap("<td></td>");
bb.num.unbind(".pagination").bind("keydown.pagination",function(e){
if(e.keyCode==13){
var _a=parseInt($(this).val())||1;
_10(_2,_a);
return false;
}
});
bb.after=$("<span style=\"padding-right:6px;\"></span>").appendTo(tr).wrap("<td></td>");
}else{
if(_8=="refresh"){
bb.refresh=_9("refresh");
}else{
if(_8=="links"){
$("<td class=\"pagination-links\"></td>").appendTo(tr);
}
}
}
}
}
}
}
}
}
}
if(_4.buttons){
$("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr);
if($.isArray(_4.buttons)){
for(var i=0;i<_4.buttons.length;i++){
var _b=_4.buttons[i];
if(_b=="-"){
$("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr);
}else{
var td=$("<td></td>").appendTo(tr);
var a=$("<a href=\"javascript:;\"></a>").appendTo(td);
a[0].onclick=eval(_b.handler||function(){
});
a.linkbutton($.extend({},_b,{plain:true}));
}
}
}else{
var td=$("<td></td>").appendTo(tr);
$(_4.buttons).appendTo(td).show();
}
}
$("<div class=\"pagination-info\"></div>").appendTo(_5);
$("<div style=\"clear:both;\"></div>").appendTo(_5);
function _9(_c){
var _d=_4.nav[_c];
var a=$("<a href=\"javascript:;\"></a>").appendTo(tr);
a.wrap("<td></td>");
a.linkbutton({iconCls:_d.iconCls,plain:true}).unbind(".pagination").bind("click.pagination",function(){
_d.handler.call(_2);
});
return a;
};
function _6(aa,_e){
var _f=$.inArray(_e,aa);
if(_f>=0){
aa.splice(_f,1);
}
return aa;
};
};
function _10(_11,_12){
var _13=$.data(_11,"pagination").options;
_14(_11,{pageNumber:_12});
_13.onSelectPage.call(_11,_13.pageNumber,_13.pageSize);
};
function _14(_15,_16){
var _17=$.data(_15,"pagination");
var _18=_17.options;
var bb=_17.bb;
$.extend(_18,_16||{});
var ps=$(_15).find("select.pagination-page-list");
if(ps.length){
ps.val(_18.pageSize+"");
_18.pageSize=parseInt(ps.val());
}
var _19=Math.ceil(_18.total/_18.pageSize)||1;
if(_18.pageNumber<1){
_18.pageNumber=1;
}
if(_18.pageNumber>_19){
_18.pageNumber=_19;
}
if(_18.total==0){
_18.pageNumber=0;
_19=0;
}
if(bb.num){
bb.num.val(_18.pageNumber);
}
if(bb.after){
bb.after.html(_18.afterPageText.replace(/{pages}/,_19));
}
var td=$(_15).find("td.pagination-links");
if(td.length){
td.empty();
var _1a=_18.pageNumber-Math.floor(_18.links/2);
if(_1a<1){
_1a=1;
}
var _1b=_1a+_18.links-1;
if(_1b>_19){
_1b=_19;
}
_1a=_1b-_18.links+1;
if(_1a<1){
_1a=1;
}
for(var i=_1a;i<=_1b;i++){
var a=$("<a class=\"pagination-link\" href=\"javascript:;\"></a>").appendTo(td);
a.linkbutton({plain:true,text:i});
if(i==_18.pageNumber){
a.linkbutton("select");
}else{
a.unbind(".pagination").bind("click.pagination",{pageNumber:i},function(e){
_10(_15,e.data.pageNumber);
});
}
}
}
var _1c=_18.displayMsg;
_1c=_1c.replace(/{from}/,_18.total==0?0:_18.pageSize*(_18.pageNumber-1)+1);
_1c=_1c.replace(/{to}/,Math.min(_18.pageSize*(_18.pageNumber),_18.total));
_1c=_1c.replace(/{total}/,_18.total);
$(_15).find("div.pagination-info").html(_1c);
if(bb.first){
bb.first.linkbutton({disabled:((!_18.total)||_18.pageNumber==1)});
}
if(bb.prev){
bb.prev.linkbutton({disabled:((!_18.total)||_18.pageNumber==1)});
}
if(bb.next){
bb.next.linkbutton({disabled:(_18.pageNumber==_19)});
}
if(bb.last){
bb.last.linkbutton({disabled:(_18.pageNumber==_19)});
}
_1d(_15,_18.loading);
};
function _1d(_1e,_1f){
var _20=$.data(_1e,"pagination");
var _21=_20.options;
_21.loading=_1f;
if(_21.showRefresh&&_20.bb.refresh){
_20.bb.refresh.linkbutton({iconCls:(_21.loading?"pagination-loading":"pagination-load")});
}
};
$.fn.pagination=function(_22,_23){
if(typeof _22=="string"){
return $.fn.pagination.methods[_22](this,_23);
}
_22=_22||{};
return this.each(function(){
var _24;
var _25=$.data(this,"pagination");
if(_25){
_24=$.extend(_25.options,_22);
}else{
_24=$.extend({},$.fn.pagination.defaults,$.fn.pagination.parseOptions(this),_22);
$.data(this,"pagination",{options:_24});
}
_1(this);
_14(this);
});
};
$.fn.pagination.methods={options:function(jq){
return $.data(jq[0],"pagination").options;
},loading:function(jq){
return jq.each(function(){
_1d(this,true);
});
},loaded:function(jq){
return jq.each(function(){
_1d(this,false);
});
},refresh:function(jq,_26){
return jq.each(function(){
_14(this,_26);
});
},select:function(jq,_27){
return jq.each(function(){
_10(this,_27);
});
}};
$.fn.pagination.parseOptions=function(_28){
var t=$(_28);
return $.extend({},$.parser.parseOptions(_28,[{total:"number",pageSize:"number",pageNumber:"number",links:"number"},{loading:"boolean",showPageList:"boolean",showRefresh:"boolean"}]),{pageList:(t.attr("pageList")?eval(t.attr("pageList")):undefined)});
};
$.fn.pagination.defaults={total:1,pageSize:10,pageNumber:1,pageList:[10,20,30,50],loading:false,buttons:null,showPageList:true,showRefresh:true,links:10,layout:["list","sep","first","prev","sep","manual","sep","next","last","sep","refresh"],onSelectPage:function(_29,_2a){
},onBeforeRefresh:function(_2b,_2c){
},onRefresh:function(_2d,_2e){
},onChangePageSize:function(_2f){
},beforePageText:"Page",afterPageText:"of {pages}",displayMsg:"Displaying {from} to {to} of {total} items",nav:{first:{iconCls:"pagination-first",handler:function(){
var _30=$(this).pagination("options");
if(_30.pageNumber>1){
$(this).pagination("select",1);
}
}},prev:{iconCls:"pagination-prev",handler:function(){
var _31=$(this).pagination("options");
if(_31.pageNumber>1){
$(this).pagination("select",_31.pageNumber-1);
}
}},next:{iconCls:"pagination-next",handler:function(){
var _32=$(this).pagination("options");
var _33=Math.ceil(_32.total/_32.pageSize);
if(_32.pageNumber<_33){
$(this).pagination("select",_32.pageNumber+1);
}
}},last:{iconCls:"pagination-last",handler:function(){
var _34=$(this).pagination("options");
var _35=Math.ceil(_34.total/_34.pageSize);
if(_34.pageNumber<_35){
$(this).pagination("select",_35);
}
}},refresh:{iconCls:"pagination-refresh",handler:function(){
var _36=$(this).pagination("options");
if(_36.onBeforeRefresh.call(this,_36.pageNumber,_36.pageSize)!=false){
$(this).pagination("select",_36.pageNumber);
_36.onRefresh.call(this,_36.pageNumber,_36.pageSize);
}
}}}};
})(jQuery);
| uoi00/basic | web/public/plugins/jquery.pagination.js | JavaScript | bsd-3-clause | 7,613 |