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 |
|---|---|---|---|---|---|
var hotspots = (function () {
var exports = {};
exports.show = function (hotspot_list) {
$('.hotspot').hide();
for (var i = 0; i < hotspot_list.length; i += 1) {
$("#hotspot_".concat(hotspot_list[i])).show();
}
};
exports.initialize = function () {
exports.show(page_params.hotspots);
};
function mark_hotspot_as_read(hotspot) {
channel.post({
url: '/json/users/me/hotspots',
data: {hotspot: JSON.stringify(hotspot)},
});
}
$(function () {
$("#hotspot_welcome").on('click', function (e) {
mark_hotspot_as_read("welcome");
e.preventDefault();
e.stopPropagation();
});
$("#hotspot_streams").on('click', function (e) {
mark_hotspot_as_read("streams");
e.preventDefault();
e.stopPropagation();
});
$("#hotspot_topics").on('click', function (e) {
mark_hotspot_as_read("topics");
e.preventDefault();
e.stopPropagation();
});
$("#hotspot_narrowing").on('click', function (e) {
mark_hotspot_as_read("narrowing");
e.preventDefault();
e.stopPropagation();
});
$("#hotspot_replying").on('click', function (e) {
mark_hotspot_as_read("replying");
e.preventDefault();
e.stopPropagation();
});
$("#hotspot_get_started").on('click', function (e) {
mark_hotspot_as_read("get_started");
e.preventDefault();
e.stopPropagation();
});
});
return exports;
}());
if (typeof module !== 'undefined') {
module.exports = hotspots;
}
| christi3k/zulip | static/js/hotspots.js | JavaScript | apache-2.0 | 1,556 |
/// 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 ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-195.js
* @description Object.defineProperty - 'writable' property in 'Attributes' is the Math object (8.10.5 step 6.b)
*/
function testcase() {
var obj = {};
Object.defineProperty(obj, "property", { writable: Math });
var beforeWrite = obj.hasOwnProperty("property");
obj.property = "isWritable";
var afterWrite = (obj.property === "isWritable");
return beforeWrite === true && afterWrite === true;
}
runTestCase(testcase);
| hippich/typescript | tests/Fidelity/test262/suite/ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-195.js | JavaScript | apache-2.0 | 935 |
/**
* Visual Blocks Editor
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Colour blocks for Blockly.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Blocks.colour');
goog.require('Blockly.Blocks');
Blockly.Blocks['colour_picker'] = {
// Colour picker.
init: function() {
this.setHelpUrl(Blockly.Msg.COLOUR_PICKER_HELPURL);
this.setColour(20);
this.appendDummyInput()
.appendField(new Blockly.FieldColour('#ff0000'), 'COLOUR');
this.setOutput(true, 'Colour');
this.setTooltip(Blockly.Msg.COLOUR_PICKER_TOOLTIP);
}
};
Blockly.Blocks['colour_random'] = {
// Random colour.
init: function() {
this.setHelpUrl(Blockly.Msg.COLOUR_RANDOM_HELPURL);
this.setColour(20);
this.appendDummyInput()
.appendField(Blockly.Msg.COLOUR_RANDOM_TITLE);
this.setOutput(true, 'Colour');
this.setTooltip(Blockly.Msg.COLOUR_RANDOM_TOOLTIP);
}
};
Blockly.Blocks['colour_rgb'] = {
// Compose a colour from RGB components.
init: function() {
this.setHelpUrl(Blockly.Msg.COLOUR_RGB_HELPURL);
this.setColour(20);
this.appendValueInput('RED')
.setCheck('Number')
.setAlign(Blockly.ALIGN_RIGHT)
.appendField(Blockly.Msg.COLOUR_RGB_TITLE)
.appendField(Blockly.Msg.COLOUR_RGB_RED);
this.appendValueInput('GREEN')
.setCheck('Number')
.setAlign(Blockly.ALIGN_RIGHT)
.appendField(Blockly.Msg.COLOUR_RGB_GREEN);
this.appendValueInput('BLUE')
.setCheck('Number')
.setAlign(Blockly.ALIGN_RIGHT)
.appendField(Blockly.Msg.COLOUR_RGB_BLUE);
this.setOutput(true, 'Colour');
this.setTooltip(Blockly.Msg.COLOUR_RGB_TOOLTIP);
}
};
Blockly.Blocks['colour_blend'] = {
// Blend two colours together.
init: function() {
this.setHelpUrl(Blockly.Msg.COLOUR_BLEND_HELPURL);
this.setColour(20);
this.appendValueInput('COLOUR1')
.setCheck('Colour')
.setAlign(Blockly.ALIGN_RIGHT)
.appendField(Blockly.Msg.COLOUR_BLEND_TITLE)
.appendField(Blockly.Msg.COLOUR_BLEND_COLOUR1);
this.appendValueInput('COLOUR2')
.setCheck('Colour')
.setAlign(Blockly.ALIGN_RIGHT)
.appendField(Blockly.Msg.COLOUR_BLEND_COLOUR2);
this.appendValueInput('RATIO')
.setCheck('Number')
.setAlign(Blockly.ALIGN_RIGHT)
.appendField(Blockly.Msg.COLOUR_BLEND_RATIO);
this.setOutput(true, 'Colour');
this.setTooltip(Blockly.Msg.COLOUR_BLEND_TOOLTIP);
}
};
| carloszuluaga/drl-blockly | blocks/colour.js | JavaScript | apache-2.0 | 3,106 |
/// 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 ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-141-1.js
* @description Object.defineProperty - 'Attributes' is a String object that uses Object's [[Get]] method to access the 'value' property of prototype object (8.10.5 step 5.a)
*/
function testcase() {
var obj = {};
try {
String.prototype.value = "String";
var strObj = new String("abc");
Object.defineProperty(obj, "property", strObj);
return obj.property === "String";
} finally {
delete String.prototype.value;
}
}
runTestCase(testcase);
| hippich/typescript | tests/Fidelity/test262/suite/ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-141-1.js | JavaScript | apache-2.0 | 1,000 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: let P be the empty string if pattern is undefined
es5id: 15.10.4.1_A3_T2
description: RegExp is new RegExp(void 0)
---*/
var __re = new RegExp(void 0);
//CHECK#2
if (__re.multiline !== false) {
$ERROR('#2: __re = new RegExp(void 0); __re.multiline === false. Actual: ' + (__re.multiline));
}
//CHECK#3
if (__re.global !== false) {
$ERROR('#3: __re = new RegExp(void 0); __re.global === false. Actual: ' + (__re.global));
}
//CHECK#4
if (__re.ignoreCase !== false) {
$ERROR('#4: __re = new RegExp(void 0); __re.ignoreCase === false. Actual: ' + (__re.ignoreCase));
}
| sebastienros/jint | Jint.Tests.Test262/test/built-ins/RegExp/S15.10.4.1_A3_T2.js | JavaScript | bsd-2-clause | 721 |
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule RelayDefaultNetworkLayer
* @typechecks
* @flow
*/
'use strict';
import type RelayMutationRequest from 'RelayMutationRequest';
import type RelayQueryRequest from 'RelayQueryRequest';
const fetch = require('fetch');
const fetchWithRetries = require('fetchWithRetries');
import type {InitWithRetries} from 'fetchWithRetries';
type GraphQLError = {
message: string;
locations: Array<GraphQLErrorLocation>;
};
type GraphQLErrorLocation = {
column: number;
line: number;
};
class RelayDefaultNetworkLayer {
_uri: string;
_init: $FlowIssue; // InitWithRetries
constructor(uri: string, init?: ?InitWithRetries) {
this._uri = uri;
this._init = {...init};
// Bind instance methods to facilitate reuse when creating custom network
// layers.
var self: any = this;
self.sendMutation = this.sendMutation.bind(this);
self.sendQueries = this.sendQueries.bind(this);
self.supports = this.supports.bind(this);
}
sendMutation(request: RelayMutationRequest): Promise {
return this._sendMutation(request).then(
result => result.json()
).then(payload => {
if (payload.hasOwnProperty('errors')) {
var error = new Error(
'Server request for mutation `' + request.getDebugName() + '` ' +
'failed for the following reasons:\n\n' +
formatRequestErrors(request, payload.errors)
);
(error: any).source = payload;
request.reject(error);
} else {
request.resolve({response: payload.data});
}
}).catch(
error => request.reject(error)
);
}
sendQueries(requests: Array<RelayQueryRequest>): Promise {
return Promise.all(requests.map(request => (
this._sendQuery(request).then(
result => result.json()
).then(payload => {
if (payload.hasOwnProperty('errors')) {
var error = new Error(
'Server request for query `' + request.getDebugName() + '` ' +
'failed for the following reasons:\n\n' +
formatRequestErrors(request, payload.errors)
);
(error: any).source = payload;
request.reject(error);
} else if (!payload.hasOwnProperty('data')) {
request.reject(new Error(
'Server response was missing for query `' + request.getDebugName() +
'`.'
));
} else {
request.resolve({response: payload.data});
}
}).catch(
error => request.reject(error)
)
)));
}
supports(...options: Array<string>): boolean {
// Does not support the only defined option, "defer".
return false;
}
/**
* Sends a POST request with optional files.
*/
_sendMutation(request: RelayMutationRequest): Promise {
var init;
var files = request.getFiles();
if (files) {
if (!global.FormData) {
throw new Error('Uploading files without `FormData` not supported.');
}
var formData = new FormData();
formData.append('query', request.getQueryString());
formData.append('variables', JSON.stringify(request.getVariables()));
for (var filename in files) {
if (files.hasOwnProperty(filename)) {
formData.append(filename, files[filename]);
}
}
init = {
...this._init,
body: formData,
method: 'POST',
};
} else {
init = {
...this._init,
body: JSON.stringify({
query: request.getQueryString(),
variables: request.getVariables(),
}),
headers: {
...this._init.headers,
'Accept': '*/*',
'Content-Type': 'application/json',
},
method: 'POST',
};
}
return fetch(this._uri, init).then(throwOnServerError);
}
/**
* Sends a POST request and retries if the request fails or times out.
*/
_sendQuery(request: RelayQueryRequest): Promise {
return fetchWithRetries(this._uri, {
...this._init,
body: JSON.stringify({
query: request.getQueryString(),
variables: request.getVariables(),
}),
headers: {
...this._init.headers,
'Accept': '*/*',
'Content-Type': 'application/json',
},
method: 'POST',
});
}
}
/**
* Rejects HTTP responses with a status code that is not >= 200 and < 300.
* This is done to follow the internal behavior of `fetchWithRetries`.
*/
function throwOnServerError(response: any): any {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
}
/**
* Formats an error response from GraphQL server request.
*/
function formatRequestErrors(
request: RelayMutationRequest | RelayQueryRequest,
errors: Array<GraphQLError>
): string {
var CONTEXT_BEFORE = 20;
var CONTEXT_LENGTH = 60;
var queryLines = request.getQueryString().split('\n');
return errors.map(({locations, message}, ii) => {
var prefix = (ii + 1) + '. ';
var indent = ' '.repeat(prefix.length);
//custom errors thrown in graphql-server may not have locations
var locationMessage = locations ?
('\n' + locations.map(({column, line}) => {
var queryLine = queryLines[line - 1];
var offset = Math.min(column - 1, CONTEXT_BEFORE);
return [
queryLine.substr(column - 1 - offset, CONTEXT_LENGTH),
' '.repeat(offset) + '^^^',
].map(messageLine => indent + messageLine).join('\n');
}).join('\n')) :
'';
return prefix + message + locationMessage;
}).join('\n');
}
module.exports = RelayDefaultNetworkLayer;
| michaelchum/relay | src/network-layer/default/RelayDefaultNetworkLayer.js | JavaScript | bsd-3-clause | 5,927 |
vde.App.controller('DataCtrl', function($scope, $rootScope, $http, timeline, Vis, vg, d3) {
$scope.dMdl = {
src: {},
formats: ['json', 'csv', 'tsv'],
parsings: ['string', 'number', 'boolean', 'date']
};
$scope.finishedLoading = function() {
var src = $scope.dMdl.src;
src.format.parse = {};
if(vg.isArray(src.values)) {
for(var k in src.values[0])
src.format.parse[k] = vg.isNumber(src.values[0][k]) ? 'number' : 'string';
}
$scope.dMdl.isLoading = false;
$scope.dMdl.hasLoaded = true;
$scope.dMdl.isObj = !vg.isArray(src.values);
$scope.dMdl.properties = vg.keys(src.values);
};
$scope.loadValues = function() {
var src = $scope.dMdl.src, req = vg.duplicate(src);
if($scope.dMdl.from == 'url') {
req.url = 'proxy.php?url=' + encodeURIComponent(req.url);
$scope.dMdl.isLoading = true;
var dataModel = vg.parse.data([req], function() {
$scope.$apply(function() {
src.values = dataModel.load[src.name];
$scope.finishedLoading();
});
});
} else {
var type = $scope.dMdl.src.format.type;
if(type == 'json') {
$scope.dMdl.src.values = JSON.parse($scope.dMdl.values);
$scope.finishedLoading();
}
else {
$scope.dMdl.src.values = d3[type].parse($scope.dMdl.values);
$scope.finishedLoading();
}
}
};
$scope.add = function() {
var src = $scope.dMdl.src;
for(var p in src.format.parse)
if(src.format.parse[p] == 'string') delete src.format.parse[p];
Vis._data[src.name] = vg.duplicate(src);
delete Vis._data[src.name].$$hashKey; // AngularJS pollution
$rootScope.activePipeline.source = src.name;
$scope.dMdl.src = {};
$rootScope.newData = false;
timeline.save();
};
$scope.cancel = function() {
$rootScope.newData = false;
$scope.dMdl.src = {};
$scope.dMdl.isLoading = false;
$scope.dMdl.hasLoaded = false;
};
}); | jasongrout/lyra | src/js/app/ctrls/data.js | JavaScript | bsd-3-clause | 1,986 |
// Copyright 2020 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.
cr.define('cellular_setup', function() {
/** @implements {ash.cellularSetup.mojom.ESimProfile} */
class FakeProfile {
constructor(eid, iccid, fakeEuicc) {
this.properties = {
eid,
iccid,
activationCode: 'activation-code-' + iccid,
name: {
data: this.stringToCharCodeArray_('profile' + iccid),
},
nickname: {
data: this.stringToCharCodeArray_('profile' + iccid),
},
serviceProvider: {
data: this.stringToCharCodeArray_('provider' + iccid),
},
state: ash.cellularSetup.mojom.ProfileState.kPending,
};
this.deferGetProperties_ = false;
this.deferredGetPropertiesPromises_ = [];
this.fakeEuicc_ = fakeEuicc;
}
/**
* @override
* @return {!Promise<{properties:
* ash.cellularSetup.mojom.ESimProfileProperties},}>}
*/
getProperties() {
if (this.deferGetProperties_) {
const deferred = this.deferredPromise_();
this.deferredGetPropertiesPromises_.push(deferred);
return deferred.promise;
} else {
return Promise.resolve({
properties: this.properties,
});
}
}
/**
* @param {boolean} defer
*/
setDeferGetProperties(defer) {
this.deferGetProperties_ = defer;
}
resolveLastGetPropertiesPromise() {
if (!this.deferredGetPropertiesPromises_.length) {
return;
}
const deferred = this.deferredGetPropertiesPromises_.pop();
deferred.resolve({properties: this.properties});
}
/**
* @override
* @param {string} confirmationCode
* @return {!Promise<{result:
* ash.cellularSetup.mojom.ProfileInstallResult},}>}
*/
installProfile(confirmationCode) {
if (!this.profileInstallResult_ ||
this.profileInstallResult_ ===
ash.cellularSetup.mojom.ProfileInstallResult.kSuccess) {
this.properties.state = ash.cellularSetup.mojom.ProfileState.kActive;
}
this.fakeEuicc_.notifyProfileChangedForTest(this);
this.fakeEuicc_.notifyProfileListChangedForTest();
// Simulate a delay in response. This is neccessary because a few tests
// require UI to be in installing state.
return new Promise(
resolve => setTimeout(
() => resolve({
result: this.profileInstallResult_ ?
this.profileInstallResult_ :
ash.cellularSetup.mojom.ProfileInstallResult.kSuccess
}),
0));
}
/**
* @param {ash.cellularSetup.mojom.ProfileInstallResult} result
*/
setProfileInstallResultForTest(result) {
this.profileInstallResult_ = result;
}
/**
* @param {ash.cellularSetup.mojom.ESimOperationResult} result
*/
setEsimOperationResultForTest(result) {
this.esimOperationResult_ = result;
}
/**
* @param {string} string
* @private
*/
stringToCharCodeArray_(string) {
const res = [];
for (let i = 0; i < string.length; i++) {
res.push(string.charCodeAt(i));
}
return res;
}
/**
* @return {Object}
* @private
*/
deferredPromise_() {
let deferred = {};
let promise = new Promise(function(resolve, reject) {
deferred.resolve = resolve;
deferred.reject = reject;
});
deferred.promise = promise;
return deferred;
}
/**
* @override
* @param {?mojoBase.mojom.String16} nickname
* @return {!Promise<{result:
* ash.cellularSetup.mojom.ESimOperationResult},}>}
*/
setProfileNickname(nickname) {
if (!this.esimOperationResult_ ||
this.esimOperationResult_ ===
ash.cellularSetup.mojom.ESimOperationResult.kSuccess) {
this.properties.nickname = nickname;
}
this.deferredSetProfileNicknamePromise_ = this.deferredPromise_();
return this.deferredSetProfileNicknamePromise_.promise;
}
/** @private */
resolveSetProfileNicknamePromise_() {
this.deferredSetProfileNicknamePromise_.resolve({
result: this.esimOperationResult_ ?
this.esimOperationResult_ :
ash.cellularSetup.mojom.ESimOperationResult.kSuccess
});
}
/** @override */
uninstallProfile() {
this.fakeEuicc_.notifyProfileChangedForTest(this);
this.defferedUninstallProfilePromise_ = this.deferredPromise_();
return this.defferedUninstallProfilePromise_.promise;
}
/** @return {Promise<void>} */
async resolveUninstallProfilePromise() {
if (!this.esimOperationResult_ ||
this.esimOperationResult_ ===
ash.cellularSetup.mojom.ESimOperationResult.kSuccess) {
const removeProfileResult =
await this.fakeEuicc_.removeProfileForTest(this.properties.iccid);
this.defferedUninstallProfilePromise_.resolve(removeProfileResult);
return;
}
this.defferedUninstallProfilePromise_.resolve({
result: this.esimOperationResult_ ?
this.esimOperationResult_ :
ash.cellularSetup.mojom.ESimOperationResult.kSuccess
});
}
}
/** @implements {ash.cellularSetup.mojom.Euicc} */
class FakeEuicc {
constructor(eid, numProfiles, fakeESimManager) {
this.fakeESimManager_ = fakeESimManager;
this.properties = {eid};
this.profiles_ = [];
for (let i = 0; i < numProfiles; i++) {
this.addProfile();
}
this.requestPendingProfilesResult_ =
ash.cellularSetup.mojom.ESimOperationResult.kSuccess;
}
/**
* @override
* @return {!Promise<{properties:
* ash.cellularSetup.mojom.EuiccProperties},}>}
*/
getProperties() {
return Promise.resolve({properties: this.properties});
}
/**
* @override
* @return {!Promise<{result:
* ash.cellularSetup.mojom.ESimOperationResult},}>}
*/
requestPendingProfiles() {
return Promise.resolve({
result: this.requestPendingProfilesResult_,
});
}
/**
* @override
* @return {!Promise<{profiles: Array<!ESimProfile>,}>}
*/
getProfileList() {
return Promise.resolve({
profiles: this.profiles_,
});
}
/**
* @override
* @return {!Promise<{qrCode: ash.cellularSetup.mojom.QRCode} | null>}
*/
getEidQRCode() {
if (this.eidQRCode_) {
return Promise.resolve({qrCode: this.eidQRCode_});
} else {
return Promise.resolve(null);
}
}
/**
* @override
* @param {string} activationCode
* @param {string} confirmationCode
* @return {!Promise<{result:
* ash.cellularSetup.mojom.ProfileInstallResult},}>}
*/
installProfileFromActivationCode(activationCode, confirmationCode) {
this.notifyProfileListChangedForTest();
return Promise.resolve({
result: this.profileInstallResult_ ?
this.profileInstallResult_ :
ash.cellularSetup.mojom.ProfileInstallResult.kSuccess,
});
}
/**
* @param {ash.cellularSetup.mojom.ESimOperationResult} result
*/
setRequestPendingProfilesResult(result) {
this.requestPendingProfilesResult_ = result;
}
/**
* @param {ash.cellularSetup.mojom.ProfileInstallResult} result
*/
setProfileInstallResultForTest(result) {
this.profileInstallResult_ = result;
}
/**
* @param {ash.cellularSetup.mojom.QRCode} qrcode
*/
setEidQRCodeForTest(qrcode) {
this.eidQRCode_ = qrcode;
}
/**
* @param {string} iccid
*/
async removeProfileForTest(iccid) {
const result = [];
let profileRemoved = false;
for (let profile of this.profiles_) {
const property = await profile.getProperties();
if (property.properties.iccid === iccid) {
profileRemoved = true;
continue;
}
result.push(profile);
}
this.profiles_ = result;
if (profileRemoved) {
this.notifyProfileListChangedForTest();
return {result: ash.cellularSetup.mojom.ESimOperationResult.kSuccess};
}
return {result: ash.cellularSetup.mojom.ESimOperationResult.kFailure};
}
/**
* @param {FakeProfile} profile
*/
notifyProfileChangedForTest(profile) {
this.fakeESimManager_.notifyProfileChangedForTest(profile);
}
notifyProfileListChangedForTest() {
this.fakeESimManager_.notifyProfileListChangedForTest(this);
}
/** @private */
addProfile() {
const iccid = this.profiles_.length + 1 + '';
this.profiles_.push(new FakeProfile(this.properties.eid, iccid, this));
}
}
/** @implements {ash.cellularSetup.mojom.ESimManagerInterface} */
/* #export */ class FakeESimManagerRemote {
constructor() {
this.euiccs_ = [];
this.observers_ = [];
}
/**
* @override
* @return {!Promise<{euiccs: !Array<!Euicc>,}>}
*/
getAvailableEuiccs() {
return Promise.resolve({
euiccs: this.euiccs_,
});
}
/**
* @param {number} numProfiles The number of profiles the EUICC has.
* @return {FakeEuicc} The euicc that was added.
*/
addEuiccForTest(numProfiles) {
const eid = this.euiccs_.length + 1 + '';
const euicc = new FakeEuicc(eid, numProfiles, this);
this.euiccs_.push(euicc);
this.notifyAvailableEuiccListChanged();
return euicc;
}
/**
* @param {!ash.cellularSetup.mojom.ESimManagerObserverInterface} observer
*/
addObserver(observer) {
this.observers_.push(observer);
}
notifyAvailableEuiccListChanged() {
for (const observer of this.observers_) {
observer.onAvailableEuiccListChanged();
}
}
/**
* @param {FakeEuicc} euicc
*/
notifyProfileListChangedForTest(euicc) {
for (const observer of this.observers_) {
observer.onProfileListChanged(euicc);
}
}
/**
* @param {FakeProfile} profile
*/
notifyProfileChangedForTest(profile) {
for (const observer of this.observers_) {
observer.onProfileChanged(profile);
}
}
}
// #cr_define_end
return {
FakeESimManagerRemote: FakeESimManagerRemote,
};
});
| chromium/chromium | chrome/test/data/webui/cr_components/chromeos/cellular_setup/fake_esim_manager_remote.js | JavaScript | bsd-3-clause | 10,555 |
// Generated by CoffeeScript 1.9.3
var Block, Layout, SpecialString, fn, i, len, object, prop, ref, terminalWidth;
Block = require('./layout/Block');
object = require('utila').object;
SpecialString = require('./layout/SpecialString');
terminalWidth = require('./tools').getCols();
module.exports = Layout = (function() {
var self;
self = Layout;
Layout._rootBlockDefaultConfig = {
linePrependor: {
options: {
amount: 0
}
},
lineAppendor: {
options: {
amount: 0
}
},
blockPrependor: {
options: {
amount: 0
}
},
blockAppendor: {
options: {
amount: 0
}
}
};
Layout._defaultConfig = {
terminalWidth: terminalWidth
};
function Layout(config, rootBlockConfig) {
var rootConfig;
if (config == null) {
config = {};
}
if (rootBlockConfig == null) {
rootBlockConfig = {};
}
this._written = [];
this._activeBlock = null;
this._config = object.append(self._defaultConfig, config);
rootConfig = object.append(self._rootBlockDefaultConfig, rootBlockConfig);
this._root = new Block(this, null, rootConfig, '__root');
this._root._open();
}
Layout.prototype.getRootBlock = function() {
return this._root;
};
Layout.prototype._append = function(text) {
return this._written.push(text);
};
Layout.prototype._appendLine = function(text) {
var s;
this._append(text);
s = SpecialString(text);
if (s.length < this._config.terminalWidth) {
this._append('<none>\n</none>');
}
return this;
};
Layout.prototype.get = function() {
this._ensureClosed();
if (this._written[this._written.length - 1] === '<none>\n</none>') {
this._written.pop();
}
return this._written.join("");
};
Layout.prototype._ensureClosed = function() {
if (this._activeBlock !== this._root) {
throw Error("Not all the blocks have been closed. Please call block.close() on all open blocks.");
}
if (this._root.isOpen()) {
this._root.close();
}
};
return Layout;
})();
ref = ['openBlock', 'write'];
fn = function() {
var method;
method = prop;
return Layout.prototype[method] = function() {
return this._root[method].apply(this._root, arguments);
};
};
for (i = 0, len = ref.length; i < len; i++) {
prop = ref[i];
fn();
}
| mo-norant/FinHeartBel | website/node_modules/renderkid/lib/Layout.js | JavaScript | gpl-3.0 | 2,395 |
;
(function() {
var app = angular.module('dashboardApp', [
'ngRoute',
'dashboard'
]);
var dashboard = angular.module('dashboard', []);
dashboard.run(function($rootScope, invocationUtils, stringUtils, api, urls) {
$rootScope.invocationUtils = invocationUtils;
$rootScope.stringUtils = stringUtils;
$rootScope._api = api;
$rootScope._urls = urls;
});
// this is a basis for some perf improvements
// for things that only needs to bind, well, once.
app.directive('bindOnce', function () {
return {
scope: true,
link: function($scope, $element) {
setTimeout(function () {
$scope.$destroy();
$element.removeClass('ng-binding ng-scope');
}, 0);
}
};
});
dashboard.factory('$exceptionHandler', function() {
return function(exception, cause) {
exception.message += ' (caused by "' + cause + '")';
console.log(["CATCH", exception, cause]);
throw exception;
};
});
app.config(['$routeProvider',
function ($routeProvider) {
var defaultHomePage = '/jobs'; //or /functions if not in Azure Web Sites
$routeProvider.
when('/', {
redirectTo: defaultHomePage
}).
when('/jobs', {
templateUrl: 'app/views/JobsList.html',
controller: 'JobsListController'
}).
when('/jobs/triggered/:jobName', {
templateUrl: 'app/views/TriggeredJob.html',
controller: 'TriggeredJobController'
}).
when('/jobs/continuous/:jobName', {
templateUrl: 'app/views/ContinuousJob.html',
controller: 'ContinuousJobController'
}).
when('/jobs/triggered/:jobName/runs/:runId', {
templateUrl: 'app/views/TriggeredJobRun.html',
controller: 'TriggeredJobRunController'
}).
when('/functions', {
templateUrl: 'app/views/FunctionsHome.html',
controller: 'FunctionsHomeController'
}).
when('/functions/definitions/:functionId', {
templateUrl: 'app/views/Function.html',
controller: 'FunctionController'
}).
when('/functions/invocations/:invocationId', {
templateUrl: 'app/views/FunctionInvocation.html',
controller: 'FunctionInvocationController'
}).
when('/about', {
templateUrl: 'app/views/AboutHome.html',
controller: 'AboutController'
}).
when('/diagnostics/indexerLogEntry/:entryId', {
templateUrl: 'app/views/IndexerLogEntry.html',
controller: 'IndexerLogEntryController'
}).
otherwise({
redirectTo: '/'
});
}]);
// simple paging support
app.filter('startFrom', function() {
return function(input, start) {
start = +start; // ensure int
return input.slice(start);
};
});
app.run(function ($rootScope) {
// Initialize errors / warnings
$rootScope.errors = [];
$rootScope.warnings = [];
});
})();
| brendankowitz/azure-webjobs-sdk | src/Dashboard/app/main.js | JavaScript | mit | 3,603 |
/**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize exports="amd" -o ./compat/`
* 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>
*/
define(['../internals/baseIndexOf', './sortedIndex'], function(baseIndexOf, sortedIndex) {
/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeMax = Math.max;
/**
* 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);
}
return indexOf;
});
| Solid-Interactive/masseuse-todomvc | app/vendor/lodash-amd/compat/arrays/indexOf.js | JavaScript | mit | 1,826 |
version https://git-lfs.github.com/spec/v1
oid sha256:44bac44ffbed21920407278ce3bc7678e40959a50ea1544d0cb61289445b900e
size 3181
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.3.0/event/event-key.js | JavaScript | mit | 129 |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
module.exports = {
id: 'windows',
bootstrap:function() {
var cordova = require('cordova'),
exec = require('cordova/exec'),
channel = cordova.require('cordova/channel'),
modulemapper = require('cordova/modulemapper');
modulemapper.clobbers('cordova/exec/proxy', 'cordova.commandProxy');
channel.onNativeReady.fire();
var onWinJSReady = function () {
var app = WinJS.Application;
var checkpointHandler = function checkpointHandler() {
cordova.fireDocumentEvent('pause',null,true);
};
var resumingHandler = function resumingHandler() {
cordova.fireDocumentEvent('resume',null,true);
};
app.addEventListener("checkpoint", checkpointHandler);
Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", resumingHandler, false);
app.start();
};
if (!window.WinJS) {
var scriptElem = document.createElement("script");
if (navigator.appVersion.indexOf('MSAppHost/3.0') !== -1) {
// Windows 10 UWP
scriptElem.src = '/WinJS/js/base.js';
} else if (navigator.appVersion.indexOf("Windows Phone 8.1;") !== -1) {
// windows phone 8.1 + Mobile IE 11
scriptElem.src = "//Microsoft.Phone.WinJS.2.1/js/base.js";
} else if (navigator.appVersion.indexOf("MSAppHost/2.0;") !== -1) {
// windows 8.1 + IE 11
scriptElem.src = "//Microsoft.WinJS.2.0/js/base.js";
}
scriptElem.addEventListener("load", onWinJSReady);
document.head.appendChild(scriptElem);
}
else {
onWinJSReady();
}
}
};
| jonathanmz34/ztransfert | node_modules/ionic/node_modules/cordova-js/src/legacy-exec/windows/platform.js | JavaScript | mit | 2,625 |
describe('zoom normal animation', function() {
var prefixes = {
'-webkit-transform': true,
'-moz-transform': true,
'-o-transform': true,
'transform': true
};
var transform;
beforeEach(module('ngAnimate'));
beforeEach(module('ngAnimateMock'));
beforeEach(module('fx.animations'));
it("should zoom-normal in", function(done) {
inject(function($animate, $compile, $document, $rootScope, $rootElement, $window, $timeout) {
var element = $compile('<div class="fx-zoom-normal">zoom-normal</div>')($rootScope);
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
$rootScope.$digest();
$animate.enabled(true);
$animate.enter(element, $rootElement);
$rootScope.$digest();
$timeout.flush();
$window.setTimeout(function(){
angular.forEach(prefixes, function(bool, prefix){
if(element.css(prefix)){
transform = prefix;
}
});
expect(element.css('opacity')).to.be('1');
expect(element.css(transform)).to.be('matrix(1, 0, 0, 1, 0, 0)');
done();
},500);
});
});
it('should zoom-normal out', function(done){
inject(function($animate, $compile, $document, $rootScope, $rootElement, $window, $timeout) {
var element = $compile('<div class="fx-zoom-normal">zoom-normal</div>')($rootScope);
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
$rootScope.$digest();
$animate.enabled(true);
$animate.leave(element);
$rootScope.$digest();
$timeout.flush();
$window.setTimeout(function(){
expect(element.css('opacity')).to.be('0');
done();
},500);
});
});
it('should zoom-normal move', function(done){
inject(function($animate, $compile, $document, $rootScope, $rootElement, $window, $timeout) {
var element = $compile('<div class="fx-zoom-normal">zoom-normal</div>')($rootScope);
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
$rootScope.$digest();
$animate.enabled(true);
$animate.move(element, $rootElement);
$rootScope.$digest();
$timeout.flush();
$window.setTimeout(function(){
angular.forEach(prefixes, function(bool, prefix){
if(element.css(prefix)){
transform = prefix;
}
});
expect(element.css('opacity')).to.be('1');
expect(element.css(transform)).to.be('matrix(1, 0, 0, 1, 0, 0)');
done();
},500);
});
});
xit('should zoom-normal removeClass', function(done){
inject(function($animate, $compile, $document, $rootScope, $rootElement, $window, $timeout) {
var element = $compile('<div class="fx-zoom-normal ng-hide">zoom-normal</div>')($rootScope);
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
$rootScope.$digest();
$animate.enabled(true);
$animate.removeClass(element, 'ng-hide');
$rootScope.$digest();
$window.setTimeout(function(){
angular.forEach(prefixes, function(bool, prefix){
if(element.css(prefix)){
transform = prefix;
}
});
expect(element.css('opacity')).to.be('1');
expect(element.css(transform)).to.be('matrix(1, 0, 0, 1, 0, 0)');
done();
},500);
});
});
xit('should zoom-normal addClass', function(done){
inject(function($animate, $compile, $document, $rootScope, $rootElement, $window, $timeout) {
var element = $compile('<div class="fx-zoom-normal">zoom-normal</div>')($rootScope);
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
$rootScope.$digest();
$animate.enabled(true);
$animate.addClass(element, 'ng-hide');
$rootScope.$digest();
$window.setTimeout(function(){
expect(element.css('opacity')).to.be('0');
done();
},500);
});
});
});
| ChrisPTsang/ngFx | specs/animations/zooms/zoom-normalSpec.js | JavaScript | mit | 4,066 |
/**
* Original shader from http://glsl.heroku.com/e#4122.10
* Tweaked, uniforms added and converted to Phaser/PIXI by Richard Davey
*/
Phaser.Filter.LightBeam = function (game) {
Phaser.Filter.call(this, game);
this.uniforms.alpha = { type: '1f', value: 1 };
this.uniforms.thickness = { type: '1f', value: 70.0 };
this.uniforms.speed = { type: '1f', value: 1.0 };
this.uniforms.red = { type: '1f', value: 2.0 };
this.uniforms.green = { type: '1f', value: 1.0 };
this.uniforms.blue = { type: '1f', value: 1.0 };
this.fragmentSrc = [
"precision mediump float;",
"uniform vec2 resolution;",
"uniform float time;",
"uniform float alpha;",
"uniform float thickness;",
"uniform float speed;",
"uniform float red;",
"uniform float green;",
"uniform float blue;",
"void main(void) {",
"vec2 uPos = (gl_FragCoord.xy / resolution.xy);",
"uPos.y -= 0.50;",
"float vertColor = 0.0;",
"for (float i = 0.0; i < 1.0; i++)",
"{",
"float t = time * (i + speed);",
"uPos.y += sin(uPos.x + t) * 0.2;",
"float fTemp = abs(1.0 / uPos.y / thickness);",
"vertColor += fTemp;",
"}",
"vec4 color = vec4(vertColor * red, vertColor * green, vertColor * blue, alpha);",
"gl_FragColor = color;",
"}"
];
};
Phaser.Filter.LightBeam.prototype = Object.create(Phaser.Filter.prototype);
Phaser.Filter.LightBeam.prototype.constructor = Phaser.Filter.LightBeam;
Phaser.Filter.LightBeam.prototype.init = function (width, height) {
this.setResolution(width, height);
};
Object.defineProperty(Phaser.Filter.LightBeam.prototype, 'alpha', {
get: function() {
return this.uniforms.alpha.value;
},
set: function(value) {
this.uniforms.alpha.value = value;
}
});
Object.defineProperty(Phaser.Filter.LightBeam.prototype, 'red', {
get: function() {
return this.uniforms.red.value;
},
set: function(value) {
this.uniforms.red.value = value;
}
});
Object.defineProperty(Phaser.Filter.LightBeam.prototype, 'green', {
get: function() {
return this.uniforms.green.value;
},
set: function(value) {
this.uniforms.green.value = value;
}
});
Object.defineProperty(Phaser.Filter.LightBeam.prototype, 'blue', {
get: function() {
return this.uniforms.blue.value;
},
set: function(value) {
this.uniforms.blue.value = value;
}
});
Object.defineProperty(Phaser.Filter.LightBeam.prototype, 'thickness', {
get: function() {
return this.uniforms.thickness.value;
},
set: function(value) {
this.uniforms.thickness.value = value;
}
});
Object.defineProperty(Phaser.Filter.LightBeam.prototype, 'speed', {
get: function() {
return this.uniforms.speed.value;
},
set: function(value) {
this.uniforms.speed.value = value;
}
});
| ottohernandezgarzon/tanks-colored-of-war | programar/node_modules/phaser-ce/filters/LightBeam.js | JavaScript | mit | 3,239 |
/**
@ngdoc directive
@name umbraco.directives.directive:umbIcon
@restrict E
@scope
@description
Use this directive to show an render an umbraco backoffice svg icon. All svg icons used by this directive should use the following naming convention to keep things consistent: icon-[name of icon]. For example <pre>icon-alert.svg</pre>
<h3>Markup example</h3>
Simple icon
<pre>
<umb-icon icon="icon-alert"></umb-icon>
</pre>
Icon with additional attribute. It can be treated like any other dom element
<pre>
<umb-icon icon="icon-alert" class="another-class"></umb-icon>
</pre>
@example
**/
(function () {
"use strict";
function UmbIconDirective(iconHelper) {
var directive = {
replace: true,
transclude: true,
templateUrl: "views/components/umb-icon.html",
scope: {
icon: "@",
svgString: "=?"
},
link: function (scope, element) {
if (scope.svgString === undefined && scope.svgString !== null && scope.icon !== undefined && scope.icon !== null) {
const observer = new IntersectionObserver(_lazyRequestIcon, {rootMargin: "100px"});
const iconEl = element[0];
observer.observe(iconEl);
// make sure to disconnect the observer when the scope is destroyed
scope.$on('$destroy', function () {
observer.disconnect();
});
}
scope.$watch("icon", function (newValue, oldValue) {
if (newValue && oldValue) {
var newicon = newValue.split(" ")[0];
var oldicon = oldValue.split(" ")[0];
if (newicon !== oldicon) {
_requestIcon(newicon);
}
}
});
function _lazyRequestIcon(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting === true) {
observer.disconnect();
var icon = scope.icon.split(" ")[0]; // Ensure that only the first part of the icon is used as sometimes the color is added too, e.g. see umbeditorheader.directive scope.openIconPicker
_requestIcon(icon);
}
});
}
function _requestIcon(icon) {
// Reset svg string before requesting new icon.
scope.svgString = null;
iconHelper.getIcon(icon)
.then(data => {
if (data && data.svgString) {
// Watch source SVG string
scope.svgString = data.svgString;
}
});
}
}
};
return directive;
}
angular.module("umbraco.directives").directive("umbIcon", UmbIconDirective);
})();
| umbraco/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/common/directives/components/umbicon.directive.js | JavaScript | mit | 3,145 |
module.exports={title:"Craft CMS",slug:"craftcms",svg:'<svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Craft CMS icon</title><path d="M21.474 0H2.526A2.516 2.516 0 0 0 0 2.526v18.948A2.516 2.516 0 0 0 2.526 24h18.948A2.534 2.534 0 0 0 24 21.474V2.526A2.516 2.516 0 0 0 21.474 0m-9.516 14.625c.786 0 1.628-.31 2.442-1.039l1.123 1.291c-1.18.955-2.527 1.488-3.874 1.488-2.667 0-4.35-1.769-3.958-4.267.393-2.498 2.667-4.266 5.334-4.266 1.29 0 2.498.505 3.34 1.431l-1.572 1.291c-.45-.59-1.207-.982-2.05-.982-1.6 0-2.834 1.039-3.087 2.526-.224 1.488.674 2.527 2.302 2.527"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://craftcms.com/brand-resources",hex:"E5422B",license:void 0}; | cdnjs/cdnjs | ajax/libs/simple-icons/4.16.0/craftcms.min.js | JavaScript | mit | 740 |
function ProductoUtil() {
var URL_BASE = "/productos";
this.agregar = function(p, callback) {
$.ajax(URL_BASE, {
type: "post",
data: JSON.stringify(p),
contentType: "application/json"
}).done(callback)
.fail(function() {
window.alert("Error al agregar");
});
};
this.modificar = function(p, callback) {
$.ajax(URL_BASE + "/" + p.id, {
type: "put",
data: JSON.stringify(p),
contentType: "application/json"
}).done(callback)
};
this.eliminar = function(id, callback) {
$.ajax(URL_BASE + "/" + id, {
type: "delete"
}).done(callback);
};
this.obtener = function(id, callback) {
$.ajax(URL_BASE + "/" + id, {
type: "get",
dataType: "json"
}).done(callback);
};
this.obtenerTodos = function(callback) {
$.ajax(URL_BASE, {
type: "get",
dataType: "json"
}).done(function(respuesta) {
callback(respuesta);
});
};
} | camposer/curso_angularjs | ejercicio3/public/javascripts/ProductoUtil.js | JavaScript | gpl-2.0 | 890 |
function $(id) { return document.getElementById(id); }
function retrieve_mbts() {
g.network.simple_request('FM_MBTS_RETRIEVE.authoritative',[ses(),g.mbts_id],
function(req) {
try {
g.mbts = req.getResultObject();
$('mbts_id').value = g.mbts.id();
$('mbts_xact_type').value = g.mbts.xact_type();
$('mbts_xact_start').value = util.date.formatted_date( g.mbts.xact_start(), '%{localized}' );
$('mbts_xact_finish').value = g.mbts.xact_finish() ? util.date.formatted_date( g.mbts.xact_finish(), '%{localized}' ) : '';
$('mbts_total_owed').value = g.mbts.total_owed() ? util.money.sanitize( g.mbts.total_owed() ) : '';
$('mbts_total_paid').value = g.mbts.total_paid() ? util.money.sanitize( g.mbts.total_paid() ) : '';
$('mbts_balance_owed').value = g.mbts.balance_owed() ? util.money.sanitize( g.mbts.balance_owed() ) : '';
$('xact_type').value = g.mbts.xact_type(); $('xact_type').disabled = true;
} catch(E) {
g.error.sdump('D_ERROR',E);
}
}
);
}
function retrieve_circ() {
JSAN.use('util.widgets');
function render_circ(r_circ) {
$('title_label').hidden = false;
$('checked_out_label').hidden = false;
$('due_label').hidden = false;
$('checked_in_label').hidden = false;
$('checked_out').value = r_circ.xact_start() ? util.date.formatted_date( r_circ.xact_start(), '%{localized}' ) : '';
$('checked_in').value = r_circ.checkin_time() ? util.date.formatted_date( r_circ.checkin_time(), '%{localized}' ) : '';
$('due').value = r_circ.due_date() ? util.date.formatted_date( r_circ.due_date(), '%{localized}' ) : '';
g.network.simple_request(
'MODS_SLIM_RECORD_RETRIEVE_VIA_COPY.authoritative',
[ typeof r_circ.target_copy() == 'object' ? r_circ.target_copy().id() : r_circ.target_copy() ],
function (rreq) {
var r_mvr = rreq.getResultObject();
if (instanceOf(r_mvr,mvr)) {
util.widgets.remove_children('title');
$('title').appendChild( document.createTextNode( r_mvr.title() ) );
} else {
g.network.simple_request(
'FM_ACP_RETRIEVE',
[ typeof r_circ.target_copy() == 'object' ? r_circ.target_copy().id() : r_circ.target_copy() ],
function (rrreq) {
var r_acp = rrreq.getResultObject();
if (instanceOf(r_acp,acp)) {
util.widgets.remove_children('title');
$('title').appendChild( document.createTextNode( r_acp.dummy_title() ) );
}
}
);
}
}
);
}
if (g.circ) {
render_circ(g.circ);
} else {
g.network.simple_request('FM_CIRC_RETRIEVE_VIA_ID', [ ses(), g.mbts_id ],
function (req) {
var r_circ = req.getResultObject();
if (instanceOf(r_circ,circ)) {
render_circ(r_circ);
}
}
);
}
}
function retrieve_patron() {
JSAN.use('patron.util');
g.patron_id = xul_param('patron_id');
g.au_obj = xul_param('patron');
if (! g.au_obj) {
g.au_obj = patron.util.retrieve_fleshed_au_via_id( ses(), g.patron_id );
}
if (g.au_obj) {
$('patron_name').setAttribute('value',
patron.util.format_name( g.au_obj ) + ' : ' + g.au_obj.card().barcode()
);
}
}
function patron_bill_init() {
try {
if (typeof JSAN == 'undefined') { throw( $("commonStrings").getString('common.jsan.missing') ); }
JSAN.errorLevel = "die"; // none, warn, or die
JSAN.addRepository('/xul/server/');
JSAN.use('util.error'); g.error = new util.error();
g.error.sdump('D_TRACE','my_init() for patron_display.xul');
g.OpenILS = {}; JSAN.use('OpenILS.data'); g.OpenILS.data = new OpenILS.data();
g.OpenILS.data.init({'via':'stash'});
JSAN.use('util.network'); g.network = new util.network();
JSAN.use('util.date');
JSAN.use('util.money');
JSAN.use('util.widgets');
JSAN.use('util.functional');
var override_default_billing_type = xul_param('override_default_billing_type');
var billing_list = util.functional.filter_list( g.OpenILS.data.list.cbt, function (x) { return x.id() >= 100 || x.id() == override_default_billing_type } );
var ml = util.widgets.make_menulist(
util.functional.map_list(
billing_list.sort( function(a,b) { if (a.name()>b.name()) return 1; if (a.name()<b.name()) return -1; return 0; } ), //g.OpenILS.data.list.billing_type.sort(),
function(obj) { return [ obj.name(), obj.id() ]; } //function(obj) { return [ obj, obj ]; }
),
override_default_billing_type || billing_list.sort( function(a,b) { if (a.name()>b.name()) return 1; if (a.name()<b.name()) return -1; return 0; } )[0].id()
);
ml.setAttribute('id','billing_type');
document.getElementById('menu_placeholder').appendChild(ml);
window.bill_wizard_event_listeners = new EventListenerList();
window.bill_wizard_event_listeners.add(ml,
'command',
function() {
if ( g.OpenILS.data.hash.cbt[ ml.value ] ) {
$('bill_amount').value = g.OpenILS.data.hash.cbt[ ml.value ].default_price();
}
},
false
);
retrieve_patron();
$('wizard_billing_location').setAttribute('value', g.OpenILS.data.hash.aou[ g.OpenILS.data.list.au[0].ws_ou() ].name() );
if ( g.OpenILS.data.hash.cbt[ ml.value ] ) {
$('bill_amount').value = g.OpenILS.data.hash.cbt[ ml.value ].default_price();
}
var override_default_price = xul_param('override_default_price');
if (override_default_price) {
$('bill_amount').value = override_default_price;
}
$('bill_amount').select(); $('bill_amount').focus();
g.circ = xul_param('circ');
if (xul_param('xact_id')) {
g.mbts_id = xul_param('xact_id');
$('summary').hidden = false;
retrieve_mbts();
retrieve_circ();
}
} catch(E) {
var err_msg = $("commonStrings").getFormattedString('common.exception', ['patron/bill_wizard.xul', E]);
try { g.error.sdump('D_ERROR',err_msg); } catch(E) { dump(err_msg); }
alert(err_msg);
}
}
function patron_bill_cleanup() {
try {
window.bill_wizard_event_listeners.removeAll();
} catch(E) {
var err_msg = $("commonStrings").getFormattedString('common.exception', ['patron/bill_wizard.xul', E]);
try { g.error.sdump('D_ERROR',err_msg); } catch(E) { dump(err_msg); }
alert(err_msg);
}
}
function patron_bill_finish() {
try {
var do_not_process_bill = xul_param('do_not_process_bill');
var xact_id = xul_param('xact_id');
if (do_not_process_bill) {
xulG.proceed = true;
xulG.cbt_id = $('billing_type').value;
xulG.amount = $('bill_amount').value;
xulG.note = $('bill_note').value;
} else {
if (!xact_id) {
var grocery = new mg();
grocery.isnew('1');
grocery.billing_location( g.OpenILS.data.list.au[0].ws_ou() );
grocery.usr( g.au_obj.id() );
grocery.note( $('bill_note').value );
xact_id = g.network.request(
api.FM_MG_CREATE.app,
api.FM_MG_CREATE.method,
[ ses(), grocery ]
);
}
if (typeof xact_id.ilsevent == 'undefined') {
JSAN.use('util.money');
var billing = new mb();
billing.isnew('1');
billing.note( $('bill_note').value );
billing.xact( xact_id );
billing.amount( util.money.sanitize( $('bill_amount').value ) );
billing.btype( $('billing_type').value );
billing.billing_type( g.OpenILS.data.hash.cbt[$('billing_type').value].name() );
var mb_id = g.network.request(
api.FM_MB_CREATE.app,
api.FM_MB_CREATE.method,
[ ses(), billing ]
);
if (typeof mb_id.ilsevent != 'undefined') throw(mb_id);
//alert($('patronStrings').getString('staff.patron.bill_wizard.patron_bill_finish.billing_added'));
xulG.mb_id = mb_id;
xulG.xact_id = xact_id;
} else {
throw(xact_id);
}
}
} catch(E) {
g.error.standard_unexpected_error_alert('bill_wizard',E);
}
}
| kidaa/Evergreen | Open-ILS/xul/staff_client/server/patron/bill_wizard.js | JavaScript | gpl-2.0 | 9,261 |
'use strict';
var _ = require('lodash');
var Request = function(opts) {
opts = opts || {};
this.method = opts.method || this.ANY;
this.url = opts.url || this.ANY;
this.auth = opts.auth || this.ANY;
this.params = opts.params || this.ANY;
this.data = opts.data || this.ANY;
this.headers = opts.headers || this.ANY;
};
Request.prototype.ANY = '*';
Request.prototype.attributeEqual = function(lhs, rhs) {
if (lhs === this.ANY || rhs === this.ANY) {
return true;
}
lhs = lhs || undefined;
rhs = rhs || undefined;
return _.isEqual(lhs, rhs);
};
Request.prototype.isEqual = function(other) {
return (this.attributeEqual(this.method, other.method) &&
this.attributeEqual(this.url, other.url) &&
this.attributeEqual(this.auth, other.auth) &&
this.attributeEqual(this.params, other.params) &&
this.attributeEqual(this.data, other.data) &&
this.attributeEqual(this.headers, other.headers));
};
Request.prototype.toString = function() {
var auth = '';
if (this.auth && this.auth !== this.ANY) {
auth = this.auth + ' ';
}
var params = '';
if (this.params && this.params !== this.ANY) {
params = '?' + _.join(_.chain(_.keys(this.params))
.map(function(key) { return key + '=' + this.params[key]; }.bind(this))
.value(), '&');
}
var data = '';
if (this.data && this.data !== this.ANY) {
if (this.method === 'GET') {
data = '\n -G';
}
data = data + '\n' + _.join(
_.map(this.data, function(value, key) {
return ' -d ' + key + '=' + value;
}), '\n');
}
var headers = '';
if (this.headers && this.headers !== this.ANY) {
headers = '\n' + _.join(
_.map(this.headers, function(value, key) {
return ' -H ' + key + '=' + value;
}), '\n');
}
return auth + this.method + ' ' + this.url + params + data + headers;
};
module.exports = Request;
| together-web-pj/together-web-pj | node_modules/twilio/lib/http/request.js | JavaScript | gpl-3.0 | 1,907 |
/* globals describe, beforeEach, $fixture, qq, assert, it, qqtest, helpme, purl */
if (qq.supportedFeatures.imagePreviews && qqtest.canDownloadFileAsBlob) {
describe("identify.js", function() {
"use strict";
function testPreviewability(expectedToBePreviewable, key, expectedMime, done) {
qqtest.downloadFileAsBlob(key, expectedMime).then(function(blob) {
new qq.Identify(blob, function() {}).isPreviewable().then(function(mime) {
!expectedToBePreviewable && assert.fail();
assert.equal(mime, expectedMime);
done();
}, function() {
expectedToBePreviewable && assert.fail();
assert.ok(true);
done();
});
}, function() {
assert.fail("Problem downloading test file");
});
}
it("classifies gif as previewable", function(done) {
testPreviewability(true, "drop-background.gif", "image/gif", done);
});
it("classifies jpeg as previewable", function(done) {
testPreviewability(true, "fearless.jpeg", "image/jpeg", done);
});
it("classifies bmp as previewable", function(done) {
testPreviewability(true, "g04.bmp", "image/bmp", done);
});
it("classifies png as previewable", function(done) {
testPreviewability(true, "not-available_l.png", "image/png", done);
});
it("classifies tiff as previewable", function(done) {
testPreviewability(qq.supportedFeatures.tiffPreviews, "sample.tif", "image/tiff", done);
});
it("marks a non-image as not previewable", function(done) {
testPreviewability(false, "simpletext.txt", null, done);
});
});
}
| TeamDeltaQuadrant/fine-uploader | test/unit/identify.js | JavaScript | gpl-3.0 | 1,855 |
/// Copyright (c) 2009 Microsoft Corporation
///
/// 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 Microsoft 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.
ES5Harness.registerTest({
id: "15.4.4.15-5-20",
path: "TestCases/chapter15/15.4/15.4.4/15.4.4.15/15.4.4.15-5-20.js",
description: "Array.prototype.lastIndexOf when value of 'fromIndex' which is a string containing a number with leading zeros",
test: function testcase() {
var targetObj = {};
return [0, true, targetObj, 3, false].lastIndexOf(targetObj, "0002.10") === 2 &&
[0, true, 3, targetObj, false].lastIndexOf(targetObj, "0002.10") === -1;
},
precondition: function prereq() {
return fnExists(Array.prototype.lastIndexOf);
}
});
| youfoh/webkit-efl | LayoutTests/ietestcenter/Javascript/TestCases/15.4.4.15-5-20.js | JavaScript | lgpl-2.1 | 2,205 |
/* Copyright JS Foundation and other contributors, http://js.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.
*/
// tests for ECMA-262 v6 12.4.3
var tests = [
// IdentifierReference
'var obj = {a : 10, ret : function(params) {return a++ = 42;}}',
'var obj = {a : 10, ret : function(params) {return a-- = 42;}}',
// NullLiteral
'var a = null; a++ = 42',
'var a = null; a-- = 42',
// BooleanLiteral
'var a = true; a++ = 42',
'var a = false; a++ = 42',
'var a = true; a-- = 42',
'var a = false; a-- = 42',
// DecimalLiteral
'var a = 5; a++ = 42',
'var a = 1.23e4; a++ = 42',
'var a = 5; a-- = 42',
'var a = 1.23e4; a-- = 42',
// BinaryIntegerLiteral
'var a = 0b11; a++ = 42',
'var a = 0B11; a++ = 42',
'var a = 0b11; a-- = 42',
'var a = 0B11; a-- = 42',
// OctalIntegerLiteral
'var a = 0o66; a++ = 42',
'var a = 0O66; a++ = 42',
'var a = 0o66; a-- = 42',
'var a = 0O66; a-- = 42',
// HexIntegerLiteral
'var a = 0xFF; a++ = 42',
'var a = 0xFF; a++ = 42',
'var a = 0xFF; a-- = 42',
'var a = 0xFF; a-- = 42',
// StringLiteral
'var a = "foo"; a++ = 42',
'var a = "\\n"; a++ = 42',
'var a = "\\uFFFF"; a++ = 42',
'var a ="\\u{F}"; a++ = 42',
'var a = "foo"; a-- = 42',
'var a = "\\n"; a-- = 42',
'var a = "\\uFFFF"; a-- = 42',
'var a ="\\u{F}"; a-- = 42',
// ArrayLiteral
'var a = []; a++ = 42',
'var a = [1,a=5]; a++ = 42',
'var a = []; a-- = 42',
'var a = [1,a=5]; a-- = 42',
// ObjectLiteral
'var a = {}; a++ = 42',
'var a = {"foo" : 5}; a++ = 42',
'var a = {5 : 5}; a++ = 42',
'var a = {a : 5}; a++ = 42',
'var a = {[key] : 5}; a++ = 42',
'var a = {func(){}}; a++ = 42',
'var a = {get(){}}; a++ = 42',
'var a = {set(prop){}}; a++ = 42',
'var a = {*func(){}}; a++ = 42',
'var a = {}; a-- = 42',
'var a = {"foo" : 5}; a-- = 42',
'var a = {5 : 5}; a-- = 42',
'var a = {a : 5}; a-- = 42',
'var a = {[key] : 5}; a-- = 42',
'var a = {func(){}}; a-- = 42',
'var a = {get(){}}; a-- = 42',
'var a = {set(prop){}}; a-- = 42',
'var a = {*func(){}}; a-- = 42',
// ClassExpression
'class a {}; a++ = 42',
'class a {}; class b extends a {}; b++ = 42',
'class a {function(){}}; a++ = 42',
'class a {}; a-- = 42',
'class a {}; class b extends a {}; b-- = 42',
'class a {function(){}}; a-- = 42',
// GeneratorExpression
'function *a (){}; a++ = 42',
'function *a (){}; a-- = 42',
// RegularExpressionLiteral
'var a = /(?:)/; a++ = 42',
'var a = /a/; a++ = 42',
'var a = /[a]/; a++ = 42',
'var a = /a/g; a++ = 42',
'var a = /(?:)/; a-- = 42',
'var a = /a/; a-- = 42',
'var a = /[a]/; a-- = 42',
'var a = /a/g; a-- = 42',
// TemplateLiteral
'var a = ``; a++ = 42',
'a = 5; var b = (`${a}`); b++ = 42',
'var a = `foo`; a++ = 42',
'var a = `\\uFFFF`; a++ = 42',
'var a = ``; a-- = 42',
'a = 5; var b = (`${a}`); b-- = 42',
'var a = `foo`; a-- = 42',
'var a = `\\uFFFF`; a-- = 42',
// MemberExpression
'var a = [1,2,3]; a[0]++ = 42',
'var a = {0:12}; a[0]++ = 42',
'var a = {"foo":12}; a.foo++ = 42',
'var a = {func: function(){}}; a.func++ = 42',
'var a = [1,2,3]; a[0]-- = 42',
'var a = {0:12}; a[0]-- = 42',
'var a = {"foo":12}; a.foo-- = 42',
'var a = {func: function(){}}; a.func-- = 42',
// SuperProperty
'class a {constructor() {Object.defineProperty(this, \'foo\', {configurable:true, writable:true, value:1}); }} ' +
'class b extends a {constructor() {super();} foo() {super.foo++ = 42;}}',
'class a {constructor() {Object.defineProperty(this, \'foo\', {configurable:true, writable:true, value:1}); }} ' +
'class b extends a {constructor() {super();} foo() {super.foo-- = 42;}}',
// NewExpression
'function a() {}; var b = new a(); b++ = 42',
'function a() {}; var b = new a(); b-- = 42',
'class g {constructor() {Object.defineProperty(this, \'foo\', {configurable:true, writable:true, value:1}); }}; ' +
'var a = new g(); a++ = 42',
'class g {constructor() {Object.defineProperty(this, \'foo\', {configurable:true, writable:true, value:1}); }}; ' +
'var a = new g(); a-- = 42',
'class a {}; var n = new a(); a++ = 42',
'class a {}; var n = new a(); a-- = 42',
// CallExpression
'function a(prop){return prop}; var b = a(12); b++ = 42',
'function a(prop){return prop}; var b = a(12); b-- = 42',
];
for (var i = 0; i < tests.length; i++)
{
try {
eval(tests[i]);
assert(false);
} catch (e) {
assert(e instanceof SyntaxError);
}
}
| jerryscript-project/jerryscript | tests/jerry/parser-postfix-exp-assign.js | JavaScript | apache-2.0 | 4,993 |
var helper = require("../../specRuntime/testHelper"),
Browser = require("zombie");
describe("A redirect page", () => {
helper.startServerBeforeAll(__filename, [
"./TemporaryRedirectPage",
"./TemporaryRedirectWithDocumentPage",
"./PermanentRedirectPage",
"./PermanentRedirectWithDocumentPage",
"./FinalPage",
]);
helper.stopServerAfterAll();
describe("redirects temporarily to the right page", () => {
helper.testWithDocument("/temporaryRedirect", (document) => {
expect(document.location.pathname).toMatch("/final");
});
});
describe("contains the correct HTML after temp redirect", () => {
helper.testWithDocument("/temporaryRedirect", (document) => {
expect(document.querySelector("#main").innerHTML).toMatch("FinalPage");
expect(document.querySelector("body").innerHTML).not.toMatch(/TemporaryRedirectPage/);
});
});
it("gets the right status code for a temp redirect", (done) => {
var browser = new Browser();
browser.silent = true;
browser.on("redirect", (request, response, redirectRequest) => { //eslint-disable-line no-unused-vars
expect(response.status).toBe(302);
done();
});
browser.visit(`http://localhost:${helper.getPort()}/temporaryRedirect`);
});
it("gets the right body for a temp redirect", done => {
(new Browser).on("redirect", (req, res) => {
res.text().then(text => {
expect(text).toMatch('<p>Found. Redirecting to <a href="/final">/final</a></p>');
expect(text).not.toMatch('TemporaryRedirectPage');
done();
});
})
.visit(`http://localhost:${helper.getPort()}/temporaryRedirect`);
});
it("gets the right body for a temp redirect with document", done => {
(new Browser).on("redirect", (req, res) => {
res.text().then(text => {
expect(text).not.toMatch('<p>Found. Redirecting to <a href="/final">/final</a></p>');
expect(text).toMatch('TemporaryRedirectWithDocumentPage');
done();
});
})
.visit(`http://localhost:${helper.getPort()}/temporaryRedirectWithDocument`);
});
describe("redirects temporarily to the right page with document", () => {
helper.testWithDocument("/temporaryRedirectWithDocument", (document) => {
expect(document.location.pathname).toMatch("/final");
});
});
describe("redirects permanently to the right page", () => {
helper.testWithDocument("/permanentRedirect", (document) => {
expect(document.location.pathname).toMatch("/final");
});
});
describe("contains the correct HTML after permanent redirect", () => {
helper.testWithDocument("/permanentRedirect", (document) => {
expect(document.querySelector("#main").innerHTML).toMatch("FinalPage");
expect(document.querySelector("body").innerHTML).not.toMatch(/PermanentRedirectPage/);
});
});
it("gets the right status code for a permanent redirect", (done) => {
var browser = new Browser();
browser.silent = true;
browser.on("redirect", (request, response, redirectRequest) => { //eslint-disable-line no-unused-vars
expect(response.status).toBe(301);
done();
});
browser.visit(`http://localhost:${helper.getPort()}/permanentRedirect`);
});
it("gets the right body for a permanent redirect", done => {
(new Browser).on("redirect", (req, res) => {
res.text().then(text => {
expect(text).toMatch('<p>Moved Permanently. Redirecting to <a href="/final">/final</a></p>');
expect(text).not.toMatch('PermanentRedirectPage');
done();
});
})
.visit(`http://localhost:${helper.getPort()}/permanentRedirect`);
});
it("gets the right body for a permanent redirect with document", done => {
(new Browser).on("redirect", (req, res) => {
res.text().then(text => {
expect(text).not.toMatch('<p>Moved Permanently. Redirecting to <a href="/final">/final</a></p>');
expect(text).toMatch('PermanentRedirectWithDocumentPage');
done();
});
})
.visit(`http://localhost:${helper.getPort()}/permanentRedirectWithDocument`);
});
describe("redirects permanently to the right page with document", () => {
helper.testWithDocument("/permanentRedirectWithDocument", (document) => {
expect(document.location.pathname).toMatch("/final");
});
});
});
describe("A forward page", () => {
helper.startServerBeforeAll(__filename, [
"./FinalPage",
"./ForwardPage",
]);
helper.stopServerAfterAll();
describe("does NOT change its URL", () => {
helper.testWithDocument("/forward", (document) => {
expect(document.location.pathname).toMatch("/forward");
});
});
describe("contains the correct HTML after forward", () => {
helper.testWithDocument("/forward", (document) => {
expect(document.querySelector("#main").innerHTML).toMatch("FinalPage");
expect(document.querySelector("body").innerHTML).not.toMatch(/ForwardPage/);
});
});
it ("gets a 200 status code and doesn't redirect", (done) => {
var browser = new Browser();
browser.silent = true;
browser.on("redirect", (request, response, redirectRequest) => { //eslint-disable-line no-unused-vars
fail("Forward page redirected when it shouldn't have.");
done();
});
browser.visit(`http://localhost:${helper.getPort()}/forward`).then(() => {
expect(browser.resources[0].response.status).toBe(200);
done();
});
});
});
| doug-wade/react-server | packages/react-server-integration-tests/src/__tests__/redirectForward/RedirectForwardSpec.js | JavaScript | apache-2.0 | 5,209 |
var app = require('app');
var BrowserWindow = require('browser-window');
var mainWindow = null;
app.on('ready', function() {
mainWindow = new BrowserWindow({width: 400, height: 360});
mainWindow.loadUrl('file://' + __dirname + '/manager.html');
});
| EdZava/electron-sample-apps | cookies/main.js | JavaScript | apache-2.0 | 255 |
/**
*
* Search for multiple elements on the page, starting from an element. The located
* elements will be returned as a WebElement JSON objects. The table below lists the
* locator strategies that each server should support. Elements should be returned in
* the order located in the DOM.
*
* @param {String} ID ID of a WebElement JSON object to route the command to
* @param {String} selector selector to query the elements
* @return {Object[]} A list of WebElement JSON objects for the located elements.
*
* @see https://w3c.github.io/webdriver/webdriver-spec.html#find-elements-from-element
* @type protocol
*
*/
import { ProtocolError } from '../utils/ErrorHandler'
import findStrategy from '../helpers/findElementStrategy'
export default function elementIdElements (id, selector) {
if (typeof id !== 'string' && typeof id !== 'number') {
throw new ProtocolError('number or type of arguments don\'t agree with elementIdElements protocol command')
}
let found = findStrategy(selector, true)
return this.requestHandler.create(`/session/:sessionId/element/${id}/elements`, {
using: found.using,
value: found.value
}).then((result) => {
result.selector = selector
/**
* W3C webdriver protocol has changed element identifier from `ELEMENT` to
* `element-6066-11e4-a52e-4f735466cecf`. Let's make sure both identifier
* are supported.
*/
result.value = result.value.map((elem) => {
const elemValue = elem.ELEMENT || elem['element-6066-11e4-a52e-4f735466cecf']
return {
ELEMENT: elemValue,
'element-6066-11e4-a52e-4f735466cecf': elemValue
}
})
return result
})
}
| isabela-angelo/scratch-tangible-blocks | scratch-blocks/node_modules/webdriverio/lib/protocol/elementIdElements.js | JavaScript | bsd-3-clause | 1,771 |
;
define('views/courses/CoursesView', ['appframework', 'mustache', 'controllers/Courses', 'i18n!nls/courses', 'routers/coursesrouter'],
(function ($, mustache, controller, courses, router) {
var courseTemplate, currentSearch;
var $coursesSearch, $courses;
var doInit = function (data) {
router.init();
$coursesSearch = $('#user-courses-search');
$courses = $('#user-courses');
controller.init(this);
require([
'text!../tpl/course-tpl.html'
], function (tpl) {
courseTemplate = tpl;
controller.updateMyCourses(data);
/*
if($('#afui').get(0).className === 'ios7'){
$('body').removeClass('moveDown');
setTimeout(function(){
$('body').addClass('moveDown');
}, 150);
}
*/
});
};
var doShowError = function (msg) {
if (msg) {
$.ui.popup(msg);
}
};
var doShowCourse = function (data) {
var html = mustache.to_html(courseTemplate, data);
$courses.html($courses.html() + html);
};
var doClearCourses = function () {
$courses.html('');
};
var onCourseSearch = function (evt) {
var filter = this.value;
if (currentSearch) {
clearTimeout(currentSearch);
}
currentSearch = setTimeout(function () {
$courses.find('li').each(function (i, e) {
var sel = $(e).find('div strong').text().toLowerCase().trim();
var query = filter.toLowerCase();
if (sel.indexOf(query) === -1) {
$(e).hide();
} else {
$(e).show();
}
});
}, 300);
};
var doInitCoursesInteraction = function (status) {
if (status) {
$courses.bind('tap', onCourseSelection);
$coursesSearch.bind('input', onCourseSearch);
} else {
$courses.unbind('tap', onCourseSelection);
$coursesSearch.unbind('input', onCourseSearch);
}
};
var doShowLoader = function (status, message) {
if (status) {
$.ui.showMask(message || courses.loading);
} else {
$.ui.hideMask();
}
};
var onCourseSelection = function (evt) {
evt.preventDefault();
var target = $(evt.target).parents('li');
var url = target.attr('data-url'),
idCourse = url.match(/course_id=([^&]*)/)[1],
thumb = target.find('img').css('background-image'),
name = target.find('strong').text(),
canAccess = target.attr('data-can'),
courseDescription = target.find('.detail-disclosure').html();
// if(canAccess != true)return;
thumb = /^url\((['"]?)(.*)\1\)$/.exec(thumb);
thumb = thumb ? thumb[2] : '';
localStorage.setItem('currentCourseName', name);
localStorage.setItem('currentCourseThumb', thumb);
localStorage.setItem('currentCourseDescription', courseDescription);
controller.getCourseDetails(idCourse);
};
return {
init: doInit,
showError: doShowError,
showCourse: doShowCourse,
clearCourses: doClearCourses,
showLoader: doShowLoader,
initCoursesInteraction: doInitCoursesInteraction
}
})); | wesley1001/mobile-1 | www/js/views/courses/CoursesView.js | JavaScript | bsd-3-clause | 2,939 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = timeoutsAsyncScript;
var _ErrorHandler = require('../utils/ErrorHandler');
var _depcrecationWarning = require('../helpers/depcrecationWarning');
var _depcrecationWarning2 = _interopRequireDefault(_depcrecationWarning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
*
* Set the amount of time, in milliseconds, that asynchronous scripts executed
* by /session/:sessionId/execute_async are permitted to run before they are
* aborted and a |Timeout| error is returned to the client.
*
* Deprecated! Please use the `timeouts` command instead.
*
* @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#sessionsessionidtimeoutsasync_script
*
* @param {Number} ms The amount of time, in milliseconds, that time-limited commands are permitted to run.
* @type protocol
* @deprecated
*
*/
function timeoutsAsyncScript(ms) {
/*!
* parameter check
*/
if (typeof ms !== 'number') {
throw new _ErrorHandler.ProtocolError('number or type of arguments don\'t agree with timeoutsAsyncScript protocol command');
}
(0, _depcrecationWarning2.default)('timeoutsAsyncScript');
return this.requestHandler.create('/session/:sessionId/timeouts/async_script', { ms: ms });
}
module.exports = exports['default']; | isabela-angelo/scratch-tangible-blocks | scratch-blocks/node_modules/webdriverio/build/lib/protocol/timeoutsAsyncScript.js | JavaScript | bsd-3-clause | 1,392 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { isBlank, isPresent, isPrimitive, isStrictStringMap } from './facade/lang';
import * as o from './output/output_ast';
export var MODULE_SUFFIX = '';
var CAMEL_CASE_REGEXP = /([A-Z])/g;
export function camelCaseToDashCase(input) {
return input.replace(CAMEL_CASE_REGEXP, function () {
var m = [];
for (var _i = 0; _i < arguments.length; _i++) {
m[_i - 0] = arguments[_i];
}
return '-' + m[1].toLowerCase();
});
}
export function splitAtColon(input, defaultValues) {
return _splitAt(input, ':', defaultValues);
}
export function splitAtPeriod(input, defaultValues) {
return _splitAt(input, '.', defaultValues);
}
function _splitAt(input, character, defaultValues) {
var characterIndex = input.indexOf(character);
if (characterIndex == -1)
return defaultValues;
return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()];
}
export function sanitizeIdentifier(name) {
return name.replace(/\W/g, '_');
}
export function visitValue(value, visitor, context) {
if (Array.isArray(value)) {
return visitor.visitArray(value, context);
}
if (isStrictStringMap(value)) {
return visitor.visitStringMap(value, context);
}
if (isBlank(value) || isPrimitive(value)) {
return visitor.visitPrimitive(value, context);
}
return visitor.visitOther(value, context);
}
export var ValueTransformer = (function () {
function ValueTransformer() {
}
ValueTransformer.prototype.visitArray = function (arr, context) {
var _this = this;
return arr.map(function (value) { return visitValue(value, _this, context); });
};
ValueTransformer.prototype.visitStringMap = function (map, context) {
var _this = this;
var result = {};
Object.keys(map).forEach(function (key) { result[key] = visitValue(map[key], _this, context); });
return result;
};
ValueTransformer.prototype.visitPrimitive = function (value, context) { return value; };
ValueTransformer.prototype.visitOther = function (value, context) { return value; };
return ValueTransformer;
}());
export function assetUrl(pkg, path, type) {
if (path === void 0) { path = null; }
if (type === void 0) { type = 'src'; }
if (path == null) {
return "asset:@angular/lib/" + pkg + "/index";
}
else {
return "asset:@angular/lib/" + pkg + "/src/" + path;
}
}
export function createDiTokenExpression(token) {
if (isPresent(token.value)) {
return o.literal(token.value);
}
else if (token.identifierIsInstance) {
return o.importExpr(token.identifier)
.instantiate([], o.importType(token.identifier, [], [o.TypeModifier.Const]));
}
else {
return o.importExpr(token.identifier);
}
}
export var SyncAsyncResult = (function () {
function SyncAsyncResult(syncResult, asyncResult) {
if (asyncResult === void 0) { asyncResult = null; }
this.syncResult = syncResult;
this.asyncResult = asyncResult;
if (!asyncResult) {
this.asyncResult = Promise.resolve(syncResult);
}
}
return SyncAsyncResult;
}());
//# sourceMappingURL=util.js.map | gabrieldamaso7/innocircle | node_modules/@angular/compiler/src/util.js | JavaScript | mit | 3,455 |
import { AudioEncoder } from './audioEncoder';
const getUserMedia = ((navigator) => {
if (navigator.mediaDevices) {
return navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
}
const legacyGetUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (legacyGetUserMedia) {
return (options) => new Promise((resolve, reject) => {
legacyGetUserMedia.call(navigator, options, resolve, reject);
});
}
})(window.navigator);
const AudioContext = window.AudioContext || window.webkitAudioContext;
class AudioRecorder {
isSupported() {
return Boolean(getUserMedia) && Boolean(AudioContext);
}
createAudioContext() {
if (this.audioContext) {
return;
}
this.audioContext = new AudioContext();
}
destroyAudioContext() {
if (!this.audioContext) {
return;
}
this.audioContext.close();
delete this.audioContext;
}
async createStream() {
if (this.stream) {
return;
}
this.stream = await getUserMedia({ audio: true });
}
destroyStream() {
if (!this.stream) {
return;
}
this.stream.getAudioTracks().forEach((track) => track.stop());
delete this.stream;
}
async createEncoder() {
if (this.encoder) {
return;
}
const input = this.audioContext.createMediaStreamSource(this.stream);
this.encoder = new AudioEncoder(input);
}
destroyEncoder() {
if (!this.encoder) {
return;
}
this.encoder.close();
delete this.encoder;
}
async start(cb) {
try {
await this.createAudioContext();
await this.createStream();
await this.createEncoder();
cb && cb.call(this, true);
} catch (error) {
console.error(error);
this.destroyEncoder();
this.destroyStream();
this.destroyAudioContext();
cb && cb.call(this, false);
}
}
stop(cb) {
this.encoder.on('encoded', cb);
this.encoder.close();
this.destroyEncoder();
this.destroyStream();
this.destroyAudioContext();
}
}
const instance = new AudioRecorder();
export { instance as AudioRecorder };
| Sing-Li/Rocket.Chat | app/ui/client/lib/recorderjs/audioRecorder.js | JavaScript | mit | 2,047 |
version https://git-lfs.github.com/spec/v1
oid sha256:1668f227ab9bbb326809d8430e0c9d1105688b38b177ab927f0528eb9593a652
size 7357
| yogeshsaroya/new-cdnjs | ajax/libs/dojo/1.8.9/touch.js.uncompressed.js | JavaScript | mit | 129 |
import mdDialog from './mdDialog.vue';
import mdDialogTitle from './mdDialogTitle.vue';
import mdDialogContent from './mdDialogContent.vue';
import mdDialogActions from './mdDialogActions.vue';
import mdDialogAlert from './presets/mdDialogAlert.vue';
import mdDialogConfirm from './presets/mdDialogConfirm.vue';
import mdDialogPrompt from './presets/mdDialogPrompt.vue';
import mdDialogTheme from './mdDialog.theme';
export default function install(Vue) {
Vue.component('md-dialog', mdDialog);
Vue.component('md-dialog-title', mdDialogTitle);
Vue.component('md-dialog-content', mdDialogContent);
Vue.component('md-dialog-actions', mdDialogActions);
/* Presets */
Vue.component('md-dialog-alert', mdDialogAlert);
Vue.component('md-dialog-confirm', mdDialogConfirm);
Vue.component('md-dialog-prompt', mdDialogPrompt);
Vue.material.styles.push(mdDialogTheme);
}
| jaceks-iRonin/vue-material-test | src/components/mdDialog/index.js | JavaScript | mit | 880 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S10.2.2_A1.1_T3;
* @section: 10.2.2;
* @assertion: The scope chain is initialised to contain the same objects,
* in the same order, as the calling context's scope chain;
* @description: eval within global execution context;
*/
var i;
var j;
str1 = '';
str2 = '';
this.x = 1;
this.y = 2;
for(i in this){
str1+=i;
}
eval('for(j in this){\nstr2+=j;\n}');
if(!(str1 === str2)){
$ERROR("#1: scope chain must contain same objects in the same order as the calling context");
}
| seraum/nectarjs | tests/ES3/Conformance/10_Execution_Contexts/10.2_Entering_An_Execution_Context/10.2.2_Eval_Code/S10.2.2_A1.1_T3.js | JavaScript | mit | 630 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S12.14_A2;
* @section: 12.14;
* @assertion: Throwing exception with "throw" and catching it with "try" statement;
* @description: Checking if execution of "catch" catches an exception thrown with "throw";
*/
// CHECK#1
try {
throw "catchme";
$ERROR('#1: throw "catchme" lead to throwing exception');
}
catch(e){}
// CHECK#2
var c2=0;
try{
try{
throw "exc";
$ERROR('#2.1: throw "exc" lead to throwing exception');
}finally{
c2=1;
}
}
catch(e){
if (c2!==1){
$ERROR('#2.2: "finally" block must be evaluated');
}
}
// CHECK#3
var c3=0;
try{
throw "exc";
$ERROR('#3.1: throw "exc" lead to throwing exception');
}
catch(err){
var x3=1;
}
finally{
c3=1;
}
if (x3!==1){
$ERROR('#3.2: "catch" block must be evaluated');
}
if (c3!==1){
$ERROR('#3.3: "finally" block must be evaluated');
}
| seraum/nectarjs | tests/ES3/Conformance/12_Statement/12.14_The_try_Statement/S12.14_A2.js | JavaScript | mit | 983 |
/* Karma configuration for standalone build */
'use strict';
module.exports = function (config) {
console.log();
console.log('Browser (Standalone) Tests');
console.log();
config.set({
basePath: '.',
frameworks: ['mocha'],
files: [
{pattern: 'swagger-tools-standalone.js', watch: false, included: true},
{pattern: 'test-browser.js', watch: false, included: true}
],
client: {
mocha: {
reporter: 'html',
timeout: 5000,
ui: 'bdd'
}
},
plugins: [
'karma-mocha',
'karma-mocha-reporter',
'karma-phantomjs-launcher'
],
browsers: ['PhantomJS'],
reporters: ['mocha'],
colors: true,
autoWatch: false,
singleRun: true
});
};
| connected-rcheung/swagger-tools | test/browser/karma-standalone.conf.js | JavaScript | mit | 745 |
"use strict";
var inherits = require('util').inherits
, f = require('util').format
, formattedOrderClause = require('./utils').formattedOrderClause
, handleCallback = require('./utils').handleCallback
, ReadPreference = require('./read_preference')
, MongoError = require('mongodb-core').MongoError
, Readable = require('stream').Readable || require('readable-stream').Readable
, Define = require('./metadata')
, CoreCursor = require('mongodb-core').Cursor
, Map = require('mongodb-core').BSON.Map
, Query = require('mongodb-core').Query
, CoreReadPreference = require('mongodb-core').ReadPreference;
/**
* @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB
* allowing for iteration over the results returned from the underlying query. It supports
* one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X
* or higher stream
*
* **CURSORS Cannot directly be instantiated**
* @example
* var MongoClient = require('mongodb').MongoClient,
* test = require('assert');
* // Connection url
* var url = 'mongodb://localhost:27017/test';
* // Connect using MongoClient
* MongoClient.connect(url, function(err, db) {
* // Create a collection we want to drop later
* var col = db.collection('createIndexExample1');
* // Insert a bunch of documents
* col.insert([{a:1, b:1}
* , {a:2, b:2}, {a:3, b:3}
* , {a:4, b:4}], {w:1}, function(err, result) {
* test.equal(null, err);
*
* // Show that duplicate records got dropped
* col.find({}).toArray(function(err, items) {
* test.equal(null, err);
* test.equal(4, items.length);
* db.close();
* });
* });
* });
*/
/**
* Namespace provided by the mongodb-core and node.js
* @external CoreCursor
* @external Readable
*/
// Flags allowed for cursor
var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial'];
var fields = ['numberOfRetries', 'tailableRetryInterval'];
var push = Array.prototype.push;
/**
* Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly)
* @class Cursor
* @extends external:CoreCursor
* @extends external:Readable
* @property {string} sortValue Cursor query sort setting.
* @property {boolean} timeout Is Cursor able to time out.
* @property {ReadPreference} readPreference Get cursor ReadPreference.
* @fires Cursor#data
* @fires Cursor#end
* @fires Cursor#close
* @fires Cursor#readable
* @return {Cursor} a Cursor instance.
* @example
* Cursor cursor options.
*
* collection.find({}).project({a:1}) // Create a projection of field a
* collection.find({}).skip(1).limit(10) // Skip 1 and limit 10
* collection.find({}).batchSize(5) // Set batchSize on cursor to 5
* collection.find({}).filter({a:1}) // Set query on the cursor
* collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries
* collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable
* collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay
* collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout
* collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData
* collection.find({}).addCursorFlag('partial', true) // Set cursor as partial
* collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1}
* collection.find({}).max(10) // Set the cursor maxScan
* collection.find({}).maxScan(10) // Set the cursor maxScan
* collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS
* collection.find({}).min(100) // Set the cursor min
* collection.find({}).returnKey(10) // Set the cursor returnKey
* collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference
* collection.find({}).showRecordId(true) // Set the cursor showRecordId
* collection.find({}).snapshot(true) // Set the cursor snapshot
* collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query
* collection.find({}).hint('a_1') // Set the cursor hint
*
* All options are chainable, so one can do the following.
*
* collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..)
*/
var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) {
CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0));
var self = this;
var state = Cursor.INIT;
var streamOptions = {};
// Tailable cursor options
var numberOfRetries = options.numberOfRetries || 5;
var tailableRetryInterval = options.tailableRetryInterval || 500;
var currentNumberOfRetries = numberOfRetries;
// Get the promiseLibrary
var promiseLibrary = options.promiseLibrary;
// No promise library selected fall back
if(!promiseLibrary) {
promiseLibrary = typeof global.Promise == 'function' ?
global.Promise : require('es6-promise').Promise;
}
// Set up
Readable.call(this, {objectMode: true});
// Internal cursor state
this.s = {
// Tailable cursor options
numberOfRetries: numberOfRetries
, tailableRetryInterval: tailableRetryInterval
, currentNumberOfRetries: currentNumberOfRetries
// State
, state: state
// Stream options
, streamOptions: streamOptions
// BSON
, bson: bson
// Namespace
, ns: ns
// Command
, cmd: cmd
// Options
, options: options
// Topology
, topology: topology
// Topology options
, topologyOptions: topologyOptions
// Promise library
, promiseLibrary: promiseLibrary
// Current doc
, currentDoc: null
}
// Translate correctly
if(self.s.options.noCursorTimeout == true) {
self.addCursorFlag('noCursorTimeout', true);
}
// Set the sort value
this.sortValue = self.s.cmd.sort;
}
/**
* Cursor stream data event, fired for each document in the cursor.
*
* @event Cursor#data
* @type {object}
*/
/**
* Cursor stream end event
*
* @event Cursor#end
* @type {null}
*/
/**
* Cursor stream close event
*
* @event Cursor#close
* @type {null}
*/
/**
* Cursor stream readable event
*
* @event Cursor#readable
* @type {null}
*/
// Inherit from Readable
inherits(Cursor, Readable);
// Map core cursor _next method so we can apply mapping
CoreCursor.prototype._next = CoreCursor.prototype.next;
for(var name in CoreCursor.prototype) {
Cursor.prototype[name] = CoreCursor.prototype[name];
}
var define = Cursor.define = new Define('Cursor', Cursor, true);
/**
* Check if there is any document still available in the cursor
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @throws {MongoError}
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.hasNext = function(callback) {
var self = this;
// Execute using callback
if(typeof callback == 'function') {
if(self.s.currentDoc){
return callback(null, true);
} else {
return nextObject(self, function(err, doc) {
if(!doc) return callback(null, false);
self.s.currentDoc = doc;
callback(null, true);
});
}
}
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
if(self.s.currentDoc){
resolve(true);
} else {
nextObject(self, function(err, doc) {
if(self.s.state == Cursor.CLOSED || self.isDead()) return resolve(false);
if(err) return reject(err);
if(!doc) return resolve(false);
self.s.currentDoc = doc;
resolve(true);
});
}
});
}
define.classMethod('hasNext', {callback: true, promise:true});
/**
* Get the next available document from the cursor, returns null if no more documents are available.
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @throws {MongoError}
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.next = function(callback) {
var self = this;
// Execute using callback
if(typeof callback == 'function') {
// Return the currentDoc if someone called hasNext first
if(self.s.currentDoc) {
var doc = self.s.currentDoc;
self.s.currentDoc = null;
return callback(null, doc);
}
// Return the next object
return nextObject(self, callback)
};
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
// Return the currentDoc if someone called hasNext first
if(self.s.currentDoc) {
var doc = self.s.currentDoc;
self.s.currentDoc = null;
return resolve(doc);
}
nextObject(self, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
}
define.classMethod('next', {callback: true, promise:true});
/**
* Set the cursor query
* @method
* @param {object} filter The filter object used for the cursor.
* @return {Cursor}
*/
Cursor.prototype.filter = function(filter) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.query = filter;
return this;
}
define.classMethod('filter', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor maxScan
* @method
* @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query
* @return {Cursor}
*/
Cursor.prototype.maxScan = function(maxScan) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.maxScan = maxScan;
return this;
}
define.classMethod('maxScan', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor hint
* @method
* @param {object} hint If specified, then the query system will only consider plans using the hinted index.
* @return {Cursor}
*/
Cursor.prototype.hint = function(hint) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.hint = hint;
return this;
}
define.classMethod('hint', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor min
* @method
* @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order.
* @return {Cursor}
*/
Cursor.prototype.min = function(min) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.min = min;
return this;
}
define.classMethod('min', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor max
* @method
* @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order.
* @return {Cursor}
*/
Cursor.prototype.max = function(max) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.max = max;
return this;
}
define.classMethod('max', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor returnKey
* @method
* @param {object} returnKey Only return the index field or fields for the results of the query. If $returnKey is set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. Use one of the following forms:
* @return {Cursor}
*/
Cursor.prototype.returnKey = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.returnKey = value;
return this;
}
define.classMethod('returnKey', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor showRecordId
* @method
* @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find.
* @return {Cursor}
*/
Cursor.prototype.showRecordId = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.showDiskLoc = value;
return this;
}
define.classMethod('showRecordId', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor snapshot
* @method
* @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document.
* @return {Cursor}
*/
Cursor.prototype.snapshot = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.snapshot = value;
return this;
}
define.classMethod('snapshot', {callback: false, promise:false, returns: [Cursor]});
/**
* Set a node.js specific cursor option
* @method
* @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval'].
* @param {object} value The field value.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.setCursorOption = function(field, value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(fields.indexOf(field) == -1) throw MongoError.create({message: f("option %s not a supported option %s", field, fields), driver:true });
this.s[field] = value;
if(field == 'numberOfRetries')
this.s.currentNumberOfRetries = value;
return this;
}
define.classMethod('setCursorOption', {callback: false, promise:false, returns: [Cursor]});
/**
* Add a cursor flag to the cursor
* @method
* @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial'].
* @param {boolean} value The flag boolean value.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.addCursorFlag = function(flag, value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(flags.indexOf(flag) == -1) throw MongoError.create({message: f("flag %s not a supported flag %s", flag, flags), driver:true });
if(typeof value != 'boolean') throw MongoError.create({message: f("flag %s must be a boolean value", flag), driver:true});
this.s.cmd[flag] = value;
return this;
}
define.classMethod('addCursorFlag', {callback: false, promise:false, returns: [Cursor]});
/**
* Add a query modifier to the cursor query
* @method
* @param {string} name The query modifier (must start with $, such as $orderby etc)
* @param {boolean} value The flag boolean value.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.addQueryModifier = function(name, value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(name[0] != '$') throw MongoError.create({message: f("%s is not a valid query modifier"), driver:true});
// Strip of the $
var field = name.substr(1);
// Set on the command
this.s.cmd[field] = value;
// Deal with the special case for sort
if(field == 'orderby') this.s.cmd.sort = this.s.cmd[field];
return this;
}
define.classMethod('addQueryModifier', {callback: false, promise:false, returns: [Cursor]});
/**
* Add a comment to the cursor query allowing for tracking the comment in the log.
* @method
* @param {string} value The comment attached to this query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.comment = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.comment = value;
return this;
}
define.classMethod('comment', {callback: false, promise:false, returns: [Cursor]});
/**
* Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise)
* @method
* @param {number} value Number of milliseconds to wait before aborting the tailed query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.maxAwaitTimeMS = function(value) {
if(typeof value != 'number') throw MongoError.create({message: "maxAwaitTimeMS must be a number", driver:true});
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.maxAwaitTimeMS = value;
return this;
}
define.classMethod('maxAwaitTimeMS', {callback: false, promise:false, returns: [Cursor]});
/**
* Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
* @method
* @param {number} value Number of milliseconds to wait before aborting the query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.maxTimeMS = function(value) {
if(typeof value != 'number') throw MongoError.create({message: "maxTimeMS must be a number", driver:true});
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.maxTimeMS = value;
return this;
}
define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [Cursor]});
Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS;
define.classMethod('maxTimeMs', {callback: false, promise:false, returns: [Cursor]});
/**
* Sets a field projection for the query.
* @method
* @param {object} value The field projection object.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.project = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.fields = value;
return this;
}
define.classMethod('project', {callback: false, promise:false, returns: [Cursor]});
/**
* Sets the sort order of the cursor query.
* @method
* @param {(string|array|object)} keyOrList The key or keys set for the sort.
* @param {number} [direction] The direction of the sorting (1 or -1).
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.sort = function(keyOrList, direction) {
if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support sorting", driver:true});
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
var order = keyOrList;
// We have an array of arrays, we need to preserve the order of the sort
// so we will us a Map
if(Array.isArray(order) && Array.isArray(order[0])) {
order = new Map(order.map(function(x) {
var value = [x[0], null];
if(x[1] == 'asc') {
value[1] = 1;
} else if(x[1] == 'desc') {
value[1] = -1;
} else if(x[1] == 1 || x[1] == -1) {
value[1] = x[1];
} else {
throw new MongoError("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");
}
return value;
}));
}
if(direction != null) {
order = [[keyOrList, direction]];
}
this.s.cmd.sort = order;
this.sortValue = order;
return this;
}
define.classMethod('sort', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the batch size for the cursor.
* @method
* @param {number} value The batchSize for the cursor.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.batchSize = function(value) {
if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support batchSize", driver:true});
if(this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true});
this.s.cmd.batchSize = value;
this.setCursorBatchSize(value);
return this;
}
define.classMethod('batchSize', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the limit for the cursor.
* @method
* @param {number} value The limit for the cursor query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.limit = function(value) {
if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support limit", driver:true});
if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(typeof value != 'number') throw MongoError.create({message: "limit requires an integer", driver:true});
this.s.cmd.limit = value;
// this.cursorLimit = value;
this.setCursorLimit(value);
return this;
}
define.classMethod('limit', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the skip for the cursor.
* @method
* @param {number} value The skip for the cursor query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.skip = function(value) {
if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support skip", driver:true});
if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(typeof value != 'number') throw MongoError.create({message: "skip requires an integer", driver:true});
this.s.cmd.skip = value;
this.setCursorSkip(value);
return this;
}
define.classMethod('skip', {callback: false, promise:false, returns: [Cursor]});
/**
* The callback format for results
* @callback Cursor~resultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {(object|null|boolean)} result The result object if the command was executed successfully.
*/
/**
* Clone the cursor
* @function external:CoreCursor#clone
* @return {Cursor}
*/
/**
* Resets the cursor
* @function external:CoreCursor#rewind
* @return {null}
*/
/**
* Get the next available document from the cursor, returns null if no more documents are available.
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @throws {MongoError}
* @deprecated
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.nextObject = Cursor.prototype.next;
var nextObject = function(self, callback) {
// console.log("cursor:: nextObject")
if(self.s.state == Cursor.CLOSED || self.isDead && self.isDead()) return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true}));
if(self.s.state == Cursor.INIT && self.s.cmd.sort) {
try {
self.s.cmd.sort = formattedOrderClause(self.s.cmd.sort);
} catch(err) {
return handleCallback(callback, err);
}
}
// Get the next object
self._next(function(err, doc) {
self.s.state = Cursor.OPEN;
if(err) return handleCallback(callback, err);
handleCallback(callback, null, doc);
});
}
define.classMethod('nextObject', {callback: true, promise:true});
// Trampoline emptying the number of retrieved items
// without incurring a nextTick operation
var loop = function(self, callback) {
// No more items we are done
if(self.bufferedCount() == 0) return;
// Get the next document
self._next(callback);
// Loop
return loop;
}
Cursor.prototype.next = Cursor.prototype.nextObject;
define.classMethod('next', {callback: true, promise:true});
/**
* Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
* not all of the elements will be iterated if this cursor had been previouly accessed.
* In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
* **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
* at any given time if batch size is specified. Otherwise, the caller is responsible
* for making sure that the entire result can fit the memory.
* @method
* @deprecated
* @param {Cursor~resultCallback} callback The result callback.
* @throws {MongoError}
* @return {null}
*/
Cursor.prototype.each = function(callback) {
// Rewind cursor state
this.rewind();
// Set current cursor to INIT
this.s.state = Cursor.INIT;
// Run the query
_each(this, callback);
};
define.classMethod('each', {callback: true, promise:false});
// Run the each loop
var _each = function(self, callback) {
if(!callback) throw MongoError.create({message: 'callback is mandatory', driver:true});
if(self.isNotified()) return;
if(self.s.state == Cursor.CLOSED || self.isDead()) {
return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true}));
}
if(self.s.state == Cursor.INIT) self.s.state = Cursor.OPEN;
// Define function to avoid global scope escape
var fn = null;
// Trampoline all the entries
if(self.bufferedCount() > 0) {
while(fn = loop(self, callback)) fn(self, callback);
_each(self, callback);
} else {
self.next(function(err, item) {
if(err) return handleCallback(callback, err);
if(item == null) {
self.s.state = Cursor.CLOSED;
return handleCallback(callback, null, null);
}
if(handleCallback(callback, null, item) == false) return;
_each(self, callback);
})
}
}
/**
* The callback format for the forEach iterator method
* @callback Cursor~iteratorCallback
* @param {Object} doc An emitted document for the iterator
*/
/**
* The callback error format for the forEach iterator method
* @callback Cursor~endCallback
* @param {MongoError} error An error instance representing the error during the execution.
*/
/**
* Iterates over all the documents for this cursor using the iterator, callback pattern.
* @method
* @param {Cursor~iteratorCallback} iterator The iteration callback.
* @param {Cursor~endCallback} callback The end callback.
* @throws {MongoError}
* @return {null}
*/
Cursor.prototype.forEach = function(iterator, callback) {
this.each(function(err, doc){
if(err) { callback(err); return false; }
if(doc != null) { iterator(doc); return true; }
if(doc == null && callback) {
var internalCallback = callback;
callback = null;
internalCallback(null);
return false;
}
});
}
define.classMethod('forEach', {callback: true, promise:false});
/**
* Set the ReadPreference for the cursor.
* @method
* @param {(string|ReadPreference)} readPreference The new read preference for the cursor.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.setReadPreference = function(r) {
if(this.s.state != Cursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true});
if(r instanceof ReadPreference) {
this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags);
} else if(typeof r == 'string'){
this.s.options.readPreference = new CoreReadPreference(r);
} else if(r instanceof CoreReadPreference) {
this.s.options.readPreference = r;
}
return this;
}
define.classMethod('setReadPreference', {callback: false, promise:false, returns: [Cursor]});
/**
* The callback format for results
* @callback Cursor~toArrayResultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {object[]} documents All the documents the satisfy the cursor.
*/
/**
* Returns an array of documents. The caller is responsible for making sure that there
* is enough memory to store the results. Note that the array only contain partial
* results when this cursor had been previouly accessed. In that case,
* cursor.rewind() can be used to reset the cursor.
* @method
* @param {Cursor~toArrayResultCallback} [callback] The result callback.
* @throws {MongoError}
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.toArray = function(callback) {
var self = this;
if(self.s.options.tailable) throw MongoError.create({message: 'Tailable cursor cannot be converted to array', driver:true});
// Execute using callback
if(typeof callback == 'function') return toArray(self, callback);
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
toArray(self, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
}
var toArray = function(self, callback) {
var items = [];
// console.log("!!!!!!!!!!!!! toArray :: 0")
// Reset cursor
self.rewind();
self.s.state = Cursor.INIT;
// console.log("!!!!!!!!!!!!! toArray :: 1")
// Fetch all the documents
var fetchDocs = function() {
// console.log("!!!!!!!!!!!!! toArray :: 2")
self._next(function(err, doc) {
// console.log("!!!!!!!!!!!!! toArray :: 3")
if(err) return handleCallback(callback, err);
if(doc == null) {
self.s.state = Cursor.CLOSED;
return handleCallback(callback, null, items);
}
// Add doc to items
items.push(doc)
// Get all buffered objects
if(self.bufferedCount() > 0) {
var docs = self.readBufferedDocuments(self.bufferedCount())
// Transform the doc if transform method added
if(self.s.transforms && typeof self.s.transforms.doc == 'function') {
docs = docs.map(self.s.transforms.doc);
}
push.apply(items, docs);
}
// Attempt a fetch
fetchDocs();
})
}
fetchDocs();
}
define.classMethod('toArray', {callback: true, promise:true});
/**
* The callback format for results
* @callback Cursor~countResultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {number} count The count of documents.
*/
/**
* Get the count of documents for this cursor
* @method
* @param {boolean} applySkipLimit Should the count command apply limit and skip settings on the cursor or in the passed in options.
* @param {object} [options=null] Optional settings.
* @param {number} [options.skip=null] The number of documents to skip.
* @param {number} [options.limit=null] The maximum amounts to count before aborting.
* @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query.
* @param {string} [options.hint=null] An index name hint for the query.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {Cursor~countResultCallback} [callback] The result callback.
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.count = function(applySkipLimit, opts, callback) {
var self = this;
if(self.s.cmd.query == null) throw MongoError.create({message: "count can only be used with find command", driver:true});
if(typeof opts == 'function') callback = opts, opts = {};
opts = opts || {};
// Execute using callback
if(typeof callback == 'function') return count(self, applySkipLimit, opts, callback);
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
count(self, applySkipLimit, opts, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
};
var count = function(self, applySkipLimit, opts, callback) {
if(typeof applySkipLimit == 'function') {
callback = applySkipLimit;
applySkipLimit = true;
}
if(applySkipLimit) {
if(typeof self.cursorSkip() == 'number') opts.skip = self.cursorSkip();
if(typeof self.cursorLimit() == 'number') opts.limit = self.cursorLimit();
}
// Command
var delimiter = self.s.ns.indexOf('.');
var command = {
'count': self.s.ns.substr(delimiter+1), 'query': self.s.cmd.query
}
if(typeof opts.maxTimeMS == 'number') {
command.maxTimeMS = opts.maxTimeMS;
} else if(self.s.cmd && typeof self.s.cmd.maxTimeMS == 'number') {
command.maxTimeMS = self.s.cmd.maxTimeMS;
}
// Merge in any options
if(opts.skip) command.skip = opts.skip;
if(opts.limit) command.limit = opts.limit;
if(self.s.options.hint) command.hint = self.s.options.hint;
// Execute the command
self.topology.command(f("%s.$cmd", self.s.ns.substr(0, delimiter))
, command, function(err, result) {
callback(err, result ? result.result.n : null)
});
}
define.classMethod('count', {callback: true, promise:true});
/**
* Close the cursor, sending a KillCursor command and emitting close.
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.close = function(callback) {
this.s.state = Cursor.CLOSED;
// Kill the cursor
this.kill();
// Emit the close event for the cursor
this.emit('close');
// Callback if provided
if(typeof callback == 'function') return handleCallback(callback, null, this);
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
resolve();
});
}
define.classMethod('close', {callback: true, promise:true});
/**
* Map all documents using the provided function
* @method
* @param {function} [transform] The mapping transformation method.
* @return {null}
*/
Cursor.prototype.map = function(transform) {
this.cursorState.transforms = { doc: transform };
return this;
}
define.classMethod('map', {callback: false, promise:false, returns: [Cursor]});
/**
* Is the cursor closed
* @method
* @return {boolean}
*/
Cursor.prototype.isClosed = function() {
return this.isDead();
}
define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]});
Cursor.prototype.destroy = function(err) {
if(err) this.emit('error', err);
this.pause();
this.close();
}
define.classMethod('destroy', {callback: false, promise:false});
/**
* Return a modified Readable stream including a possible transform method.
* @method
* @param {object} [options=null] Optional settings.
* @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream.
* @return {Cursor}
*/
Cursor.prototype.stream = function(options) {
this.s.streamOptions = options || {};
return this;
}
define.classMethod('stream', {callback: false, promise:false, returns: [Cursor]});
/**
* Execute the explain for the cursor
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.explain = function(callback) {
var self = this;
this.s.cmd.explain = true;
// Do we have a readConcern
if(this.s.cmd.readConcern) {
delete this.s.cmd['readConcern'];
}
// Execute using callback
if(typeof callback == 'function') return this._next(callback);
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
self._next(function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
}
define.classMethod('explain', {callback: true, promise:true});
Cursor.prototype._read = function(n) {
// console.log("=== _read")
var self = this;
if(self.s.state == Cursor.CLOSED || self.isDead()) {
return self.push(null);
}
// Get the next item
self.nextObject(function(err, result) {
// console.log("=== _read 1")
// console.dir(err)
if(err) {
if(self.listeners('error') && self.listeners('error').length > 0) {
self.emit('error', err);
}
if(!self.isDead()) self.close();
// Emit end event
self.emit('end');
return self.emit('finish');
}
// If we provided a transformation method
if(typeof self.s.streamOptions.transform == 'function' && result != null) {
return self.push(self.s.streamOptions.transform(result));
}
// If we provided a map function
if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function' && result != null) {
return self.push(self.cursorState.transforms.doc(result));
}
// Return the result
self.push(result);
});
}
Object.defineProperty(Cursor.prototype, 'readPreference', {
enumerable:true,
get: function() {
if (!this || !this.s) {
return null;
}
return this.s.options.readPreference;
}
});
Object.defineProperty(Cursor.prototype, 'namespace', {
enumerable: true,
get: function() {
if (!this || !this.s) {
return null;
}
// TODO: refactor this logic into core
var ns = this.s.ns || '';
var firstDot = ns.indexOf('.');
if (firstDot < 0) {
return {
database: this.s.ns,
collection: ''
};
}
return {
database: ns.substr(0, firstDot),
collection: ns.substr(firstDot + 1)
};
}
});
/**
* The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.
* @function external:Readable#read
* @param {number} size Optional argument to specify how much data to read.
* @return {(String | Buffer | null)}
*/
/**
* Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.
* @function external:Readable#setEncoding
* @param {string} encoding The encoding to use.
* @return {null}
*/
/**
* This method will cause the readable stream to resume emitting data events.
* @function external:Readable#resume
* @return {null}
*/
/**
* This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.
* @function external:Readable#pause
* @return {null}
*/
/**
* This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.
* @function external:Readable#pipe
* @param {Writable} destination The destination for writing data
* @param {object} [options] Pipe options
* @return {null}
*/
/**
* This method will remove the hooks set up for a previous pipe() call.
* @function external:Readable#unpipe
* @param {Writable} [destination] The destination for writing data
* @return {null}
*/
/**
* This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.
* @function external:Readable#unshift
* @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue.
* @return {null}
*/
/**
* Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.)
* @function external:Readable#wrap
* @param {Stream} stream An "old style" readable stream.
* @return {null}
*/
Cursor.INIT = 0;
Cursor.OPEN = 1;
Cursor.CLOSED = 2;
Cursor.GET_MORE = 3;
module.exports = Cursor;
| csdinos/TODO-List-APIServer | node_modules/mongodb/lib/cursor.js | JavaScript | mit | 40,139 |
(function($) {
"use strict";
// Return true for float value, false otherwise
function is_float (mixed_var) {
return +mixed_var === mixed_var && (!(isFinite(mixed_var))) || Boolean((mixed_var % 1));
}
// Return number of integers after the decimal point.
function decimalCount(res){
var q = res.toString().split('.');
return q[1].length;
}
function loadSelect(myClass, min, max, res, step){
//var j = step + ((decCount ) - (step )); // 18;
for( var i = min; i <= max; i=i+res ){
//var step = 2;
//if (j === (step + ((decCount ) - (step )))) {
var n = i;
if (is_float(res)){
var decCount = decimalCount(res);
n = i.toFixed(decCount);
}
$(myClass).append(
'<option value="' + n + '">' + n + '</option>'
);
//j = 0;
//}
//j++;
}
}
$(document).ready(function() {
$('div.redux-slider-container').each(function() {
var start, toClass, defClassOne, defClassTwo, connectVal;
var DISPLAY_NONE = 0;
var DISPLAY_LABEL = 1;
var DISPLAY_TEXT = 2;
var DISPLAY_SELECT = 3;
var mainID = $(this).data('id');
var minVal = $(this).data('min');
var maxVal = $(this).data('max');
var stepVal = $(this).data('step');
var handles = $(this).data('handles');
var defValOne = $(this).data('default-one');
var defValTwo = $(this).data('default-two');
var resVal = $(this).data('resolution');
var displayValue = parseInt(($(this).data('display')));
var rtlVal = Boolean($(this).data('rtl'));
var floatMark = ($(this).data('float-mark'));
var rtl;
if (rtlVal === true) {
rtl = 'rtl';
} else {
rtl = 'ltr';
}
// range array
var range = [minVal, maxVal];
// Set default values for dual slides.
var startTwo = [defValOne, defValTwo];
// Set default value for single slide
var startOne = [defValOne];
var inputOne, inputTwo;
if (displayValue == DISPLAY_TEXT) {
defClassOne = $('.redux-slider-input-one-' + mainID);
defClassTwo = $('.redux-slider-input-two-' + mainID);
inputOne = defClassOne;
inputTwo = defClassTwo;
} else if (displayValue == DISPLAY_SELECT) {
defClassOne = $('.redux-slider-select-one-' + mainID);
defClassTwo = $('.redux-slider-select-two-' + mainID);
loadSelect(defClassOne, minVal, maxVal, resVal, stepVal);
if (handles === 2) {
loadSelect(defClassTwo, minVal, maxVal, resVal, stepVal);
}
} else if (displayValue == DISPLAY_LABEL) {
defClassOne = $('#redux-slider-label-one-' + mainID);
defClassTwo = $('#redux-slider-label-two-' + mainID);
} else if (displayValue == DISPLAY_NONE) {
defClassOne = $('.redux-slider-value-one-' + mainID);
defClassTwo = $('.redux-slider-value-two-' + mainID);
}
var classOne, classTwo;
if (displayValue == DISPLAY_LABEL) {
var x = [defClassOne, 'html'];
var y = [defClassTwo, 'html'];
classOne = [x];
classTwo = [x, y];
} else {
classOne = [defClassOne];
classTwo = [defClassOne, defClassTwo];
}
if (handles === 2) {
start = startTwo;
toClass = classTwo;
connectVal = true;
} else {
start = startOne;
toClass = classOne;
connectVal = 'lower';
}
var slider = $(this).noUiSlider({
range: range,
start: start,
handles: handles,
step: stepVal,
connect: connectVal,
behaviour: "tap-drag",
direction: rtl,
serialization: {
resolution: resVal,
to: toClass,
mark: floatMark,
},
slide: function() {
if (displayValue == DISPLAY_LABEL) {
if (handles === 2) {
var inpSliderVal = slider.val();
$('input.redux-slider-value-one-' + mainID).attr('value', inpSliderVal[0]);
$('input.redux-slider-value-two-' + mainID).attr('value', inpSliderVal[1]);
} else {
$('input.redux-slider-value-one-' + mainID).attr('value', slider.val());
}
}
if (displayValue == DISPLAY_SELECT) {
$('.redux-slider-select-one').select2('val', slider.val()[0]);
if (handles === 2) {
$('.redux-slider-select-two').select2('val', slider.val()[1]);
}
}
// Uncomment when selectize is live
// var selectize = select[0].selectize;
// selectize.setValue(slider.val()[0]);
redux_change(jQuery(this).parents('.redux-field-container:first').find('input'));
},
});
if (displayValue === DISPLAY_TEXT) {
inputOne.keydown(function( e ) {
var sliderOne = slider.val();
var value = parseInt( sliderOne[0] );
switch ( e.which ) {
case 38:
slider.val([value + 1, null] );
break;
case 40:
slider.val([value - 1, null]);
break;
case 13:
e.preventDefault();
break;
}
});
if (handles === 2) {
inputTwo.keydown(function( e ) {
var sliderTwo = slider.val();
var value = parseInt(sliderTwo[1]);
switch ( e.which ) {
case 38:
slider.val([null, value + 1] );
break;
case 40:
slider.val([null, value - 1] );
break;
case 13:
e.preventDefault();
break;
}
});
}
}
});
$('select.redux-slider-select-one, select.redux-slider-select-two').select2({
width: 'resolve',
triggerChange: true,
allowClear: true
});
// select = $('.slider-select').selectize({
// create: true,
// sortField: 'text'
// });
});
})(jQuery);
| ChristosKon/tech-in-life | wp-content/themes/virtue/themeoptions/inc/fields/slider/field_slider.js | JavaScript | gpl-2.0 | 7,911 |
( function( $ ) {
"use strict";
// Extend etCorePortability since it is declared by localization.
window.etCore.portability = $.extend( etCorePortability, {
cancelled: false,
boot: function( $instance ) {
var $this = this;
var $customizeHeader = $( '#customize-header-actions' );
var $customizePortability = $( '.et-core-customize-controls-close' );
// Moved portability button into customizer header
if ( $customizeHeader.length && $customizePortability.length ) {
$customizeHeader.append( $customizePortability );
}
$( '[data-et-core-portability]' ).each( function() {
$this.listen( $( this ) );
} );
// Release unecessary cache.
etCorePortability = null;
},
listen: function( $el ) {
var $this = this;
$el.find( '[data-et-core-portability-export]' ).click( function( e ) {
e.preventDefault();
if ( ! $this.actionsDisabled() ) {
$this.disableActions();
$this.export();
}
} );
$el.find( '.et-core-portability-export-form input[type="text"]' ).on( 'keydown', function( e ) {
if ( 13 === e.keyCode ) {
e.preventDefault();
$el.find( '[data-et-core-portability-export]' ).click();
}
} );
// Portability populate import.
$el.find( '.et-core-portability-import-form input[type="file"]' ).on( 'change', function( e ) {
$this.populateImport( $( this ).get( 0 ).files[0] );
} );
$el.find( '.et-core-portability-import' ).click( function( e ) {
e.preventDefault();
if ( ! $this.actionsDisabled() ) {
$this.disableActions();
$this.import();
}
} );
// Trigger file window.
$el.find( '.et-core-portability-import-form button' ).click( function( e ) {
e.preventDefault();
$this.instance( 'input[type="file"]' ).trigger( 'click' );
} );
// Cancel request.
$el.find( '[data-et-core-portability-cancel]' ).click( function( e ) {
e.preventDefault();
$this.cancel();
} )
},
validateImportFile: function( file, noOutput ) {
if ( undefined !== file && 'undefined' != typeof file.name && 'undefined' != typeof file.type && 'json' == file.name.split( '.' ).slice( -1 )[0] ) {
return true;
}
if ( ! noOutput ) {
etCore.modalContent( '<p>' + this.text.invalideFile + '</p>', false, 3000, '#et-core-portability-import' );
}
this.enableActions();
return false;
},
populateImport: function( file ) {
if ( ! this.validateImportFile( file ) ) {
return;
}
$( '.et-core-portability-import-placeholder' ).text( file.name );
},
import: function( noBackup ) {
var $this = this,
file = $this.instance( 'input[type="file"]' ).get( 0 ).files[0];
if ( undefined === window.FormData ) {
etCore.modalContent( '<p>' + this.text.browserSupport + '</p>', false, 3000, '#et-core-portability-import' );
$this.enableActions();
return;
}
if ( ! $this.validateImportFile( file ) ) {
return;
}
$this.addProgressBar( $this.text.importing );
// Export Backup if set.
if ( $this.instance( '[name="et-core-portability-import-backup"]' ).is( ':checked' ) && ! noBackup ) {
$this.export( true );
$( $this ).on( 'exported', function() {
$this.import( true );
} );
return;
}
$this.ajaxAction( {
action: 'et_core_portability_import',
file: file,
nonce: $this.nonces.import
}, function( response ) {
etCore.modalContent( '<div class="et-core-loader et-core-loader-success"></div>', false, 3000, '#et-core-portability-import' );
$this.toggleCancel();
$( document ).delay( 3000 ).queue( function() {
etCore.modalContent( '<div class="et-core-loader"></div>', false, false, '#et-core-portability-import' );
$( this ).dequeue().delay( 2000 ).queue( function() {
// Save post content for individual content.
if ( 'undefined' !== typeof response.data.postContent ) {
var save = $( '#save-action #save-post' );
if ( save.length === 0 ) {
save = $( '#publishing-action input[type="submit"]' );
}
if ( 'undefined' !== typeof window.tinyMCE && window.tinyMCE.get( 'content' ) && ! window.tinyMCE.get( 'content' ).isHidden() ) {
var editor = window.tinyMCE.get( 'content' );
editor.setContent( $.trim( response.data.postContent ), { format: 'html' } );
} else {
$( '#content' ).val( $.trim( response.data.postContent ) );
}
save.trigger( 'click' );
window.onbeforeunload = function() {
$( 'body' ).fadeOut( 500 );
}
} else {
$( 'body' ).fadeOut( 500, function() {
// Remove confirmation popup before relocation.
$( window ).unbind( 'beforeunload' );
window.location = window.location.href.replace(/reset\=true\&|\&reset\=true/,'');
} )
}
} );
} );
}, true );
},
export: function( backup ) {
var $this = this,
progressBarMessages = backup ? $this.text.backuping : $this.text.exporting;
$this.save( function() {
var posts = {},
content = false;
// Include selected posts.
if ( $this.instance( '[name="et-core-portability-posts"]' ).is( ':checked' ) ) {
$( '#posts-filter [name="post[]"]:checked:enabled' ).each( function() {
posts[this.id] = this.value;
} );
// do not proceed and display error message if no Items selected
if ( $.isEmptyObject( posts ) ) {
etCore.modalContent( '<div class="et-core-loader et-core-loader-fail"></div><h3>' + $this.text.noItemsSelected + '</h3>', false, true, '#' + $this.instance( '.ui-tabs-panel:visible' ).attr( 'id' ) );
$this.enableActions();
return;
}
}
$this.addProgressBar( progressBarMessages );
// Get post layout.
if ( 'undefined' !== typeof window.tinyMCE && window.tinyMCE.get( 'content' ) && ! window.tinyMCE.get( 'content' ).isHidden() ) {
content = window.tinyMCE.get( 'content' ).getContent();
} else if ( $( 'textarea#content' ).length > 0 ) {
content = $( 'textarea#content' ).val();
}
if ( false !== content ) {
content = content.replace( /^([^\[]*){1}/, '' );
content = content.replace( /([^\]]*)$/, '' );
}
$this.ajaxAction( {
action: 'et_core_portability_export',
content: content,
selection: $.isEmptyObject( posts ) ? false : JSON.stringify( posts ),
nonce: $this.nonces.export
}, function( response ) {
var time = ' ' + new Date().toJSON().replace( 'T', ' ' ).replace( ':', 'h' ).substring( 0, 16 ),
downloadURL = $this.instance( '[data-et-core-portability-export]' ).data( 'et-core-portability-export' ),
query = {
'timestamp': response.data.timestamp,
'name': encodeURIComponent( $this.instance( '.et-core-portability-export-form input' ).val() + ( backup ? time : '' ) ),
};
$.each( query, function( key, value ) {
if ( value ) {
downloadURL = downloadURL + '&' + key + '=' + value;
}
} );
// Remove confirmation popup before relocation.
$( window ).unbind( 'beforeunload' );
window.location.assign( encodeURI( downloadURL ) );
if ( ! backup ) {
etCore.modalContent( '<div class="et-core-loader et-core-loader-success"></div>', false, 3000, '#et-core-portability-export' );
$this.toggleCancel();
}
$( $this ).trigger( 'exported' );
} );
} );
},
exportFB: function( exportUrl, postId, content, fileName, importFile, page ) {
var $this = this;
page = typeof page === 'undefined' ? 1 : page;
$.ajax( {
type: 'POST',
url: etCore.ajaxurl,
dataType: 'json',
data: {
action: 'et_core_portability_export',
content: content,
timestamp: 0,
nonce: $this.nonces.export,
post: postId,
context: 'et_builder',
page: page,
},
success: function( response ) {
var errorEvent = document.createEvent( 'Event' );
errorEvent.initEvent( 'et_fb_layout_export_error', true, true );
// The error is unknown but most of the time it would be cased by the server max size being exceeded.
if ( 'string' === typeof response && '0' === response ) {
window.et_fb_export_layout_message = $this.text.maxSizeExceeded;
window.dispatchEvent( errorEvent );
return;
}
// Memory size set on server is exhausted.
else if ( 'string' === typeof response && response.toLowerCase().indexOf( 'memory size' ) >= 0 ) {
window.et_fb_export_layout_message = $this.text.memoryExhausted;
window.dispatchEvent( errorEvent );
return;
}
// Paginate.
else if ( 'undefined' !== typeof response.page ) {
if ( $this.cancelled ) {
return;
}
return $this.exportFB(exportUrl, postId, content, fileName, importFile, (page + 1));
} else if ( 'undefined' !== typeof response.data && 'undefined' !== typeof response.data.message ) {
window.et_fb_export_layout_message = $this.text[response.data.message];
window.dispatchEvent( errorEvent );
return;
}
var time = ' ' + new Date().toJSON().replace( 'T', ' ' ).replace( ':', 'h' ).substring( 0, 16 ),
downloadURL = exportUrl,
query = {
'timestamp': response.data.timestamp,
'name': '' !== fileName ? fileName : encodeURIComponent( time ),
};
$.each( query, function( key, value ) {
if ( value ) {
downloadURL = downloadURL + '&' + key + '=' + value;
}
} );
// Remove confirmation popup before relocation.
$( window ).unbind( 'beforeunload' );
window.location.assign( encodeURI( downloadURL ) );
// perform import if needed
if ( typeof importFile !== 'undefined' ) {
$this.importFB( importFile, postId );
} else {
var event = document.createEvent( 'Event' );
event.initEvent( 'et_fb_layout_export_finished', true, true );
// trigger event to communicate with FB
window.dispatchEvent( event );
}
}
} );
},
importFB: function( file, postId ) {
var $this = this;
var errorEvent = document.createEvent( 'Event' );
window.et_fb_import_progress = 0;
window.et_fb_import_estimation = 1;
errorEvent.initEvent( 'et_fb_layout_import_error', true, true );
if ( undefined === window.FormData ) {
window.et_fb_import_layout_message = this.text.browserSupport;
window.dispatchEvent( errorEvent );
return;
}
if ( ! $this.validateImportFile( file, true ) ) {
window.et_fb_import_layout_message = this.text.invalideFile;
window.dispatchEvent( errorEvent );
return;
}
var fileSize = Math.ceil( ( file.size / ( 1024 * 1024 ) ).toFixed( 2 ) ),
formData = new FormData(),
requestData = {
action: 'et_core_portability_import',
file: file,
content: false,
timestamp: 0,
nonce: $this.nonces.import,
post: postId,
context: 'et_builder'
};
// Max size set on server is exceeded.
if ( fileSize >= $this.postMaxSize || fileSize >= $this.uploadMaxSize ) {
window.et_fb_import_layout_message = this.text.maxSizeExceeded;
window.dispatchEvent( errorEvent );
return;
}
$.each( requestData, function( name, value ) {
formData.append( name, value);
} );
var importFBAjax = function( importData ) {
$.ajax( {
type: 'POST',
url: etCore.ajaxurl,
processData: false,
contentType: false,
data: formData,
success: function( response ) {
var event = document.createEvent( 'Event' );
event.initEvent( 'et_fb_layout_import_in_progress', true, true );
// Handle known error
if ( ! response.success && 'undefined' !== typeof response.data && 'undefined' !== typeof response.data.message && 'undefined' !== typeof $this.text[ response.data.message ] ) {
window.et_fb_import_layout_message = $this.text[ response.data.message ];
window.dispatchEvent( errorEvent );
}
// The error is unknown but most of the time it would be cased by the server max size being exceeded.
else if ( 'string' === typeof response && ('0' === response || '' === response) ) {
window.et_fb_import_layout_message = $this.text.maxSizeExceeded;
window.dispatchEvent( errorEvent );
return;
}
// Memory size set on server is exhausted.
else if ( 'string' === typeof response && response.toLowerCase().indexOf( 'memory size' ) >= 0 ) {
window.et_fb_import_layout_message = $this.text.memoryExhausted;
window.dispatchEvent( errorEvent );
return;
}
// Pagination
else if ( 'undefined' !== typeof response.page && 'undefined' !== typeof response.total_pages ) {
// Update progress bar
var progress = Math.ceil( ( response.page * 100 ) / response.total_pages );
var estimation = Math.ceil( ( ( response.total_pages - response.page ) * 6 ) / 60 );
window.et_fb_import_progress = progress;
window.et_fb_import_estimation = estimation;
// Import data
var nextImportData = importData;
nextImportData.append( 'page', ( parseInt(response.page) + 1 ) );
nextImportData.append( 'timestamp', response.timestamp );
nextImportData.append( 'file', null );
importFBAjax( nextImportData );
// trigger event to communicate with FB
window.dispatchEvent( event );
} else {
// Update progress bar
window.et_fb_import_progress = 100;
window.et_fb_import_estimation = 0;
// trigger event to communicate with FB
window.dispatchEvent( event );
// Allow some time for animations to animate
setTimeout( function() {
var event = document.createEvent( 'Event' );
event.initEvent( 'et_fb_layout_import_finished', true, true );
// save the data into global variable for later use in FB
window.et_fb_import_layout_response = response;
// trigger event to communicate with FB (again)
window.dispatchEvent( event );
}, 1300 );
}
}
} );
};
importFBAjax(formData)
},
ajaxAction: function( data, callback, fileSupport ) {
var $this = this;
// Reset cancelled.
this.cancelled = false;
data = $.extend( {
nonce: $this.nonce,
file: null,
content: false,
timestamp: 0,
post: $( '#post_ID' ).val(),
context: $this.instance().data( 'et-core-portability' ),
page: 1,
}, data );
var ajax = {
type: 'POST',
url: etCore.ajaxurl,
data: data,
success: function( response ) {
// The error is unknown but most of the time it would be caused by the server max size being exceeded.
if ( 'string' === typeof response && '0' === response ) {
etCore.modalContent( '<p>' + $this.text.maxSizeExceeded + '</p>', false, true, '#' + $this.instance( '.ui-tabs-panel:visible' ).attr( 'id' ) );
$this.enableActions();
return;
}
// Memory size set on server is exhausted.
else if ( 'string' === typeof response && response.toLowerCase().indexOf( 'memory size' ) >= 0 ) {
etCore.modalContent( '<p>' + $this.text.memoryExhausted + '</p>', false, true, '#' + $this.instance( '.ui-tabs-panel:visible' ).attr( 'id' ) );
$this.enableActions();
return;
}
// Paginate.
else if ( 'undefined' !== typeof response.page ) {
var progress = Math.ceil( ( response.page * 100 ) / response.total_pages );
if ( $this.cancelled ) {
return;
}
$this.toggleCancel( true );
$this.ajaxAction( $.extend( data, {
page: parseInt( response.page ) + 1,
timestamp: response.timestamp,
file: null,
} ), callback, false );
$this.instance( '.et-core-progress-bar' )
.width( progress + '%' )
.text( progress + '%' );
$this.instance( '.et-core-progress-subtext span' ).text( Math.ceil( ( ( response.total_pages - response.page ) * 6 ) / 60 ) );
return;
} else if ( 'undefined' !== typeof response.data && 'undefined' !== typeof response.data.message ) {
etCore.modalContent( '<p>' + $this.text[response.data.message] + '</p>', false, 3000, '#' + $this.instance( '.ui-tabs-panel:visible' ).attr( 'id' ) );
$this.enableActions();
return;
}
// Timestamp when AJAX response is received
var ajax_returned_timestamp = new Date().getTime();
// Animate Progresss Bar
var animateCoreProgressBar = function( DOMHighResTimeStamp ) {
// Check has been performed for 3s and progress bar DOM still can't be found, consider it fail to avoid infinite loop
var current_timestamp = new Date().getTime();
if ((current_timestamp - ajax_returned_timestamp) > 3000) {
$this.enableActions();
etCore.modalContent( '<div class="et-core-loader et-core-loader-fail"></div>', false, 3000, '#' + $this.instance( '.ui-tabs-panel:visible' ).attr( 'id' ) );
return;
}
// Check if core progress DOM exists
if ($this.instance( '.et-core-progress' ).length ) {
$this.instance( '.et-core-progress' )
.removeClass( 'et-core-progress-striped' )
.find( '.et-core-progress-bar' ).width( '100%' )
.text( '100%' )
.delay( 1000 )
.queue( function() {
$this.enableActions();
if ( 'undefined' === typeof response.data || ( 'undefined' !== typeof response.data && ! response.data.timestamp ) ) {
etCore.modalContent( '<div class="et-core-loader et-core-loader-fail"></div>', false, 3000, '#' + $this.instance( '.ui-tabs-panel:visible' ).attr( 'id' ) );
return;
}
$( this ).dequeue();
callback( response );
} );
} else {
// Recheck on the next animation frame
window.requestAnimationFrame(animateCoreProgressBar);
}
}
animateCoreProgressBar();
}
};
if ( fileSupport ) {
var fileSize = Math.ceil( ( data.file.size / ( 1024 * 1024 ) ).toFixed( 2 ) ),
formData = new FormData();
// Max size set on server is exceeded.
if ( fileSize >= $this.postMaxSize || fileSize >= $this.uploadMaxSize ) {
etCore.modalContent( '<p>' + $this.text.maxSizeExceeded + '</p>', false, true, '#' + $this.instance( '.ui-tabs-panel:visible' ).attr( 'id' ) );
$this.enableActions();
return;
}
$.each( ajax.data, function( name, value ) {
formData.append( name, value);
} );
ajax = $.extend( ajax, {
data: formData,
processData: false,
contentType : false,
} );
}
$.ajax( ajax );
},
// This function should be overwritten for options portability type to make sure data are saved before exporting.
save: function( callback ) {
if ( 'undefined' !== typeof wp && 'undefined' !== typeof wp.customize ) {
var saveCallback = function() {
callback();
wp.customize.unbind( 'saved', saveCallback );
}
$( '#save' ).click();
wp.customize.bind( 'saved', saveCallback );
} else {
// Add a slight delay for animation purposes.
setTimeout( function() {
callback();
}, 1000 )
}
},
addProgressBar: function( message ) {
etCore.modalContent( '<div class="et-core-progress et-core-progress-striped et-core-active"><div class="et-core-progress-bar" style="width: 10%;">1%</div><span class="et-core-progress-subtext">' + message + '</span></div>', false, false, '#' + this.instance( '.ui-tabs-panel:visible' ).attr( 'id' ) );
},
actionsDisabled: function() {
if ( this.instance( '.et-core-modal-action' ).hasClass( 'et-core-disabled' ) ) {
return true;
}
return false;
},
disableActions: function() {
this.instance( '.et-core-modal-action' ).addClass( 'et-core-disabled' );
},
enableActions: function() {
this.instance( '.et-core-modal-action' ).removeClass( 'et-core-disabled' );
},
toggleCancel: function( cancel ) {
var $target = this.instance( '.ui-tabs-panel:visible [data-et-core-portability-cancel]' );
if ( cancel && ! $target.is( ':visible' ) ) {
$target.show().animate( { opacity: 1 }, 600 );
} else if ( ! cancel && $target.is( ':visible' ) ) {
$target.animate( { opacity: 0 }, 600, function() {
$( this ).hide();
} );
}
},
cancel: function( cancel ) {
this.cancelled = true;
// Remove all temp files. Set a delay as temp files might still be in the process of being added.
setTimeout( function() {
$.ajax( {
type: 'POST',
url: etCore.ajaxurl,
data: {
nonce: this.nonces.cancel,
context: this.instance().data( 'et-core-portability' ),
action: 'et_core_portability_cancel',
}
} );
}.bind( this ), 3000 );
etCore.modalContent( '<div class="et-core-loader et-core-loader-success"></div>', false, 3000, '#' + this.instance( '.ui-tabs-panel:visible' ).attr( 'id' ) );
this.toggleCancel();
this.enableActions();
},
instance: function( element ) {
return $( '.et-core-active[data-et-core-portability]' + ( element ? ' ' + element : '' ) );
},
} );
$( document ).ready( function() {
window.etCore.portability.boot();
});
})( jQuery );
| kirsley/repobase | wp-content/themes/Divi/core/admin/js/portability.js | JavaScript | gpl-2.0 | 21,145 |
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var prefix = 'far';
var iconName = 'save';
var width = 448;
var height = 512;
var ligatures = [];
var unicode = 'f0c7';
var svgPathData = 'M433.941 129.941l-83.882-83.882A48 48 0 0 0 316.118 32H48C21.49 32 0 53.49 0 80v352c0 26.51 21.49 48 48 48h352c26.51 0 48-21.49 48-48V163.882a48 48 0 0 0-14.059-33.941zM272 80v80H144V80h128zm122 352H54a6 6 0 0 1-6-6V86a6 6 0 0 1 6-6h42v104c0 13.255 10.745 24 24 24h176c13.255 0 24-10.745 24-24V83.882l78.243 78.243a6 6 0 0 1 1.757 4.243V426a6 6 0 0 1-6 6zM224 232c-48.523 0-88 39.477-88 88s39.477 88 88 88 88-39.477 88-88-39.477-88-88-88zm0 128c-22.056 0-40-17.944-40-40s17.944-40 40-40 40 17.944 40 40-17.944 40-40 40z';
exports.definition = {
prefix: prefix,
iconName: iconName,
icon: [
width,
height,
ligatures,
unicode,
svgPathData
]};
exports.faSave = 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-regular-svg-icons/faSave.js | JavaScript | gpl-3.0 | 1,142 |
$(document).ready(function () {
//selecting supplier
// $('body').off('click','supplier_id.select_popup').on('click','supplier_id.select_popup' ,function () {
// void window.open('select.php?class_name=supplier', '_blank',
// 'width=1200,height=1000,TOOLBAR=no,MENUBAR=no,SCROLLBARS=yes,RESIZABLE=yes,LOCATION=no,DIRECTORIES=no,STATUS=no');
// return false;
// });
//Popup for selecting address
$('body').off('click','.address_popup').on('click','.address_popup',function (e) {
e.preventDefault();
var rowClass = $(this).closest('div').prop('class');
localStorage.setItem("addressPopupDivClass", rowClass);
void window.open('form.php?class_name=address&mode=9&window_type=popup', '_blank',
'width=1200,height=1000,TOOLBAR=no,MENUBAR=no,SCROLLBARS=yes,RESIZABLE=yes,LOCATION=no,DIRECTORIES=no,STATUS=no');
return false;
});
$("#supplier_site_name").on("change", function () {
if ($(this).val() == 'newentry') {
if (confirm("Do you want to create a new supplier site?")) {
$(this).replaceWith('<input id="supplier_site_name" class="textfield supplier_site_name" type="text" size="25" maxlength="50" name="supplier_site_name[]">');
$(".show.supplier_site_id").hide();
$("#supplier_site_id").val("");
$("#supplier_site_number").val("");
}
}
});
});
| kkassed/inoERP | inoerp/modules/ap/supplier/supplier.js | JavaScript | mpl-2.0 | 1,319 |
import { useBackend, useSharedState } from '../backend';
import { Box, Button, Dimmer, Icon, LabeledList, Section, Tabs } from '../components';
import { Window } from '../layouts';
export const Limbgrower = (props, context) => {
const { act, data } = useBackend(context);
const {
reagents = [],
total_reagents,
max_reagents,
categories = [],
busy,
} = data;
const [tab, setTab] = useSharedState(
context, 'category', categories[0]?.name);
const designList = categories
.find(category => category.name === tab)
?.designs || [];
return (
<Window
title="Limb Grower"
width={400}
height={550}>
{!!busy && (
<Dimmer fontSize="32px">
<Icon name="cog" spin={1} />
{' Building...'}
</Dimmer>
)}
<Window.Content scrollable>
<Section title="Reagents">
<Box mb={1}>
{total_reagents} / {max_reagents} reagent capacity used.
</Box>
<LabeledList>
{reagents.map(reagent => (
<LabeledList.Item
key={reagent.reagent_name}
label={reagent.reagent_name}
buttons={(
<Button.Confirm
textAlign="center"
width="120px"
content="Remove Reagent"
color="bad"
onClick={() => act('empty_reagent', {
reagent_type: reagent.reagent_type,
})} />
)}>
{reagent.reagent_amount}u
</LabeledList.Item>
))}
</LabeledList>
</Section>
<Section title="Designs">
<Tabs>
{categories.map(category => (
<Tabs.Tab
fluid
key={category.name}
selected={tab === category.name}
onClick={() => setTab(category.name)}>
{category.name}
</Tabs.Tab>
))}
</Tabs>
<LabeledList>
{designList.map(design => (
<LabeledList.Item
key={design.name}
label={design.name}
buttons={(
<Button
content="Make"
color="good"
onClick={() => act('make_limb', {
design_id: design.id,
active_tab: design.parent_category,
})} />
)}>
{design.needed_reagents.map(reagent => (
<Box key={reagent.name}>
{reagent.name}: {reagent.amount}u
</Box>
))}
</LabeledList.Item>
))}
</LabeledList>
</Section>
</Window.Content>
</Window>
);
};
| Bawhoppen/-tg-station | tgui/packages/tgui/interfaces/Limbgrower.js | JavaScript | agpl-3.0 | 2,874 |
var myTabOption = [
{optionValue:"Default", optionText:"Default", addClass:"", url:"index.html"},
{optionValue:"scriptTab", optionText:"Script Tab", addClass:"", url:"scriptTab.html"}
//{optionValue:"script2Depth", optionText:"Script 2Depth", addClass:"", url:"script2DepthTab.html"}
];
var pageTabChange = function(selectedObject, value){
location.href = selectedObject.url;
};
$(document.body).ready(function(){
var myPageID = "";
try{
myPageID = pageID;
}catch(e){
}
$("#demoPageTabTarget").bindTab({
value: (myPageID||""),
overflow: "scroll",
options: myTabOption,
onchange: pageTabChange
});
}); | thomasJang/axisj | samples/AXTabs/pageTab.js | JavaScript | lgpl-2.1 | 631 |
function(doc) {
if(doc.tags.length > 0) {
for(var idx in doc.tags) {
emit(doc.tags[idx], null);
}
}
} | Arcticwolf/Ektorp | org.ektorp/src/test/resources/org/ektorp/support/map.js | JavaScript | apache-2.0 | 119 |
#!/usr/bin/env node
var fs = require('fs'),
path = require('path');
//kansorc = require('kanso/kansorc');
//kansorc.load(function (err, cfg) {
var commands = {
'clear-cache': null,
'create': null,
'createdb': null,
'deletedb': null,
'listdb': null,
'replicate': null,
'help': [{list: [
'clear-cache',
'create',
'createdb',
'deletedb',
'listdb',
'replicate',
'help',
'install',
'update',
'ls',
'pack',
'publish',
'push',
'show',
'transform',
'unpublish',
'upload',
'uuids'
]}],
'install': [{directories: true, filenames: /.*\.tar\.gz$/}],
'update': null,
'ls': [{directories: true}],
'pack': [{directories: true}],
'publish': [{directories: true}],
// TODO: add lookup of environments in .kansorc
'push': [{environments: true, directories: true}, {environments: true}],
'show': [{directories: true}],
'transform': [
{list: ['clear-ids', 'add-ids', 'csv', 'map']},
{filenames: /.*/, directories: true}, // could be .json or .csv / .tsv
{filenames: /.*\.json$/, directories: true}
],
'unpublish': null,
'upload': [{filenames: /.*\.json$/, directories: true}, {environments: true}],
'uuids': null
};
var args = process.argv.slice(3);
var arglen = 0;
for (var i = 0; i < args.length; i++) {
if (args[i] && args[i][0] !== '-') {
arglen++;
}
}
var command = null;
for (var j = 0; j < args.length; j++) {
if (args[j] && args[j][0] !== '-') {
command = args[j];
break;
}
}
// the current text being entered
var curr = args[args.length - 1];
function trim(str) {
return str.replace(/^\s+/, '').replace(/\s+$/, '');
}
function matchList(list, curr, /*optional*/nextlist) {
var m = [];
list.forEach(function (l) {
if (l.indexOf(curr) === 0) {
m.push(l + ' ');
}
});
if (m.length === 1 && trim(m[0]) === trim(curr)) {
return nextlist || [];
}
return m;
}
function completeList(argdef) {
if (!argdef) {
return [];
}
var l = [];
if (argdef.list) {
l = l.concat(argdef.list);
}
if (argdef.directories) {
l = l.concat(
fs.readdirSync('.').filter(function (f) {
return fs.statSync(f).isDirectory();
})
);
}
if (argdef.filenames) {
l = l.concat(
fs.readdirSync('.').filter(function (f) {
return argdef.filenames.test(f);
})
);
}
return l;
}
var matches = [];
// list all commands
if (arglen === 0) {
matches = Object.keys(commands);
}
// complete first command
else if (arglen === 1) {
matches = matchList(
Object.keys(commands),
curr,
commands[curr] && completeList(commands[curr][0])
);
}
// match command arguments
else if (arglen > 1) {
if (commands[command] && commands[command][arglen - 2]) {
var argdef = commands[command][arglen - 2];
var next_argdef = commands[command][arglen - 1];
if (argdef.list) {
matches = matches.concat(
matchList(
argdef.list, curr, completeList(next_argdef)
)
);
}
if (argdef.directories) {
var wd = './';
if (curr && /\/$/.test(curr)) {
wd = curr;
}
else if (curr) {
wd = path.dirname(curr) + '/';
}
var files = fs.readdirSync(wd);
var dirs = files.filter(function (f) {
return fs.statSync(wd === './' ? f: wd + f).isDirectory();
}).map(function (d) {
return wd === './' ? d: wd + d;
});
matches = matches.concat(
matchList(dirs, curr, completeList(next_argdef))
);
}
if (argdef.filenames) {
var wd = './';
if (curr && /\/$/.test(curr)) {
wd = curr;
}
else if (curr) {
wd = path.dirname(curr) + '/';
}
var files = fs.readdirSync(wd);
var dirs = files.filter(function (f) {
return argdef.filenames.test(wd === './' ? f: wd + f);
}).map(function (d) {
return wd === './' ? d: wd + d;
});
matches = matches.concat(
matchList(dirs, curr, completeList(next_argdef))
);
}
}
}
process.stdout.write(matches.join('\n'));
//});
| kanso/kanso | scripts/autocomp.js | JavaScript | apache-2.0 | 4,694 |
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
function loadDashboards() {
var dashboards = dashboardProperties.dashboards;
var dashboard_list = '';
for (var i=0; i<dashboards.length; i++) {
var showDashboard = false;
if (dashboards[i].runtimes[0] == "all") {
showDashboard = true;
} else {
for (var j=0; j<dashboards[i].runtimes.length; j++) {
if (dashboards[i].runtimes[j] == selectedApplicationRevision.runtimeId) {
showDashboard = true;
break;
}
}
}
var isAvailable = (dashboards[i].isAvailable == 'true');
var url = dataAnalyticsServerUrl + dashboards[i].dashboardContext + eval(dashboards[i].dashboardTypeUtil).getQueryString();
if (showDashboard) {
var dashboard = '' +
'<div class="col-xs-12 col-md-12 col-lg-12" data-toggle="tooltip" title="' + dashboards[i].title + '">' +
'<a class="block-anch" href="' + url + ' " onclick="return ' + isAvailable +'" target="_blank">' +
'<div class="block-monitoring wrapper">';
if (!isAvailable) {
dashboard += '<div class="ribbon-wrapper"><div class="ribbon">Available Soon</div></div>';
}
dashboard += '<h3 class="ellipsis"><i class="fw fw-dashboard fw-lg icon"></i>' + dashboards[i].title + '</h3>' +
'</div>' +
'</a>' +
'</div>';
dashboard_list += dashboard;
}
}
$("#dashboards").html(dashboard_list);
}
// DashboardTypeUtil interface
var DashboardTypeUtil = {
getQueryString: function () {}
};
// define classes
var OperationalDashboardTypeUtil = function () {};
var HttpMonitoringDashboardTypeUtil = function () {};
var ESBAnalyticsDashboardTypeUtil = function () {};
// extend the DashboardTypeUtil interface
OperationalDashboardTypeUtil.prototype = Object.create(DashboardTypeUtil);
HttpMonitoringDashboardTypeUtil.prototype = Object.create(DashboardTypeUtil);
ESBAnalyticsDashboardTypeUtil.prototype = Object.create(DashboardTypeUtil);
// actual implementation goes here
OperationalDashboardTypeUtil.prototype.getQueryString = function () {
return "/t/" + tenantDomain + "/dashboards/operational-dashboard/?shared=true&id=" + applicationName + "_" + selectedRevision + "_" + selectedApplicationRevision.hashId;
};
HttpMonitoringDashboardTypeUtil.prototype.getQueryString = function () {
return "?";
};
ESBAnalyticsDashboardTypeUtil.prototype.getQueryString = function () {
var currentTime = new Date().getTime();
var prevTime = currentTime - 3600000;
return "/t/" + tenantDomain + "/dashboards/esb-analytics/?shared=true&timeFrom=" + prevTime + "&timeTo=" + currentTime;
}; | mcvidanagama/app-cloud | modules/jaggeryapps/appmgt/src/site/themes/default/templates/home/js/dashboard.js | JavaScript | apache-2.0 | 3,475 |
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
/**
* Explains a computed value by displaying a hierarchy of its inputs.
*/
(function($) {
/** @constructor */
function DepGraphViewer(_$container, _parentGridName, rowId, colId, _liveResultsClient, _userConfig) {
var self = this;
var _logger = new Logger("DepGraphViewer", "debug");
var _grid;
var _gridHelper;
var _dataView;
var _columns;
var _fullRows
function init() {
_dataView = new Slick.Data.DataView();
var targetColumn = {
id : "target",
name : "Target",
field : "target",
width : 300,
formatter : formatTargetName
};
_columns = [
{
colId: 'targetType',
header: "Type",
typeFormatter: PrimitiveFormatter,
width: 40
},
{
colId: 'valueName',
header: "Value Name",
typeFormatter: PrimitiveFormatter
},
{
colId: 0,
header: "Value",
typeFormatter: PrimitiveFormatter,
nullValue: "null",
dynamic: true,
width: 250
},
{
colId: 'function',
header: "Function",
typeFormatter: PrimitiveFormatter,
nullValue: "null",
width: 200
},
{
colId: 'properties',
header: "Properties",
typeFormatter: PrimitiveFormatter,
nullValue: "",
width: 400
}
];
var gridColumns = SlickGridHelper.makeGridColumns(self, [targetColumn], _columns, 150, _userConfig);
var gridOptions = {
editable: false,
enableAddRow: false,
enableCellNavigation: false,
asyncEditorLoading: false,
};
var $depGraphGridContainer = $("<div class='grid'></div>").appendTo(_$container);
_grid = new Slick.Grid($depGraphGridContainer, _dataView.rows, gridColumns, gridOptions);
_grid.onClick = onGridClicked;
_gridHelper = new SlickGridHelper(_grid, _dataView, _liveResultsClient.triggerImmediateUpdate, false);
_gridHelper.afterViewportStable.subscribe(afterGridViewportStable);
_liveResultsClient.beforeUpdateRequested.subscribe(beforeUpdateRequested);
_userConfig.onSparklinesToggled.subscribe(onSparklinesToggled);
}
function formatValue(row, cell, value, columnDef, dataContext) {
return "<span class='cell-value'>" + value + "</span>";
}
//-----------------------------------------------------------------------
// Event handling
function beforeUpdateRequested(updateMetadata) {
var gridId = _parentGridName + "-" + rowId + "-" + colId;
updateMetadata.depGraphViewport[gridId] = {};
_gridHelper.populateViewportData(updateMetadata.depGraphViewport[gridId]);
}
function onGridClicked(e, row, cell) {
if ($(e.target).hasClass("toggle")) {
var item = _dataView.rows[row];
if (item) {
if (!item._collapsed) {
item._collapsed = true;
} else {
item._collapsed = false;
}
_dataView.updateItem(item.rowId, item);
_grid.removeAllRows();
_grid.render();
_liveResultsClient.triggerImmediateUpdate();
}
return true;
}
return false;
}
function afterGridViewportStable() {
_liveResultsClient.triggerImmediateUpdate();
}
function onSparklinesToggled(sparklinesEnabled) {
_grid.reprocessAllRows();
}
//-----------------------------------------------------------------------
function dataViewFilter(item) {
var idx = _dataView.getIdxById(item.rowId);
if (item.parentRowId != null) {
var parent = _dataView.getItemById(item.parentRowId);
while (parent) {
if (parent._collapsed) {
return false;
}
parent = _dataView.getItemById(parent.parentRowId);
}
}
return true;
}
function formatTargetName(row, cell, value, columnDef, dataContext) {
var rowIndex = _dataView.getIdxById(dataContext.rowId);
if (!_fullRows) {
return null;
} else {
return SlickGridHelper.formatCellWithToggle(_fullRows, rowIndex, dataContext, value);
}
}
//-----------------------------------------------------------------------
// Public API
this.updateValue = function(update) {
if (!update) {
return;
}
if (!_fullRows) {
if (!update['grid']) {
// Cannot do anything with the update
_logger.warn("Dependency graph update received without grid structure");
return;
}
self.popupManager = new PopupManager(null, null, null, update['grid']['name'], _dataView, _liveResultsClient, _userConfig);
_fullRows = update['grid']['rows'];
$.each(_fullRows, function(idx, row) {
if (row.indent >= 2) {
row._collapsed = true;
}
});
_dataView.beginUpdate();
_dataView.setItems(_fullRows, 'rowId');
_dataView.setFilter(dataViewFilter);
_dataView.endUpdate();
_gridHelper.handleUpdate(update['update'], _columns);
} else {
_gridHelper.handleUpdate(update, _columns);
}
}
this.resize = function() {
_grid.resizeCanvas();
}
this.destroy = function() {
_userConfig.onSparklinesToggled.unsubscribe(onSparklinesToggled);
_liveResultsClient.beforeUpdateRequested.unsubscribe(beforeUpdateRequested);
_gridHelper.destroy();
_grid.onClick = null;
_grid.destroy();
}
//-----------------------------------------------------------------------
init();
}
$.extend(true, window, {
DepGraphViewer : DepGraphViewer
});
}(jQuery)); | McLeodMoores/starling | projects/web/web-engine/analytics/js/depGraphViewer.js | JavaScript | apache-2.0 | 6,149 |
//// [test.tsx]
export class C {
factory() {
return <div></div>;
}
}
//// [test.js]
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.C = void 0;
class C {
factory() {
return factory.createElement("div", null);
}
}
exports.C = C;
| Microsoft/TypeScript | tests/baselines/reference/jsxFactoryMissingErrorInsideAClass.js | JavaScript | apache-2.0 | 312 |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(241)
var __weex_style__ = __webpack_require__(242)
var __weex_script__ = __webpack_require__(243)
__weex_define__('@weex-component/c0df89e239d226d3a0c6f418314cda04', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
__weex_bootstrap__('@weex-component/c0df89e239d226d3a0c6f418314cda04',undefined,undefined)
/***/ },
/***/ 241:
/***/ function(module, exports) {
module.exports = {
"type": "container",
"children": [
{
"type": "text",
"classList": [
"btn"
],
"attr": {
"value": function () {return this.board}
}
},
{
"type": "container",
"repeat": function () {return this.row},
"style": {
"flexDirection": "row",
"flex": 1
},
"children": [
{
"type": "container",
"repeat": function () {return this.col},
"style": {
"flex": 1
},
"children": [
{
"type": "text",
"attr": {
"tid": function () {return this.tid},
"around": function () {return this.around},
"value": function () {return this.text}
},
"events": {
"click": "onclick",
"longpress": "onlongpress"
},
"classList": function () {return [this.state, 'tile']}
}
]
}
]
},
{
"type": "text",
"events": {
"click": "restart"
},
"classList": [
"btn"
],
"attr": {
"value": "START"
}
}
]
}
/***/ },
/***/ 242:
/***/ function(module, exports) {
module.exports = {
"btn": {
"margin": 2,
"backgroundColor": "#e74c3c",
"color": "#ffffff",
"textAlign": "center",
"flex": 1,
"fontSize": 66,
"height": 80
},
"normal": {
"backgroundColor": "#95a5a6"
},
"open": {
"backgroundColor": "#34495e",
"color": "#ffffff"
},
"flag": {
"backgroundColor": "#95a5a6"
},
"tile": {
"margin": 2,
"fontSize": 56,
"height": 80,
"paddingTop": 0,
"textAlign": "center"
}
}
/***/ },
/***/ 243:
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){"use strict";
module.exports = {
data: function () {return {
size: 9,
max: 10,
board: 0,
row: [],
vector: [[-1, 0], [-1, -1], [0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1]],
strings: {
mine: "💣",
flag: "🚩",
win: "YOU WIN!",
lose: "YOU LOSE~"
},
finished: false
}},
methods: {
map: function map(x, y, callback) {
for (var i = 0; i < 8; ++i) {
var mx = x + this.vector[i][0];
var my = y + this.vector[i][1];
if (mx >= 0 && my >= 0 && mx < this.size && my < this.size) {
callback(this.row[mx].col[my]);
}
}
},
dfs: function dfs(tile) {
var pos = this.position(tile.tid);
var context = this;
tile.state = "open";
this.map(pos["x"], pos["y"], function (node) {
if (node.around == 0 && node.state == "normal") {
context.dfs(node);
} else {
context.display(node);
}
});
},
random: function random(min, max) {
return parseInt(Math.random() * (max - min) + min);
},
plant: function plant() {
var count = 0;
while (count < this.max) {
var x = this.random(0, this.size);
var y = this.random(0, this.size);
var tile = this.row[x].col[y];
if (tile.value == 0) {
++count;
tile.value = 1;
}
}
},
calculate: function calculate() {
for (var i = 0; i < this.size; ++i) {
for (var j = 0; j < this.size; ++j) {
var around = 0;
this.map(i, j, function (tile) {
around += tile.value;
});
this.row[i].col[j].around = around;
}
}
},
restart: function restart(e) {
var row = [];
var count = 0;
this.board = this.max;
this.finished = false;
for (var i = 0; i < this.size; ++i) {
var col = { "col": [] };
for (var j = 0; j < this.size; ++j) {
var tid = i * this.size + j;
col["col"][j] = {
tid: "" + tid,
state: "normal",
value: 0,
text: "",
around: 0
};
}
row[i] = col;
}
this.row = row;
this.plant();
this.calculate();
},
unfinished: function unfinished() {
var finished = this.finished;
if (this.finished) {
this.restart();
}
return !finished;
},
position: function position(tid) {
var row = parseInt(tid / this.size);
var col = tid % this.size;
return { x: row, y: col };
},
display: function display(tile) {
tile.state = "open";
tile.text = tile.around == 0 ? "" : tile.around;
},
tile: function tile(event) {
var tid = event.target.attr["tid"];
var pos = this.position(tid);
return this.row[pos["x"]].col[pos["y"]];
},
onclick: function onclick(event) {
if (this.unfinished()) {
var tile = this.tile(event);
if (tile.state == "normal") {
if (tile.value == 1) {
this.onfail();
} else {
this.display(tile);
if (tile.around == 0) {
this.dfs(tile);
}
this.judge();
}
}
}
},
onlongpress: function onlongpress(event) {
if (this.unfinished()) {
var tile = this.tile(event);
tile.state = tile.state == "flag" ? "normal" : "flag";
if (tile.state == "flag") {
--this.board;
tile.text = this.strings.flag;
} else {
++this.board;
tile.text = "";
}
this.judge();
}
},
foreach: function foreach(callback) {
for (var i = 0; i < this.size; ++i) {
for (var j = 0; j < this.size; ++j) {
callback(this.row[i].col[j]);
}
}
},
judge: function judge() {
var count = 0;
this.foreach(function (tile) {
if (tile.state == "open" || tile.state == "flag") {
++count;
}
});
if (count == this.size * this.size) {
this.finished = true;
this.board = this.strings.win;
}
},
onfail: function onfail() {
this.board = this.strings.lose;
this.finished = true;
var mine = this.strings.mine;
this.foreach(function (tile) {
if (tile.value == 1) {
tile.text = mine;
}
});
}
}
};}
/* generated by weex-loader */
/***/ }
/******/ }); | MrRaindrop/incubator-weex | android/playground/app/src/main/assets/showcase/minesweeper.js | JavaScript | apache-2.0 | 8,825 |
define(["Ti/_", "Ti/_/declare", "Ti/_/lang", "Ti/_/Evented", "Ti/Network", "Ti/Blob", "Ti/_/event"],
function(_, declare, lang, Evented, Network, Blob, event) {
var is = require.is,
on = require.on;
return declare("Ti.Network.HTTPClient", Evented, {
constructor: function() {
var xhr = this._xhr = new XMLHttpRequest;
this._handles = [
on(xhr, "error", this, "_onError"),
on(xhr.upload, "error", this, "_onError"),
on(xhr, "progress", this, function(evt) {
evt.progress = evt.lengthComputable ? evt.loaded / evt.total : false;
is(this.ondatastream, "Function") && this.ondatastream.call(this, evt);
}),
on(xhr.upload, "progress", this, function(evt) {
evt.progress = evt.lengthComputable ? evt.loaded / evt.total : false;
is(this.onsendstream, "Function") && this.onsendstream.call(this, evt);
})
];
xhr.onreadystatechange = lang.hitch(this, function() {
var c = this.constants;
switch (xhr.readyState) {
case 0: c.readyState = this.UNSENT; break;
case 1: c.readyState = this.OPENED; break;
case 2: c.readyState = this.LOADING; break;
case 3: c.readyState = this.HEADERS_RECEIVED; break;
case 4:
clearTimeout(this._timeoutTimer);
this._completed = 1;
c.readyState = this.DONE;
if (xhr.status == 200) {
if (this.file) {
Filesystem.getFile(Filesystem.applicationDataDirectory,
this.file).write(xhr.responseText);
}
c.responseText = xhr.responseText;
c.responseData = new Blob({
data: xhr.responseText,
length: xhr.responseText.length,
mimeType: xhr.getResponseHeader("Content-Type")
});
c.responseXML = xhr.responseXML;
is(this.onload, "Function") && this.onload.call(this);
} else {
xhr.status / 100 | 0 > 3 && this._onError();
}
}
this._fireStateChange();
});
},
destroy: function() {
if (this._xhr) {
this._xhr.abort();
this._xhr = null;
}
event.off(this._handles);
Evented.destroy.apply(this, arguments);
},
_onError: function(error) {
this.abort();
is(error, "Object") || (error = { message: error });
error.error || (error.error = error.message || this._xhr.status);
parseInt(error.error) || (error.error = "Can't reach host");
is(this.onerror, "Function") && this.onerror.call(this, error);
},
abort: function() {
var c = this.constants;
c.responseText = c.responseXML = c.responseData = "";
this._completed = true;
clearTimeout(this._timeoutTimer);
this.connected && this._xhr.abort();
c.readyState = this.UNSENT;
this._fireStateChange();
},
_fireStateChange: function() {
is(this.onreadystatechange, "Function") && this.onreadystatechange.call(this);
},
getResponseHeader: function(name) {
return this._xhr.readyState > 1 ? this._xhr.getResponseHeader(name) : null;
},
open: function(method, url, async) {
var httpURLFormatter = Ti.Network.httpURLFormatter,
c = this.constants,
wc = this.withCredentials,
async = wc ? true : !!async;
this.abort();
this._xhr.open(
c.connectionType = method,
c.location = _.getAbsolutePath(httpURLFormatter ? httpURLFormatter(url) : url),
async
);
wc && (this._xhr.withCredentials = wc);
},
send: function(args){
try {
var timeout = this.timeout | 0;
this._completed = false;
args = is(args, "Object") ? lang.urlEncode(args) : args;
args && this._xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
this._xhr.send(args);
clearTimeout(this._timeoutTimer);
timeout && (this._timeoutTimer = setTimeout(lang.hitch(this, function() {
if (this.connected) {
this.abort();
!this._completed && this._onError("Request timed out");
}
}, timeout)));
} catch (ex) {console.debug(ex)}
},
setRequestHeader: function(name, value) {
this._xhr.setRequestHeader(name, value);
},
properties: {
ondatastream: void 0,
onerror: void 0,
onload: void 0,
onreadystatechange: void 0,
onsendstream: void 0,
timeout: void 0,
withCredentials: false
},
constants: {
DONE: 4,
HEADERS_RECEIVED: 2,
LOADING: 3,
OPENED: 1,
UNSENT: 1,
connected: function() {
return this.readyState >= this.OPENED;
},
connectionType: void 0,
location: void 0,
readyState: this.UNSENT,
responseData: void 0,
responseText: void 0,
responseXML: void 0,
status: function() {
return this._xhr.status;
},
statusText: function() {
return this._xhr.statusText;
}
}
});
});
| lpaulger/gitTogether | build/mobileweb/titanium/Ti/Network/HTTPClient.js | JavaScript | apache-2.0 | 4,635 |
jQuery(document).ready(function($){
//check if the .cd-image-container is in the viewport
//if yes, animate it
checkPosition($('.cd-image-container'));
$(window).on('scroll', function(){
checkPosition($('.cd-image-container'));
});
//make the .cd-handle element draggable and modify .cd-resize-img width according to its position
$('.cd-image-container').each(function(){
var actual = $(this);
drags(actual.find('.cd-handle'), actual.find('.cd-resize-img'), actual, actual.find('.cd-image-label[data-type="original"]'), actual.find('.cd-image-label[data-type="modified"]'));
});
//upadate images label visibility
$(window).on('resize', function(){
$('.cd-image-container').each(function(){
var actual = $(this);
updateLabel(actual.find('.cd-image-label[data-type="modified"]'), actual.find('.cd-resize-img'), 'left');
updateLabel(actual.find('.cd-image-label[data-type="original"]'), actual.find('.cd-resize-img'), 'right');
});
});
});
function checkPosition(container) {
container.each(function(){
var actualContainer = $(this);
if( $(window).scrollTop() + $(window).height()*0.5 > actualContainer.offset().top) {
actualContainer.addClass('is-visible');
}
});
}
//draggable funtionality - credits to http://css-tricks.com/snippets/jquery/draggable-without-jquery-ui/
function drags(dragElement, resizeElement, container, labelContainer, labelResizeElement) {
dragElement.on("mousedown vmousedown", function(e) {
dragElement.addClass('draggable');
resizeElement.addClass('resizable');
var dragWidth = dragElement.outerWidth(),
xPosition = dragElement.offset().left + dragWidth - e.pageX,
containerOffset = container.offset().left,
containerWidth = container.outerWidth(),
minLeft = containerOffset + 10,
maxLeft = containerOffset + containerWidth - dragWidth - 10;
dragElement.parents().on("mousemove vmousemove", function(e) {
leftValue = e.pageX + xPosition - dragWidth;
//constrain the draggable element to move inside his container
if(leftValue < minLeft ) {
leftValue = minLeft;
} else if ( leftValue > maxLeft) {
leftValue = maxLeft;
}
widthValue = (leftValue + dragWidth/2 - containerOffset)*100/containerWidth+'%';
$('.draggable').css('left', widthValue).on("mouseup vmouseup", function() {
$(this).removeClass('draggable');
resizeElement.removeClass('resizable');
});
$('.resizable').css('width', widthValue);
updateLabel(labelResizeElement, resizeElement, 'left');
updateLabel(labelContainer, resizeElement, 'right');
}).on("mouseup vmouseup", function(e){
dragElement.removeClass('draggable');
resizeElement.removeClass('resizable');
});
e.preventDefault();
}).on("mouseup vmouseup", function(e) {
dragElement.removeClass('draggable');
resizeElement.removeClass('resizable');
});
}
function updateLabel(label, resizeElement, position) {
if(position == 'left') {
( label.offset().left + label.outerWidth() < resizeElement.offset().left + resizeElement.outerWidth() ) ? label.removeClass('is-hidden') : label.addClass('is-hidden') ;
} else {
( label.offset().left > resizeElement.offset().left + resizeElement.outerWidth() ) ? label.removeClass('is-hidden') : label.addClass('is-hidden') ;
}
} | yakunichkin/portfolio-diana | web/comparison/js/main.js | JavaScript | bsd-3-clause | 3,722 |
/*!
* @package yii2-grid
* @author Kartik Visweswaran <kartikv2@gmail.com>
* @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
* @version 3.0.1
*
* Client actions for yii2-grid CheckboxColumn
*
* Author: Kartik Visweswaran
* Copyright: 2015, Kartik Visweswaran, Krajee.com
* For more JQuery plugins visit http://plugins.krajee.com
* For more Yii related demos visit http://demos.krajee.com
*/
var kvSelectRow = function (gridId, css) {
"use strict";
(function ($) {
var $grid = $('#' + gridId), $el;
$grid.find(".kv-row-select input").on('change', function () {
$el = $(this);
if ($el.is(':checked')) {
$el.parents("tr:first").removeClass(css).addClass(css);
} else {
$el.parents("tr:first").removeClass(css);
}
});
$grid.find(".kv-all-select input").on('change', function () {
if ($(this).is(':checked')) {
$grid.find(".kv-row-select").parents("tr").removeClass(css).addClass(css);
}
else {
$grid.find(".kv-row-select").parents("tr").removeClass(css);
}
});
})(window.jQuery);
}; | yoganurdani/yiibi | web/assets/ea577e1c/js/kv-grid-checkbox.js | JavaScript | bsd-3-clause | 1,234 |
function nextLevel(nodeList, startIndex, hlevel, prefix, tocString)
{
var hIndex = 1;
var i = startIndex;
while (i < nodeList.length) {
var currentNode = nodeList[i];
if (currentNode.tagName != "H"+hlevel)
break;
if (currentNode.className == "no-toc") {
++i;
continue;
}
var sectionString = prefix+hIndex;
// Update the TOC
var text = currentNode.innerHTML;
// Strip off names specified via <a name="..."></a>
var tocText = text.replace(/<a name=[\'\"][^\'\"]*[\'\"]>([^<]*)<\/a>/g, "$1");
tocString.s += "<li class='toc-h"+hlevel+"'><a href='#"+sectionString+"'><span class='secno'>"+sectionString+"</span>"+tocText+"</a></li>\n";
// Modify the header
currentNode.innerHTML = "<span class=secno>"+sectionString+"</span> "+text;
currentNode.id = sectionString;
// traverse children
i = nextLevel(nodeList, i+1, hlevel+1, sectionString+".", tocString);
hIndex++;
}
return i;
}
function generateTOC(toc)
{
var nodeList = $("h2,h3,h4,h5,h6");
var tocString = { s:"<ul class='toc'>\n" };
nextLevel(nodeList, 0, 2, "", tocString);
toc.innerHTML = tocString.s;
// Now position the document, in case a #xxx directive was given
var id = window.location.hash.substring(1);
if (id.length > 0) {
var target = document.getElementById(id);
if (target) {
var rect = target.getBoundingClientRect();
setTimeout(function() { window.scrollTo(0, rect.top) }, 0);
}
}
}
| mxOBS/deb-pkg_trusty_chromium-browser | third_party/webgl/src/resources/generateTOC.js | JavaScript | bsd-3-clause | 1,688 |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2008-2009, The KiWi Project (http://www.kiwi-project.eu)
* 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 the KiWi Project 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.
*
* Contributor(s):
* Sebastian Schaffert
*
*/
/**
* A jQuery widget to display the KiWi tags for a context content item. Can be
* invoked on arbitrary elements selected by jQuery. The widget currently supports two modes:
* - list: returns the list of currently assigned tags of the content item
* - recommendations: returns the list of tag recommendations for the content item based on text
* analysis
*
* The widget takes the following options when initialising:
* - uri: the URI of the currently displayed content item (either the currentContentItem in KiWi or
* the URL of some external page using the widget); defaults to currently displayed page
*
* - webServiceUrl: the URL to locate the KiWi ActivityWidgetWebService; defaults to
* http://localhost:8080/KiWi/seam/resource/services/widgets/tags/{mode}
*
* - num: the number of results to return (recommendations only); defaults to 10
*
* - mode: one of list/recommendations; defaults to 'list'
*
* - callback: a function that takes the returned JSON data as arguments and returns the HTML to
* be inserted in the tag cloud; defaults to a simple list that renders each tag as
* a link to the search function
*
* Example:
*
* <p id="tags">Test</p>
* <script>
* $(document).ready(function(){
* $('#tags').tags({uri: 'http://localhost:8080/KiWi/content/FrontPage'});
* });
* </script>
*
*/
(function($){
$.widget("kiwi.tags", {
/**
* Constructor;
*/
_init: function() {
this.refresh();
},
refresh: function() {
var webservice = this.getWebServiceUrl();
var context = this.getUri();
var num = this.getNum();
var mode = this.getMode();
var callback = this.getCallback();
if(!callback) {
callback = function(data) {
if(data.length == 0) {
element.html("<em>no tags</em>");
} else {
var html="";
$.each(data, function(i, item) {
html += "<a href=\"\">" + item.tag.@title + "</a> ";
});
}
return html;
}
}
if(webservice.charAt(webservice.length-1) != '/') {
webservice += '/';
}
// compose the query to the webservice
var url = webservice + mode + "?" + $.param({ uri: context, num: num, user: user }) + "&jsonpCallback=?";
this.element.html("Loading ... ");
var element = this.element;
// call the TagsWidgetWebService using JSONP and create a <ul> list of items
$.getJSON(url,
function(data) {
var html= callback(data);
element.html(html);
}
);
},
/**
* The URI of the currently visited page
*/
getUri: function() {
return this._getData("uri");
},
setUri: function(data) {
this._setData("uri",data);
},
/**
* The URL of the web service to connect to
*/
getWebServiceUrl: function() {
return this._getData("webServiceUrl");
},
/**
* The result count to return.
*/
getNum: function() {
return this._getData("num");
},
/**
* The currently active user
*/
getUser: function() {
return this._getData("user");
},
/**
* The mode of the recommendation widget; one of simple/multifactor/personal
*
*/
getMode: function() {
return this._getData("mode");
}
});
$.kiwi.tags.defaults = {
webServiceUrl: 'http://localhost:8080/KiWi/seam/resource/services/widgets/tags',
mode: 'list',
uri: window.location.href,
num: 10
};
})(jQuery);
| StexX/KiWi-OSE | view/widgets/tags/widget.tags.js | JavaScript | bsd-3-clause | 5,551 |
/*! =========================================================
* bootstrap-slider.js
*
* Maintainers:
* Kyle Kemp
* - Twitter: @seiyria
* - Github: seiyria
* Rohit Kalkur
* - Twitter: @Rovolutionary
* - Github: rovolution
*
* =========================================================
*
* 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.
* ========================================================= */
/**
* Bridget makes jQuery widgets
* v1.0.1
* MIT license
*/
(function(root, factory) {
if(typeof define === "function" && define.amd) {
define(["jquery"], factory);
} else if(typeof module === "object" && module.exports) {
var jQuery;
try {
jQuery = require("jquery");
} catch (err) {
jQuery = null;
}
module.exports = factory(jQuery);
} else {
root.Slider = factory(root.jQuery);
}
}(this, function($) {
// Reference to Slider constructor
var Slider;
(function( $ ) {
'use strict';
// -------------------------- utils -------------------------- //
var slice = Array.prototype.slice;
function noop() {}
// -------------------------- definition -------------------------- //
function defineBridget( $ ) {
// bail if no jQuery
if ( !$ ) {
return;
}
// -------------------------- addOptionMethod -------------------------- //
/**
* adds option method -> $().plugin('option', {...})
* @param {Function} PluginClass - constructor class
*/
function addOptionMethod( PluginClass ) {
// don't overwrite original option method
if ( PluginClass.prototype.option ) {
return;
}
// option setter
PluginClass.prototype.option = function( opts ) {
// bail out if not an object
if ( !$.isPlainObject( opts ) ){
return;
}
this.options = $.extend( true, this.options, opts );
};
}
// -------------------------- plugin bridge -------------------------- //
// helper function for logging errors
// $.error breaks jQuery chaining
var logError = typeof console === 'undefined' ? noop :
function( message ) {
console.error( message );
};
/**
* jQuery plugin bridge, access methods like $elem.plugin('method')
* @param {String} namespace - plugin name
* @param {Function} PluginClass - constructor class
*/
function bridge( namespace, PluginClass ) {
// add to jQuery fn namespace
$.fn[ namespace ] = function( options ) {
if ( typeof options === 'string' ) {
// call plugin method when first argument is a string
// get arguments for method
var args = slice.call( arguments, 1 );
for ( var i=0, len = this.length; i < len; i++ ) {
var elem = this[i];
var instance = $.data( elem, namespace );
if ( !instance ) {
logError( "cannot call methods on " + namespace + " prior to initialization; " +
"attempted to call '" + options + "'" );
continue;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === '_' ) {
logError( "no such method '" + options + "' for " + namespace + " instance" );
continue;
}
// trigger method with arguments
var returnValue = instance[ options ].apply( instance, args);
// break look and return first value if provided
if ( returnValue !== undefined && returnValue !== instance) {
return returnValue;
}
}
// return this if no return value
return this;
} else {
var objects = this.map( function() {
var instance = $.data( this, namespace );
if ( instance ) {
// apply options & init
instance.option( options );
instance._init();
} else {
// initialize new instance
instance = new PluginClass( this, options );
$.data( this, namespace, instance );
}
return $(this);
});
if(!objects || objects.length > 1) {
return objects;
} else {
return objects[0];
}
}
};
}
// -------------------------- bridget -------------------------- //
/**
* converts a Prototypical class into a proper jQuery plugin
* the class must have a ._init method
* @param {String} namespace - plugin name, used in $().pluginName
* @param {Function} PluginClass - constructor class
*/
$.bridget = function( namespace, PluginClass ) {
addOptionMethod( PluginClass );
bridge( namespace, PluginClass );
};
return $.bridget;
}
// get jquery from browser global
defineBridget( $ );
})( $ );
/*************************************************
BOOTSTRAP-SLIDER SOURCE CODE
**************************************************/
(function($) {
var ErrorMsgs = {
formatInvalidInputErrorMsg : function(input) {
return "Invalid input value '" + input + "' passed in";
},
callingContextNotSliderInstance : "Calling context element does not have instance of Slider bound to it. Check your code to make sure the JQuery object returned from the call to the slider() initializer is calling the method"
};
/*************************************************
CONSTRUCTOR
**************************************************/
Slider = function(element, options) {
createNewSlider.call(this, element, options);
return this;
};
function createNewSlider(element, options) {
/*************************************************
Create Markup
**************************************************/
if(typeof element === "string") {
this.element = document.querySelector(element);
} else if(element instanceof HTMLElement) {
this.element = element;
}
var origWidth = this.element.style.width;
var updateSlider = false;
var parent = this.element.parentNode;
var sliderTrackSelection;
var sliderMinHandle;
var sliderMaxHandle;
if (this.sliderElem) {
updateSlider = true;
} else {
/* Create elements needed for slider */
this.sliderElem = document.createElement("div");
this.sliderElem.className = "slider";
/* Create slider track elements */
var sliderTrack = document.createElement("div");
sliderTrack.className = "slider-track";
sliderTrackSelection = document.createElement("div");
sliderTrackSelection.className = "slider-selection";
sliderMinHandle = document.createElement("div");
sliderMinHandle.className = "slider-handle min-slider-handle";
sliderMaxHandle = document.createElement("div");
sliderMaxHandle.className = "slider-handle max-slider-handle";
sliderTrack.appendChild(sliderTrackSelection);
sliderTrack.appendChild(sliderMinHandle);
sliderTrack.appendChild(sliderMaxHandle);
var createAndAppendTooltipSubElements = function(tooltipElem) {
var arrow = document.createElement("div");
arrow.className = "tooltip-arrow";
var inner = document.createElement("div");
inner.className = "tooltip-inner";
tooltipElem.appendChild(arrow);
tooltipElem.appendChild(inner);
};
/* Create tooltip elements */
var sliderTooltip = document.createElement("div");
sliderTooltip.className = "tooltip tooltip-main";
createAndAppendTooltipSubElements(sliderTooltip);
var sliderTooltipMin = document.createElement("div");
sliderTooltipMin.className = "tooltip tooltip-min";
createAndAppendTooltipSubElements(sliderTooltipMin);
var sliderTooltipMax = document.createElement("div");
sliderTooltipMax.className = "tooltip tooltip-max";
createAndAppendTooltipSubElements(sliderTooltipMax);
/* Append components to sliderElem */
this.sliderElem.appendChild(sliderTrack);
this.sliderElem.appendChild(sliderTooltip);
this.sliderElem.appendChild(sliderTooltipMin);
this.sliderElem.appendChild(sliderTooltipMax);
/* Append slider element to parent container, right before the original <input> element */
parent.insertBefore(this.sliderElem, this.element);
/* Hide original <input> element */
this.element.style.display = "none";
}
/* If JQuery exists, cache JQ references */
if($) {
this.$element = $(this.element);
this.$sliderElem = $(this.sliderElem);
}
/*************************************************
Process Options
**************************************************/
options = options ? options : {};
var optionTypes = Object.keys(this.defaultOptions);
for(var i = 0; i < optionTypes.length; i++) {
var optName = optionTypes[i];
// First check if an option was passed in via the constructor
var val = options[optName];
// If no data attrib, then check data atrributes
val = (typeof val !== 'undefined') ? val : getDataAttrib(this.element, optName);
// Finally, if nothing was specified, use the defaults
val = (val !== null) ? val : this.defaultOptions[optName];
// Set all options on the instance of the Slider
if(!this.options) {
this.options = {};
}
this.options[optName] = val;
}
function getDataAttrib(element, optName) {
var dataName = "data-slider-" + optName;
var dataValString = element.getAttribute(dataName);
try {
return JSON.parse(dataValString);
}
catch(err) {
return dataValString;
}
}
/*************************************************
Setup
**************************************************/
this.eventToCallbackMap = {};
this.sliderElem.id = this.options.id;
this.touchCapable = 'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch);
this.tooltip = this.sliderElem.querySelector('.tooltip-main');
this.tooltipInner = this.tooltip.querySelector('.tooltip-inner');
this.tooltip_min = this.sliderElem.querySelector('.tooltip-min');
this.tooltipInner_min = this.tooltip_min.querySelector('.tooltip-inner');
this.tooltip_max = this.sliderElem.querySelector('.tooltip-max');
this.tooltipInner_max= this.tooltip_max.querySelector('.tooltip-inner');
if (updateSlider === true) {
// Reset classes
this._removeClass(this.sliderElem, 'slider-horizontal');
this._removeClass(this.sliderElem, 'slider-vertical');
this._removeClass(this.tooltip, 'hide');
this._removeClass(this.tooltip_min, 'hide');
this._removeClass(this.tooltip_max, 'hide');
// Undo existing inline styles for track
["left", "top", "width", "height"].forEach(function(prop) {
this._removeProperty(this.trackSelection, prop);
}, this);
// Undo inline styles on handles
[this.handle1, this.handle2].forEach(function(handle) {
this._removeProperty(handle, 'left');
this._removeProperty(handle, 'top');
}, this);
// Undo inline styles and classes on tooltips
[this.tooltip, this.tooltip_min, this.tooltip_max].forEach(function(tooltip) {
this._removeProperty(tooltip, 'left');
this._removeProperty(tooltip, 'top');
this._removeProperty(tooltip, 'margin-left');
this._removeProperty(tooltip, 'margin-top');
this._removeClass(tooltip, 'right');
this._removeClass(tooltip, 'top');
}, this);
}
if(this.options.orientation === 'vertical') {
this._addClass(this.sliderElem,'slider-vertical');
this.stylePos = 'top';
this.mousePos = 'pageY';
this.sizePos = 'offsetHeight';
this._addClass(this.tooltip, 'right');
this.tooltip.style.left = '100%';
this._addClass(this.tooltip_min, 'right');
this.tooltip_min.style.left = '100%';
this._addClass(this.tooltip_max, 'right');
this.tooltip_max.style.left = '100%';
} else {
this._addClass(this.sliderElem, 'slider-horizontal');
this.sliderElem.style.width = origWidth;
this.options.orientation = 'horizontal';
this.stylePos = 'left';
this.mousePos = 'pageX';
this.sizePos = 'offsetWidth';
this._addClass(this.tooltip, 'top');
this.tooltip.style.top = -this.tooltip.outerHeight - 14 + 'px';
this._addClass(this.tooltip_min, 'top');
this.tooltip_min.style.top = -this.tooltip_min.outerHeight - 14 + 'px';
this._addClass(this.tooltip_max, 'top');
this.tooltip_max.style.top = -this.tooltip_max.outerHeight - 14 + 'px';
}
if (this.options.value instanceof Array) {
this.options.range = true;
} else if (this.options.range) {
// User wants a range, but value is not an array
this.options.value = [this.options.value, this.options.max];
}
this.trackSelection = sliderTrackSelection || this.trackSelection;
if (this.options.selection === 'none') {
this._addClass(this.trackSelection, 'hide');
}
this.handle1 = sliderMinHandle || this.handle1;
this.handle2 = sliderMaxHandle || this.handle2;
if (updateSlider === true) {
// Reset classes
this._removeClass(this.handle1, 'round triangle');
this._removeClass(this.handle2, 'round triangle hide');
}
var availableHandleModifiers = ['round', 'triangle', 'custom'];
var isValidHandleType = availableHandleModifiers.indexOf(this.options.handle) !== -1;
if (isValidHandleType) {
this._addClass(this.handle1, this.options.handle);
this._addClass(this.handle2, this.options.handle);
}
this.offset = this._offset(this.sliderElem);
this.size = this.sliderElem[this.sizePos];
this.setValue(this.options.value);
/******************************************
Bind Event Listeners
******************************************/
// Bind keyboard handlers
this.handle1Keydown = this._keydown.bind(this, 0);
this.handle1.addEventListener("keydown", this.handle1Keydown, false);
this.handle2Keydown = this._keydown.bind(this, 1);
this.handle2.addEventListener("keydown", this.handle2Keydown, false);
if (this.touchCapable) {
// Bind touch handlers
this.mousedown = this._mousedown.bind(this);
this.sliderElem.addEventListener("touchstart", this.mousedown, false);
} else {
// Bind mouse handlers
this.mousedown = this._mousedown.bind(this);
this.sliderElem.addEventListener("mousedown", this.mousedown, false);
}
// Bind tooltip-related handlers
if(this.options.tooltip === 'hide') {
this._addClass(this.tooltip, 'hide');
this._addClass(this.tooltip_min, 'hide');
this._addClass(this.tooltip_max, 'hide');
} else if(this.options.tooltip === 'always') {
this._showTooltip();
this._alwaysShowTooltip = true;
} else {
this.showTooltip = this._showTooltip.bind(this);
this.hideTooltip = this._hideTooltip.bind(this);
this.sliderElem.addEventListener("mouseenter", this.showTooltip, false);
this.sliderElem.addEventListener("mouseleave", this.hideTooltip, false);
this.handle1.addEventListener("focus", this.showTooltip, false);
this.handle1.addEventListener("blur", this.hideTooltip, false);
this.handle2.addEventListener("focus", this.showTooltip, false);
this.handle2.addEventListener("blur", this.hideTooltip, false);
}
if(this.options.enabled) {
this.enable();
} else {
this.disable();
}
}
/*************************************************
INSTANCE PROPERTIES/METHODS
- Any methods bound to the prototype are considered
part of the plugin's `public` interface
**************************************************/
Slider.prototype = {
_init: function() {}, // NOTE: Must exist to support bridget
constructor: Slider,
defaultOptions: {
id: "",
min: 0,
max: 10,
step: 1,
precision: 0,
orientation: 'horizontal',
value: 5,
range: false,
selection: 'before',
tooltip: 'show',
tooltip_split: false,
handle: 'round',
reversed: false,
enabled: true,
formatter: function(val) {
if(val instanceof Array) {
return val[0] + " : " + val[1];
} else {
return val;
}
},
natural_arrow_keys: false
},
over: false,
inDrag: false,
getValue: function() {
if (this.options.range) {
return this.options.value;
}
return this.options.value[0];
},
setValue: function(val, triggerSlideEvent) {
if (!val) {
val = 0;
}
this.options.value = this._validateInputValue(val);
var applyPrecision = this._applyPrecision.bind(this);
if (this.options.range) {
this.options.value[0] = applyPrecision(this.options.value[0]);
this.options.value[1] = applyPrecision(this.options.value[1]);
this.options.value[0] = Math.max(this.options.min, Math.min(this.options.max, this.options.value[0]));
this.options.value[1] = Math.max(this.options.min, Math.min(this.options.max, this.options.value[1]));
} else {
this.options.value = applyPrecision(this.options.value);
this.options.value = [ Math.max(this.options.min, Math.min(this.options.max, this.options.value))];
this._addClass(this.handle2, 'hide');
if (this.options.selection === 'after') {
this.options.value[1] = this.options.max;
} else {
this.options.value[1] = this.options.min;
}
}
this.diff = this.options.max - this.options.min;
if (this.diff > 0) {
this.percentage = [
(this.options.value[0] - this.options.min) * 100 / this.diff,
(this.options.value[1] - this.options.min) * 100 / this.diff,
this.options.step * 100 / this.diff
];
} else {
this.percentage = [0, 0, 100];
}
this._layout();
var sliderValue = this.options.range ? this.options.value : this.options.value[0];
this._setDataVal(sliderValue);
if(triggerSlideEvent === true) {
this._trigger('slide', sliderValue);
}
return this;
},
destroy: function(){
// Remove event handlers on slider elements
this._removeSliderEventHandlers();
// Remove the slider from the DOM
this.sliderElem.parentNode.removeChild(this.sliderElem);
/* Show original <input> element */
this.element.style.display = "";
// Clear out custom event bindings
this._cleanUpEventCallbacksMap();
// Remove data values
this.element.removeAttribute("data");
// Remove JQuery handlers/data
if($) {
this._unbindJQueryEventHandlers();
this.$element.removeData('slider');
}
},
disable: function() {
this.options.enabled = false;
this.handle1.removeAttribute("tabindex");
this.handle2.removeAttribute("tabindex");
this._addClass(this.sliderElem, 'slider-disabled');
this._trigger('slideDisabled');
return this;
},
enable: function() {
this.options.enabled = true;
this.handle1.setAttribute("tabindex", 0);
this.handle2.setAttribute("tabindex", 0);
this._removeClass(this.sliderElem, 'slider-disabled');
this._trigger('slideEnabled');
return this;
},
toggle: function() {
if(this.options.enabled) {
this.disable();
} else {
this.enable();
}
return this;
},
isEnabled: function() {
return this.options.enabled;
},
on: function(evt, callback) {
if($) {
this.$element.on(evt, callback);
this.$sliderElem.on(evt, callback);
} else {
this._bindNonQueryEventHandler(evt, callback);
}
return this;
},
getAttribute: function(attribute) {
if(attribute) {
return this.options[attribute];
} else {
return this.options;
}
},
setAttribute: function(attribute, value) {
this.options[attribute] = value;
return this;
},
refresh: function() {
this._removeSliderEventHandlers();
createNewSlider.call(this, this.element, this.options);
if($) {
// Bind new instance of slider to the element
$.data(this.element, 'slider', this);
}
return this;
},
/******************************+
HELPERS
- Any method that is not part of the public interface.
- Place it underneath this comment block and write its signature like so:
_fnName : function() {...}
********************************/
_removeSliderEventHandlers: function() {
// Remove event listeners from handle1
this.handle1.removeEventListener("keydown", this.handle1Keydown, false);
this.handle1.removeEventListener("focus", this.showTooltip, false);
this.handle1.removeEventListener("blur", this.hideTooltip, false);
// Remove event listeners from handle2
this.handle2.removeEventListener("keydown", this.handle2Keydown, false);
this.handle2.removeEventListener("focus", this.handle2Keydown, false);
this.handle2.removeEventListener("blur", this.handle2Keydown, false);
// Remove event listeners from sliderElem
this.sliderElem.removeEventListener("mouseenter", this.showTooltip, false);
this.sliderElem.removeEventListener("mouseleave", this.hideTooltip, false);
this.sliderElem.removeEventListener("touchstart", this.mousedown, false);
this.sliderElem.removeEventListener("mousedown", this.mousedown, false);
},
_bindNonQueryEventHandler: function(evt, callback) {
if(this.eventToCallbackMap[evt]===undefined) {
this.eventToCallbackMap[evt] = [];
}
this.eventToCallbackMap[evt].push(callback);
},
_cleanUpEventCallbacksMap: function() {
var eventNames = Object.keys(this.eventToCallbackMap);
for(var i = 0; i < eventNames.length; i++) {
var eventName = eventNames[i];
this.eventToCallbackMap[eventName] = null;
}
},
_showTooltip: function() {
if (this.options.tooltip_split === false ){
this._addClass(this.tooltip, 'in');
} else {
this._addClass(this.tooltip_min, 'in');
this._addClass(this.tooltip_max, 'in');
}
this.over = true;
},
_hideTooltip: function() {
if (this.inDrag === false && this.alwaysShowTooltip !== true) {
this._removeClass(this.tooltip, 'in');
this._removeClass(this.tooltip_min, 'in');
this._removeClass(this.tooltip_max, 'in');
}
this.over = false;
},
_layout: function() {
var positionPercentages;
if(this.options.reversed) {
positionPercentages = [ 100 - this.percentage[0], this.percentage[1] ];
} else {
positionPercentages = [ this.percentage[0], this.percentage[1] ];
}
this.handle1.style[this.stylePos] = positionPercentages[0]+'%';
this.handle2.style[this.stylePos] = positionPercentages[1]+'%';
if (this.options.orientation === 'vertical') {
this.trackSelection.style.top = Math.min(positionPercentages[0], positionPercentages[1]) +'%';
this.trackSelection.style.height = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%';
} else {
this.trackSelection.style.left = Math.min(positionPercentages[0], positionPercentages[1]) +'%';
this.trackSelection.style.width = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%';
var offset_min = this.tooltip_min.getBoundingClientRect();
var offset_max = this.tooltip_max.getBoundingClientRect();
if (offset_min.right > offset_max.left) {
this._removeClass(this.tooltip_max, 'top');
this._addClass(this.tooltip_max, 'bottom');
this.tooltip_max.style.top = 18 + 'px';
} else {
this._removeClass(this.tooltip_max, 'bottom');
this._addClass(this.tooltip_max, 'top');
this.tooltip_max.style.top = -30 + 'px';
}
}
var formattedTooltipVal;
if (this.options.range) {
formattedTooltipVal = this.options.formatter(this.options.value);
this._setText(this.tooltipInner, formattedTooltipVal);
this.tooltip.style[this.stylePos] = (positionPercentages[1] + positionPercentages[0])/2 + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
var innerTooltipMinText = this.options.formatter(this.options.value[0]);
this._setText(this.tooltipInner_min, innerTooltipMinText);
var innerTooltipMaxText = this.options.formatter(this.options.value[1]);
this._setText(this.tooltipInner_max, innerTooltipMaxText);
this.tooltip_min.style[this.stylePos] = positionPercentages[0] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip_min, 'margin-top', -this.tooltip_min.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip_min, 'margin-left', -this.tooltip_min.offsetWidth / 2 + 'px');
}
this.tooltip_max.style[this.stylePos] = positionPercentages[1] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip_max, 'margin-top', -this.tooltip_max.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip_max, 'margin-left', -this.tooltip_max.offsetWidth / 2 + 'px');
}
} else {
formattedTooltipVal = this.options.formatter(this.options.value[0]);
this._setText(this.tooltipInner, formattedTooltipVal);
this.tooltip.style[this.stylePos] = positionPercentages[0] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
}
},
_removeProperty: function(element, prop) {
if (element.style.removeProperty) {
element.style.removeProperty(prop);
} else {
element.style.removeAttribute(prop);
}
},
_mousedown: function(ev) {
if(!this.options.enabled) {
return false;
}
this._triggerFocusOnHandle();
this.offset = this._offset(this.sliderElem);
this.size = this.sliderElem[this.sizePos];
var percentage = this._getPercentage(ev);
if (this.options.range) {
var diff1 = Math.abs(this.percentage[0] - percentage);
var diff2 = Math.abs(this.percentage[1] - percentage);
this.dragged = (diff1 < diff2) ? 0 : 1;
} else {
this.dragged = 0;
}
this.percentage[this.dragged] = this.options.reversed ? 100 - percentage : percentage;
this._layout();
if (this.touchCapable) {
document.removeEventListener("touchmove", this.mousemove, false);
document.removeEventListener("touchend", this.mouseup, false);
}
if(this.mousemove){
document.removeEventListener("mousemove", this.mousemove, false);
}
if(this.mouseup){
document.removeEventListener("mouseup", this.mouseup, false);
}
this.mousemove = this._mousemove.bind(this);
this.mouseup = this._mouseup.bind(this);
if (this.touchCapable) {
// Touch: Bind touch events:
document.addEventListener("touchmove", this.mousemove, false);
document.addEventListener("touchend", this.mouseup, false);
}
// Bind mouse events:
document.addEventListener("mousemove", this.mousemove, false);
document.addEventListener("mouseup", this.mouseup, false);
this.inDrag = true;
var val = this._calculateValue();
this._trigger('slideStart', val);
this._setDataVal(val);
this.setValue(val);
this._pauseEvent(ev);
return true;
},
_triggerFocusOnHandle: function(handleIdx) {
if(handleIdx === 0) {
this.handle1.focus();
}
if(handleIdx === 1) {
this.handle2.focus();
}
},
_keydown: function(handleIdx, ev) {
if(!this.options.enabled) {
return false;
}
var dir;
switch (ev.keyCode) {
case 37: // left
case 40: // down
dir = -1;
break;
case 39: // right
case 38: // up
dir = 1;
break;
}
if (!dir) {
return;
}
// use natural arrow keys instead of from min to max
if (this.options.natural_arrow_keys) {
var ifVerticalAndNotReversed = (this.options.orientation === 'vertical' && !this.options.reversed);
var ifHorizontalAndReversed = (this.options.orientation === 'horizontal' && this.options.reversed);
if (ifVerticalAndNotReversed || ifHorizontalAndReversed) {
dir = dir * -1;
}
}
var oneStepValuePercentageChange = dir * this.percentage[2];
var percentage = this.percentage[handleIdx] + oneStepValuePercentageChange;
if (percentage > 100) {
percentage = 100;
} else if (percentage < 0) {
percentage = 0;
}
this.dragged = handleIdx;
this._adjustPercentageForRangeSliders(percentage);
this.percentage[this.dragged] = percentage;
this._layout();
var val = this._calculateValue();
this._trigger('slideStart', val);
this._setDataVal(val);
this.setValue(val, true);
this._trigger('slideStop', val);
this._setDataVal(val);
this._pauseEvent(ev);
return false;
},
_pauseEvent: function(ev) {
if(ev.stopPropagation) {
ev.stopPropagation();
}
if(ev.preventDefault) {
ev.preventDefault();
}
ev.cancelBubble=true;
ev.returnValue=false;
},
_mousemove: function(ev) {
if(!this.options.enabled) {
return false;
}
var percentage = this._getPercentage(ev);
this._adjustPercentageForRangeSliders(percentage);
this.percentage[this.dragged] = this.options.reversed ? 100 - percentage : percentage;
this._layout();
var val = this._calculateValue();
this.setValue(val, true);
return false;
},
_adjustPercentageForRangeSliders: function(percentage) {
if (this.options.range) {
if (this.dragged === 0 && this.percentage[1] < percentage) {
this.percentage[0] = this.percentage[1];
this.dragged = 1;
} else if (this.dragged === 1 && this.percentage[0] > percentage) {
this.percentage[1] = this.percentage[0];
this.dragged = 0;
}
}
},
_mouseup: function() {
if(!this.options.enabled) {
return false;
}
if (this.touchCapable) {
// Touch: Unbind touch event handlers:
document.removeEventListener("touchmove", this.mousemove, false);
document.removeEventListener("touchend", this.mouseup, false);
}
// Unbind mouse event handlers:
document.removeEventListener("mousemove", this.mousemove, false);
document.removeEventListener("mouseup", this.mouseup, false);
this.inDrag = false;
if (this.over === false) {
this._hideTooltip();
}
var val = this._calculateValue();
this._layout();
this._setDataVal(val);
this._trigger('slideStop', val);
return false;
},
_calculateValue: function() {
var val;
if (this.options.range) {
val = [this.options.min,this.options.max];
if (this.percentage[0] !== 0){
val[0] = (Math.max(this.options.min, this.options.min + Math.round((this.diff * this.percentage[0]/100)/this.options.step)*this.options.step));
val[0] = this._applyPrecision(val[0]);
}
if (this.percentage[1] !== 100){
val[1] = (Math.min(this.options.max, this.options.min + Math.round((this.diff * this.percentage[1]/100)/this.options.step)*this.options.step));
val[1] = this._applyPrecision(val[1]);
}
this.options.value = val;
} else {
val = (this.options.min + Math.round((this.diff * this.percentage[0]/100)/this.options.step)*this.options.step);
if (val < this.options.min) {
val = this.options.min;
}
else if (val > this.options.max) {
val = this.options.max;
}
val = parseFloat(val);
val = this._applyPrecision(val);
this.options.value = [val, this.options.value[1]];
}
return val;
},
_applyPrecision: function(val) {
var precision = this.options.precision || this._getNumDigitsAfterDecimalPlace(this.options.step);
return this._applyToFixedAndParseFloat(val, precision);
},
_getNumDigitsAfterDecimalPlace: function(num) {
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0));
},
_applyToFixedAndParseFloat: function(num, toFixedInput) {
var truncatedNum = num.toFixed(toFixedInput);
return parseFloat(truncatedNum);
},
/*
Credits to Mike Samuel for the following method!
Source: http://stackoverflow.com/questions/10454518/javascript-how-to-retrieve-the-number-of-decimals-of-a-string-number
*/
_getPercentage: function(ev) {
if (this.touchCapable && (ev.type === 'touchstart' || ev.type === 'touchmove')) {
ev = ev.touches[0];
}
var percentage = (ev[this.mousePos] - this.offset[this.stylePos])*100/this.size;
percentage = Math.round(percentage/this.percentage[2])*this.percentage[2];
return Math.max(0, Math.min(100, percentage));
},
_validateInputValue: function(val) {
if(typeof val === 'number') {
return val;
} else if(val instanceof Array) {
this._validateArray(val);
return val;
} else {
throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(val) );
}
},
_validateArray: function(val) {
for(var i = 0; i < val.length; i++) {
var input = val[i];
if (typeof input !== 'number') { throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(input) ); }
}
},
_setDataVal: function(val) {
var value = "value: '" + val + "'";
this.element.setAttribute('data', value);
this.element.setAttribute('value', val);
},
_trigger: function(evt, val) {
val = (val || val === 0) ? val : undefined;
var callbackFnArray = this.eventToCallbackMap[evt];
if(callbackFnArray && callbackFnArray.length) {
for(var i = 0; i < callbackFnArray.length; i++) {
var callbackFn = callbackFnArray[i];
callbackFn(val);
}
}
/* If JQuery exists, trigger JQuery events */
if($) {
this._triggerJQueryEvent(evt, val);
}
},
_triggerJQueryEvent: function(evt, val) {
var eventData = {
type: evt,
value: val
};
this.$element.trigger(eventData);
this.$sliderElem.trigger(eventData);
},
_unbindJQueryEventHandlers: function() {
this.$element.off();
this.$sliderElem.off();
},
_setText: function(element, text) {
if(typeof element.innerText !== "undefined") {
element.innerText = text;
} else if(typeof element.textContent !== "undefined") {
element.textContent = text;
}
},
_removeClass: function(element, classString) {
var classes = classString.split(" ");
var newClasses = element.className;
for(var i = 0; i < classes.length; i++) {
var classTag = classes[i];
var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
newClasses = newClasses.replace(regex, " ");
}
element.className = newClasses.trim();
},
_addClass: function(element, classString) {
var classes = classString.split(" ");
var newClasses = element.className;
for(var i = 0; i < classes.length; i++) {
var classTag = classes[i];
var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
var ifClassExists = regex.test(newClasses);
if(!ifClassExists) {
newClasses += " " + classTag;
}
}
element.className = newClasses.trim();
},
_offset: function (obj) {
var ol = 0;
var ot = 0;
if (obj.offsetParent) {
do {
ol += obj.offsetLeft;
ot += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return {
left: ol,
top: ot
};
},
_css: function(elementRef, styleName, value) {
if ($) {
$.style(elementRef, styleName, value);
} else {
var style = styleName.replace(/^-ms-/, "ms-").replace(/-([\da-z])/gi, function (all, letter) {
return letter.toUpperCase();
});
elementRef.style[style] = value;
}
}
};
/*********************************
Attach to global namespace
*********************************/
if($) {
var namespace = $.fn.slider ? 'bootstrapSlider' : 'slider';
$.bridget(namespace, Slider);
}
})( $ );
return Slider;
})); | mithundas79/angularTemplateSample | vendor/bootstrap-slider/bootstrap-slider.js | JavaScript | mit | 37,391 |
/*
YUI 3.5.0 (build 5089)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add("lang/datatype-date-format_fr",function(a){a.Intl.add("datatype-date-format","fr",{"a":["dim.","lun.","mar.","mer.","jeu.","ven.","sam."],"A":["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"],"b":["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc."],"B":["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre"],"c":"%a %d %b %Y %H:%M:%S %Z","p":["AM","PM"],"P":["am","pm"],"x":"%d/%m/%y","X":"%H:%M:%S"});},"3.5.0"); | sitron/scrum-toolbox | src/Sitronnier/SmBoxBundle/Resources/public/js/yui/datatype-date-format/lang/datatype-date-format_fr.js | JavaScript | mit | 677 |
version https://git-lfs.github.com/spec/v1
oid sha256:ecdcfeb6d9c10e04bf103e6105698af7bda97180bfc3c7545cce74ce2a73f5eb
size 4291
| yogeshsaroya/new-cdnjs | ajax/libs/dojo/1.9.7/cldr/nls/persian.js | JavaScript | mit | 129 |
/**
* @ngdoc service
* @name merchello.models.extendedDataDisplayBuilder
*
* @description
* A utility service that builds ExtendedDataBuilder models
*/
angular.module('merchello.models')
.factory('extendedDataDisplayBuilder',
['genericModelBuilder', 'ExtendedDataDisplay', 'ExtendedDataItemDisplay',
function(genericModelBuilder, ExtendedDataDisplay, ExtendedDataItemDisplay) {
var Constructor = ExtendedDataDisplay;
return {
createDefault: function() {
return new Constructor();
},
transform: function(jsonResult) {
var extendedData = new Constructor();
if (jsonResult !== undefined) {
var items = genericModelBuilder.transform(jsonResult, ExtendedDataItemDisplay);
if(items.length > 0) {
extendedData.items = items;
}
}
return extendedData;
}
};
}]);
| BluefinDigital/Merchello | src/Merchello.Web.UI.Client/src/common/models/factories/extendedDataDisplayBuilder.factory.js | JavaScript | mit | 1,198 |
import Ember from 'ember-metal/core'; // reexports
import Test from 'ember-testing/test';
import Adapter from 'ember-testing/adapters/adapter';
import setupForTesting from 'ember-testing/setup_for_testing';
import require from 'require';
import 'ember-testing/support'; // to handle various edge cases
import 'ember-testing/ext/application';
import 'ember-testing/ext/rsvp';
import 'ember-testing/helpers'; // adds helpers to helpers object in Test
import 'ember-testing/initializers'; // to setup initializer
/**
@module ember
@submodule ember-testing
*/
Ember.Test = Test;
Ember.Test.Adapter = Adapter;
Ember.setupForTesting = setupForTesting;
Object.defineProperty(Test, 'QUnitAdapter', {
get: () => require('ember-testing/adapters/qunit').default
});
| bmac/ember.js | packages/ember-testing/lib/index.js | JavaScript | mit | 774 |
CKEDITOR.plugins.setLang( 'html5audio', 'de', {
button: 'HTML5 Audio einfügen',
title: 'HTML5 Audio',
infoLabel: 'Audio Infos',
urlMissing: 'Sie haben keine URL zur Audio-Datei angegeben.',
audioProperties: 'Audio-Einstellungen',
upload: 'Hochladen',
btnUpload: 'Zum Server senden',
advanced: 'Erweitert',
autoplay: 'Autoplay?',
allowdownload: 'Download zulassen?',
yes: 'Ja',
no: 'Nein'
} );
| bachnxhedspi/web_tieng_anh_1 | xcrud/editors/ckeditor/plugins/html5audio/lang/de.js | JavaScript | mit | 442 |
function foo() {
console.log('foo');
}
| jimenglish81/ember-suave | tests/fixtures/rules/require-spaces-in-function/good/function-declaration.js | JavaScript | mit | 41 |
/**
@license
* @pnp/logging v1.0.3 - pnp - light-weight, subscribable logging framework
* MIT (https://github.com/pnp/pnp/blob/master/LICENSE)
* Copyright (c) 2018 Microsoft
* docs: http://officedev.github.io/PnP-JS-Core
* source: https://github.com/pnp/pnp
* bugs: https://github.com/pnp/pnp/issues
*/
/**
* Class used to subscribe ILogListener and log messages throughout an application
*
*/
class Logger {
/**
* Gets or sets the active log level to apply for log filtering
*/
static get activeLogLevel() {
return Logger.instance.activeLogLevel;
}
static set activeLogLevel(value) {
Logger.instance.activeLogLevel = value;
}
static get instance() {
if (typeof Logger._instance === "undefined" || Logger._instance === null) {
Logger._instance = new LoggerImpl();
}
return Logger._instance;
}
/**
* Adds ILogListener instances to the set of subscribed listeners
*
* @param listeners One or more listeners to subscribe to this log
*/
static subscribe(...listeners) {
listeners.map(listener => Logger.instance.subscribe(listener));
}
/**
* Clears the subscribers collection, returning the collection before modifiction
*/
static clearSubscribers() {
return Logger.instance.clearSubscribers();
}
/**
* Gets the current subscriber count
*/
static get count() {
return Logger.instance.count;
}
/**
* Writes the supplied string to the subscribed listeners
*
* @param message The message to write
* @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose)
*/
static write(message, level = 0 /* Verbose */) {
Logger.instance.log({ level: level, message: message });
}
/**
* Writes the supplied string to the subscribed listeners
*
* @param json The json object to stringify and write
* @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose)
*/
static writeJSON(json, level = 0 /* Verbose */) {
Logger.instance.log({ level: level, message: JSON.stringify(json) });
}
/**
* Logs the supplied entry to the subscribed listeners
*
* @param entry The message to log
*/
static log(entry) {
Logger.instance.log(entry);
}
/**
* Logs an error object to the subscribed listeners
*
* @param err The error object
*/
static error(err) {
Logger.instance.log({ data: err, level: 3 /* Error */, message: err.message });
}
}
class LoggerImpl {
constructor(activeLogLevel = 2 /* Warning */, subscribers = []) {
this.activeLogLevel = activeLogLevel;
this.subscribers = subscribers;
}
subscribe(listener) {
this.subscribers.push(listener);
}
clearSubscribers() {
const s = this.subscribers.slice(0);
this.subscribers.length = 0;
return s;
}
get count() {
return this.subscribers.length;
}
write(message, level = 0 /* Verbose */) {
this.log({ level: level, message: message });
}
log(entry) {
if (typeof entry !== "undefined" && this.activeLogLevel <= entry.level) {
this.subscribers.map(subscriber => subscriber.log(entry));
}
}
}
/**
* Implementation of LogListener which logs to the console
*
*/
class ConsoleListener {
/**
* Any associated data that a given logging listener may choose to log or ignore
*
* @param entry The information to be logged
*/
log(entry) {
const msg = this.format(entry);
switch (entry.level) {
case 0 /* Verbose */:
case 1 /* Info */:
console.log(msg);
break;
case 2 /* Warning */:
console.warn(msg);
break;
case 3 /* Error */:
console.error(msg);
break;
}
}
/**
* Formats the message
*
* @param entry The information to format into a string
*/
format(entry) {
const msg = [];
msg.push("Message: " + entry.message);
if (typeof entry.data !== "undefined") {
msg.push(" Data: " + JSON.stringify(entry.data));
}
return msg.join("");
}
}
/**
* Implementation of LogListener which logs to the supplied function
*
*/
class FunctionListener {
/**
* Creates a new instance of the FunctionListener class
*
* @constructor
* @param method The method to which any logging data will be passed
*/
constructor(method) {
this.method = method;
}
/**
* Any associated data that a given logging listener may choose to log or ignore
*
* @param entry The information to be logged
*/
log(entry) {
this.method(entry);
}
}
export { Logger, ConsoleListener, FunctionListener };
//# sourceMappingURL=logging.js.map
| jonobr1/cdnjs | ajax/libs/pnp-logging/1.0.3/logging.js | JavaScript | mit | 5,231 |
/**
@module ember
@submodule ember-runtime
*/
import { get } from "ember-metal/property_get";
import { set } from "ember-metal/property_set";
import { required } from "ember-metal/mixin";
import { Freezable } from "ember-runtime/mixins/freezable";
import { Mixin } from 'ember-metal/mixin';
import { fmt } from "ember-runtime/system/string";
import EmberError from 'ember-metal/error';
/**
Implements some standard methods for copying an object. Add this mixin to
any object you create that can create a copy of itself. This mixin is
added automatically to the built-in array.
You should generally implement the `copy()` method to return a copy of the
receiver.
Note that `frozenCopy()` will only work if you also implement
`Ember.Freezable`.
@class Copyable
@namespace Ember
@since Ember 0.9
*/
export default Mixin.create({
/**
Override to return a copy of the receiver. Default implementation raises
an exception.
@method copy
@param {Boolean} deep if `true`, a deep copy of the object should be made
@return {Object} copy of receiver
*/
copy: required(Function),
/**
If the object implements `Ember.Freezable`, then this will return a new
copy if the object is not frozen and the receiver if the object is frozen.
Raises an exception if you try to call this method on a object that does
not support freezing.
You should use this method whenever you want a copy of a freezable object
since a freezable object can simply return itself without actually
consuming more memory.
@method frozenCopy
@return {Object} copy of receiver or receiver
*/
frozenCopy: function() {
if (Freezable && Freezable.detect(this)) {
return get(this, 'isFrozen') ? this : this.copy().freeze();
} else {
throw new EmberError(fmt("%@ does not support freezing", [this]));
}
}
});
| g13013/ember.js | packages_es6/ember-runtime/lib/mixins/copyable.js | JavaScript | mit | 1,883 |
/*
* Atari Arcade SDK
* Developed by gskinner.com in partnership with Atari
* Visit http://atari.com/arcade/developers for documentation, updates and examples.
*
* Copyright (c) Atari Interactive, Inc. All Rights Reserved. Atari and the Atari logo are trademarks owned by Atari Interactive, Inc.
*
* Distributed under the terms of the MIT license.
* http://www.opensource.org/licenses/mit-license.html
*
* This notice shall be included in all copies or substantial portions of the Software.
*/
/** @module GameLibs */
(function(scope) {
/**
* A component which monitors the performance of the game, and toggles low quality
* mode if the
* @class PerformanceMonitor
* @param {Function} callback A function to fire when the performance is deemed to be unacceptable.
* @param {Number} threshold The amount of time in milliseconds that the game is allowed to have poor FPS
* before it toggles low quality.
* @constructor
*/
var PerformanceMonitor = function(callback, minFPS, threshold) {
this.initialize(callback, minFPS, threshold);
}
var s = PerformanceMonitor;
/**
* The default threshold value
* @property DEFAULT_THRESHOLD
* @type {Number}
* @default 3000
* @static
*/
s.DEFAULT_THRESHOLD = 3000;
var p = PerformanceMonitor.prototype = {
maxMs: null,
/**
* The minimum FPS allowed.
* @property minFPS
* @type Number
* @default 30
*/
minFPS: 30,
/**
* The number of milliseconds that can pass before the low quality mode is toggled.
* @property threshold
* @type Number
* @default 3000
*/
threshold:s.DEFAULT_THRESHOLD,
/**
* The method to call when the game enters low quality mode. It is recommended to use a proxy
* method to maintain scope. The callback takes a single argument, which indicates if the game
* is in low quality mode.
* @property callback
* @type Function
*/
callback: null,
/**
* If the game is currently in low quality mode.
* @property lowQualityMode
* @type Boolean
* @default false
*/
lowQualityMode: false,
/**
* The amount of time that has elapsed since the framerate has been acceptable.
* @property timeOnLow
* @type Number
* @default 0
*/
timeOnLow: 0,
initialize: function(callback, minFPS, threshold) {
this.callback = callback;
if(!isNaN(threshold)) { this.threshold = threshold; }
if(!isNaN(minFPS)){ this.minFPS = minFPS; }
this.maxMs = 1000 / minFPS;
this.prevTime = createjs.Ticker.getTime();
createjs.Ticker.addListener(this);
},
/**
* Reset the PerformanceMonitor. This happens whenever a game is restarted or continued.
* Note: Currently NOT implemented in any games.
* @method reset
*/
reset: function() {
this.timeOnLow = 0;
this.lowQualityMode = false;
this.prevTime = createjs.Ticker.getTime();
createjs.Ticker.setFPS(60); //TODO: This should lookup the actual FPS we need.
createjs.Ticker.addListener(this);
this.callback(false);
},
tick: function(){
var deltaT = createjs.Ticker.getTime() - this.prevTime;
this.prevTime = createjs.Ticker.getTime();
if(deltaT < 200 && deltaT > this.maxMs){
this.timeOnLow += deltaT;
if(this.timeOnLow > this.threshold) {
/*
Atari.trace("*** Low Quality Mode toggled.")
*/
this.lowQualityMode = true;
this.callback(true);
createjs.Ticker.setFPS(30);
createjs.Ticker.removeListener(this);
}
} else {
this.timeOnLow = 0;
}
}
}
scope.PerformanceMonitor = PerformanceMonitor;
}(window.GameLibs)) | tom-christie/tom-christie.github.io | stimulus_js/js/libs/gamelibs/PerformanceMonitor.js | JavaScript | gpl-2.0 | 3,738 |
/*
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
((function(){var a={instances:{}};if(typeof this.RokSprocket=="undefined"){this.RokSprocket=a;}else{Object.merge(this.RokSprocket,{instances:{}});}if(MooTools.version<"1.4.4"&&(Browser.name=="ie"&&Browser.version<9)){((function(){var b=["rel","data-next","data-previous","data-tabs","data-tabs-navigation","data-tabs-panel","data-tabs-next","data-tabs-previous","data-lists","data-lists-items","data-lists-item","data-lists-toggler","data-lists-content","data-lists-page","data-lists-next","data-lists-previous","data-headlines","data-headlines-item","data-headlines-next","data-headlines-previous","data-features","data-features-pagination","data-features-next","data-features-previous","data-slideshow","data-slideshow-pagination","data-slideshow-next","data-slideshow-previous","data-showcase","data-showcase-pagination","data-showcase-next","data-showcase-previous"];
b.each(function(c){Element.Properties[c]={get:function(){return this.getAttribute(c);}};});})());}})()); | C3Style/appuihec | tmp/install_5141d25be0783/com_roksprocket/site/assets/js/roksprocket.js | JavaScript | gpl-2.0 | 1,163 |
var searchData=
[
['error_2eh',['error.h',['../error_8h.html',1,'']]]
];
| sherman5/MeleeModdingLibrary | docs/search/files_2.js | JavaScript | gpl-3.0 | 75 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
* global ko
*/
//var viewmodelraw=
//{
// Name:"David",
// LastName:"Desmaisons",
// Local:{ City:'Florianopolis', Region:'SC'},
// Skills: [{Type:'Langage', Name:'French'},{Type:'Info', Name:'C++'}]
//};
//var viewmodel= ko.MapToCommitObservable(viewmodelraw);
////MapToObservable
//ko.applyBindings(viewmodel);
| David-Desmaisons/MVVM.CEF.Glue | Examples/Example.ChromiumFX.Ko.UI/src/src/js/main.js | JavaScript | lgpl-3.0 | 514 |
/*
* Copyright (c) 2011-2014 YY Digital Pty Ltd. All Rights Reserved.
* Please see the LICENSE file included with this distribution for details.
*/
var jshint = require("jshint").JSHINT,
logger = require("../../server/logger"),
fs = require("fs"),
path =require("path");
exports.checkContent = function(filename, filecontent) {
if (!jshint(filecontent)) {
jshint.data().errors.forEach(function(error) {
logger.error(filename + (error ? " line: " + error.line + ", column:" + error.character + ", " + error.reason : "") );
});
}
};
exports.checkPath = function(target_path) {
fs.getList(target_path).files.forEach(function(file) {
if (file.match("js$") || file.match("json$")) {
exports.checkContent(file, fs.readFileSync(path.join(target_path, file)).toString());
}
});
};
| cb1kenobi/TiShadow | cli/support/jshint_runner.js | JavaScript | apache-2.0 | 828 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor
* license agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. The ASF licenses this file to
* You under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
* by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
* OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
$(window).on('load',(function () {
// for each record, unroll the array pointed to by "fieldpath" into a new
// record for each element of the array
function unnest (table, fieldpath, dest) {
var faccess = accessor(fieldpath);
return $.map(table, function (record, index) {
var ra = [];
var nested = faccess(record);
if (nested !== undefined) {
for (var i = 0; i < nested.length; i++) {
var newrec = $.extend({}, record);
newrec[dest] = nested[i];
ra.push(newrec);
}
}
return ra;
});
}
// for each record, project "fieldpath" into "dest".
function extract (table, fieldpath, dest) {
var faccess = accessor(fieldpath);
return $.map(table, function (record, index) {
var newrec = $.extend({}, record);
newrec[dest] = faccess(newrec);
return newrec;
});
}
// creates a function that will traverse tree of objects based the '.'
// delimited "path"
function accessor (path) {
path = path.split(".");
return function (obj) {
for (var i = 0; i < path.length; i++)
obj = obj[path[i]];
return obj;
}
}
// sample use of unnest/extract
function extractminortimes (profile) {
var t1 = unnest([profile], "fragmentProfile", "ma");
var t2 = unnest(t1, "ma.minorFragmentProfile", "mi");
var timetable = $.map(t2, function (record, index) {
var newrec = {
"name" : record.ma.majorFragmentId + "-" +
record.mi.minorFragmentId,
"category" : record.ma.majorFragmentId,
"start" : (record.mi.startTime - record.start) / 1000.0,
"end" : (record.mi.endTime - record.start) / 1000.0
};
return newrec;
});
timetable.sort(function (r1, r2) {
if (r1.category == r2.category) {
//return r1.name > r2.name;
return r1.end - r1.start > r2.end - r2.start ? 1 : -1;
}
else return r1.category > r2.category ? 1 : -1;
});
return timetable;
}
// write the "fieldpaths" for the table "table" into the "domtable"
function builddomtable (domtable, table, fieldpaths) {
var faccessors = $.map(fieldpaths, function (d, i) {
return accessor(d);
});
var domrow = domtable.append("tr");
for (var i = 0; i < fieldpaths.length; i++)
domrow.append("th").text(fieldpaths[i]);
for (var i = 0; i < table.length; i++) {
domrow = domtable.append("tr");
for (var j = 0; j < faccessors.length; j++)
domrow.append("td").text(faccessors[j](table[i]));
}
}
// parse the short physical plan into a dagreeD3 structure
function parseplan (planstring) {
//Map for implicit links
var implicitSrcMap = {};
var g = new dagreD3.Digraph();
//Produce 2D array (3 x M): [[0:majorMinor] [1:] [2:opName]] / [[<major>-<minor>, "<indent>", opName]]
let opPlanArray = planstring.trim().split("\n");
var operatorRegex = new RegExp("^([0-9-]+)( *)([a-zA-Z]*)");
//Regex to capture source operator
var srcOpRegex = new RegExp("srcOp=[0-9-]+");
var opTuple = $.map(opPlanArray,
function (lineStr) {
//Tokenize via Regex
let opToken = operatorRegex.exec(lineStr).slice(1);
//Extract Implicit Source via Regex
let implicitSrc = srcOpRegex.exec(lineStr);
let srcOp = null;
let tgtOp = opToken[0];
if (implicitSrc != null) {
srcOp = implicitSrc.toString().split("=")[1];
implicitSrcMap[tgtOp]=srcOp;
}
return [opToken];
});
// parse, build & inject nodes
for (var i = 0; i < opTuple.length; i++) {
let majorMinor = opTuple[i][0];
let majorId = parseInt(majorMinor.split("-")[0]);
let opName = opTuple[i][2];
g.addNode(majorMinor, {
label: opName + " " + majorMinor,
fragment: majorId
});
}
// Define edges by traversing graph from root node (Screen)
//NOTE: The indentation value in opTuple which is opTuple[1] represents the relative level of each operator in tree w.r.t root operator
var nodeStack = [opTuple[0]]; //Add Root
for (var i = 1; i < opTuple.length; i++) {
let top = nodeStack.pop();
let currItem = opTuple[i];
let stackTopIndent = top[1].length;
let currItemIndent = currItem[1].length; //Since tokenizing gives indent size at index 1
//Compare top-of-stack indent with current iterItem indent
while (stackTopIndent >= currItemIndent) {
top = nodeStack.pop();
stackTopIndent = top[1].length;
}
//Found parent
//Add edge if Implicit src exists
//Refer: https://dagrejs.github.io/project/dagre-d3/latest/demo/style-attrs.html / https://github.com/d3/d3-shape#curves
if (implicitSrcMap[currItem[0]] != null) {
//Note: Order matters because it affects layout (currently: BT)
//Ref: //https://github.com/dagrejs/dagre/issues/116
g.addEdge(null, currItem[0], implicitSrcMap[currItem[0]], {
style: "fill:none; stroke:gray; stroke-width:3px; stroke-dasharray: 5,5;marker-end:none"
});
}
//Adding edge
g.addEdge(null, currItem[0], top[0]);
if (currItemIndent != stackTopIndent)
nodeStack.push(top);
if (currItemIndent >= stackTopIndent)
nodeStack.push(currItem);
}
return g;
}
// graph a "planstring" into the d3 svg handle "svg"
function buildplangraph (svg, planstring) {
var padding = 20;
var graph = parseplan(planstring);
var renderer = new dagreD3.Renderer();
renderer.zoom(function () {return function (graph, root) {}});
var oldDrawNodes = renderer.drawNodes();
renderer.drawNodes(function(graph, root) {
var svgNodes = oldDrawNodes(graph, root);
svgNodes.each(function(u) {
var fc = d3.rgb(globalconfig.majorcolorscale(graph.node(u).fragment));
d3.select(this).select("rect")
.style("fill", graph.node(u).label.split(" ")[0].endsWith("Exchange") ? "white" : fc)
.style("stroke", "#000")
.style("stroke-width", "1px")
});
return svgNodes;
});
var oldDrawEdgePaths = renderer.drawEdgePaths();
renderer.drawEdgePaths(function(graph, root) {
var svgEdgePaths = oldDrawEdgePaths(graph, root);
svgEdgePaths.each(function(u) {
d3.select(this).select("path")
.style("fill", "none")
.style("stroke", "#000")
.style("stroke-width", "1px")
});
return svgEdgePaths;
});
var shiftedgroup = svg.append("g")
.attr("transform", "translate(" + padding + "," + padding + ")");
var layout = dagreD3.layout().nodeSep(20).rankDir("BT");
var result = renderer.layout(layout).run(graph, shiftedgroup);
svg.attr("width", result.graph().width + 2 * padding)
.attr("height", result.graph().height + 2 * padding);
}
// Fragment Gantt Chart
function buildtimingchart (svgdest, timetable) {
var chartprops = {
"w" : 850,
"h" : 20,
"svg" : svgdest,
"bheight" : 2,
"bpad" : 0,
"margin" : 35,
"scaler" : null,
"colorer" : null,
};
chartprops.h = Math.max(timetable.length * (chartprops.bheight + chartprops.bpad * 2), chartprops.h);
chartprops.svg
.attr("width", chartprops.w + 2 * chartprops.margin)
.attr("height", chartprops.h + 2 * chartprops.margin)
.attr("class", "svg");
chartprops.scaler = d3.scale.linear()
.domain([d3.min(timetable, accessor("start")),
d3.max(timetable, accessor("end"))])
.range([0, chartprops.w - chartprops.bpad * 2]);
chartprops.colorer = globalconfig.majorcolorscale;
// backdrop
chartprops.svg.append("g")
.selectAll("rect")
.data(timetable)
.enter()
// TODO: Prototype to jump to related Major Fragment
//.append("a")
// .attr("xlink:href", function(d) {
// return "#fragment-" + parseInt(d.category);
// })
.append("rect")
.attr("x", 0)
.attr("y", function(d, i) {return i * (chartprops.bheight + 2 * chartprops.bpad);})
.attr("width", chartprops.w)
.attr("height", chartprops.bheight + chartprops.bpad * 2)
.attr("stroke", "none")
.attr("fill", function(d) {return d3.rgb(chartprops.colorer(d.category));})
.attr("opacity", 0.1)
.attr("transform", "translate(" + chartprops.margin + "," +
chartprops.margin + ")")
.attr("style", "cursor: pointer;")
.append("title")
.text(function(d) {
var id = parseInt(d.category);
return ((id < 10) ? ("0" + id) : id) + "-XX-XX";
});
// bars
chartprops.svg.append('g')
.selectAll("rect")
.data(timetable)
.enter()
// TODO: Prototype to jump to related Major Fragment
//.append("a")
// .attr("xlink:href", function(d) {
// return "#fragment-" + parseInt(d.category);
// })
.append("rect")
//.attr("rx", 3)
//.attr("ry", 3)
.attr("x", function(d) {return chartprops.scaler(d.start) + chartprops.bpad;})
.attr("y", function(d, i) {return i * (chartprops.bheight + 2 * chartprops.bpad) + chartprops.bpad;})
.attr("width", function(d) {return (chartprops.scaler(d.end) - chartprops.scaler(d.start));})
.attr("height", chartprops.bheight)
.attr("stroke", "none")
.attr("fill", function(d) {return d3.rgb(chartprops.colorer(d.category));})
.attr("transform", "translate(" + chartprops.margin + "," +
chartprops.margin + ")")
.attr("style", "cursor: pointer;")
.append("title")
.text(function(d) {
var id = parseInt(d.category);
return ((id < 10) ? ("0" + id) : id) + "-XX-XX";
});
// grid lines
chartprops.svg.append("g")
.attr("transform", "translate(" +
(chartprops.bpad + chartprops.margin) + "," +
(chartprops.h + chartprops.margin) + ")")
.attr("class", "grid")
.call(d3.svg.axis()
.scale(chartprops.scaler)
.tickSize(-chartprops.h, 0)
.tickFormat(""))
.style("stroke", "#000")
.style("opacity", 0.2);
// ticks
chartprops.svg.append("g")
.attr("transform", "translate(" +
(chartprops.bpad + chartprops.margin) + "," +
(chartprops.h + chartprops.margin) + ")")
.attr("class", "grid")
.call(d3.svg.axis()
.scale(chartprops.scaler)
.orient('bottom')
.tickSize(0, 0)
.tickFormat(d3.format(".2f")));
// X Axis Label (Centered above graph)
chartprops.svg.append("text")
.attr("transform", "rotate(0)")
.attr("y", 0)
.attr("x", chartprops.w/2 + chartprops.margin)
.attr("dy", "1.5em")
.style("text-anchor", "middle")
.text("Elapsed Timeline");
//Y Axis (center of y axis)
chartprops.svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0)
// Aligning to center of Y-axis with minimum Svg height
.attr("x",0 - Math.max(chartprops.h/2 + chartprops.margin, 40))
.attr("dy", "1.5em")
.style("text-anchor", "middle")
.html("Fragments");
}
function loadprofile (queryid, callback) {
$.ajax({
type: "GET",
dataType: "json",
url: "/profiles/" + queryid + ".json",
success: callback,
error: function (x, y, z) {
console.log(x);
console.log(y);
console.log(z);
}
});
}
function setupglobalconfig (profile) {
globalconfig.profile = profile;
if (profile.fragmentProfile !== undefined) {
globalconfig.majorcolorscale = d3.scale.category20()
.domain([0, d3.max(profile.fragmentProfile, accessor("majorFragmentId"))]);
}
}
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
loadprofile(globalconfig.queryid, function (profile) {
setupglobalconfig(profile);
var queryvisualdrawn = false;
var timingoverviewdrawn = false;
var jsonprofileshown = false;
// trigger svg drawing when visible
$('#query-tabs').on('shown.bs.tab', function (e) {
if (profile.plan === undefined || queryvisualdrawn || !e.target.href.endsWith("#query-visual")) return;
buildplangraph(d3.select("#query-visual-canvas"), profile.plan);
queryvisualdrawn = true;
})
$('#fragment-accordion').on('shown.bs.collapse', function (e) {
if (timingoverviewdrawn || e.target.id != "fragment-overview") return;
buildtimingchart(d3.select("#fragment-overview-canvas"), extractminortimes(profile));
timingoverviewdrawn = true;
});
// select default tabs
$('#fragment-overview').collapse('show');
$('#operator-overview').collapse('show');
$('#query-tabs a[href="#query-query"]').tab('show');
// add json profile on click
$('#full-json-profile-json').on('shown.bs.collapse', function (e) {
if (jsonprofileshown) return;
$('#full-json-profile-json').text(JSON.stringify(globalconfig.profile, null, 4)).html();
});
//builddomtable(d3.select("#timing-table")
// .append("tbody"), extractminortimes(profile),
// ["name", "start", "end"]);
});
}));
| apache/drill | exec/java-exec/src/main/resources/rest/static/js/graph.js | JavaScript | apache-2.0 | 15,966 |
__zl([{"1":0,"2":0,"3":0,"20":1,"23":2,"24":3,"25":4,"26":5,"27":6,"28":7,"29":8,"30":9,"31":10,"32":11,"34":12,"35":13,"36":14,"40":15,"43":16,"44":17,"45":18,"46":19,"47":20,"49":21,"50":22,"60":23,"61":24,"63":25,"64":26,"65":27,"70":28,"72":29,"73":30,"74":31,"80":32,"81":33,"82":34,"83":35},["Columbus","Brownstown","Butlerville","Canaan","Clarksburg","Clifford","Commiskey","Cortland","Crothersville","Deputy","Dupont","Elizabethtown","Flat Rock","Freetown","Grammer","Greensburg","Hanover","Hartsville","Hayden","Hope","Jonesville","Kurtz","Madison","Medora","Millhousen","New Point","Norman","North Vernon","Paris Crossing","Saint Paul","Scipio","Seymour","Taylorsville","Vallonia","Vernon","Westport"],["IN|Indiana"]]); | andrefyg/ziplookup | public/ziplookup/db/us/472.js | JavaScript | apache-2.0 | 729 |
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import {defaults as defaultControls, ZoomToExtent} from '../src/ol/control.js';
import TileLayer from '../src/ol/layer/Tile.js';
import OSM from '../src/ol/source/OSM.js';
const map = new Map({
controls: defaultControls().extend([
new ZoomToExtent({
extent: [
813079.7791264898, 5929220.284081122,
848966.9639063801, 5936863.986909639
]
})
]),
layers: [
new TileLayer({
source: new OSM()
})
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2
})
});
| fredj/ol3 | examples/navigation-controls.js | JavaScript | bsd-2-clause | 605 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
/**
* This object encapsulates everything related to tasks execution.
*
* TODO(hirono): Pass each component instead of the entire FileManager.
* @param {FileManager} fileManager FileManager instance.
* @param {Object=} opt_params File manager load parameters.
* @constructor
*/
function FileTasks(fileManager, opt_params) {
this.fileManager_ = fileManager;
this.params_ = opt_params;
this.tasks_ = null;
this.defaultTask_ = null;
this.entries_ = null;
/**
* List of invocations to be called once tasks are available.
*
* @private
* @type {Array.<Object>}
*/
this.pendingInvocations_ = [];
}
/**
* Location of the Chrome Web Store.
*
* @const
* @type {string}
*/
FileTasks.CHROME_WEB_STORE_URL = 'https://chrome.google.com/webstore';
/**
* Base URL of apps list in the Chrome Web Store. This constant is used in
* FileTasks.createWebStoreLink().
*
* @const
* @type {string}
*/
FileTasks.WEB_STORE_HANDLER_BASE_URL =
'https://chrome.google.com/webstore/category/collection/file_handlers';
/**
* The app ID of the video player app.
* @const
* @type {string}
*/
FileTasks.VIDEO_PLAYER_ID = 'jcgeabjmjgoblfofpppfkcoakmfobdko';
/**
* Returns URL of the Chrome Web Store which show apps supporting the given
* file-extension and mime-type.
*
* @param {string} extension Extension of the file (with the first dot).
* @param {string} mimeType Mime type of the file.
* @return {string} URL
*/
FileTasks.createWebStoreLink = function(extension, mimeType) {
if (!extension)
return FileTasks.CHROME_WEB_STORE_URL;
if (extension[0] === '.')
extension = extension.substr(1);
else
console.warn('Please pass an extension with a dot to createWebStoreLink.');
var url = FileTasks.WEB_STORE_HANDLER_BASE_URL;
url += '?_fe=' + extension.toLowerCase().replace(/[^\w]/g, '');
// If a mime is given, add it into the URL.
if (mimeType)
url += '&_fmt=' + mimeType.replace(/[^-\w\/]/g, '');
return url;
};
/**
* Complete the initialization.
*
* @param {Array.<Entry>} entries List of file entries.
* @param {Array.<string>=} opt_mimeTypes List of MIME types for each
* of the files.
*/
FileTasks.prototype.init = function(entries, opt_mimeTypes) {
this.entries_ = entries;
this.mimeTypes_ = opt_mimeTypes || [];
// TODO(mtomasz): Move conversion from entry to url to custom bindings.
var urls = util.entriesToURLs(entries);
if (urls.length > 0) {
chrome.fileBrowserPrivate.getFileTasks(urls, this.mimeTypes_,
this.onTasks_.bind(this));
}
};
/**
* Returns amount of tasks.
*
* @return {number} amount of tasks.
*/
FileTasks.prototype.size = function() {
return (this.tasks_ && this.tasks_.length) || 0;
};
/**
* Callback when tasks found.
*
* @param {Array.<Object>} tasks The tasks.
* @private
*/
FileTasks.prototype.onTasks_ = function(tasks) {
this.processTasks_(tasks);
for (var index = 0; index < this.pendingInvocations_.length; index++) {
var name = this.pendingInvocations_[index][0];
var args = this.pendingInvocations_[index][1];
this[name].apply(this, args);
}
this.pendingInvocations_ = [];
};
/**
* The list of known extensions to record UMA.
* Note: Because the data is recorded by the index, so new item shouldn't be
* inserted.
*
* @const
* @type {Array.<string>}
* @private
*/
FileTasks.UMA_INDEX_KNOWN_EXTENSIONS_ = Object.freeze([
'other', '.3ga', '.3gp', '.aac', '.alac', '.asf', '.avi', '.bmp', '.csv',
'.doc', '.docx', '.flac', '.gif', '.jpeg', '.jpg', '.log', '.m3u', '.m3u8',
'.m4a', '.m4v', '.mid', '.mkv', '.mov', '.mp3', '.mp4', '.mpg', '.odf',
'.odp', '.ods', '.odt', '.oga', '.ogg', '.ogv', '.pdf', '.png', '.ppt',
'.pptx', '.ra', '.ram', '.rar', '.rm', '.rtf', '.wav', '.webm', '.webp',
'.wma', '.wmv', '.xls', '.xlsx',
]);
/**
* The list of executable file extensions.
*
* @const
* @type {Array.<string>}
*/
FileTasks.EXECUTABLE_EXTENSIONS = Object.freeze([
'.exe', '.lnk', '.deb', '.dmg', '.jar', '.msi',
]);
/**
* The list of extensions to skip the suggest app dialog.
* @const
* @type {Array.<string>}
* @private
*/
FileTasks.EXTENSIONS_TO_SKIP_SUGGEST_APPS_ = Object.freeze([
'.crdownload', '.dsc', '.inf', '.crx',
]);
/**
* Records trial of opening file grouped by extensions.
*
* @param {Array.<Entry>} entries The entries to be opened.
* @private
*/
FileTasks.recordViewingFileTypeUMA_ = function(entries) {
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var extension = FileType.getExtension(entry).toLowerCase();
if (FileTasks.UMA_INDEX_KNOWN_EXTENSIONS_.indexOf(extension) < 0) {
extension = 'other';
}
metrics.recordEnum(
'ViewingFileType', extension, FileTasks.UMA_INDEX_KNOWN_EXTENSIONS_);
}
};
/**
* Returns true if the taskId is for an internal task.
*
* @param {string} taskId Task identifier.
* @return {boolean} True if the task ID is for an internal task.
* @private
*/
FileTasks.isInternalTask_ = function(taskId) {
var taskParts = taskId.split('|');
var appId = taskParts[0];
var taskType = taskParts[1];
var actionId = taskParts[2];
// The action IDs here should match ones used in executeInternalTask_().
return (appId === chrome.runtime.id &&
taskType === 'file' &&
(actionId === 'play' ||
actionId === 'mount-archive' ||
actionId === 'gallery' ||
actionId === 'gallery-video'));
};
/**
* Processes internal tasks.
*
* @param {Array.<Object>} tasks The tasks.
* @private
*/
FileTasks.prototype.processTasks_ = function(tasks) {
this.tasks_ = [];
var id = chrome.runtime.id;
var isOnDrive = false;
var fm = this.fileManager_;
for (var index = 0; index < this.entries_.length; ++index) {
var locationInfo = fm.volumeManager.getLocationInfo(this.entries_[index]);
if (locationInfo && locationInfo.isDriveBased) {
isOnDrive = true;
break;
}
}
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
var taskParts = task.taskId.split('|');
// Skip internal Files.app's handlers.
if (taskParts[0] === id && (taskParts[2] === 'auto-open' ||
taskParts[2] === 'select' || taskParts[2] === 'open')) {
continue;
}
// Tweak images, titles of internal tasks.
if (taskParts[0] === id && taskParts[1] === 'file') {
if (taskParts[2] === 'play') {
// TODO(serya): This hack needed until task.iconUrl is working
// (see GetFileTasksFileBrowserFunction::RunImpl).
task.iconType = 'audio';
task.title = loadTimeData.getString('ACTION_LISTEN');
} else if (taskParts[2] === 'mount-archive') {
task.iconType = 'archive';
task.title = loadTimeData.getString('MOUNT_ARCHIVE');
} else if (taskParts[2] === 'gallery' ||
taskParts[2] === 'gallery-video') {
task.iconType = 'image';
task.title = loadTimeData.getString('ACTION_OPEN');
} else if (taskParts[2] === 'open-hosted-generic') {
if (this.entries_.length > 1)
task.iconType = 'generic';
else // Use specific icon.
task.iconType = FileType.getIcon(this.entries_[0]);
task.title = loadTimeData.getString('ACTION_OPEN');
} else if (taskParts[2] === 'open-hosted-gdoc') {
task.iconType = 'gdoc';
task.title = loadTimeData.getString('ACTION_OPEN_GDOC');
} else if (taskParts[2] === 'open-hosted-gsheet') {
task.iconType = 'gsheet';
task.title = loadTimeData.getString('ACTION_OPEN_GSHEET');
} else if (taskParts[2] === 'open-hosted-gslides') {
task.iconType = 'gslides';
task.title = loadTimeData.getString('ACTION_OPEN_GSLIDES');
} else if (taskParts[2] === 'view-swf') {
// Do not render this task if disabled.
if (!loadTimeData.getBoolean('SWF_VIEW_ENABLED'))
continue;
task.iconType = 'generic';
task.title = loadTimeData.getString('ACTION_VIEW');
} else if (taskParts[2] === 'view-pdf') {
// Do not render this task if disabled.
if (!loadTimeData.getBoolean('PDF_VIEW_ENABLED'))
continue;
task.iconType = 'pdf';
task.title = loadTimeData.getString('ACTION_VIEW');
} else if (taskParts[2] === 'view-in-browser') {
task.iconType = 'generic';
task.title = loadTimeData.getString('ACTION_VIEW');
}
}
if (!task.iconType && taskParts[1] === 'web-intent') {
task.iconType = 'generic';
}
this.tasks_.push(task);
if (this.defaultTask_ === null && task.isDefault) {
this.defaultTask_ = task;
}
}
if (!this.defaultTask_ && this.tasks_.length > 0) {
// If we haven't picked a default task yet, then just pick the first one.
// This is not the preferred way we want to pick this, but better this than
// no default at all if the C++ code didn't set one.
this.defaultTask_ = this.tasks_[0];
}
};
/**
* Executes default task.
*
* @param {function(boolean, Array.<string>)=} opt_callback Called when the
* default task is executed, or the error is occurred.
* @private
*/
FileTasks.prototype.executeDefault_ = function(opt_callback) {
FileTasks.recordViewingFileTypeUMA_(this.entries_);
this.executeDefaultInternal_(this.entries_, opt_callback);
};
/**
* Executes default task.
*
* @param {Array.<Entry>} entries Entries to execute.
* @param {function(boolean, Array.<Entry>)=} opt_callback Called when the
* default task is executed, or the error is occurred.
* @private
*/
FileTasks.prototype.executeDefaultInternal_ = function(entries, opt_callback) {
var callback = opt_callback || function(arg1, arg2) {};
if (this.defaultTask_ !== null) {
this.executeInternal_(this.defaultTask_.taskId, entries);
callback(true, entries);
return;
}
// We don't have tasks, so try to show a file in a browser tab.
// We only do that for single selection to avoid confusion.
if (entries.length !== 1 || !entries[0])
return;
var filename = entries[0].name;
var extension = util.splitExtension(filename)[1];
var mimeType = this.mimeTypes_[0];
var showAlert = function() {
var textMessageId;
var titleMessageId;
switch (extension) {
case '.exe':
textMessageId = 'NO_ACTION_FOR_EXECUTABLE';
break;
case '.crx':
textMessageId = 'NO_ACTION_FOR_CRX';
titleMessageId = 'NO_ACTION_FOR_CRX_TITLE';
break;
default:
textMessageId = 'NO_ACTION_FOR_FILE';
}
var webStoreUrl = FileTasks.createWebStoreLink(extension, mimeType);
var text = strf(textMessageId, webStoreUrl, str('NO_ACTION_FOR_FILE_URL'));
var title = titleMessageId ? str(titleMessageId) : filename;
this.fileManager_.alert.showHtml(title, text, function() {});
callback(false, entries);
}.bind(this);
var onViewFilesFailure = function() {
var fm = this.fileManager_;
if (!fm.isOnDrive() ||
!entries[0] ||
FileTasks.EXTENSIONS_TO_SKIP_SUGGEST_APPS_.indexOf(extension) !== -1) {
showAlert();
return;
}
fm.openSuggestAppsDialog(
entries[0],
function() {
var newTasks = new FileTasks(fm);
newTasks.init(entries, this.mimeTypes_);
newTasks.executeDefault();
callback(true, entries);
}.bind(this),
// Cancelled callback.
function() {
callback(false, entries);
},
showAlert);
}.bind(this);
var onViewFiles = function(result) {
switch (result) {
case 'opened':
callback(success, entries);
break;
case 'message_sent':
util.isTeleported(window).then(function(teleported) {
if (teleported) {
util.showOpenInOtherDesktopAlert(
this.fileManager_.ui.alertDialog, entries);
}
}.bind(this));
callback(success, entries);
break;
case 'empty':
callback(success, entries);
break;
case 'failed':
onViewFilesFailure();
break;
}
}.bind(this);
this.checkAvailability_(function() {
// TODO(mtomasz): Pass entries instead.
var urls = util.entriesToURLs(entries);
var taskId = chrome.runtime.id + '|file|view-in-browser';
chrome.fileBrowserPrivate.executeTask(taskId, urls, onViewFiles);
}.bind(this));
};
/**
* Executes a single task.
*
* @param {string} taskId Task identifier.
* @param {Array.<Entry>=} opt_entries Entries to xecute on instead of
* this.entries_|.
* @private
*/
FileTasks.prototype.execute_ = function(taskId, opt_entries) {
var entries = opt_entries || this.entries_;
FileTasks.recordViewingFileTypeUMA_(entries);
this.executeInternal_(taskId, entries);
};
/**
* The core implementation to execute a single task.
*
* @param {string} taskId Task identifier.
* @param {Array.<Entry>} entries Entries to execute.
* @private
*/
FileTasks.prototype.executeInternal_ = function(taskId, entries) {
this.checkAvailability_(function() {
if (FileTasks.isInternalTask_(taskId)) {
var taskParts = taskId.split('|');
this.executeInternalTask_(taskParts[2], entries);
} else {
// TODO(mtomasz): Pass entries instead.
var urls = util.entriesToURLs(entries);
chrome.fileBrowserPrivate.executeTask(taskId, urls, function(result) {
if (result !== 'message_sent')
return;
util.isTeleported(window).then(function(teleported) {
if (teleported) {
util.showOpenInOtherDesktopAlert(
this.fileManager_.ui.alertDialog, entries);
}
}.bind(this));
}.bind(this));
}
}.bind(this));
};
/**
* Checks whether the remote files are available right now.
*
* @param {function} callback The callback.
* @private
*/
FileTasks.prototype.checkAvailability_ = function(callback) {
var areAll = function(props, name) {
var isOne = function(e) {
// If got no properties, we safely assume that item is unavailable.
return e && e[name];
};
return props.filter(isOne).length === props.length;
};
var fm = this.fileManager_;
var entries = this.entries_;
var isDriveOffline = fm.volumeManager.getDriveConnectionState().type ===
VolumeManagerCommon.DriveConnectionType.OFFLINE;
if (fm.isOnDrive() && isDriveOffline) {
fm.metadataCache_.get(entries, 'drive', function(props) {
if (areAll(props, 'availableOffline')) {
callback();
return;
}
fm.alert.showHtml(
loadTimeData.getString('OFFLINE_HEADER'),
props[0].hosted ?
loadTimeData.getStringF(
entries.length === 1 ?
'HOSTED_OFFLINE_MESSAGE' :
'HOSTED_OFFLINE_MESSAGE_PLURAL') :
loadTimeData.getStringF(
entries.length === 1 ?
'OFFLINE_MESSAGE' :
'OFFLINE_MESSAGE_PLURAL',
loadTimeData.getString('OFFLINE_COLUMN_LABEL')));
});
return;
}
var isOnMetered = fm.volumeManager.getDriveConnectionState().type ===
VolumeManagerCommon.DriveConnectionType.METERED;
if (fm.isOnDrive() && isOnMetered) {
fm.metadataCache_.get(entries, 'drive', function(driveProps) {
if (areAll(driveProps, 'availableWhenMetered')) {
callback();
return;
}
fm.metadataCache_.get(entries, 'filesystem', function(fileProps) {
var sizeToDownload = 0;
for (var i = 0; i !== entries.length; i++) {
if (!driveProps[i].availableWhenMetered)
sizeToDownload += fileProps[i].size;
}
fm.confirm.show(
loadTimeData.getStringF(
entries.length === 1 ?
'CONFIRM_MOBILE_DATA_USE' :
'CONFIRM_MOBILE_DATA_USE_PLURAL',
util.bytesToString(sizeToDownload)),
callback);
});
});
return;
}
callback();
};
/**
* Executes an internal task.
*
* @param {string} id The short task id.
* @param {Array.<Entry>} entries The entries to execute on.
* @private
*/
FileTasks.prototype.executeInternalTask_ = function(id, entries) {
var fm = this.fileManager_;
if (id === 'play') {
var selectedEntry = entries[0];
if (entries.length === 1) {
// If just a single audio file is selected pass along every audio file
// in the directory.
entries = fm.getAllEntriesInCurrentDirectory().filter(FileType.isAudio);
}
// TODO(mtomasz): Pass entries instead.
var urls = util.entriesToURLs(entries);
var position = urls.indexOf(selectedEntry.toURL());
chrome.fileBrowserPrivate.getProfiles(function(profiles,
currentId,
displayedId) {
fm.backgroundPage.launchAudioPlayer({items: urls, position: position},
displayedId);
});
return;
}
if (id === 'mount-archive') {
this.mountArchivesInternal_(entries);
return;
}
if (id === 'gallery' || id === 'gallery-video') {
this.openGalleryInternal_(entries);
return;
}
console.error('Unexpected action ID: ' + id);
};
/**
* Mounts archives.
*
* @param {Array.<Entry>} entries Mount file entries list.
*/
FileTasks.prototype.mountArchives = function(entries) {
FileTasks.recordViewingFileTypeUMA_(entries);
this.mountArchivesInternal_(entries);
};
/**
* The core implementation of mounts archives.
*
* @param {Array.<Entry>} entries Mount file entries list.
* @private
*/
FileTasks.prototype.mountArchivesInternal_ = function(entries) {
var fm = this.fileManager_;
var tracker = fm.directoryModel.createDirectoryChangeTracker();
tracker.start();
// TODO(mtomasz): Pass Entries instead of URLs.
var urls = util.entriesToURLs(entries);
fm.resolveSelectResults_(urls, function(resolvedURLs) {
for (var index = 0; index < resolvedURLs.length; ++index) {
// TODO(mtomasz): Pass Entry instead of URL.
fm.volumeManager.mountArchive(resolvedURLs[index],
function(volumeInfo) {
if (tracker.hasChanged) {
tracker.stop();
return;
}
volumeInfo.resolveDisplayRoot(function(displayRoot) {
if (tracker.hasChanged) {
tracker.stop();
return;
}
fm.directoryModel.changeDirectoryEntry(displayRoot);
}, function() {
console.warn('Failed to resolve the display root after mounting.');
tracker.stop();
});
}, function(url, error) {
tracker.stop();
var path = util.extractFilePath(url);
var namePos = path.lastIndexOf('/');
fm.alert.show(strf('ARCHIVE_MOUNT_FAILED',
path.substr(namePos + 1), error));
}.bind(null, resolvedURLs[index]));
}
});
};
/**
* Open the Gallery.
*
* @param {Array.<Entry>} entries List of selected entries.
*/
FileTasks.prototype.openGallery = function(entries) {
FileTasks.recordViewingFileTypeUMA_(entries);
this.openGalleryInternal_(entries);
};
/**
* The core implementation to open the Gallery.
*
* @param {Array.<Entry>} entries List of selected entries.
* @private
*/
FileTasks.prototype.openGalleryInternal_ = function(entries) {
var fm = this.fileManager_;
var allEntries =
fm.getAllEntriesInCurrentDirectory().filter(FileType.isImageOrVideo);
var galleryFrame = fm.document_.createElement('iframe');
galleryFrame.className = 'overlay-pane';
galleryFrame.scrolling = 'no';
galleryFrame.setAttribute('webkitallowfullscreen', true);
if (this.params_ && this.params_.gallery) {
// Remove the Gallery state from the location, we do not need it any more.
// TODO(mtomasz): Consider keeping the selection path.
util.updateAppState(
null, /* keep current directory */
'', /* remove current selection */
'' /* remove search. */);
}
var savedAppState = JSON.parse(JSON.stringify(window.appState));
var savedTitle = document.title;
// Push a temporary state which will be replaced every time the selection
// changes in the Gallery and popped when the Gallery is closed.
util.updateAppState();
var onBack = function(selectedEntries) {
fm.directoryModel.selectEntries(selectedEntries);
fm.closeFilePopup(); // Will call Gallery.unload.
window.appState = savedAppState;
util.saveAppState();
document.title = savedTitle;
};
var onAppRegionChanged = function(visible) {
fm.onFilePopupAppRegionChanged(visible);
};
galleryFrame.onload = function() {
galleryFrame.contentWindow.ImageUtil.metrics = metrics;
// TODO(haruki): isOnReadonlyDirectory() only checks the permission for the
// root. We should check more granular permission to know whether the file
// is writable or not.
var readonly = fm.isOnReadonlyDirectory();
var currentDir = fm.getCurrentDirectoryEntry();
var downloadsVolume = fm.volumeManager.getCurrentProfileVolumeInfo(
VolumeManagerCommon.RootType.DOWNLOADS);
var downloadsDir = downloadsVolume && downloadsVolume.fileSystem.root;
// TODO(mtomasz): Pass Entry instead of localized name. Conversion to a
// display string should be done in gallery.js.
var readonlyDirName = null;
if (readonly && currentDir)
readonlyDirName = util.getEntryLabel(fm.volumeManager, currentDir);
var context = {
// We show the root label in readonly warning (e.g. archive name).
readonlyDirName: readonlyDirName,
curDirEntry: currentDir,
saveDirEntry: readonly ? downloadsDir : null,
searchResults: fm.directoryModel.isSearching(),
metadataCache: fm.metadataCache_,
pageState: this.params_,
appWindow: chrome.app.window.current(),
onBack: onBack,
onClose: fm.onClose.bind(fm),
onMaximize: fm.onMaximize.bind(fm),
onMinimize: fm.onMinimize.bind(fm),
onAppRegionChanged: onAppRegionChanged,
loadTimeData: fm.backgroundPage.background.stringData
};
galleryFrame.contentWindow.Gallery.open(
context, fm.volumeManager, allEntries, entries);
}.bind(this);
galleryFrame.src = 'gallery.html';
fm.openFilePopup(galleryFrame, fm.updateTitle_.bind(fm));
};
/**
* Displays the list of tasks in a task picker combobutton.
*
* @param {cr.ui.ComboButton} combobutton The task picker element.
* @private
*/
FileTasks.prototype.display_ = function(combobutton) {
if (this.tasks_.length === 0) {
combobutton.hidden = true;
return;
}
combobutton.clear();
combobutton.hidden = false;
combobutton.defaultItem = this.createCombobuttonItem_(this.defaultTask_);
var items = this.createItems_();
if (items.length > 1) {
var defaultIdx = 0;
for (var j = 0; j < items.length; j++) {
combobutton.addDropDownItem(items[j]);
if (items[j].task.taskId === this.defaultTask_.taskId)
defaultIdx = j;
}
combobutton.addSeparator();
var changeDefaultMenuItem = combobutton.addDropDownItem({
label: loadTimeData.getString('CHANGE_DEFAULT_MENU_ITEM')
});
changeDefaultMenuItem.classList.add('change-default');
}
};
/**
* Creates sorted array of available task descriptions such as title and icon.
*
* @return {Array} created array can be used to feed combobox, menus and so on.
* @private
*/
FileTasks.prototype.createItems_ = function() {
var items = [];
var title = this.defaultTask_.title + ' ' +
loadTimeData.getString('DEFAULT_ACTION_LABEL');
items.push(this.createCombobuttonItem_(this.defaultTask_, title, true));
for (var index = 0; index < this.tasks_.length; index++) {
var task = this.tasks_[index];
if (task !== this.defaultTask_)
items.push(this.createCombobuttonItem_(task));
}
items.sort(function(a, b) {
return a.label.localeCompare(b.label);
});
return items;
};
/**
* Updates context menu with default item.
* @private
*/
FileTasks.prototype.updateMenuItem_ = function() {
this.fileManager_.updateContextMenuActionItems(this.defaultTask_,
this.tasks_.length > 1);
};
/**
* Creates combobutton item based on task.
*
* @param {Object} task Task to convert.
* @param {string=} opt_title Title.
* @param {boolean=} opt_bold Make a menu item bold.
* @return {Object} Item appendable to combobutton drop-down list.
* @private
*/
FileTasks.prototype.createCombobuttonItem_ = function(task, opt_title,
opt_bold) {
return {
label: opt_title || task.title,
iconUrl: task.iconUrl,
iconType: task.iconType,
task: task,
bold: opt_bold || false
};
};
/**
* Shows modal action picker dialog with currently available list of tasks.
*
* @param {DefaultActionDialog} actionDialog Action dialog to show and update.
* @param {string} title Title to use.
* @param {string} message Message to use.
* @param {function(Object)} onSuccess Callback to pass selected task.
*/
FileTasks.prototype.showTaskPicker = function(actionDialog, title, message,
onSuccess) {
var items = this.createItems_();
var defaultIdx = 0;
for (var j = 0; j < items.length; j++) {
if (items[j].task.taskId === this.defaultTask_.taskId)
defaultIdx = j;
}
actionDialog.show(
title,
message,
items, defaultIdx,
function(item) {
onSuccess(item.task);
});
};
/**
* Decorates a FileTasks method, so it will be actually executed after the tasks
* are available.
* This decorator expects an implementation called |method + '_'|.
*
* @param {string} method The method name.
*/
FileTasks.decorate = function(method) {
var privateMethod = method + '_';
FileTasks.prototype[method] = function() {
if (this.tasks_) {
this[privateMethod].apply(this, arguments);
} else {
this.pendingInvocations_.push([privateMethod, arguments]);
}
return this;
};
};
FileTasks.decorate('display');
FileTasks.decorate('updateMenuItem');
FileTasks.decorate('execute');
FileTasks.decorate('executeDefault');
| boundarydevices/android_external_chromium_org | ui/file_manager/file_manager/foreground/js/file_tasks.js | JavaScript | bsd-3-clause | 26,503 |
/*!
* @package yii2-grid
* @author Kartik Visweswaran <kartikv2@gmail.com>
* @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2016
* @version 3.1.3
*
* Grid Export Validation Module for Yii's Gridview. Supports export of
* grid data as CSV, HTML, or Excel.
*
* Author: Kartik Visweswaran
* Copyright: 2015, Kartik Visweswaran, Krajee.com
* For more JQuery plugins visit http://plugins.krajee.com
* For more Yii related demos visit http://demos.krajee.com
*/
(function ($) {
"use strict";
var replaceAll, isEmpty, popupDialog, slug, templates, GridExport, urn = "urn:schemas-microsoft-com:office:";
replaceAll = function (str, from, to) {
return str.split(from).join(to);
};
isEmpty = function (value, trim) {
return value === null || value === undefined || value.length === 0 || (trim && $.trim(value) === '');
};
popupDialog = function (url, name, w, h) {
var left = (screen.width / 2) - (w / 2), top = 60, existWin = window.open('', name, '', true);
existWin.close();
return window.open(url, name,
'toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=no, ' +
'resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
};
slug = function (strText) {
return strText.toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g, '-');
};
//noinspection XmlUnusedNamespaceDeclaration
templates = {
html: '<!DOCTYPE html>' +
'<meta http-equiv="Content-Type" content="text/html;charset={encoding}"/>' +
'<meta http-equiv="X-UA-Compatible" content="IE=edge;chrome=1"/>' +
'{css}' +
'<style>' +
'.kv-wrap{padding:20px;}' +
'.kv-align-center{text-align:center;}' +
'.kv-align-left{text-align:left;}' +
'.kv-align-right{text-align:right;}' +
'.kv-align-top{vertical-align:top!important;}' +
'.kv-align-bottom{vertical-align:bottom!important;}' +
'.kv-align-middle{vertical-align:middle!important;}' +
'.kv-page-summary{border-top:4px double #ddd;font-weight: bold;}' +
'.kv-table-footer{border-top:4px double #ddd;font-weight: bold;}' +
'.kv-table-caption{font-size:1.5em;padding:8px;border:1px solid #ddd;border-bottom:none;}' +
'</style>' +
'<body class="kv-wrap">' +
'{data}' +
'</body>',
pdf: '{before}\n{data}\n{after}',
excel: '<html xmlns:o="' + urn + 'office" xmlns:x="' + urn + 'excel" xmlns="http://www.w3.org/TR/REC-html40">' +
'<head>' +
'<meta http-equiv="Content-Type" content="text/html;charset={encoding}"/>' +
'{css}' +
'<!--[if gte mso 9]>' +
'<xml>' +
'<x:ExcelWorkbook>' +
'<x:ExcelWorksheets>' +
'<x:ExcelWorksheet>' +
'<x:Name>{worksheet}</x:Name>' +
'<x:WorksheetOptions>' +
'<x:DisplayGridlines/>' +
'</x:WorksheetOptions>' +
'</x:ExcelWorksheet>' +
'</x:ExcelWorksheets>' +
'</x:ExcelWorkbook>' +
'</xml>' +
'<![endif]-->' +
'</head>' +
'<body>' +
'{data}' +
'</body>' +
'</html>',
popup: '<html style="display:table;width:100%;height:100%;">' +
'<title>Grid Export - © Krajee</title>' +
'<body style="display:table-cell;font-family:Helvetica,Arial,sans-serif;color:#888;font-weight:bold;line-height:1.4em;text-align:center;vertical-align:middle;width:100%;height:100%;padding:0 10px;">' +
'{msg}' +
'</body>' +
'</html>'
};
GridExport = function (element, options) {
//noinspection JSUnresolvedVariable
var self = this, gridOpts = options.gridOpts, genOpts = options.genOpts;
self.$element = $(element);
//noinspection JSUnresolvedVariable
self.gridId = gridOpts.gridId;
self.$grid = $("#" + gridOpts.gridId);
self.dialogLib = options.dialogLib;
self.messages = gridOpts.messages;
self.target = gridOpts.target;
self.exportConversions = gridOpts.exportConversions;
self.showConfirmAlert = gridOpts.showConfirmAlert;
self.filename = genOpts.filename;
self.showHeader = genOpts.showHeader;
self.showFooter = genOpts.showFooter;
self.showPageSummary = genOpts.showPageSummary;
self.$table = self.$grid.find('.kv-grid-table:first');
self.$form = self.$grid.find('form.kv-export-form');
self.encoding = self.$form.find('[name="export_encoding"]').val();
self.columns = self.showHeader ? 'td,th' : 'td';
self.alertMsg = options.alertMsg;
self.config = options.config;
self.popup = '';
self.listen();
};
GridExport.prototype = {
constructor: GridExport,
getArray: function (expType) {
var self = this, $table = self.clean(expType), head = [], data = {};
/** @namespace self.config.colHeads */
/** @namespace self.config.slugColHeads */
if (self.config.colHeads !== undefined && self.config.colHeads.length > 0) {
head = self.config.colHeads;
} else {
$table.find('thead tr th').each(function (i) {
var str = $(this).text().trim(), slugStr = slug(str);
head[i] = (!self.config.slugColHeads || isEmpty(slugStr)) ? 'col_' + i : slugStr;
});
}
$table.find('tbody tr:has("td")').each(function (i) {
data[i] = {};
//noinspection JSValidateTypes
$(this).children('td').each(function (j) {
var col = head[j];
data[i][col] = $(this).text().trim();
});
});
return data;
},
setPopupAlert: function (msg) {
var self = this;
if (self.popup.document === undefined) {
return;
}
if (arguments.length && arguments[1]) {
var el = self.popup.document.getElementsByTagName('body');
setTimeout(function () {
el[0].innerHTML = msg;
}, 4000);
} else {
var newmsg = templates.popup.replace('{msg}', msg);
self.popup.document.write(newmsg);
}
},
processExport: function(callback, arg) {
var self = this;
setTimeout(function() {
if (!isEmpty(arg)) {
self[callback](arg);
} else {
self[callback]();
}
}, 100);
},
listenClick: function (callback) {
var self = this, arg = arguments.length > 1 ? arguments[1] : '', lib = window[self.dialogLib];
self.$element.off("click.gridexport").on("click.gridexport", function (e) {
e.stopPropagation();
e.preventDefault();
if (!self.showConfirmAlert) {
self.processExport(callback, arg);
return;
}
var msgs = self.messages, msg1 = isEmpty(self.alertMsg) ? '' : self.alertMsg,
msg2 = isEmpty(msgs.allowPopups) ? '' : msgs.allowPopups,
msg3 = isEmpty(msgs.confirmDownload) ? '' : msgs.confirmDownload, msg = '';
if (msg1.length && msg2.length) {
msg = msg1 + '\n\n' + msg2;
} else {
if (!msg1.length && msg2.length) {
msg = msg2;
} else {
msg = (msg1.length && !msg2.length) ? msg1 : '';
}
}
if (msg3.length) {
msg = msg + '\n\n' + msg3;
}
if (isEmpty(msg)) {
return;
}
lib.confirm(msg, function(result) {
if (result) {
self.processExport(callback, arg);
}
e.preventDefault();
});
return false;
});
},
listen: function () {
var self = this;
if (self.target === '_popup') {
self.$form.on('submit.gridexport', function () {
setTimeout(function () {
self.setPopupAlert(self.messages.downloadComplete, true);
}, 1000);
});
}
if (self.$element.hasClass('export-csv')) {
self.listenClick('exportTEXT', 'csv');
}
if (self.$element.hasClass('export-txt')) {
self.listenClick('exportTEXT', 'txt');
}
if (self.$element.hasClass('export-html')) {
self.listenClick('exportHTML');
}
if (self.$element.hasClass('export-xls')) {
self.listenClick('exportEXCEL');
}
if (self.$element.hasClass('export-json')) {
self.listenClick('exportJSON');
}
if (self.$element.hasClass('export-pdf')) {
self.listenClick('exportPDF');
}
},
clean: function (expType) {
var self = this, $table = self.$table.clone(),
$tHead = self.$table.closest('.kv-grid-container').find('.kv-thead-float thead'),
safeRemove = function(selector) {
$table.find(selector + '.' + self.gridId).remove();
};
if ($tHead.length) {
$tHead = $tHead.clone();
$table.find('thead').before($tHead).remove();
}
// Skip the filter rows and header rowspans
$table.find('tr.filters').remove();
$table.find('th').removeAttr('rowspan');
// remove link tags
$table.find('th').find('a').each(function () {
$(this).contents().unwrap();
});
$table.find('input').remove(); // remove any form inputs
if (!self.showHeader) {
$table.children('thead').remove();
}
if (!self.showPageSummary) {
safeRemove('.kv-page-summary-container');
}
if (!self.showFooter) {
safeRemove('.kv-footer-container');
}
if (!self.showCaption) {
safeRemove('.kv-caption-container');
}
$table.find('.skip-export').remove();
$table.find('.skip-export-' + expType).remove();
var htmlContent = $table.html();
htmlContent = self.preProcess(htmlContent);
$table.html(htmlContent);
return $table;
},
preProcess: function (content) {
var self = this, conv = self.exportConversions, l = conv.length, processed = content, c;
if (l > 0) {
for (var i = 0; i < l; i++) {
c = conv[i];
processed = replaceAll(processed, c.from, c.to);
}
}
return processed;
},
download: function (type, content) {
var self = this, fmt = self.$element.data('format'),
config = isEmpty(self.config) ? {} : self.config;
self.$form.find('[name="export_filetype"]').val(type);
self.$form.find('[name="export_filename"]').val(self.filename);
self.$form.find('[name="export_content"]').val(content);
self.$form.find('[name="export_mime"]').val(fmt);
if (type === 'pdf') {
self.$form.find('[name="export_config"]').val(JSON.stringify(config));
} else {
self.$form.find('[name="export_config"]').val('');
}
if (self.target === '_popup') {
self.popup = popupDialog('', 'kvDownloadDialog', 350, 120);
self.popup.focus();
self.setPopupAlert(self.messages.downloadProgress);
}
self.$form.submit();
},
exportHTML: function () {
/** @namespace self.config.cssFile */
var self = this, $table = self.clean('html'), cfg = self.config,
css = (self.config.cssFile && cfg.cssFile.length) ? '<link href="' + self.config.cssFile + '" rel="stylesheet">' : '',
html = templates.html.replace('{encoding}', self.encoding).replace('{css}', css).replace('{data}',
$('<div />').html($table).html());
self.download('html', html);
},
exportPDF: function () {
var self = this, $table = self.clean('pdf');
/** @namespace self.config.contentAfter */
/** @namespace self.config.contentBefore */
var before = isEmpty(self.config.contentBefore) ? '' : self.config.contentBefore,
after = isEmpty(self.config.contentAfter) ? '' : self.config.contentAfter,
css = self.config.css,
pdf = templates.pdf.replace('{css}', css)
.replace('{before}', before)
.replace('{after}', after)
.replace('{data}', $('<div />').html($table).html());
self.download('pdf', pdf);
},
exportTEXT: function (expType) {
var self = this, $table = self.clean(expType),
$rows = $table.find('tr:has(' + self.columns + ')');
// temporary delimiter characters unlikely to be typed by keyboard,
// this is to avoid accidentally splitting the actual contents
var tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0); // null character
// actual delimiter characters for CSV format
/** @namespace self.config.rowDelimiter */
/** @namespace self.config.colDelimiter */
var colD = '"' + self.config.colDelimiter + '"', rowD = '"' + self.config.rowDelimiter + '"';
// grab text from table into CSV formatted string
var txt = '"' + $rows.map(function (i, row) {
var $row = $(row), $cols = $row.find(self.columns);
return $cols.map(function (j, col) {
var $col = $(col), text = $col.text().trim();
return text.replace(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowD)
.split(tmpColDelim).join(colD) + '"';
self.download(expType, txt);
},
exportJSON: function () {
var self = this, out = self.getArray('json');
/** @namespace self.config.indentSpace */
/** @namespace self.config.jsonReplacer */
out = JSON.stringify(out, self.config.jsonReplacer, self.config.indentSpace);
self.download('json', out);
},
exportEXCEL: function () {
var self = this, $table = self.clean('xls'), cfg = self.config, xls, $td,
css = (cfg.cssFile && self.config.cssFile.length) ? '<link href="' + self.config.cssFile + '" rel="stylesheet">' : '';
$table.find('td[data-raw-value]').each(function () {
$td = $(this);
if ($td.css('mso-number-format') || $td.css('mso-number-format') === 0 || $td.css(
'mso-number-format') === '0') {
$td.html($td.attr('data-raw-value')).removeAttr('data-raw-value');
}
});
/** @namespace self.config.worksheet */
xls = templates.excel.replace('{encoding}', self.encoding).replace('{css}', css).replace('{worksheet}',
self.config.worksheet).replace('{data}', $('<div />').html($table).html()).replace(/"/g, '\'');
self.download('xls', xls);
}
};
//GridExport plugin definition
$.fn.gridexport = function (option) {
var args = Array.apply(null, arguments);
args.shift();
return this.each(function () {
var $this = $(this),
data = $this.data('gridexport'),
options = typeof option === 'object' && option;
if (!data) {
$this.data('gridexport',
(data = new GridExport(this, $.extend({}, $.fn.gridexport.defaults, options, $(this).data()))));
}
if (typeof option === 'string') {
data[option].apply(data, args);
}
});
};
$.fn.gridexport.defaults = {dialogLib: 'krajeeDialog'};
$.fn.gridexport.Constructor = GridExport;
})(window.jQuery); | Lucianoj/puro_perro | web/assets/4a9d339f/js/kv-grid-export.js | JavaScript | bsd-3-clause | 17,047 |
var Example = function Example() {
"use strict";
babelHelpers.classCallCheck(this, Example);
var _Example;
};
var t = new Example();
| Skillupco/babel | packages/babel-plugin-transform-classes/test/fixtures/spec/constructor-binding-collision/output.js | JavaScript | mit | 142 |
'use strict';
module.exports = function (math, config) {
var util = require('../../util/index'),
Matrix = math.type.Matrix,
Unit = require('../../type/Unit'),
collection = math.collection,
isBoolean = util['boolean'].isBoolean,
isInteger = util.number.isInteger,
isNumber = util.number.isNumber,
isCollection = collection.isCollection;
/**
* Bitwise right logical shift of value x by y number of bits, `x >>> y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.rightLogShift(x, y)
*
* Examples:
*
* math.rightLogShift(4, 2); // returns Number 1
*
* math.rightLogShift([16, -32, 64], 4); // returns Array [1, 2, 3]
*
* See also:
*
* bitAnd, bitNot, bitOr, bitXor, leftShift, rightArithShift
*
* @param {Number | Boolean | Array | Matrix | null} x Value to be shifted
* @param {Number | Boolean | null} y Amount of shifts
* @return {Number | Array | Matrix} `x` zero-filled shifted right `y` times
*/
math.rightLogShift = function rightLogShift(x, y) {
if (arguments.length != 2) {
throw new math.error.ArgumentsError('rightLogShift', arguments.length, 2);
}
if (isNumber(x) && isNumber(y)) {
if (!isInteger(x) || !isInteger(y)) {
throw new Error('Parameters in function rightLogShift must be integer numbers');
}
return x >>> y;
}
if (isCollection(x) && isNumber(y)) {
return collection.deepMap2(x, y, rightLogShift);
}
if (isBoolean(x) || x === null) {
return rightLogShift(+x, y);
}
if (isBoolean(y) || y === null) {
return rightLogShift(x, +y);
}
throw new math.error.UnsupportedTypeError('rightLogShift', math['typeof'](x), math['typeof'](y));
};
};
| MonoHearted/Flowerbless | node_modules/mathjs/lib/function/bitwise/rightLogShift.js | JavaScript | mit | 1,895 |
import defaults from './defaults.js';
import _ from './underscore.js';
import './templateSettings.js';
// When customizing `_.templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
function escapeChar(match) {
return '\\' + escapes[match];
}
// In order to prevent third-party code injection through
// `_.templateSettings.variable`, we test it against the following regular
// expression. It is intentionally a bit more liberal than just matching valid
// identifiers, but still prevents possible loopholes through defaults or
// destructuring assignment.
var bareIdentifier = /^\s*(\w|\$)+\s*$/;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
export default function template(text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offset.
return match;
});
source += "';\n";
var argument = settings.variable;
if (argument) {
// Insure against third-party code injection. (CVE-2021-23358)
if (!bareIdentifier.test(argument)) throw new Error(
'variable is not a bare identifier: ' + argument
);
} else {
// If a variable is not specified, place data values in local scope.
source = 'with(obj||{}){\n' + source + '}\n';
argument = 'obj';
}
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';
var render;
try {
render = new Function(argument, '_', source);
} catch (e) {
e.source = source;
throw e;
}
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
}
| ealbertos/dotfiles | vscode.symlink/extensions/ms-mssql.mssql-1.11.1/node_modules/underscore/modules/template.js | JavaScript | mit | 3,283 |
var _ref =
/*#__PURE__*/
<foo />;
function render() {
return _ref;
}
var _ref2 =
/*#__PURE__*/
<div className="foo"><input type="checkbox" checked={true} /></div>;
function render() {
return _ref2;
}
| samwgoldman/babel | packages/babel-plugin-transform-react-constant-elements/test/fixtures/constant-elements/html-element/output.js | JavaScript | mit | 207 |
exports.forward = require('./forward');
exports.respond = require('./respond');
| umissthestars/nproxy | lib/middlewares/index.js | JavaScript | mit | 80 |
'use strict';
/* globals generateInputCompilerHelper: false */
describe('ngModel', function() {
describe('NgModelController', function() {
/* global NgModelController: false */
var ctrl, scope, element, parentFormCtrl;
beforeEach(inject(function($rootScope, $controller) {
var attrs = {name: 'testAlias', ngModel: 'value'};
parentFormCtrl = {
$$setPending: jasmine.createSpy('$$setPending'),
$setValidity: jasmine.createSpy('$setValidity'),
$setDirty: jasmine.createSpy('$setDirty'),
$$clearControlValidity: noop
};
element = jqLite('<form><input></form>');
scope = $rootScope;
ctrl = $controller(NgModelController, {
$scope: scope,
$element: element.find('input'),
$attrs: attrs
});
//Assign the mocked parentFormCtrl to the model controller
ctrl.$$parentForm = parentFormCtrl;
}));
afterEach(function() {
dealoc(element);
});
it('should init the properties', function() {
expect(ctrl.$untouched).toBe(true);
expect(ctrl.$touched).toBe(false);
expect(ctrl.$dirty).toBe(false);
expect(ctrl.$pristine).toBe(true);
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
expect(ctrl.$viewValue).toBeDefined();
expect(ctrl.$modelValue).toBeDefined();
expect(ctrl.$formatters).toEqual([]);
expect(ctrl.$parsers).toEqual([]);
expect(ctrl.$name).toBe('testAlias');
});
describe('setValidity', function() {
function expectOneError() {
expect(ctrl.$error).toEqual({someError: true});
expect(ctrl.$$success).toEqual({});
expect(ctrl.$pending).toBeUndefined();
}
function expectOneSuccess() {
expect(ctrl.$error).toEqual({});
expect(ctrl.$$success).toEqual({someError: true});
expect(ctrl.$pending).toBeUndefined();
}
function expectOnePending() {
expect(ctrl.$error).toEqual({});
expect(ctrl.$$success).toEqual({});
expect(ctrl.$pending).toEqual({someError: true});
}
function expectCleared() {
expect(ctrl.$error).toEqual({});
expect(ctrl.$$success).toEqual({});
expect(ctrl.$pending).toBeUndefined();
}
it('should propagate validity to the parent form', function() {
expect(parentFormCtrl.$setValidity).not.toHaveBeenCalled();
ctrl.$setValidity('ERROR', false);
expect(parentFormCtrl.$setValidity).toHaveBeenCalledOnceWith('ERROR', false, ctrl);
});
it('should transition from states correctly', function() {
expectCleared();
ctrl.$setValidity('someError', false);
expectOneError();
ctrl.$setValidity('someError', undefined);
expectOnePending();
ctrl.$setValidity('someError', true);
expectOneSuccess();
ctrl.$setValidity('someError', null);
expectCleared();
});
it('should set valid/invalid with multiple errors', function() {
ctrl.$setValidity('first', false);
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
ctrl.$setValidity('second', false);
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
ctrl.$setValidity('third', undefined);
expect(ctrl.$valid).toBeUndefined();
expect(ctrl.$invalid).toBeUndefined();
ctrl.$setValidity('third', null);
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
ctrl.$setValidity('second', true);
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
ctrl.$setValidity('first', true);
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
});
});
describe('setPristine', function() {
it('should set control to its pristine state', function() {
ctrl.$setViewValue('edit');
expect(ctrl.$dirty).toBe(true);
expect(ctrl.$pristine).toBe(false);
ctrl.$setPristine();
expect(ctrl.$dirty).toBe(false);
expect(ctrl.$pristine).toBe(true);
});
});
describe('setDirty', function() {
it('should set control to its dirty state', function() {
expect(ctrl.$pristine).toBe(true);
expect(ctrl.$dirty).toBe(false);
ctrl.$setDirty();
expect(ctrl.$pristine).toBe(false);
expect(ctrl.$dirty).toBe(true);
});
it('should set parent form to its dirty state', function() {
ctrl.$setDirty();
expect(parentFormCtrl.$setDirty).toHaveBeenCalled();
});
});
describe('setUntouched', function() {
it('should set control to its untouched state', function() {
ctrl.$setTouched();
ctrl.$setUntouched();
expect(ctrl.$touched).toBe(false);
expect(ctrl.$untouched).toBe(true);
});
});
describe('setTouched', function() {
it('should set control to its touched state', function() {
ctrl.$setUntouched();
ctrl.$setTouched();
expect(ctrl.$touched).toBe(true);
expect(ctrl.$untouched).toBe(false);
});
});
describe('view -> model', function() {
it('should set the value to $viewValue', function() {
ctrl.$setViewValue('some-val');
expect(ctrl.$viewValue).toBe('some-val');
});
it('should pipeline all registered parsers and set result to $modelValue', function() {
var log = [];
ctrl.$parsers.push(function(value) {
log.push(value);
return value + '-a';
});
ctrl.$parsers.push(function(value) {
log.push(value);
return value + '-b';
});
ctrl.$setViewValue('init');
expect(log).toEqual(['init', 'init-a']);
expect(ctrl.$modelValue).toBe('init-a-b');
});
it('should fire viewChangeListeners when the value changes in the view (even if invalid)',
function() {
var spy = jasmine.createSpy('viewChangeListener');
ctrl.$viewChangeListeners.push(spy);
ctrl.$setViewValue('val');
expect(spy).toHaveBeenCalledOnce();
spy.calls.reset();
// invalid
ctrl.$parsers.push(function() {return undefined;});
ctrl.$setViewValue('val2');
expect(spy).toHaveBeenCalledOnce();
});
it('should reset the model when the view is invalid', function() {
ctrl.$setViewValue('aaaa');
expect(ctrl.$modelValue).toBe('aaaa');
// add a validator that will make any input invalid
ctrl.$parsers.push(function() {return undefined;});
expect(ctrl.$modelValue).toBe('aaaa');
ctrl.$setViewValue('bbbb');
expect(ctrl.$modelValue).toBeUndefined();
});
it('should not reset the model when the view is invalid due to an external validator', function() {
ctrl.$setViewValue('aaaa');
expect(ctrl.$modelValue).toBe('aaaa');
ctrl.$setValidity('someExternalError', false);
ctrl.$setViewValue('bbbb');
expect(ctrl.$modelValue).toBe('bbbb');
});
it('should not reset the view when the view is invalid', function() {
// this test fails when the view changes the model and
// then the model listener in ngModel picks up the change and
// tries to update the view again.
// add a validator that will make any input invalid
ctrl.$parsers.push(function() {return undefined;});
spyOn(ctrl, '$render');
// first digest
ctrl.$setViewValue('bbbb');
expect(ctrl.$modelValue).toBeUndefined();
expect(ctrl.$viewValue).toBe('bbbb');
expect(ctrl.$render).not.toHaveBeenCalled();
expect(scope.value).toBeUndefined();
// further digests
scope.$apply('value = "aaa"');
expect(ctrl.$viewValue).toBe('aaa');
ctrl.$render.calls.reset();
ctrl.$setViewValue('cccc');
expect(ctrl.$modelValue).toBeUndefined();
expect(ctrl.$viewValue).toBe('cccc');
expect(ctrl.$render).not.toHaveBeenCalled();
expect(scope.value).toBeUndefined();
});
it('should call parentForm.$setDirty only when pristine', function() {
ctrl.$setViewValue('');
expect(ctrl.$pristine).toBe(false);
expect(ctrl.$dirty).toBe(true);
expect(parentFormCtrl.$setDirty).toHaveBeenCalledOnce();
parentFormCtrl.$setDirty.calls.reset();
ctrl.$setViewValue('');
expect(ctrl.$pristine).toBe(false);
expect(ctrl.$dirty).toBe(true);
expect(parentFormCtrl.$setDirty).not.toHaveBeenCalled();
});
it('should remove all other errors when any parser returns undefined', function() {
var a, b, val = function(val, x) {
return x ? val : x;
};
ctrl.$parsers.push(function(v) { return val(v, a); });
ctrl.$parsers.push(function(v) { return val(v, b); });
ctrl.$validators.high = function(value) {
return !isDefined(value) || value > 5;
};
ctrl.$validators.even = function(value) {
return !isDefined(value) || value % 2 === 0;
};
a = b = true;
ctrl.$setViewValue('3');
expect(ctrl.$error).toEqual({ high: true, even: true });
ctrl.$setViewValue('10');
expect(ctrl.$error).toEqual({});
a = undefined;
ctrl.$setViewValue('12');
expect(ctrl.$error).toEqual({ parse: true });
a = true;
b = undefined;
ctrl.$setViewValue('14');
expect(ctrl.$error).toEqual({ parse: true });
a = undefined;
b = undefined;
ctrl.$setViewValue('16');
expect(ctrl.$error).toEqual({ parse: true });
a = b = false; //not undefined
ctrl.$setViewValue('2');
expect(ctrl.$error).toEqual({ high: true });
});
it('should not remove external validators when a parser failed', function() {
ctrl.$parsers.push(function(v) { return undefined; });
ctrl.$setValidity('externalError', false);
ctrl.$setViewValue('someValue');
expect(ctrl.$error).toEqual({ externalError: true, parse: true });
});
it('should remove all non-parse-related CSS classes from the form when a parser fails',
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" >' +
'</form>')($rootScope);
var inputElm = element.find('input');
var ctrl = $rootScope.myForm.myControl;
var parserIsFailing = false;
ctrl.$parsers.push(function(value) {
return parserIsFailing ? undefined : value;
});
ctrl.$validators.alwaysFail = function() {
return false;
};
ctrl.$setViewValue('123');
scope.$digest();
expect(element).toHaveClass('ng-valid-parse');
expect(element).not.toHaveClass('ng-invalid-parse');
expect(element).toHaveClass('ng-invalid-always-fail');
parserIsFailing = true;
ctrl.$setViewValue('12345');
scope.$digest();
expect(element).not.toHaveClass('ng-valid-parse');
expect(element).toHaveClass('ng-invalid-parse');
expect(element).not.toHaveClass('ng-invalid-always-fail');
dealoc(element);
}));
it('should set the ng-invalid-parse and ng-valid-parse CSS class when parsers fail and pass', function() {
var pass = true;
ctrl.$parsers.push(function(v) {
return pass ? v : undefined;
});
var input = element.find('input');
ctrl.$setViewValue('1');
expect(input).toHaveClass('ng-valid-parse');
expect(input).not.toHaveClass('ng-invalid-parse');
pass = undefined;
ctrl.$setViewValue('2');
expect(input).not.toHaveClass('ng-valid-parse');
expect(input).toHaveClass('ng-invalid-parse');
});
it('should update the model after all async validators resolve', inject(function($q) {
var defer;
ctrl.$asyncValidators.promiseValidator = function(value) {
defer = $q.defer();
return defer.promise;
};
// set view value on first digest
ctrl.$setViewValue('b');
expect(ctrl.$modelValue).toBeUndefined();
expect(scope.value).toBeUndefined();
defer.resolve();
scope.$digest();
expect(ctrl.$modelValue).toBe('b');
expect(scope.value).toBe('b');
// set view value on further digests
ctrl.$setViewValue('c');
expect(ctrl.$modelValue).toBe('b');
expect(scope.value).toBe('b');
defer.resolve();
scope.$digest();
expect(ctrl.$modelValue).toBe('c');
expect(scope.value).toBe('c');
}));
it('should not throw an error if the scope has been destroyed', function() {
scope.$destroy();
ctrl.$setViewValue('some-val');
expect(ctrl.$viewValue).toBe('some-val');
});
});
describe('model -> view', function() {
it('should set the value to $modelValue', function() {
scope.$apply('value = 10');
expect(ctrl.$modelValue).toBe(10);
});
it('should pipeline all registered formatters in reversed order and set result to $viewValue',
function() {
var log = [];
ctrl.$formatters.unshift(function(value) {
log.push(value);
return value + 2;
});
ctrl.$formatters.unshift(function(value) {
log.push(value);
return value + '';
});
scope.$apply('value = 3');
expect(log).toEqual([3, 5]);
expect(ctrl.$viewValue).toBe('5');
});
it('should $render only if value changed', function() {
spyOn(ctrl, '$render');
scope.$apply('value = 3');
expect(ctrl.$render).toHaveBeenCalledOnce();
ctrl.$render.calls.reset();
ctrl.$formatters.push(function() {return 3;});
scope.$apply('value = 5');
expect(ctrl.$render).not.toHaveBeenCalled();
});
it('should clear the view even if invalid', function() {
spyOn(ctrl, '$render');
ctrl.$formatters.push(function() {return undefined;});
scope.$apply('value = 5');
expect(ctrl.$render).toHaveBeenCalledOnce();
});
it('should render immediately even if there are async validators', inject(function($q) {
spyOn(ctrl, '$render');
ctrl.$asyncValidators.someValidator = function() {
return $q.defer().promise;
};
scope.$apply('value = 5');
expect(ctrl.$viewValue).toBe(5);
expect(ctrl.$render).toHaveBeenCalledOnce();
}));
it('should not rerender nor validate in case view value is not changed', function() {
ctrl.$formatters.push(function(value) {
return 'nochange';
});
spyOn(ctrl, '$render');
ctrl.$validators.spyValidator = jasmine.createSpy('spyValidator');
scope.$apply('value = "first"');
scope.$apply('value = "second"');
expect(ctrl.$validators.spyValidator).toHaveBeenCalledOnce();
expect(ctrl.$render).toHaveBeenCalledOnce();
});
it('should always format the viewValue as a string for a blank input type when the value is present',
inject(function($compile, $rootScope, $sniffer) {
var form = $compile('<form name="form"><input name="field" ng-model="val" /></form>')($rootScope);
$rootScope.val = 123;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe('123');
$rootScope.val = null;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe(null);
dealoc(form);
}));
it('should always format the viewValue as a string for a `text` input type when the value is present',
inject(function($compile, $rootScope, $sniffer) {
var form = $compile('<form name="form"><input type="text" name="field" ng-model="val" /></form>')($rootScope);
$rootScope.val = 123;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe('123');
$rootScope.val = null;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe(null);
dealoc(form);
}));
it('should always format the viewValue as a string for an `email` input type when the value is present',
inject(function($compile, $rootScope, $sniffer) {
var form = $compile('<form name="form"><input type="email" name="field" ng-model="val" /></form>')($rootScope);
$rootScope.val = 123;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe('123');
$rootScope.val = null;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe(null);
dealoc(form);
}));
it('should always format the viewValue as a string for a `url` input type when the value is present',
inject(function($compile, $rootScope, $sniffer) {
var form = $compile('<form name="form"><input type="url" name="field" ng-model="val" /></form>')($rootScope);
$rootScope.val = 123;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe('123');
$rootScope.val = null;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe(null);
dealoc(form);
}));
it('should set NaN as the $modelValue when an asyncValidator is present',
inject(function($q) {
ctrl.$asyncValidators.test = function() {
return $q(function(resolve, reject) {
resolve();
});
};
scope.$apply('value = 10');
expect(ctrl.$modelValue).toBe(10);
expect(function() {
scope.$apply(function() {
scope.value = NaN;
});
}).not.toThrow();
expect(ctrl.$modelValue).toBeNaN();
}));
describe('$processModelValue', function() {
// Emulate setting the model on the scope
function setModelValue(ctrl, value) {
ctrl.$modelValue = ctrl.$$rawModelValue = value;
ctrl.$$parserValid = undefined;
}
it('should run the model -> view pipeline', function() {
var log = [];
var input = ctrl.$$element;
ctrl.$formatters.unshift(function(value) {
log.push(value);
return value + 2;
});
ctrl.$formatters.unshift(function(value) {
log.push(value);
return value + '';
});
spyOn(ctrl, '$render');
setModelValue(ctrl, 3);
expect(ctrl.$modelValue).toBe(3);
ctrl.$processModelValue();
expect(ctrl.$modelValue).toBe(3);
expect(log).toEqual([3, 5]);
expect(ctrl.$viewValue).toBe('5');
expect(ctrl.$render).toHaveBeenCalledOnce();
});
it('should add the validation and empty-state classes',
inject(function($compile, $rootScope, $animate) {
var input = $compile('<input name="myControl" maxlength="1" ng-model="value" >')($rootScope);
$rootScope.$digest();
spyOn($animate, 'addClass');
spyOn($animate, 'removeClass');
var ctrl = input.controller('ngModel');
expect(input).toHaveClass('ng-empty');
expect(input).toHaveClass('ng-valid');
setModelValue(ctrl, 3);
ctrl.$processModelValue();
// $animate adds / removes classes in the $$postDigest, which
// we cannot trigger with $digest, because that would set the model from the scope,
// so we simply check if the functions have been called
expect($animate.removeClass.calls.mostRecent().args[0][0]).toBe(input[0]);
expect($animate.removeClass.calls.mostRecent().args[1]).toBe('ng-empty');
expect($animate.addClass.calls.mostRecent().args[0][0]).toBe(input[0]);
expect($animate.addClass.calls.mostRecent().args[1]).toBe('ng-not-empty');
$animate.removeClass.calls.reset();
$animate.addClass.calls.reset();
setModelValue(ctrl, 35);
ctrl.$processModelValue();
expect($animate.addClass.calls.argsFor(1)[0][0]).toBe(input[0]);
expect($animate.addClass.calls.argsFor(1)[1]).toBe('ng-invalid');
expect($animate.addClass.calls.argsFor(2)[0][0]).toBe(input[0]);
expect($animate.addClass.calls.argsFor(2)[1]).toBe('ng-invalid-maxlength');
})
);
// this is analogue to $setViewValue
it('should run the model -> view pipeline even if the value has not changed', function() {
var log = [];
ctrl.$formatters.unshift(function(value) {
log.push(value);
return value + 2;
});
ctrl.$formatters.unshift(function(value) {
log.push(value);
return value + '';
});
spyOn(ctrl, '$render');
setModelValue(ctrl, 3);
ctrl.$processModelValue();
expect(ctrl.$modelValue).toBe(3);
expect(ctrl.$viewValue).toBe('5');
expect(log).toEqual([3, 5]);
expect(ctrl.$render).toHaveBeenCalledOnce();
ctrl.$processModelValue();
expect(ctrl.$modelValue).toBe(3);
expect(ctrl.$viewValue).toBe('5');
expect(log).toEqual([3, 5, 3, 5]);
// $render() is not called if the viewValue didn't change
expect(ctrl.$render).toHaveBeenCalledOnce();
});
});
});
describe('validation', function() {
describe('$validate', function() {
it('should perform validations when $validate() is called', function() {
scope.$apply('value = ""');
var validatorResult = false;
ctrl.$validators.someValidator = function(value) {
return validatorResult;
};
ctrl.$validate();
expect(ctrl.$valid).toBe(false);
validatorResult = true;
ctrl.$validate();
expect(ctrl.$valid).toBe(true);
});
it('should pass the last parsed modelValue to the validators', function() {
ctrl.$parsers.push(function(modelValue) {
return modelValue + 'def';
});
ctrl.$setViewValue('abc');
ctrl.$validators.test = function(modelValue, viewValue) {
return true;
};
spyOn(ctrl.$validators, 'test');
ctrl.$validate();
expect(ctrl.$validators.test).toHaveBeenCalledWith('abcdef', 'abc');
});
it('should set the model to undefined when it becomes invalid', function() {
var valid = true;
ctrl.$validators.test = function(modelValue, viewValue) {
return valid;
};
scope.$apply('value = "abc"');
expect(scope.value).toBe('abc');
valid = false;
ctrl.$validate();
expect(scope.value).toBeUndefined();
});
it('should update the model when it becomes valid', function() {
var valid = true;
ctrl.$validators.test = function(modelValue, viewValue) {
return valid;
};
scope.$apply('value = "abc"');
expect(scope.value).toBe('abc');
valid = false;
ctrl.$validate();
expect(scope.value).toBeUndefined();
valid = true;
ctrl.$validate();
expect(scope.value).toBe('abc');
});
it('should not update the model when it is valid, but there is a parse error', function() {
ctrl.$parsers.push(function(modelValue) {
return undefined;
});
ctrl.$setViewValue('abc');
expect(ctrl.$error.parse).toBe(true);
expect(scope.value).toBeUndefined();
ctrl.$validators.test = function(modelValue, viewValue) {
return true;
};
ctrl.$validate();
expect(ctrl.$error).toEqual({parse: true});
expect(scope.value).toBeUndefined();
});
it('should not set an invalid model to undefined when validity is the same', function() {
ctrl.$validators.test = function() {
return false;
};
scope.$apply('value = "invalid"');
expect(ctrl.$valid).toBe(false);
expect(scope.value).toBe('invalid');
ctrl.$validate();
expect(ctrl.$valid).toBe(false);
expect(scope.value).toBe('invalid');
});
it('should not change a model that has a formatter', function() {
ctrl.$validators.test = function() {
return true;
};
ctrl.$formatters.push(function(modelValue) {
return 'xyz';
});
scope.$apply('value = "abc"');
expect(ctrl.$viewValue).toBe('xyz');
ctrl.$validate();
expect(scope.value).toBe('abc');
});
it('should not change a model that has a parser', function() {
ctrl.$validators.test = function() {
return true;
};
ctrl.$parsers.push(function(modelValue) {
return 'xyz';
});
scope.$apply('value = "abc"');
ctrl.$validate();
expect(scope.value).toBe('abc');
});
});
describe('view -> model update', function() {
it('should always perform validations using the parsed model value', function() {
var captures;
ctrl.$validators.raw = function() {
captures = Array.prototype.slice.call(arguments);
return captures[0];
};
ctrl.$parsers.push(function(value) {
return value.toUpperCase();
});
ctrl.$setViewValue('my-value');
expect(captures).toEqual(['MY-VALUE', 'my-value']);
});
it('should always perform validations using the formatted view value', function() {
var captures;
ctrl.$validators.raw = function() {
captures = Array.prototype.slice.call(arguments);
return captures[0];
};
ctrl.$formatters.push(function(value) {
return value + '...';
});
scope.$apply('value = "matias"');
expect(captures).toEqual(['matias', 'matias...']);
});
it('should only perform validations if the view value is different', function() {
var count = 0;
ctrl.$validators.countMe = function() {
count++;
};
ctrl.$setViewValue('my-value');
expect(count).toBe(1);
ctrl.$setViewValue('my-value');
expect(count).toBe(1);
ctrl.$setViewValue('your-value');
expect(count).toBe(2);
});
});
it('should perform validations twice each time the model value changes within a digest', function() {
var count = 0;
ctrl.$validators.number = function(value) {
count++;
return (/^\d+$/).test(value);
};
scope.$apply('value = ""');
expect(count).toBe(1);
scope.$apply('value = 1');
expect(count).toBe(2);
scope.$apply('value = 1');
expect(count).toBe(2);
scope.$apply('value = ""');
expect(count).toBe(3);
});
it('should only validate to true if all validations are true', function() {
ctrl.$modelValue = undefined;
ctrl.$validators.a = valueFn(true);
ctrl.$validators.b = valueFn(true);
ctrl.$validators.c = valueFn(false);
ctrl.$validate();
expect(ctrl.$valid).toBe(false);
ctrl.$validators.c = valueFn(true);
ctrl.$validate();
expect(ctrl.$valid).toBe(true);
});
it('should treat all responses as boolean for synchronous validators', function() {
var expectValid = function(value, expected) {
ctrl.$modelValue = undefined;
ctrl.$validators.a = valueFn(value);
ctrl.$validate();
expect(ctrl.$valid).toBe(expected);
};
// False tests
expectValid(false, false);
expectValid(undefined, false);
expectValid(null, false);
expectValid(0, false);
expectValid(NaN, false);
expectValid('', false);
// True tests
expectValid(true, true);
expectValid(1, true);
expectValid('0', true);
expectValid('false', true);
expectValid([], true);
expectValid({}, true);
});
it('should register invalid validations on the $error object', function() {
ctrl.$modelValue = undefined;
ctrl.$validators.unique = valueFn(false);
ctrl.$validators.tooLong = valueFn(false);
ctrl.$validators.notNumeric = valueFn(true);
ctrl.$validate();
expect(ctrl.$error.unique).toBe(true);
expect(ctrl.$error.tooLong).toBe(true);
expect(ctrl.$error.notNumeric).not.toBe(true);
});
it('should render a validator asynchronously when a promise is returned', inject(function($q) {
var defer;
ctrl.$asyncValidators.promiseValidator = function(value) {
defer = $q.defer();
return defer.promise;
};
scope.$apply('value = ""');
expect(ctrl.$valid).toBeUndefined();
expect(ctrl.$invalid).toBeUndefined();
expect(ctrl.$pending.promiseValidator).toBe(true);
defer.resolve();
scope.$digest();
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
expect(ctrl.$pending).toBeUndefined();
scope.$apply('value = "123"');
defer.reject();
scope.$digest();
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(ctrl.$pending).toBeUndefined();
}));
it('should throw an error when a promise is not returned for an asynchronous validator', inject(function($q) {
ctrl.$asyncValidators.async = function(value) {
return true;
};
expect(function() {
scope.$apply('value = "123"');
}).toThrowMinErr('ngModel', 'nopromise',
'Expected asynchronous validator to return a promise but got \'true\' instead.');
}));
it('should only run the async validators once all the sync validators have passed',
inject(function($q) {
var stages = {};
stages.sync = { status1: false, status2: false, count: 0 };
ctrl.$validators.syncValidator1 = function(modelValue, viewValue) {
stages.sync.count++;
return stages.sync.status1;
};
ctrl.$validators.syncValidator2 = function(modelValue, viewValue) {
stages.sync.count++;
return stages.sync.status2;
};
stages.async = { defer: null, count: 0 };
ctrl.$asyncValidators.asyncValidator = function(modelValue, viewValue) {
stages.async.defer = $q.defer();
stages.async.count++;
return stages.async.defer.promise;
};
scope.$apply('value = "123"');
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(stages.sync.count).toBe(2);
expect(stages.async.count).toBe(0);
stages.sync.status1 = true;
scope.$apply('value = "456"');
expect(stages.sync.count).toBe(4);
expect(stages.async.count).toBe(0);
stages.sync.status2 = true;
scope.$apply('value = "789"');
expect(stages.sync.count).toBe(6);
expect(stages.async.count).toBe(1);
stages.async.defer.resolve();
scope.$apply();
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
}));
it('should ignore expired async validation promises once delivered', inject(function($q) {
var defer, oldDefer, newDefer;
ctrl.$asyncValidators.async = function(value) {
defer = $q.defer();
return defer.promise;
};
scope.$apply('value = ""');
oldDefer = defer;
scope.$apply('value = "123"');
newDefer = defer;
newDefer.reject();
scope.$digest();
oldDefer.resolve();
scope.$digest();
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(ctrl.$pending).toBeUndefined();
}));
it('should clear and ignore all pending promises when the model value changes', inject(function($q) {
ctrl.$validators.sync = function(value) {
return true;
};
var defers = [];
ctrl.$asyncValidators.async = function(value) {
var defer = $q.defer();
defers.push(defer);
return defer.promise;
};
scope.$apply('value = "123"');
expect(ctrl.$pending).toEqual({async: true});
expect(ctrl.$valid).toBeUndefined();
expect(ctrl.$invalid).toBeUndefined();
expect(defers.length).toBe(1);
expect(isObject(ctrl.$pending)).toBe(true);
scope.$apply('value = "456"');
expect(ctrl.$pending).toEqual({async: true});
expect(ctrl.$valid).toBeUndefined();
expect(ctrl.$invalid).toBeUndefined();
expect(defers.length).toBe(2);
expect(isObject(ctrl.$pending)).toBe(true);
defers[1].resolve();
scope.$digest();
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
expect(isObject(ctrl.$pending)).toBe(false);
}));
it('should clear and ignore all pending promises when a parser fails', inject(function($q) {
var failParser = false;
ctrl.$parsers.push(function(value) {
return failParser ? undefined : value;
});
var defer;
ctrl.$asyncValidators.async = function(value) {
defer = $q.defer();
return defer.promise;
};
ctrl.$setViewValue('x..y..z');
expect(ctrl.$valid).toBeUndefined();
expect(ctrl.$invalid).toBeUndefined();
failParser = true;
ctrl.$setViewValue('1..2..3');
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(isObject(ctrl.$pending)).toBe(false);
defer.resolve();
scope.$digest();
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(isObject(ctrl.$pending)).toBe(false);
}));
it('should clear all errors from async validators if a parser fails', inject(function($q) {
var failParser = false;
ctrl.$parsers.push(function(value) {
return failParser ? undefined : value;
});
ctrl.$asyncValidators.async = function(value) {
return $q.reject();
};
ctrl.$setViewValue('x..y..z');
expect(ctrl.$error).toEqual({async: true});
failParser = true;
ctrl.$setViewValue('1..2..3');
expect(ctrl.$error).toEqual({parse: true});
}));
it('should clear all errors from async validators if a sync validator fails', inject(function($q) {
var failValidator = false;
ctrl.$validators.sync = function(value) {
return !failValidator;
};
ctrl.$asyncValidators.async = function(value) {
return $q.reject();
};
ctrl.$setViewValue('x..y..z');
expect(ctrl.$error).toEqual({async: true});
failValidator = true;
ctrl.$setViewValue('1..2..3');
expect(ctrl.$error).toEqual({sync: true});
}));
it('should be possible to extend Object prototype and still be able to do form validation',
inject(function($compile, $rootScope) {
// eslint-disable-next-line no-extend-native
Object.prototype.someThing = function() {};
var element = $compile('<form name="myForm">' +
'<input type="text" name="username" ng-model="username" minlength="10" required />' +
'</form>')($rootScope);
var inputElm = element.find('input');
var formCtrl = $rootScope.myForm;
var usernameCtrl = formCtrl.username;
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(true);
expect(formCtrl.$invalid).toBe(true);
usernameCtrl.$setViewValue('valid-username');
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(false);
delete Object.prototype.someThing;
dealoc(element);
}));
it('should re-evaluate the form validity state once the asynchronous promise has been delivered',
inject(function($compile, $rootScope, $q) {
var element = $compile('<form name="myForm">' +
'<input type="text" name="username" ng-model="username" minlength="10" required />' +
'<input type="number" name="age" ng-model="age" min="10" required />' +
'</form>')($rootScope);
var inputElm = element.find('input');
var formCtrl = $rootScope.myForm;
var usernameCtrl = formCtrl.username;
var ageCtrl = formCtrl.age;
var usernameDefer;
usernameCtrl.$asyncValidators.usernameAvailability = function() {
usernameDefer = $q.defer();
return usernameDefer.promise;
};
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(true);
expect(formCtrl.$invalid).toBe(true);
usernameCtrl.$setViewValue('valid-username');
$rootScope.$digest();
expect(formCtrl.$pending.usernameAvailability).toBeTruthy();
expect(usernameCtrl.$invalid).toBeUndefined();
expect(formCtrl.$invalid).toBeUndefined();
usernameDefer.resolve();
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(true);
ageCtrl.$setViewValue(22);
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(false);
expect(ageCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(false);
usernameCtrl.$setViewValue('valid');
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(true);
expect(ageCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(true);
usernameCtrl.$setViewValue('another-valid-username');
$rootScope.$digest();
usernameDefer.resolve();
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(false);
expect(formCtrl.$pending).toBeFalsy();
expect(ageCtrl.$invalid).toBe(false);
dealoc(element);
}));
it('should always use the most recent $viewValue for validation', function() {
ctrl.$parsers.push(function(value) {
if (value && value.substr(-1) === 'b') {
value = 'a';
ctrl.$setViewValue(value);
ctrl.$render();
}
return value;
});
ctrl.$validators.mock = function(modelValue) {
return true;
};
spyOn(ctrl.$validators, 'mock').and.callThrough();
ctrl.$setViewValue('ab');
expect(ctrl.$validators.mock).toHaveBeenCalledWith('a', 'a');
expect(ctrl.$validators.mock).toHaveBeenCalledTimes(2);
});
it('should validate even if the modelValue did not change', function() {
ctrl.$parsers.push(function(value) {
if (value && value.substr(-1) === 'b') {
value = 'a';
}
return value;
});
ctrl.$validators.mock = function(modelValue) {
return true;
};
spyOn(ctrl.$validators, 'mock').and.callThrough();
ctrl.$setViewValue('a');
expect(ctrl.$validators.mock).toHaveBeenCalledWith('a', 'a');
expect(ctrl.$validators.mock).toHaveBeenCalledTimes(1);
ctrl.$setViewValue('ab');
expect(ctrl.$validators.mock).toHaveBeenCalledWith('a', 'ab');
expect(ctrl.$validators.mock).toHaveBeenCalledTimes(2);
});
it('should validate correctly when $parser name equals $validator key', function() {
ctrl.$validators.parserOrValidator = function(value) {
switch (value) {
case 'allInvalid':
case 'parseValid-validatorsInvalid':
case 'stillParseValid-validatorsInvalid':
return false;
default:
return true;
}
};
ctrl.$validators.validator = function(value) {
switch (value) {
case 'allInvalid':
case 'parseValid-validatorsInvalid':
case 'stillParseValid-validatorsInvalid':
return false;
default:
return true;
}
};
ctrl.$parsers.push(function(value) {
switch (value) {
case 'allInvalid':
case 'stillAllInvalid':
case 'parseInvalid-validatorsValid':
case 'stillParseInvalid-validatorsValid':
ctrl.$$parserName = 'parserOrValidator';
return undefined;
default:
return value;
}
});
//Parser and validators are invalid
scope.$apply('value = "allInvalid"');
expect(scope.value).toBe('allInvalid');
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$validate();
expect(scope.value).toEqual('allInvalid');
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$setViewValue('stillAllInvalid');
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true});
ctrl.$validate();
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true});
//Parser is valid, validators are invalid
scope.$apply('value = "parseValid-validatorsInvalid"');
expect(scope.value).toBe('parseValid-validatorsInvalid');
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$validate();
expect(scope.value).toBe('parseValid-validatorsInvalid');
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$setViewValue('stillParseValid-validatorsInvalid');
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$validate();
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
//Parser is invalid, validators are valid
scope.$apply('value = "parseInvalid-validatorsValid"');
expect(scope.value).toBe('parseInvalid-validatorsValid');
expect(ctrl.$error).toEqual({});
ctrl.$validate();
expect(scope.value).toBe('parseInvalid-validatorsValid');
expect(ctrl.$error).toEqual({});
ctrl.$setViewValue('stillParseInvalid-validatorsValid');
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true});
ctrl.$validate();
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true});
});
});
describe('override ModelOptions', function() {
it('should replace the previous model options', function() {
var $options = ctrl.$options;
ctrl.$overrideModelOptions({});
expect(ctrl.$options).not.toBe($options);
});
it('should set the given options', function() {
var $options = ctrl.$options;
ctrl.$overrideModelOptions({ debounce: 1000, updateOn: 'blur' });
expect(ctrl.$options.getOption('debounce')).toEqual(1000);
expect(ctrl.$options.getOption('updateOn')).toEqual('blur');
expect(ctrl.$options.getOption('updateOnDefault')).toBe(false);
});
it('should inherit from a parent model options if specified', inject(function($compile, $rootScope) {
var element = $compile(
'<form name="form" ng-model-options="{debounce: 1000, updateOn: \'blur\'}">' +
' <input ng-model="value" name="input">' +
'</form>')($rootScope);
var ctrl = $rootScope.form.input;
ctrl.$overrideModelOptions({ debounce: 2000, '*': '$inherit' });
expect(ctrl.$options.getOption('debounce')).toEqual(2000);
expect(ctrl.$options.getOption('updateOn')).toEqual('blur');
expect(ctrl.$options.getOption('updateOnDefault')).toBe(false);
dealoc(element);
}));
it('should not inherit from a parent model options if not specified', inject(function($compile, $rootScope) {
var element = $compile(
'<form name="form" ng-model-options="{debounce: 1000, updateOn: \'blur\'}">' +
' <input ng-model="value" name="input">' +
'</form>')($rootScope);
var ctrl = $rootScope.form.input;
ctrl.$overrideModelOptions({ debounce: 2000 });
expect(ctrl.$options.getOption('debounce')).toEqual(2000);
expect(ctrl.$options.getOption('updateOn')).toEqual('');
expect(ctrl.$options.getOption('updateOnDefault')).toBe(true);
dealoc(element);
}));
});
});
describe('CSS classes', function() {
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
it('should set ng-empty or ng-not-empty when the view value changes',
inject(function($compile, $rootScope, $sniffer) {
var element = $compile('<input ng-model="value" />')($rootScope);
$rootScope.$digest();
expect(element).toBeEmpty();
$rootScope.value = 'XXX';
$rootScope.$digest();
expect(element).toBeNotEmpty();
element.val('');
browserTrigger(element, $sniffer.hasEvent('input') ? 'input' : 'change');
expect(element).toBeEmpty();
element.val('YYY');
browserTrigger(element, $sniffer.hasEvent('input') ? 'input' : 'change');
expect(element).toBeNotEmpty();
}));
it('should set css classes (ng-valid, ng-invalid, ng-pristine, ng-dirty, ng-untouched, ng-touched)',
inject(function($compile, $rootScope, $sniffer) {
var element = $compile('<input type="email" ng-model="value" />')($rootScope);
$rootScope.$digest();
expect(element).toBeValid();
expect(element).toBePristine();
expect(element).toBeUntouched();
expect(element.hasClass('ng-valid-email')).toBe(true);
expect(element.hasClass('ng-invalid-email')).toBe(false);
$rootScope.$apply('value = \'invalid-email\'');
expect(element).toBeInvalid();
expect(element).toBePristine();
expect(element.hasClass('ng-valid-email')).toBe(false);
expect(element.hasClass('ng-invalid-email')).toBe(true);
element.val('invalid-again');
browserTrigger(element, ($sniffer.hasEvent('input')) ? 'input' : 'change');
expect(element).toBeInvalid();
expect(element).toBeDirty();
expect(element.hasClass('ng-valid-email')).toBe(false);
expect(element.hasClass('ng-invalid-email')).toBe(true);
element.val('vojta@google.com');
browserTrigger(element, $sniffer.hasEvent('input') ? 'input' : 'change');
expect(element).toBeValid();
expect(element).toBeDirty();
expect(element.hasClass('ng-valid-email')).toBe(true);
expect(element.hasClass('ng-invalid-email')).toBe(false);
browserTrigger(element, 'blur');
expect(element).toBeTouched();
dealoc(element);
}));
it('should set invalid classes on init', inject(function($compile, $rootScope) {
var element = $compile('<input type="email" ng-model="value" required />')($rootScope);
$rootScope.$digest();
expect(element).toBeInvalid();
expect(element).toHaveClass('ng-invalid-required');
dealoc(element);
}));
});
describe('custom formatter and parser that are added by a directive in post linking', function() {
var inputElm, scope;
beforeEach(module(function($compileProvider) {
$compileProvider.directive('customFormat', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.push(function(value) {
return value.part;
});
ngModelCtrl.$parsers.push(function(value) {
return {part: value};
});
}
};
});
}));
afterEach(function() {
dealoc(inputElm);
});
function createInput(type) {
inject(function($compile, $rootScope) {
scope = $rootScope;
inputElm = $compile('<input type="' + type + '" ng-model="val" custom-format/>')($rootScope);
});
}
it('should use them after the builtin ones for text inputs', function() {
createInput('text');
scope.$apply('val = {part: "a"}');
expect(inputElm.val()).toBe('a');
inputElm.val('b');
browserTrigger(inputElm, 'change');
expect(scope.val).toEqual({part: 'b'});
});
it('should use them after the builtin ones for number inputs', function() {
createInput('number');
scope.$apply('val = {part: 1}');
expect(inputElm.val()).toBe('1');
inputElm.val('2');
browserTrigger(inputElm, 'change');
expect(scope.val).toEqual({part: 2});
});
it('should use them after the builtin ones for date inputs', function() {
createInput('date');
scope.$apply(function() {
scope.val = {part: new Date(2000, 10, 8)};
});
expect(inputElm.val()).toBe('2000-11-08');
inputElm.val('2001-12-09');
browserTrigger(inputElm, 'change');
expect(scope.val).toEqual({part: new Date(2001, 11, 9)});
});
});
describe('$touched', function() {
it('should set the control touched state on "blur" event', inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" >' +
'</form>')($rootScope);
var inputElm = element.find('input');
var control = $rootScope.myForm.myControl;
expect(control.$touched).toBe(false);
expect(control.$untouched).toBe(true);
browserTrigger(inputElm, 'blur');
expect(control.$touched).toBe(true);
expect(control.$untouched).toBe(false);
dealoc(element);
}));
it('should not cause a digest on "blur" event if control is already touched',
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" >' +
'</form>')($rootScope);
var inputElm = element.find('input');
var control = $rootScope.myForm.myControl;
control.$setTouched();
spyOn($rootScope, '$apply');
browserTrigger(inputElm, 'blur');
expect($rootScope.$apply).not.toHaveBeenCalled();
dealoc(element);
}));
it('should digest asynchronously on "blur" event if a apply is already in progress',
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" >' +
'</form>')($rootScope);
var inputElm = element.find('input');
var control = $rootScope.myForm.myControl;
$rootScope.$apply(function() {
expect(control.$touched).toBe(false);
expect(control.$untouched).toBe(true);
browserTrigger(inputElm, 'blur');
expect(control.$touched).toBe(false);
expect(control.$untouched).toBe(true);
});
expect(control.$touched).toBe(true);
expect(control.$untouched).toBe(false);
dealoc(element);
}));
});
describe('nested in a form', function() {
it('should register/deregister a nested ngModel with parent form when entering or leaving DOM',
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input ng-if="inputPresent" name="myControl" ng-model="value" required >' +
'</form>')($rootScope);
var isFormValid;
$rootScope.inputPresent = false;
$rootScope.$watch('myForm.$valid', function(value) { isFormValid = value; });
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(true);
expect(isFormValid).toBe(true);
expect($rootScope.myForm.myControl).toBeUndefined();
$rootScope.inputPresent = true;
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(false);
expect(isFormValid).toBe(false);
expect($rootScope.myForm.myControl).toBeDefined();
$rootScope.inputPresent = false;
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(true);
expect(isFormValid).toBe(true);
expect($rootScope.myForm.myControl).toBeUndefined();
dealoc(element);
}));
it('should register/deregister a nested ngModel with parent form when entering or leaving DOM with animations',
function() {
// ngAnimate performs the dom manipulation after digest, and since the form validity can be affected by a form
// control going away we must ensure that the deregistration happens during the digest while we are still doing
// dirty checking.
module('ngAnimate');
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input ng-if="inputPresent" name="myControl" ng-model="value" required >' +
'</form>')($rootScope);
var isFormValid;
$rootScope.inputPresent = false;
// this watch ensure that the form validity gets updated during digest (so that we can observe it)
$rootScope.$watch('myForm.$valid', function(value) { isFormValid = value; });
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(true);
expect(isFormValid).toBe(true);
expect($rootScope.myForm.myControl).toBeUndefined();
$rootScope.inputPresent = true;
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(false);
expect(isFormValid).toBe(false);
expect($rootScope.myForm.myControl).toBeDefined();
$rootScope.inputPresent = false;
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(true);
expect(isFormValid).toBe(true);
expect($rootScope.myForm.myControl).toBeUndefined();
dealoc(element);
});
});
it('should keep previously defined watches consistent when changes in validity are made',
inject(function($compile, $rootScope) {
var isFormValid;
$rootScope.$watch('myForm.$valid', function(value) { isFormValid = value; });
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" required >' +
'</form>')($rootScope);
$rootScope.$apply();
expect(isFormValid).toBe(false);
expect($rootScope.myForm.$valid).toBe(false);
$rootScope.value = 'value';
$rootScope.$apply();
expect(isFormValid).toBe(true);
expect($rootScope.myForm.$valid).toBe(true);
dealoc(element);
}));
});
describe('animations', function() {
function findElementAnimations(element, queue) {
var node = element[0];
var animations = [];
for (var i = 0; i < queue.length; i++) {
var animation = queue[i];
if (animation.element[0] === node) {
animations.push(animation);
}
}
return animations;
}
function assertValidAnimation(animation, event, classNameA, classNameB) {
expect(animation.event).toBe(event);
expect(animation.args[1]).toBe(classNameA);
if (classNameB) expect(animation.args[2]).toBe(classNameB);
}
var doc, input, scope, model;
beforeEach(module('ngAnimateMock'));
beforeEach(inject(function($rootScope, $compile, $rootElement, $animate) {
scope = $rootScope.$new();
doc = jqLite('<form name="myForm">' +
' <input type="text" ng-model="input" name="myInput" />' +
'</form>');
$rootElement.append(doc);
$compile(doc)(scope);
$animate.queue = [];
input = doc.find('input');
model = scope.myForm.myInput;
}));
afterEach(function() {
dealoc(input);
});
it('should trigger an animation when invalid', inject(function($animate) {
model.$setValidity('required', false);
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'removeClass', 'ng-valid');
assertValidAnimation(animations[1], 'addClass', 'ng-invalid');
assertValidAnimation(animations[2], 'addClass', 'ng-invalid-required');
}));
it('should trigger an animation when valid', inject(function($animate) {
model.$setValidity('required', false);
$animate.queue = [];
model.$setValidity('required', true);
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'addClass', 'ng-valid');
assertValidAnimation(animations[1], 'removeClass', 'ng-invalid');
assertValidAnimation(animations[2], 'addClass', 'ng-valid-required');
assertValidAnimation(animations[3], 'removeClass', 'ng-invalid-required');
}));
it('should trigger an animation when dirty', inject(function($animate) {
model.$setViewValue('some dirty value');
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'removeClass', 'ng-empty');
assertValidAnimation(animations[1], 'addClass', 'ng-not-empty');
assertValidAnimation(animations[2], 'removeClass', 'ng-pristine');
assertValidAnimation(animations[3], 'addClass', 'ng-dirty');
}));
it('should trigger an animation when pristine', inject(function($animate) {
model.$setPristine();
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'removeClass', 'ng-dirty');
assertValidAnimation(animations[1], 'addClass', 'ng-pristine');
}));
it('should trigger an animation when untouched', inject(function($animate) {
model.$setUntouched();
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'setClass', 'ng-untouched');
expect(animations[0].args[2]).toBe('ng-touched');
}));
it('should trigger an animation when touched', inject(function($animate) {
model.$setTouched();
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'setClass', 'ng-touched', 'ng-untouched');
expect(animations[0].args[2]).toBe('ng-untouched');
}));
it('should trigger custom errors as addClass/removeClass when invalid/valid', inject(function($animate) {
model.$setValidity('custom-error', false);
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'removeClass', 'ng-valid');
assertValidAnimation(animations[1], 'addClass', 'ng-invalid');
assertValidAnimation(animations[2], 'addClass', 'ng-invalid-custom-error');
$animate.queue = [];
model.$setValidity('custom-error', true);
animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'addClass', 'ng-valid');
assertValidAnimation(animations[1], 'removeClass', 'ng-invalid');
assertValidAnimation(animations[2], 'addClass', 'ng-valid-custom-error');
assertValidAnimation(animations[3], 'removeClass', 'ng-invalid-custom-error');
}));
});
});
| mosoft521/angular.js | test/ng/directive/ngModelSpec.js | JavaScript | mit | 60,818 |
/* flatpickr v4.4.2, @license MIT */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.ms = {})));
}(this, (function (exports) { 'use strict';
var fp = typeof window !== "undefined" && window.flatpickr !== undefined ? window.flatpickr : {
l10ns: {}
};
var Malaysian = {
weekdays: {
shorthand: ["Min", "Isn", "Sel", "Rab", "Kha", "Jum", "Sab"],
longhand: ["Minggu", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu"]
},
months: {
shorthand: ["Jan", "Feb", "Mac", "Apr", "Mei", "Jun", "Jul", "Ogo", "Sep", "Okt", "Nov", "Dis"],
longhand: ["Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember"]
},
firstDayOfWeek: 1,
ordinal: function ordinal() {
return "";
}
};
var ms = fp.l10ns;
exports.Malaysian = Malaysian;
exports.default = ms;
Object.defineProperty(exports, '__esModule', { value: true });
})));
| jonobr1/cdnjs | ajax/libs/flatpickr/4.4.2/l10n/ms.js | JavaScript | mit | 1,160 |
/**
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
Ext.ns('TYPO3');
TYPO3.backendContentIframePanel = Ext.extend(TYPO3.iframePanel ,{
setUrl: function(source) {
var card;
var wrapper;
wrapper = Ext.getCmp('typo3-contentContainerWrapper');
this.url = source;
if(wrapper) {
card = Ext.getCmp('typo3-card-' + TYPO3.ModuleMenu.App.loadedModule);
if((card != undefined) && (source.search('extjspaneldummy.html') > -1)) {
wrapper.getLayout().setActiveItem('typo3-card-' + TYPO3.ModuleMenu.App.loadedModule);
if (typeof wrapper.getComponent(('typo3-card-' + TYPO3.ModuleMenu.App.loadedModule)).setUrl === 'function') {
wrapper.getComponent(('typo3-card-' + TYPO3.ModuleMenu.App.loadedModule)).setUrl(source);
}
} else {
wrapper.getLayout().setActiveItem(this.id);
this.body.dom.src = source;
this.setMask();
}
}
},
getUrl: function () {
var wrapper;
var card;
wrapper = Ext.getCmp('typo3-contentContainerWrapper');
if(wrapper) {
card = wrapper.getLayout().activeItem;
if(card.id == this.id) {
return this.body.dom.src;
} else if(typeof card.getUrl == 'function') {
return card.getUrl();
} else {
return this.url;
}
}
}
});
Ext.reg('backendContentIframePanel', TYPO3.backendContentIframePanel); | demonege/sutogo | typo3/js/extjs/backendcontentiframe.js | JavaScript | gpl-2.0 | 1,655 |
/*! jQuery UI - v1.10.0 - 2013-02-06
* http://jqueryui.com
* Includes: jquery.ui.datepicker-de.js
* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.de={closeText:"schließen",prevText:"<zurück",nextText:"Vor>",currentText:"heute",monthNames:["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],monthNamesShort:["Jan","Feb","Mär","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"],dayNames:["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"],dayNamesShort:["So","Mo","Di","Mi","Do","Fr","Sa"],dayNamesMin:["So","Mo","Di","Mi","Do","Fr","Sa"],weekHeader:"KW",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.de)}); | dxSpikes/discoverfun | wp-content/plugins/discoverfun/js/jquery-ui-1.10.0.custom/development-bundle/ui/minified/i18n/jquery.ui.datepicker-de.min.js | JavaScript | gpl-2.0 | 852 |
jQuery(document).ready(function($){
// Pricing Tables Deleting
$('.uds-pricing-admin-table .pricing-delete').click(function(){
if(!confirm("Really delete table?")) {
return false;
}
});
// products
$('#uds-pricing-products form').submit(function(){
$('#uds-pricing-products .product').each(function(i, el){
$("input[type=checkbox]", this).each(function() {
$(this).attr('name', $(this).attr('name').replace('[]', '[' + i + ']'));
});
$("input[type=radio]", this).each(function() {
$(this).val(i);
});
});
});
// products moving
$('#uds-pricing-products').sortable({
containment: '#uds-pricing-products',
cursor: 'crosshair',
forcePlaceholderSize: true,
forceHelpserSize: true,
handle: '.move',
items: '.product',
placeholder: 'placeholder',
opacity: 0.6,
tolerance: 'pointer',
axis: 'y'
});
// products deleting
$('#uds-pricing-products .delete').click(function(){
if(confirm("Really delete product?")) {
$(this).parents('.product').slideUp(300, function(){
$(this).remove();
});
}
});
// products collapsing
$('#uds-pricing-products h3.collapsible').click(function(){
$('.options', $(this).parent()).slideToggle(300);
$(this).add($(this).parent()).toggleClass('collapsed');
}).trigger('click');
var collapsed = true;
$('.collapse-all').click(function(){
if(collapsed) {
$('.options').slideDown(300);
$('.product').add('h3.collapsible').removeClass('collapsed');
collapsed = false;
$(this).html('Collapse all');
} else {
$('.options').slideUp(300);
$('.product').add('h3.collapsible').addClass('collapsed');
collapsed = true;
$(this).html('Open all');
}
return false;
});
// table changer
$('.uds-change-table').click(function(){
window.location = window.location + "&uds_pricing_edit=" + $('.uds-load-pricing-table').val();
});
//structure
$('#uds-pricing-properties table').sortable({
containment: '#uds-pricing-properties',
cursor: 'crosshair',
forcePlaceHolderSize: true,
handle: '.move',
items: 'tr',
axis: 'y'
});
// properties deleting
$('#uds-pricing-properties .delete').live('click', function(){
if(confirm("Really delete?")) {
$(this).parents("tr").remove();
$('#uds-pricing-properties table').sortable('refresh');
}
});
// properties adding
var empty = $('#uds-pricing-properties tr:last').clone();
$('#uds-pricing-properties .add').live('click', function(){
$('#uds-pricing-properties table').append($(empty).clone());
$('#uds-pricing-properties table').sortable('refresh');
});
// Tooltips
$('.tooltip').hover(function(){
$tt = $(this).parent().find('.tooltip-content');
$tt.stop().css({
display: 'block',
top: $(this).position().top,
left: $(this).position().left + 40 + 'px',
opacity: 0
}).animate({
opacity: 1
}, 300);
}, function(){
$tt = $(this).parent().find('.tooltip-content');
$tt.stop().css({
opacity: 1
}).animate({
opacity: 0
}, {
duration: 300,
complete: function(){
$(this).css('display', 'none');
}
});
});
}); | How2ForFree/development | wp-content/themes/Superb_v1.0.1/Superb/uPricing/js/pricing-admin.js | JavaScript | gpl-2.0 | 3,075 |
elementResizeEvent = require('../index.js');
element = document.getElementById("resize");
window.p = p = document.getElementById("width");
console.log(p);
console.log(elementResizeEvent);
console.log(elementResizeEvent(element, function() {
console.log("resized!");
console.log(element.offsetWidth);
console.log(p);
console.log(element.offsetWidth + "px wide");
p.innerHTML = element.offsetWidth + "px wide";
}));
| Jorginho211/TFG | web/node_modules/element-resize-event/example/index.js | JavaScript | gpl-3.0 | 425 |
OC.L10N.register(
"updatenotification",
{
"Update notifications" : "Обновяване на известията",
"{version} is available. Get more information on how to update." : "{version} е излязла. Прочетете повече как да обновите до нея. ",
"Updated channel" : "Обновен канал",
"ownCloud core" : "ownCloud core",
"Update for %1$s to version %2$s is available." : "Излязло е ново обновление за %1$s до версия %2$s .",
"Updater" : "Център за обновяване",
"A new version is available: %s" : "Излязла е нова версия: %s",
"Open updater" : "Отворяне на център за обновяване",
"Show changelog" : "Показване на доклада с промени",
"Your version is up to date." : "Вие разполагате с най-новата версия.",
"Checked on %s" : "Проверено на %s",
"Update channel:" : "Обновяване на канал:",
"You can always update to a newer version / experimental channel. But you can never downgrade to a more stable channel." : "Винаги може да обновите до по-нова версия / експирементален канал. Но не можете вече да върнете до по-стабилен канал.",
"Notify members of the following groups about available updates:" : "Уведомяване на членовете на следните групи за излязлите нови версии:",
"Only notification for app updates are available, because the selected update channel for ownCloud itself does not allow notifications." : "Има само известия за обновения на приложения, защото избраният канал за обновяване на ownCloud не предоставя известия."
},
"nplurals=2; plural=(n != 1);");
| jacklicn/owncloud | apps/updatenotification/l10n/bg_BG.js | JavaScript | agpl-3.0 | 2,010 |
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
'use strict';
const assert = require('assert');
const sinon = require('sinon');
const command = require('../../lib/command');
const error = require('../../lib/error');
const input = require('../../lib/input');
const {WebElement} = require('../../lib/webdriver');
describe('input.Actions', function() {
class StubExecutor {
constructor(...responses) {
this.responses = responses;
this.commands = [];
}
execute(command) {
const name = command.getName();
const parameters = command.getParameters();
this.commands.push({name, parameters});
return this.responses.shift()
|| Promise.reject(
new Error('unexpected command: ' + command.getName()));
}
}
describe('perform()', function() {
it('omits idle devices', async function() {
let executor = new StubExecutor(
Promise.resolve(),
Promise.resolve(),
Promise.resolve(),
Promise.resolve());
await new input.Actions(executor).perform();
assert.deepEqual(executor.commands, []);
await new input.Actions(executor).pause().perform();
assert.deepEqual(executor.commands, []);
await new input.Actions(executor).pause(1).perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [
{
id: 'default keyboard',
type: 'key',
actions: [{type: 'pause', duration: 1}],
},
{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [{type: 'pause', duration: 1}],
},
],
}
}]);
executor.commands.length = 0;
let actions = new input.Actions(executor);
await actions.pause(1, actions.keyboard()).perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default keyboard',
type: 'key',
actions: [{type: 'pause', duration: 1}],
}],
}
}]);
});
it('can be called multiple times', async function() {
const executor = new StubExecutor(Promise.resolve(), Promise.resolve());
const actions = new input.Actions(executor).keyDown(input.Key.SHIFT);
const expected = {
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default keyboard',
type: 'key',
actions: [{type: 'keyDown', value: input.Key.SHIFT}],
}]}
};
await actions.perform();
assert.deepEqual(executor.commands, [expected]);
await actions.perform();
assert.deepEqual(executor.commands, [expected, expected]);
});
});
describe('pause()', function() {
it('defaults to all devices', async function() {
const executor = new StubExecutor(Promise.resolve());
await new input.Actions(executor).pause(3).perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [
{
id: 'default keyboard',
type: 'key',
actions: [{type: 'pause', duration: 3}],
},
{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [{type: 'pause', duration: 3}],
},
],
}
}]);
});
it('duration defaults to 0', async function() {
const executor = new StubExecutor(Promise.resolve());
await new input.Actions(executor)
.pause()
.pause(3)
.perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [
{
id: 'default keyboard',
type: 'key',
actions: [
{type: 'pause', duration: 0},
{type: 'pause', duration: 3},
],
},
{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{type: 'pause', duration: 0},
{type: 'pause', duration: 3},
],
},
],
}
}]);
});
it('single device w/ synchronization', async function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor);
await actions
.pause(100, actions.keyboard())
.pause(100, actions.mouse())
.perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [
{
id: 'default keyboard',
type: 'key',
actions: [
{type: 'pause', duration: 100},
{type: 'pause', duration: 0},
],
},
{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{type: 'pause', duration: 0},
{type: 'pause', duration: 100},
],
},
],
}
}]);
});
it('single device w/o synchronization', async function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor, {async: true});
await actions
.pause(100, actions.keyboard())
.pause(100, actions.mouse())
.perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [
{
id: 'default keyboard',
type: 'key',
actions: [
{type: 'pause', duration: 100},
],
},
{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{type: 'pause', duration: 100},
],
},
],
}
}]);
});
it('pause a single device multiple times by specifying it multiple times',
async function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor);
await actions
.pause(100, actions.keyboard(), actions.keyboard())
.perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default keyboard',
type: 'key',
actions: [
{type: 'pause', duration: 100},
{type: 'pause', duration: 100},
],
}],
}
}]);
});
});
describe('keyDown()', function() {
it('sends normalized code point', async function() {
let executor = new StubExecutor(Promise.resolve());
await new input.Actions(executor).keyDown('\u0041\u030a').perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default keyboard',
type: 'key',
actions: [{type: 'keyDown', value: '\u00c5'}],
}],
}
}]);
});
it('rejects keys that are not a single code point', function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor);
assert.throws(
() => actions.keyDown('\u1E9B\u0323'),
error.InvalidArgumentError);
});
});
describe('keyUp()', function() {
it('sends normalized code point', async function() {
let executor = new StubExecutor(Promise.resolve());
await new input.Actions(executor).keyUp('\u0041\u030a').perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default keyboard',
type: 'key',
actions: [{type: 'keyUp', value: '\u00c5'}],
}],
}
}]);
});
it('rejects keys that are not a single code point', function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor);
assert.throws(
() => actions.keyUp('\u1E9B\u0323'),
error.InvalidArgumentError);
});
});
describe('sendKeys()', function() {
it('sends down/up for single key', async function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor);
await actions.sendKeys('a').perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default keyboard',
type: 'key',
actions: [
{type: 'keyDown', value: 'a'},
{type: 'keyUp', value: 'a'},
],
}],
}
}]);
});
it('sends down/up for vararg keys', async function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor);
await actions.sendKeys('a', 'b').perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default keyboard',
type: 'key',
actions: [
{type: 'keyDown', value: 'a'},
{type: 'keyUp', value: 'a'},
{type: 'keyDown', value: 'b'},
{type: 'keyUp', value: 'b'},
],
}],
}
}]);
});
it('sends down/up for multichar strings in varargs', async function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor);
await actions.sendKeys('a', 'bc', 'd').perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default keyboard',
type: 'key',
actions: [
{type: 'keyDown', value: 'a'},
{type: 'keyUp', value: 'a'},
{type: 'keyDown', value: 'b'},
{type: 'keyUp', value: 'b'},
{type: 'keyDown', value: 'c'},
{type: 'keyUp', value: 'c'},
{type: 'keyDown', value: 'd'},
{type: 'keyUp', value: 'd'},
],
}],
}
}]);
});
it('synchronizes with other devices', async function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor);
await actions.sendKeys('ab').pause(100, actions.mouse()).perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [
{
id: 'default keyboard',
type: 'key',
actions: [
{type: 'keyDown', value: 'a'},
{type: 'keyUp', value: 'a'},
{type: 'keyDown', value: 'b'},
{type: 'keyUp', value: 'b'},
{type: 'pause', duration: 0},
],
},
{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{type: 'pause', duration: 0},
{type: 'pause', duration: 0},
{type: 'pause', duration: 0},
{type: 'pause', duration: 0},
{type: 'pause', duration: 100},
],
},
],
}
}]);
});
it('without device synchronization', async function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor, {async: true});
await actions.sendKeys('ab').pause(100, actions.mouse()).perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [
{
id: 'default keyboard',
type: 'key',
actions: [
{type: 'keyDown', value: 'a'},
{type: 'keyUp', value: 'a'},
{type: 'keyDown', value: 'b'},
{type: 'keyUp', value: 'b'},
],
},
{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [{type: 'pause', duration: 100}],
},
],
}
}]);
});
});
describe('click()', function() {
it('clicks immediately if no element provided', async function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor);
await actions.click().perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
],
}],
},
}]);
});
it('moves to target element before clicking', async function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor);
const fakeElement = {};
await actions.click(fakeElement).perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{
type: 'pointerMove',
origin: fakeElement,
duration: 100,
x: 0,
y: 0,
},
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
],
}],
},
}]);
});
it('synchronizes with other devices', async function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor);
const fakeElement = {};
await actions.click(fakeElement).sendKeys('a').perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default keyboard',
type: 'key',
actions: [
{type: 'pause', duration: 0},
{type: 'pause', duration: 0},
{type: 'pause', duration: 0},
{type: 'keyDown', value: 'a'},
{type: 'keyUp', value: 'a'},
],
}, {
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{
type: 'pointerMove',
origin: fakeElement,
duration: 100,
x: 0,
y: 0,
},
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
{type: 'pause', duration: 0},
{type: 'pause', duration: 0},
],
}],
},
}]);
});
});
describe('dragAndDrop', function() {
it('dragAndDrop(fromEl, toEl)', async function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor);
const e1 = new WebElement(null, 'abc123');
const e2 = new WebElement(null, 'def456');
await actions.dragAndDrop(e1, e2).perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{
type: 'pointerMove',
duration: 100,
origin: e1,
x: 0,
y: 0,
},
{type: 'pointerDown', button: input.Button.LEFT},
{
type: 'pointerMove',
duration: 100,
origin: e2,
x: 0,
y: 0,
},
{type: 'pointerUp', button: input.Button.LEFT},
],
}],
}
}]);
});
it('dragAndDrop(el, offset)', async function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor);
const e1 = new WebElement(null, 'abc123');
await actions.dragAndDrop(e1, {x: 30, y: 40}).perform();
assert.deepEqual(executor.commands, [{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{
type: 'pointerMove',
duration: 100,
origin: e1,
x: 0,
y: 0,
},
{type: 'pointerDown', button: input.Button.LEFT},
{
type: 'pointerMove',
duration: 100,
origin: input.Origin.POINTER,
x: 30,
y: 40,
},
{type: 'pointerUp', button: input.Button.LEFT},
],
}],
}
}]);
});
it('throws if target is invalid', async function() {
const executor = new StubExecutor(Promise.resolve());
const actions = new input.Actions(executor);
const e = new WebElement(null, 'abc123');
assert.throws(
() => actions.dragAndDrop(e),
error.InvalidArgumentError);
assert.throws(
() => actions.dragAndDrop(e, null),
error.InvalidArgumentError);
assert.throws(
() => actions.dragAndDrop(e, {}),
error.InvalidArgumentError);
assert.throws(
() => actions.dragAndDrop(e, {x:0}),
error.InvalidArgumentError);
assert.throws(
() => actions.dragAndDrop(e, {y:0}),
error.InvalidArgumentError);
assert.throws(
() => actions.dragAndDrop(e, {x:0, y:'a'}),
error.InvalidArgumentError);
assert.throws(
() => actions.dragAndDrop(e, {x:'a', y:0}),
error.InvalidArgumentError);
});
});
describe('bridge mode', function() {
it('cannot enable async and bridge at the same time', function() {
let exe = new StubExecutor;
assert.throws(
() => new input.Actions(exe, {async: true, bridge: true}),
error.InvalidArgumentError);
});
it('behaves as normal if first command succeeds', async function() {
const actions = new input.Actions(new StubExecutor(Promise.resolve()));
await actions.click().sendKeys('a').perform();
});
it('handles pauses locally', async function() {
const start = Date.now();
const actions =
new input.Actions(
new StubExecutor(
Promise.reject(new error.UnknownCommandError)),
{bridge: true});
await actions.pause(100).perform();
const elapsed = Date.now() - start;
assert.ok(elapsed >= 100, elapsed);
});
it('requires non-modifier keys to be used in keydown/up sequences', async function() {
const actions =
new input.Actions(
new StubExecutor(
Promise.reject(new error.UnknownCommandError)),
{bridge: true});
try {
await actions.keyDown(input.Key.SHIFT).keyDown('a').perform();
return Promise.reject(Error('should have failed!'));
} catch (err) {
if (!(err instanceof error.UnsupportedOperationError)
|| !err.message.endsWith('must be followed by a keyup for the same key')) {
throw err;
}
}
});
it('key sequence', async function() {
const executor =
new StubExecutor(
Promise.reject(new error.UnknownCommandError),
Promise.resolve('shift down'),
Promise.resolve(),
Promise.resolve(),
Promise.resolve(),
Promise.resolve('shift up'));
const actions = new input.Actions(executor, {bridge: true});
await actions
.keyDown(input.Key.SHIFT)
.sendKeys('abc')
.keyUp(input.Key.SHIFT)
.sendKeys('de')
.perform();
assert.deepEqual(executor.commands, [
{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default keyboard',
type: 'key',
actions: [
{type: 'keyDown', value: input.Key.SHIFT},
{type: 'keyDown', value: 'a'},
{type: 'keyUp', value: 'a'},
{type: 'keyDown', value: 'b'},
{type: 'keyUp', value: 'b'},
{type: 'keyDown', value: 'c'},
{type: 'keyUp', value: 'c'},
{type: 'keyUp', value: input.Key.SHIFT},
{type: 'keyDown', value: 'd'},
{type: 'keyUp', value: 'd'},
{type: 'keyDown', value: 'e'},
{type: 'keyUp', value: 'e'},
],
}],
}
},
{
name: command.Name.LEGACY_ACTION_SEND_KEYS,
parameters: {value: [input.Key.SHIFT]}
},
{
name: command.Name.LEGACY_ACTION_SEND_KEYS,
parameters: {value: ['a', 'b', 'c']}
},
{
name: command.Name.LEGACY_ACTION_SEND_KEYS,
parameters: {value: [input.Key.SHIFT]}
},
{
name: command.Name.LEGACY_ACTION_SEND_KEYS,
parameters: {value: ['d', 'e']}
},
]);
});
it('mouse movements cannot be relative to the viewport', async function() {
const actions =
new input.Actions(
new StubExecutor(
Promise.reject(new error.UnknownCommandError)),
{bridge: true});
try {
await actions.move({x: 10, y: 15}).perform();
return Promise.reject(Error('should have failed!'));
} catch (err) {
if (!(err instanceof error.UnsupportedOperationError)
|| !err.message.startsWith('pointer movements relative to viewport')) {
throw err;
}
}
});
describe('detects clicks', function() {
it('press/release for same button is a click', async function() {
const executor =
new StubExecutor(
Promise.reject(new error.UnknownCommandError),
Promise.resolve());
const actions = new input.Actions(executor, {bridge: true});
const element = new WebElement(null, 'abc123');
await actions
.press(input.Button.LEFT)
.release(input.Button.LEFT)
.perform();
assert.deepEqual(executor.commands, [
{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
],
}],
}
},
{
name: command.Name.LEGACY_ACTION_CLICK,
parameters: {button: input.Button.LEFT},
},
]);
});
it('not a click if release is a different button', async function() {
const executor =
new StubExecutor(
Promise.reject(new error.UnknownCommandError),
Promise.resolve(),
Promise.resolve(),
Promise.resolve(),
Promise.resolve());
const actions = new input.Actions(executor, {bridge: true});
const element = new WebElement(null, 'abc123');
await actions
.press(input.Button.LEFT)
.press(input.Button.RIGHT)
.release(input.Button.LEFT)
.release(input.Button.RIGHT)
.perform();
assert.deepEqual(executor.commands, [
{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerDown', button: input.Button.RIGHT},
{type: 'pointerUp', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.RIGHT},
],
}],
}
},
{
name: command.Name.LEGACY_ACTION_MOUSE_DOWN,
parameters: {button: input.Button.LEFT},
},
{
name: command.Name.LEGACY_ACTION_MOUSE_DOWN,
parameters: {button: input.Button.RIGHT},
},
{
name: command.Name.LEGACY_ACTION_MOUSE_UP,
parameters: {button: input.Button.LEFT},
},
{
name: command.Name.LEGACY_ACTION_MOUSE_UP,
parameters: {button: input.Button.RIGHT},
},
]);
});
it('click() shortcut', async function() {
const executor =
new StubExecutor(
Promise.reject(new error.UnknownCommandError),
Promise.resolve());
const actions = new input.Actions(executor, {bridge: true});
const element = new WebElement(null, 'abc123');
await actions.click().perform();
assert.deepEqual(executor.commands, [
{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
],
}],
}
},
{
name: command.Name.LEGACY_ACTION_CLICK,
parameters: {button: input.Button.LEFT},
},
]);
});
it('detects context-clicks', async function() {
const executor =
new StubExecutor(
Promise.reject(new error.UnknownCommandError),
Promise.resolve());
const actions = new input.Actions(executor, {bridge: true});
const element = new WebElement(null, 'abc123');
await actions
.press(input.Button.RIGHT)
.release(input.Button.RIGHT)
.perform();
assert.deepEqual(executor.commands, [
{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{type: 'pointerDown', button: input.Button.RIGHT},
{type: 'pointerUp', button: input.Button.RIGHT},
],
}],
}
},
{
name: command.Name.LEGACY_ACTION_CLICK,
parameters: {button: input.Button.RIGHT},
},
]);
});
it('contextClick() shortcut', async function() {
const executor =
new StubExecutor(
Promise.reject(new error.UnknownCommandError),
Promise.resolve());
const actions = new input.Actions(executor, {bridge: true});
const element = new WebElement(null, 'abc123');
await actions.contextClick().perform();
assert.deepEqual(executor.commands, [
{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{type: 'pointerDown', button: input.Button.RIGHT},
{type: 'pointerUp', button: input.Button.RIGHT},
],
}],
}
},
{
name: command.Name.LEGACY_ACTION_CLICK,
parameters: {button: input.Button.RIGHT},
},
]);
});
it('click(element)', async function() {
const executor =
new StubExecutor(
Promise.reject(new error.UnknownCommandError),
Promise.resolve([0, 0]),
Promise.resolve(),
Promise.resolve());
const actions = new input.Actions(executor, {bridge: true});
const element = new WebElement(null, 'abc123');
await actions.click(element).perform();
assert.deepEqual(executor.commands, [
{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{
type: 'pointerMove',
duration: 100,
origin: element,
x: 0,
y: 0,
},
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
],
}],
}
},
{
name: command.Name.EXECUTE_SCRIPT,
parameters: {
script: input.INTERNAL_COMPUTE_OFFSET_SCRIPT,
args: [element],
},
},
{
name: command.Name.LEGACY_ACTION_MOUSE_MOVE,
parameters: {
element: 'abc123',
xoffset: 0,
yoffset: 0,
},
},
{
name: command.Name.LEGACY_ACTION_CLICK,
parameters: {button: input.Button.LEFT},
},
]);
});
});
describe('detects double-clicks', function() {
it('press/release x2 for same button is a double-click', async function() {
const executor =
new StubExecutor(
Promise.reject(new error.UnknownCommandError),
Promise.resolve());
const actions = new input.Actions(executor, {bridge: true});
const element = new WebElement(null, 'abc123');
await actions
.press(input.Button.LEFT)
.release(input.Button.LEFT)
.press(input.Button.LEFT)
.release(input.Button.LEFT)
.perform();
assert.deepEqual(executor.commands, [
{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
],
}],
}
},
{
name: command.Name.LEGACY_ACTION_DOUBLE_CLICK,
parameters: {button: input.Button.LEFT},
},
]);
});
it('doubleClick() shortcut', async function() {
const executor =
new StubExecutor(
Promise.reject(new error.UnknownCommandError),
Promise.resolve());
const actions = new input.Actions(executor, {bridge: true});
await actions.doubleClick().perform();
assert.deepEqual(executor.commands, [
{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
],
}],
}
},
{
name: command.Name.LEGACY_ACTION_DOUBLE_CLICK,
parameters: {button: input.Button.LEFT},
},
]);
});
it('not a double-click if second click is another button', async function() {
const executor =
new StubExecutor(
Promise.reject(new error.UnknownCommandError),
Promise.resolve(),
Promise.resolve());
const actions = new input.Actions(executor, {bridge: true});
await actions.click().contextClick().perform();
assert.deepEqual(executor.commands, [
{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
{type: 'pointerDown', button: input.Button.RIGHT},
{type: 'pointerUp', button: input.Button.RIGHT},
],
}],
}
},
{
name: command.Name.LEGACY_ACTION_CLICK,
parameters: {button: input.Button.LEFT},
},
{
name: command.Name.LEGACY_ACTION_CLICK,
parameters: {button: input.Button.RIGHT},
},
]);
});
it('doubleClick(element)', async function() {
const executor =
new StubExecutor(
Promise.reject(new error.UnknownCommandError),
Promise.resolve([7, 10]),
Promise.resolve(),
Promise.resolve());
const actions = new input.Actions(executor, {bridge: true});
const element = new WebElement(null, 'abc123');
await actions.doubleClick(element).perform();
assert.deepEqual(executor.commands, [
{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{
type: 'pointerMove',
duration: 100,
origin: element,
x: 0,
y: 0,
},
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
],
}],
}
},
{
name: command.Name.EXECUTE_SCRIPT,
parameters: {
script: input.INTERNAL_COMPUTE_OFFSET_SCRIPT,
args: [element],
},
},
{
name: command.Name.LEGACY_ACTION_MOUSE_MOVE,
parameters: {
element: 'abc123',
xoffset: 7,
yoffset: 10,
},
},
{
name: command.Name.LEGACY_ACTION_DOUBLE_CLICK,
parameters: {button: input.Button.LEFT},
},
]);
});
});
it('mouse sequence', async function() {
const executor =
new StubExecutor(
Promise.reject(new error.UnknownCommandError),
Promise.resolve([-6, 9]),
Promise.resolve(),
Promise.resolve(),
Promise.resolve(),
Promise.resolve());
const actions = new input.Actions(executor, {bridge: true});
const element = new WebElement(null, 'abc123');
await actions
.move({x: 5, y: 5, origin: element})
.click()
.move({x: 10, y: 15, origin: input.Origin.POINTER})
.doubleClick()
.perform();
assert.deepEqual(executor.commands, [
{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{
type: 'pointerMove',
duration: 100,
origin: element,
x: 5,
y: 5,
},
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
{
type: 'pointerMove',
duration: 100,
origin: input.Origin.POINTER,
x: 10,
y: 15,
},
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
{type: 'pointerDown', button: input.Button.LEFT},
{type: 'pointerUp', button: input.Button.LEFT},
],
}],
}
},
{
name: command.Name.EXECUTE_SCRIPT,
parameters: {
script: input.INTERNAL_COMPUTE_OFFSET_SCRIPT,
args: [element],
},
},
{
name: command.Name.LEGACY_ACTION_MOUSE_MOVE,
parameters: {
element: 'abc123',
xoffset: -1,
yoffset: 14,
},
},
{
name: command.Name.LEGACY_ACTION_CLICK,
parameters: {button: input.Button.LEFT},
},
{
name: command.Name.LEGACY_ACTION_MOUSE_MOVE,
parameters: {xoffset: 10, yoffset: 15},
},
{
name: command.Name.LEGACY_ACTION_DOUBLE_CLICK,
parameters: {button: input.Button.LEFT},
},
]);
});
it('dragAndDrop', async function() {
const executor =
new StubExecutor(
Promise.reject(new error.UnknownCommandError),
Promise.resolve([15, 20]),
Promise.resolve(),
Promise.resolve(),
Promise.resolve([25, 30]),
Promise.resolve(),
Promise.resolve());
const actions = new input.Actions(executor, {bridge: true});
const e1 = new WebElement(null, 'abc123');
const e2 = new WebElement(null, 'def456');
await actions.dragAndDrop(e1, e2).perform();
assert.deepEqual(executor.commands, [
{
name: command.Name.ACTIONS,
parameters: {
actions: [{
id: 'default mouse',
type: 'pointer',
parameters: {pointerType: 'mouse'},
actions: [
{
type: 'pointerMove',
duration: 100,
origin: e1,
x: 0,
y: 0,
},
{type: 'pointerDown', button: input.Button.LEFT},
{
type: 'pointerMove',
duration: 100,
origin: e2,
x: 0,
y: 0,
},
{type: 'pointerUp', button: input.Button.LEFT},
],
}],
}
},
{
name: command.Name.EXECUTE_SCRIPT,
parameters: {
script: input.INTERNAL_COMPUTE_OFFSET_SCRIPT,
args: [e1],
},
},
{
name: command.Name.LEGACY_ACTION_MOUSE_MOVE,
parameters: {
element: 'abc123',
xoffset: 15,
yoffset: 20,
},
},
{
name: command.Name.LEGACY_ACTION_MOUSE_DOWN,
parameters: {button: input.Button.LEFT},
},
{
name: command.Name.EXECUTE_SCRIPT,
parameters: {
script: input.INTERNAL_COMPUTE_OFFSET_SCRIPT,
args: [e2],
},
},
{
name: command.Name.LEGACY_ACTION_MOUSE_MOVE,
parameters: {
element: 'def456',
xoffset: 25,
yoffset: 30,
},
},
{
name: command.Name.LEGACY_ACTION_MOUSE_UP,
parameters: {button: input.Button.LEFT},
},
]);
});
});
});
| twalpole/selenium | javascript/node/selenium-webdriver/test/lib/input_test.js | JavaScript | apache-2.0 | 43,613 |
(function(){
// Back to Top - by CodyHouse.co
var backTop = document.getElementsByClassName('js-cd-top')[0],
offset = 300, // browser window scroll (in pixels) after which the "back to top" link is shown
offsetOpacity = 1200, //browser window scroll (in pixels) after which the "back to top" link opacity is reduced
scrollDuration = 700,
scrolling = false;
if( backTop ) {
//update back to top visibility on scrolling
window.addEventListener("scroll", function(event) {
if( !scrolling ) {
scrolling = true;
(!window.requestAnimationFrame) ? setTimeout(checkBackToTop, 250) : window.requestAnimationFrame(checkBackToTop);
}
});
//smooth scroll to top
backTop.addEventListener('click', function(event) {
event.preventDefault();
(!window.requestAnimationFrame) ? window.scrollTo(0, 0) : Util.scrollTo(0, scrollDuration);
});
}
function checkBackToTop() {
var windowTop = window.scrollY || document.documentElement.scrollTop;
( windowTop > offset ) ? Util.addClass(backTop, 'cd-top--is-visible') : Util.removeClass(backTop, 'cd-top--is-visible cd-top--fade-out');
( windowTop > offsetOpacity ) && Util.addClass(backTop, 'cd-top--fade-out');
scrolling = false;
}
})(); | wso2/siddhi | docs/assets/lib/backtotop/js/main.js | JavaScript | apache-2.0 | 1,223 |
var gulp = require('gulp');
var config = require('../config').markup;
var browserSync = require('browser-sync');
var taskDef = function () {
return gulp.src(config.src)
.pipe(gulp.dest(config.dest))
.pipe(browserSync.reload({
stream: true
}));
};
module.exports = taskDef;
gulp.task('markup', taskDef);
| artbychenko/bootstrap-marionette-gulp-starter | gulp/tasks/markup.js | JavaScript | mit | 346 |
/*global jasmine*/
var excludes = [
"map_events.html",
"map_lazy_init.html",
"map-lazy-load.html",
"marker_with_dynamic_position.html",
"marker_with_dynamic_address.html",
"marker_with_info_window.html",
"places-auto-complete.html"
];
function using(values, func){
for (var i = 0, count = values.length; i < count; i++) {
if (Object.prototype.toString.call(values[i]) !== '[object Array]') {
values[i] = [values[i]];
}
func.apply(this, values[i]);
jasmine.currentEnv_.currentSpec.description += ' (with using ' + values[i].join(', ') + ')';
}
}
describe('testapp directory', function() {
'use strict';
//var urls = ["aerial-rotate.html", "aerial-simple.html", "hello_map.html", "map_control.html"];
var files = require('fs').readdirSync(__dirname + "/../../testapp");
var urls = files.filter(function(filename) {
return filename.match(/\.html$/) && excludes.indexOf(filename) === -1;
});
console.log('urls', urls);
using(urls, function(url){
it('testapp/'+url, function() {
browser.get(url);
browser.wait( function() {
return browser.executeScript( function() {
var el = document.querySelector("map");
var scope = angular.element(el).scope();
//return scope.map.getCenter().lat();
return scope.map.getCenter();
}).then(function(result) {
return result;
});
}, 5000);
//element(by.css("map")).evaluate('map.getCenter().lat()').then(function(lat) {
// console.log('lat', lat);
// expect(lat).toNotEqual(0);
//});
browser.manage().logs().get('browser').then(function(browserLog) {
(browserLog.length > 0) && console.log('log: ' + require('util').inspect(browserLog));
expect(browserLog).toEqual([]);
});
});
});
});
| ionicthemes/building-a-complete-mobile-app-with-ionic-framework | www/lib/ngmap/spec/e2e/testapp_spec.js | JavaScript | mit | 1,856 |
module.exports = {
description: 'does not include called-in-unused-code import'
};
| Victorystick/rollup | test/form/unused-called-with-side-effects/_config.js | JavaScript | mit | 84 |
//////////////////////////////////////////////////////////////////////////
// //
// This is a generated file. You can view the original //
// source in your browser if your browser supports source maps. //
// Source maps are supported by all recent versions of Chrome, Safari, //
// and Firefox, and by Internet Explorer 11. //
// //
//////////////////////////////////////////////////////////////////////////
(function () {
/* Imports */
var Meteor = Package.meteor.Meteor;
var _ = Package.underscore._;
var ReactiveDict = Package['reactive-dict'].ReactiveDict;
var EJSON = Package.ejson.EJSON;
/* Package-scope variables */
var Session;
(function(){
/////////////////////////////////////////////////////////////////////////////////
// //
// packages/session/session.js //
// //
/////////////////////////////////////////////////////////////////////////////////
//
Session = new ReactiveDict('session'); // 1
// 2
// Documentation here is really awkward because the methods are defined // 3
// elsewhere // 4
// 5
/** // 6
* @memberOf Session // 7
* @method set // 8
* @summary Set a variable in the session. Notify any listeners that the value
* has changed (eg: redraw templates, and rerun any // 10
* [`Tracker.autorun`](#tracker_autorun) computations, that called // 11
* [`Session.get`](#session_get) on this `key`.) // 12
* @locus Client // 13
* @param {String} key The key to set, eg, `selectedItem` // 14
* @param {EJSONable | undefined} value The new value for `key` // 15
*/ // 16
// 17
/** // 18
* @memberOf Session // 19
* @method setDefault // 20
* @summary Set a variable in the session if it hasn't been set before. // 21
* Otherwise works exactly the same as [`Session.set`](#session_set). // 22
* @locus Client // 23
* @param {String} key The key to set, eg, `selectedItem` // 24
* @param {EJSONable | undefined} value The new value for `key` // 25
*/ // 26
// 27
/** // 28
* @memberOf Session // 29
* @method get // 30
* @summary Get the value of a session variable. If inside a [reactive // 31
* computation](#reactivity), invalidate the computation the next time the // 32
* value of the variable is changed by [`Session.set`](#session_set). This // 33
* returns a clone of the session value, so if it's an object or an array, // 34
* mutating the returned value has no effect on the value stored in the // 35
* session. // 36
* @locus Client // 37
* @param {String} key The name of the session variable to return // 38
*/ // 39
// 40
/** // 41
* @memberOf Session // 42
* @method equals // 43
* @summary Test if a session variable is equal to a value. If inside a // 44
* [reactive computation](#reactivity), invalidate the computation the next // 45
* time the variable changes to or from the value. // 46
* @locus Client // 47
* @param {String} key The name of the session variable to test // 48
* @param {String | Number | Boolean | null | undefined} value The value to // 49
* test against // 50
*/ // 51
// 52
/////////////////////////////////////////////////////////////////////////////////
}).call(this);
/* Exports */
if (typeof Package === 'undefined') Package = {};
Package.session = {
Session: Session
};
})();
| SFII/equip | src/.meteor/local/build/programs/web.browser/packages/session.js | JavaScript | mit | 5,959 |
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
frappe.ui.form.Grid = Class.extend({
init: function(opts) {
$.extend(this, opts);
this.fieldinfo = {};
this.doctype = this.df.options;
this.template = null;
if(this.frm.meta.__form_grid_templates
&& this.frm.meta.__form_grid_templates[this.df.fieldname]) {
this.template = this.frm.meta.__form_grid_templates[this.df.fieldname];
}
this.is_grid = true;
},
make: function() {
var me = this;
this.wrapper = $('<div>\
<div class="form-grid">\
<div class="grid-heading-row" style="font-size: 15px;"></div>\
<div class="panel-body" style="padding-top: 7px;">\
<div class="rows"></div>\
<div class="small grid-footer">\
<a href="#" class="grid-add-row pull-right" style="margin-left: 10px;">+ '
+__("Add new row")+'.</a>\
<a href="#" class="grid-add-multiple-rows pull-right hide" style="margin-left: 10px;">+ '
+__("Add multiple rows")+'.</a>\
<span class="text-muted pull-right" style="margin-right: 5px;">'
+ __("Click on row to view / edit.") + '</span>\
<div class="clearfix"></div>\
</div>\
</div>\
</div>\
</div>')
.appendTo(this.parent)
.attr("data-fieldname", this.df.fieldname);
$(this.wrapper).find(".grid-add-row").click(function() {
me.add_new_row(null, null, true);
return false;
})
},
make_head: function() {
// labels
this.header_row = new frappe.ui.form.GridRow({
parent: $(this.parent).find(".grid-heading-row"),
parent_df: this.df,
docfields: this.docfields,
frm: this.frm,
grid: this
});
},
refresh: function(force) {
!this.wrapper && this.make();
var me = this,
$rows = $(me.parent).find(".rows"),
data = this.get_data();
this.docfields = frappe.meta.get_docfields(this.doctype, this.frm.docname);
this.display_status = frappe.perm.get_field_display_status(this.df, this.frm.doc,
this.perm);
if(this.display_status==="None") return;
if(!force && this.data_rows_are_same(data)) {
// soft refresh
this.header_row && this.header_row.refresh();
for(var i in this.grid_rows) {
this.grid_rows[i].refresh();
}
} else {
// redraw
var _scroll_y = window.scrollY;
this.wrapper.find(".grid-row").remove();
this.make_head();
this.grid_rows = [];
this.grid_rows_by_docname = {};
for(var ri in data) {
var d = data[ri];
var grid_row = new frappe.ui.form.GridRow({
parent: $rows,
parent_df: this.df,
docfields: this.docfields,
doc: d,
frm: this.frm,
grid: this
});
this.grid_rows.push(grid_row)
this.grid_rows_by_docname[d.name] = grid_row;
}
this.wrapper.find(".grid-add-row, .grid-add-multiple-rows").toggle(this.can_add_rows());
if(this.is_editable()) {
this.make_sortable($rows);
}
this.last_display_status = this.display_status;
this.last_docname = this.frm.docname;
scroll(0, _scroll_y);
}
},
refresh_row: function(docname) {
this.grid_rows_by_docname[docname] &&
this.grid_rows_by_docname[docname].refresh();
},
data_rows_are_same: function(data) {
if(this.grid_rows) {
var same = data.length==this.grid_rows.length
&& this.display_status==this.last_display_status
&& this.frm.docname==this.last_docname
&& !$.map(this.grid_rows, function(g, i) {
return (g.doc && g.doc.name==data[i].name) ? null : true;
}).length;
return same;
}
},
make_sortable: function($rows) {
var me =this;
$rows.sortable({
handle: ".data-row, .panel-heading",
helper: 'clone',
update: function(event, ui) {
me.frm.doc[me.df.fieldname] = [];
$rows.find(".grid-row").each(function(i, item) {
var doc = $(item).data("doc");
doc.idx = i + 1;
$(this).find(".row-index").html(i + 1);
me.frm.doc[me.df.fieldname].push(doc);
});
me.frm.dirty();
}
});
},
get_data: function() {
var data = this.frm.doc[this.df.fieldname] || [];
data.sort(function(a, b) { return a.idx - b.idx});
return data;
},
set_column_disp: function(fieldname, show) {
if($.isArray(fieldname)) {
var me = this;
$.each(fieldname, function(i, fname) {
frappe.meta.get_docfield(me.doctype, fname, me.frm.docname).hidden = show ? 0 : 1;
});
} else {
frappe.meta.get_docfield(this.doctype, fieldname, this.frm.docname).hidden = show ? 0 : 1;
}
this.refresh(true);
},
toggle_reqd: function(fieldname, reqd) {
frappe.meta.get_docfield(this.doctype, fieldname, this.frm.docname).reqd = reqd;
this.refresh();
},
get_field: function(fieldname) {
// Note: workaround for get_query
if(!this.fieldinfo[fieldname])
this.fieldinfo[fieldname] = {
}
return this.fieldinfo[fieldname];
},
set_value: function(fieldname, value, doc) {
if(this.display_status!=="None")
this.grid_rows_by_docname[doc.name].refresh_field(fieldname);
},
add_new_row: function(idx, callback, show) {
if(this.is_editable()) {
var d = frappe.model.add_child(this.frm.doc, this.df.options, this.df.fieldname, idx);
this.frm.script_manager.trigger(this.df.fieldname + "_add", d.doctype, d.name);
this.refresh();
if(show) {
if(idx) {
this.wrapper.find("[data-idx='"+idx+"']").data("grid_row")
.toggle_view(true, callback);
} else {
this.wrapper.find(".grid-row:last").data("grid_row").toggle_view(true, callback);
}
}
return d;
}
},
is_editable: function() {
return this.display_status=="Write" && !this.static_rows
},
can_add_rows: function() {
return this.is_editable() && !this.cannot_add_rows
},
set_multiple_add: function(link, qty) {
if(this.multiple_set) return;
var me = this;
var link_field = frappe.meta.get_docfield(this.df.options, link);
$(this.wrapper).find(".grid-add-multiple-rows")
.removeClass("hide")
.on("click", function() {
new frappe.ui.form.LinkSelector({
doctype: link_field.options,
fieldname: link,
qty_fieldname: qty,
target: me,
txt: ""
});
return false;
});
this.multiple_set = true;
}
});
frappe.ui.form.GridRow = Class.extend({
init: function(opts) {
$.extend(this, opts);
this.show = false;
this.make();
},
make: function() {
var me = this;
this.wrapper = $('<div class="grid-row"></div>').appendTo(this.parent).data("grid_row", this);
this.row = $('<div class="data-row" style="min-height: 26px;"></div>').appendTo(this.wrapper)
.on("click", function() {
me.toggle_view();
return false;
});
this.divider = $('<div class="divider row"></div>').appendTo(this.wrapper);
this.set_row_index();
this.make_static_display();
if(this.doc) {
this.set_data();
}
},
set_row_index: function() {
if(this.doc) {
this.wrapper
.attr("data-idx", this.doc.idx)
.find(".row-index").html(this.doc.idx)
}
},
remove: function() {
if(this.grid.is_editable()) {
var me = this;
me.wrapper.toggle(false);
frappe.model.clear_doc(me.doc.doctype, me.doc.name);
me.frm.script_manager.trigger(me.grid.df.fieldname + "_remove", me.doc.doctype, me.doc.name);
me.frm.dirty();
me.grid.refresh();
}
},
insert: function(show) {
var idx = this.doc.idx;
this.toggle_view(false);
this.grid.add_new_row(idx, null, show);
},
refresh: function() {
if(this.doc)
this.doc = locals[this.doc.doctype][this.doc.name];
// re write columns
this.grid.static_display_template = null;
this.make_static_display();
// refersh form fields
if(this.show) {
this.layout.refresh(this.doc);
}
},
make_static_display: function() {
var me = this;
this.row.empty();
$('<div class="col-xs-1 row-index">' + (this.doc ? this.doc.idx : "#")+ '</div>')
.appendTo(this.row);
if(this.grid.template) {
$('<div class="col-xs-10">').appendTo(this.row)
.html(frappe.render(this.grid.template, {
doc: this.doc ? frappe.get_format_helper(this.doc) : null,
frm: this.frm,
row: this
}));
} else {
this.add_visible_columns();
}
this.add_buttons();
$(this.frm.wrapper).trigger("grid-row-render", [this]);
},
add_buttons: function() {
var me = this;
if(this.doc && this.grid.is_editable()) {
if(!this.grid.$row_actions) {
this.grid.$row_actions = $('<div class="col-xs-1 pull-right" \
style="text-align: right; padding-right: 5px;">\
<span class="text-success grid-insert-row" style="padding: 4px;">\
<i class="icon icon-plus-sign"></i></span>\
<span class="grid-delete-row" style="padding: 4px;">\
<i class="icon icon-trash"></i></span>\
</div>');
}
$col = this.grid.$row_actions.clone().appendTo(this.row);
if($col.width() < 50) {
$col.toggle(false);
} else {
$col.toggle(true);
$col.find(".grid-insert-row").click(function() { me.insert(); return false; });
$col.find(".grid-delete-row").click(function() { me.remove(); return false; });
}
} else {
$('<div class="col-xs-1"></div>').appendTo(this.row);
}
},
add_visible_columns: function() {
this.make_static_display_template();
for(var ci in this.static_display_template) {
var df = this.static_display_template[ci][0];
var colsize = this.static_display_template[ci][1];
var txt = this.doc ?
frappe.format(this.doc[df.fieldname], df, null, this.doc) :
__(df.label);
if(this.doc && df.fieldtype === "Select") {
txt = __(txt);
}
var add_class = (["Text", "Small Text"].indexOf(df.fieldtype)===-1) ?
" grid-overflow-ellipsis" : " grid-overflow-no-ellipsis";
add_class += (["Int", "Currency", "Float"].indexOf(df.fieldtype)!==-1) ?
" text-right": "";
$col = $('<div class="col col-xs-'+colsize+add_class+'"></div>')
.html(txt)
.attr("data-fieldname", df.fieldname)
.data("df", df)
.appendTo(this.row)
if(!this.doc) $col.css({"font-weight":"bold"})
}
},
make_static_display_template: function() {
if(this.static_display_template) return;
var total_colsize = 1;
this.static_display_template = [];
for(var ci in this.docfields) {
var df = this.docfields[ci];
if(!df.hidden && df.in_list_view && this.grid.frm.get_perm(df.permlevel, "read")
&& !in_list(frappe.model.layout_fields, df.fieldtype)) {
var colsize = 2;
switch(df.fieldtype) {
case "Text":
case "Small Text":
colsize = 3;
break;
case "Check":
colsize = 1;
break;
}
total_colsize += colsize
if(total_colsize > 11)
return false;
this.static_display_template.push([df, colsize]);
}
}
// redistribute if total-col size is less than 12
var passes = 0;
while(total_colsize < 11 && passes < 10) {
for(var i in this.static_display_template) {
var df = this.static_display_template[i][0];
var colsize = this.static_display_template[i][1];
if(colsize>1 && colsize<12 && ["Int", "Currency", "Float"].indexOf(df.fieldtype)===-1) {
this.static_display_template[i][1] += 1;
total_colsize++;
}
if(total_colsize >= 11)
break;
}
passes++;
}
},
toggle_view: function(show, callback) {
if(!this.doc) return this;
this.doc = locals[this.doc.doctype][this.doc.name];
// hide other
var open_row = $(".grid-row-open").data("grid_row");
this.fields = [];
this.fields_dict = {};
this.show = show===undefined ?
show = !this.show :
show
// call blur
document.activeElement && document.activeElement.blur()
if(show && open_row) {
if(open_row==this) {
// already open, do nothing
callback();
return;
} else {
// close other views
open_row.toggle_view(false);
}
}
this.wrapper.toggleClass("grid-row-open", this.show);
if(this.show) {
if(!this.form_panel) {
this.form_panel = $('<div class="panel panel-warning" style="display: none;"></div>')
.insertBefore(this.divider);
}
this.render_form();
this.row.toggle(false);
this.form_panel.toggle(true);
if(this.frm.doc.docstatus===0) {
var first = this.form_area.find(":input:first");
if(first.length && first.attr("data-fieldtype")!="Date") {
try {
first.get(0).focus();
} catch(e) {
console.log("Dialog: unable to focus on first input: " + e);
}
}
}
} else {
if(this.form_panel)
this.form_panel.toggle(false);
this.row.toggle(true);
this.make_static_display();
}
callback && callback();
return this;
},
open_prev: function() {
if(this.grid.grid_rows[this.doc.idx-2]) {
this.grid.grid_rows[this.doc.idx-2].toggle_view(true);
}
},
open_next: function() {
if(this.grid.grid_rows[this.doc.idx]) {
this.grid.grid_rows[this.doc.idx].toggle_view(true);
} else {
this.grid.add_new_row(null, null, true);
}
},
toggle_add_delete_button_display: function($parent) {
$parent.find(".grid-delete-row, .grid-insert-row, .grid-append-row")
.toggle(this.grid.is_editable());
},
render_form: function() {
var me = this;
this.make_form();
this.form_area.empty();
this.layout = new frappe.ui.form.Layout({
fields: this.docfields,
body: this.form_area,
no_submit_on_enter: true,
frm: this.frm,
});
this.layout.make();
this.fields = this.layout.fields;
this.fields_dict = this.layout.fields_dict;
this.layout.refresh(this.doc);
// copy get_query to fields
$.each(this.grid.fieldinfo || {}, function(fieldname, fi) {
$.extend(me.fields_dict[fieldname], fi);
})
this.toggle_add_delete_button_display(this.wrapper.find(".panel:first"));
this.grid.open_grid_row = this;
this.frm.script_manager.trigger(this.doc.parentfield + "_on_form_rendered", this);
},
make_form: function() {
if(!this.form_area) {
$('<div class="panel-heading">\
<div class="toolbar">\
<span class="panel-title">' + __("Editing Row") + ' #<span class="row-index"></span></span>\
<span class="text-success pull-right grid-toggle-row" \
title="'+__("Close")+'"\
style="margin-left: 7px;">\
<i class="icon-chevron-up"></i></span>\
<span class="pull-right grid-insert-row" \
title="'+__("Insert Row")+'"\
style="margin-left: 7px;">\
<i class="icon-plus grid-insert-row"></i></span>\
<span class="pull-right grid-delete-row"\
title="'+__("Delete Row")+'"\
><i class="icon-trash grid-delete-row"></i></span>\
</div>\
</div>\
<div class="panel-body">\
<div class="form-area"></div>\
<div class="toolbar footer-toolbar" style="margin-top: 15px">\
<span class="text-muted"><a href="#" class="shortcuts"><i class="icon-keyboard"></i>' + __("Shortcuts") + '</a></span>\
<span class="text-success pull-right grid-toggle-row" \
title="'+__("Close")+'"\
style="margin-left: 7px; cursor: pointer;">\
<i class="icon-chevron-up"></i></span>\
<span class="pull-right grid-append-row" \
title="'+__("Insert Below")+'"\
style="margin-left: 7px; cursor: pointer;">\
<i class="icon-plus"></i></span>\
</div>\
</div>').appendTo(this.form_panel);
this.form_area = this.wrapper.find(".form-area");
this.set_row_index();
this.set_form_events();
}
},
set_form_events: function() {
var me = this;
this.form_panel.find(".grid-delete-row")
.click(function() { me.remove(); return false; })
this.form_panel.find(".grid-insert-row")
.click(function() { me.insert(true); return false; })
this.form_panel.find(".grid-append-row")
.click(function() {
me.toggle_view(false);
me.grid.add_new_row(me.doc.idx+1, null, true);
return false;
})
this.form_panel.find(".panel-heading, .grid-toggle-row").on("click", function() {
me.toggle_view();
return false;
});
this.form_panel.find(".shortcuts").on("click", function() {
msgprint(__('Move Up: {0}', ['Ctrl+<i class="icon-arrow-up"></i>']));
msgprint(__('Move Down: {0}', ['Ctrl+<i class="icon-arrow-down"></i>']));
msgprint(__('Close: {0}', ['Esc']));
return false;
})
},
set_data: function() {
this.wrapper.data({
"doc": this.doc
})
},
refresh_field: function(fieldname) {
var $col = this.row.find("[data-fieldname='"+fieldname+"']");
if($col.length) {
$col.html(frappe.format(this.doc[fieldname],
frappe.meta.get_docfield(this.doc.doctype, fieldname, this.frm.docname), null, this.frm.doc));
}
// in form
if(this.fields_dict && this.fields_dict[fieldname]) {
this.fields_dict[fieldname].refresh();
this.layout.refresh_dependency();
}
},
get_visible_columns: function(blacklist) {
var me = this;
var visible_columns = $.map(this.docfields, function(df) {
var visible = !df.hidden && df.in_list_view && me.grid.frm.get_perm(df.permlevel, "read")
&& !in_list(frappe.model.layout_fields, df.fieldtype) && !in_list(blacklist, df.fieldname);
return visible ? df : null;
});
return visible_columns;
}
});
| gangadharkadam/shfr | frappe/public/js/frappe/form/grid.js | JavaScript | mit | 16,815 |
// The translations in this file are added by default.
'use strict';
module.exports = {
counterpart: {
names: require('date-names/en'),
pluralize: require('pluralizers/en'),
formats: {
date: {
default: '%a, %e %b %Y',
long: '%A, %B %o, %Y',
short: '%b %e',
},
time: {
default: '%H:%M',
long: '%H:%M:%S %z',
short: '%H:%M',
},
datetime: {
default: '%a, %e %b %Y %H:%M',
long: '%A, %B %o, %Y %H:%M:%S %z',
short: '%e %b %H:%M',
},
},
},
};
| TimCliff/steemit.com | src/app/locales/counterpart/zh.js | JavaScript | mit | 699 |
module.exports={A:{A:{"2":"J C G E B VB","132":"A"},B:{"132":"D Y g H L"},C:{"2":"0 1 3 4 5 6 TB z F I J C G E B A D Y g H L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s x y u t RB QB"},D:{"2":"0 1 3 4 5 6 F I J C G E B A D Y g H L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s x y u t FB AB CB UB DB"},E:{"2":"9 F I J C G E B EB GB HB IB JB KB","513":"A LB"},F:{"2":"7 8 E A D H L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s MB NB OB PB SB w"},G:{"1":"A","2":"2 9 G BB WB XB YB ZB aB bB cB dB"},H:{"2":"eB"},I:{"2":"2 z F fB gB hB iB jB kB","258":"t"},J:{"2":"C B"},K:{"2":"7 8 B A D K w"},L:{"258":"AB"},M:{"2":"u"},N:{"2":"B A"},O:{"2":"lB"},P:{"2":"F","258":"I"},Q:{"2":"mB"},R:{"2":"nB"}},B:6,C:"HEVC/H.265 video format"};
| hellokidder/js-studying | 微信小程序/wxtest/node_modules/caniuse-lite/data/features/hevc.js | JavaScript | mit | 791 |
/*!
* OOjs UI v0.25.0
* https://www.mediawiki.org/wiki/OOjs_UI
*
* Copyright 2011–2018 OOjs UI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2018-01-10T00:26:02Z
*/
( function ( OO ) {
'use strict';
/**
* @class
* @extends OO.ui.Theme
*
* @constructor
*/
OO.ui.WikimediaUITheme = function OoUiWikimediaUITheme() {
// Parent constructor
OO.ui.WikimediaUITheme.parent.call( this );
};
/* Setup */
OO.inheritClass( OO.ui.WikimediaUITheme, OO.ui.Theme );
/* Methods */
/**
* @inheritdoc
*/
OO.ui.WikimediaUITheme.prototype.getElementClasses = function ( element ) {
// Parent method
var variant, isFramed, isActive,
variants = {
warning: false,
invert: false,
progressive: false,
destructive: false
},
// Parent method
classes = OO.ui.WikimediaUITheme.parent.prototype.getElementClasses.call( this, element );
if ( element.supports( [ 'hasFlag' ] ) ) {
isFramed = element.supports( [ 'isFramed' ] ) && element.isFramed();
isActive = element.supports( [ 'isActive' ] ) && element.isActive();
if (
// Button with a dark background
isFramed && ( isActive || element.isDisabled() || element.hasFlag( 'primary' ) ) ||
// Toolbar with a dark background
OO.ui.ToolGroup && element instanceof OO.ui.ToolGroup && ( isActive || element.hasFlag( 'primary' ) )
) {
// … use white icon / indicator, regardless of other flags
variants.invert = true;
} else if ( !isFramed && element.isDisabled() ) {
// Frameless disabled button, always use black icon / indicator regardless of other flags
variants.invert = false;
} else if ( !element.isDisabled() ) {
// Any other kind of button, use the right colored icon / indicator if available
variants.progressive = element.hasFlag( 'progressive' );
variants.destructive = element.hasFlag( 'destructive' );
variants.warning = element.hasFlag( 'warning' );
}
}
for ( variant in variants ) {
classes[ variants[ variant ] ? 'on' : 'off' ].push( 'oo-ui-image-' + variant );
}
return classes;
};
/**
* @inheritdoc
*/
OO.ui.WikimediaUITheme.prototype.getDialogTransitionDuration = function () {
return 250;
};
/* Instantiation */
OO.ui.theme = new OO.ui.WikimediaUITheme();
}( OO ) );
//# sourceMappingURL=oojs-ui-wikimediaui.js.map | extend1994/cdnjs | ajax/libs/oojs-ui/0.25.0/oojs-ui-wikimediaui.js | JavaScript | mit | 2,323 |
/*
eZ Online Editor MCE popup : common js code used in popups
Created on: <06-Feb-2008 00:00:00 ar>
Copyright (c) 1999-2014 eZ Systems AS
Licensed under the GPL 2.0 License:
http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
*/
var eZOEPopupUtils = {
embedObject: {},
settings: {
// optional css class to add to tag when we save ( does not replace any class selectors you have)
cssClass: '',
// the ez xml name of the tag
tagName: '',
// optional a checkbox / dropdown that selects the tag type
tagSelector: false,
// optional custom call back funtion if tagSelector change
tagSelectorCallBack: false,
// optional a function to generate the html for the tag ( on create in save() )
tagGenerator: false,
// optional a function to do cleanup after tag has been created ( after create in save() )
onTagGenerated: false,
// optional function to edit the tag ( on edit in save() )
tagEditor: false,
// optional function to generate attribute
attributeGenerator: {},
// optional custom function to handle setting attributes on element edit and create
tagAttributeEditor: false,
// form id that save() is attached to
form: '',
// optional canel button that cancel function is attached to
cancelButton: '',
// content type switch for embed tags
contentType: '',
// internal element in editor ( false on create ), set by init()
editorElement: false,
// event to call on init
onInit: false,
// event to call after init
onInitDone : false,
// events to call after init
onInitDoneArray : [],
// custom attribute to style map to be able to preview style changes
customAttributeStyleMap: false,
// set on init if no editorElement is present and selected text is without newlines
editorSelectedText: false,
// Same as above but with markup
editorSelectedHtml: false,
// the selected node in the editor, set on init
editorSelectedNode: false,
// generates class name for tr elements in browse / search / bookmark list
browseClassGenerator: function(){ return ''; },
// generates browse link for a specific mode
browseLinkGenerator: false,
// custom init function pr custom attribute
customAttributeInitHandler: [],
// custom save function pr custom attribute
customAttributeSaveHandler: [],
// Title text to set on tilte tag and h2#tag-edit-title tag in tag edit / create dialogs
tagEditTitleText: '',
// the default image alias to use while browsing
browseImageAlias: 'small'
},
/**
* Initialize page with values from current editor element or if not defined; default values and settings
*
* @param {Object} settings Hash with settings, is saved to eZOEPopupUtils.settings for the rest of the execution.
*/
init: function( settings )
{
eZOEPopupUtils.settings = jQuery.extend( false, eZOEPopupUtils.settings, settings );
var ed = tinyMCEPopup.editor, el = tinyMCEPopup.getWindowArg('selected_node'), s = eZOEPopupUtils.settings;
if ( !s.selectedTag ) s.selectedTag = s.tagName;
if ( s.form && (s.form = jQuery( '#' + s.form )) )
s.form.submit( eZOEPopupUtils.save );
if ( s.cancelButton && (s.cancelButton = jQuery( '#' + s.cancelButton )) )
s.cancelButton.click( eZOEPopupUtils.cancel );
if ( el && el.nodeName )
{
s.editorElement = el;
if ( s.tagEditTitleText )
{
document.title = s.tagEditTitleText;
jQuery( '#tag-edit-title').html( s.tagEditTitleText );
if ( window.parent && window.parent.ez )
{
// set title on inline popup if inlinepopup tinyMCE plugin is used
var tinyInlinePopupsTitle = window.parent.jQuery('div.clearlooks2');
if ( tinyInlinePopupsTitle && tinyInlinePopupsTitle.size() )
window.parent.document.getElementById( tinyInlinePopupsTitle[0].id + '_title').innerHTML = s.tagEditTitleText;
}
}
}
else
{
var selectedHtml = ed.selection.getContent( {format:'text'} );
if ( !/\n/.test( selectedHtml ) && jQuery.trim( selectedHtml ) !== '' )
s.editorSelectedText = selectedHtml;
selectedHtml = ed.selection.getContent( {format:'html'} );
if ( jQuery.trim( selectedHtml ) !== '' )
s.editorSelectedHtml = selectedHtml;
}
s.editorSelectedNode = ed.selection.getNode();
if ( s.onInit && s.onInit.call )
s.onInit.call( eZOEPopupUtils, s.editorElement, s.tagName, ed );
if ( s.tagSelector && ( s.tagSelector = jQuery( '#' + s.tagSelector ) ) && s.tagSelector.size() && s.tagSelector[0].value
&& ( s.tagSelector[0].checked === undefined || s.tagSelector[0].checked === true ) )
s.selectedTag = s.tagSelector[0].value;
if ( s.editorElement )
{
eZOEPopupUtils.initGeneralmAttributes( s.tagName + '_attributes', s.editorElement );
eZOEPopupUtils.initCustomAttributeValue( s.selectedTag + '_customattributes', s.editorElement.getAttribute('customattributes'))
}
if ( s.tagSelector && s.tagSelector.size() )
{
// toggle custom attributes based on selected custom tag
if ( s.tagSelectorCallBack && s.tagSelectorCallBack.call )
{
// custom function to call when tag selector change
// 'this' is jQuery object of selector
// first param is event/false and second is element of selector
s.tagSelectorCallBack.call( s.tagSelector, false, s.tagSelector[0] );
s.tagSelector.change( s.tagSelectorCallBack );
}
else
{
// by default tag selector refreshes custom attribute values
eZOEPopupUtils.toggleCustomAttributes.call( s.tagSelector );
s.tagSelector.change( eZOEPopupUtils.toggleCustomAttributes );
}
}
if ( s.onInitDone && s.onInitDone.call )
s.onInitDone.call( eZOEPopupUtils, s.editorElement, s.tagName, ed );
if ( s.onInitDoneArray && s.onInitDoneArray.length )
jQuery.each( s.onInitDoneArray, function( i, fn ){
if ( fn && fn.call )
fn.call( eZOEPopupUtils, s.editorElement, s.tagName, ed );
} );
},
/**
* Save changes from form values to editor element attributes but first:
* - validate values according to class names and stop if not valid
* - create editor element if it does not exist either using callbacks or defaults
* - or call optional edit callback to edit/fixup existing element
* - Set attributes from form values using callback if set or default TinyMCE handler
*/
save: function()
{
var ed = tinyMCEPopup.editor, s = eZOEPopupUtils.settings, n, arr, tmp, f = document.forms[0];
if ( s.tagSelector && s.tagSelector.size() && s.tagSelector[0].value )
{
if ( s.tagSelector[0].checked === undefined || s.tagSelector[0].checked === true )
s.selectedTag = s.tagSelector[0].value;
else if ( s.tagSelector[0].checked === false )
s.selectedTag = s.tagName;
}
// validate the general attributes
if ( (errorArray = AutoValidator.validate( jQuery( '#' + s.tagName + '_attributes' )[0] ) ) && errorArray.length )
{
tinyMCEPopup.alert(tinyMCEPopup.getLang('invalid_data') + "\n" + errorArray.join(", ") );
return false;
}
// validate the custom attributes
if ( (errorArray = AutoValidator.validate( jQuery( '#' + s.selectedTag + '_customattributes' )[0] ) ) && errorArray.length )
{
tinyMCEPopup.alert(tinyMCEPopup.getLang('invalid_data') + "\n" + errorArray.join(", ") );
return false;
}
if ( tinymce.isWebKit )
ed.getWin().focus();
var args = jQuery.extend(
false,
eZOEPopupUtils.getCustomAttributeArgs( s.selectedTag + '_customattributes'),
eZOEPopupUtils.getGeneralAttributeArgs( s.tagName + '_attributes')
);
if ( s.cssClass )
args['class'] = s.cssClass + ( args['class'] ? ' ' + args['class'] : '');
ed.execCommand('mceBeginUndoLevel');
if ( !s.editorElement )
{
// create new node if none is defined and if tag type is defined in ezXmlToXhtmlHash or tagGenerator is defined
if ( s.tagGenerator )
{
s.editorElement = eZOEPopupUtils.insertHTMLCleanly( ed, s.tagGenerator.call( eZOEPopupUtils, s.tagName, s.selectedTag, s.editorSelectedHtml ), '__mce_tmp' );
}
else if ( s.tagCreator )
{
s.editorElement = s.tagCreator.call( eZOEPopupUtils, ed, s.tagName, s.selectedTag, s.editorSelectedHtml );
}
else if ( s.tagName === 'link' )
{
var tempid = args['id'];
args['id'] = '__mce_tmp';
ed.execCommand('mceInsertLink', false, args, {skip_undo : 1} );
s.editorElement = ed.dom.get('__mce_tmp');
// fixup if we are inside embed tag
if ( tmp = eZOEPopupUtils.getParentByTag( s.editorElement, 'div,span', 'ezoeItemNonEditable' ) )
{
var span = document.createElement("span");
span.innerHTML = s.editorElement.innerHTML;
s.editorElement.parentNode.replaceChild(span, s.editorElement);
s.editorElement.innerHTML = '';
tmp.parentNode.insertBefore(s.editorElement, tmp);
s.editorElement.appendChild( tmp );
}
args['id'] = tempid;
}
else if ( eZOEPopupUtils.xmlToXhtmlHash[s.tagName] )
{
s.editorElement = eZOEPopupUtils.insertTagCleanly( ed, eZOEPopupUtils.xmlToXhtmlHash[s.tagName], tinymce.isIE ? ' ' : '<br data-mce-bogus="1" />' );
}
if ( s.onTagGenerated )
{
n = s.onTagGenerated.call( eZOEPopupUtils, s.editorElement, ed, args );
if ( n && n.nodeName )
s.editorElement = n;
}
}
else if ( s.tagEditor )
{
// we already have a element, if custom tagEditor function is defined it can edit it
n = s.tagEditor.call( eZOEPopupUtils, s.editorElement, ed, s.selectedTag, args );
if ( n && n.nodeName )
s.editorElement = n;
}
if ( s.editorElement )
{
if ( s.tagAttributeEditor )
{
n = s.tagAttributeEditor.call( eZOEPopupUtils, ed, s.editorElement, args );
if ( n && n.nodeName )
s.editorElement = n;
}
else
ed.dom.setAttribs( s.editorElement, args );
if ( args['id'] === undefined )
ed.dom.setAttrib( s.editorElement, 'id', '' );
if ( 'TABLE'.indexOf( s.editorElement.tagName ) === 0 )
ed.selection.select( jQuery( s.editorElement ).find( "tr:first-child > *:first-child" ).get(0), true );
else if ( 'DIV'.indexOf( s.editorElement.tagName ) === 0 )
ed.selection.select( s.editorElement );
else
ed.selection.select( s.editorElement, true );
ed.nodeChanged();
}
ed.execCommand('mceEndUndoLevel');
ed.execCommand('mceRepaint');
tinyMCEPopup.close();
return false;
},
/**
* Insert raw html and tries to cleanup any issues that might happen (related to paragraphs and block tags)
* makes sure block nodes do not break the html structure they are inserted into
*
* @param ed TinyMCE editor instance
* @param {String} html
* @param {String} id
* @return HtmlElement
*/
insertHTMLCleanly: function( ed, html, id )
{
var paragraphCleanup = false, newElement;
if ( html.indexOf( '<div' ) === 0 || html.indexOf( '<pre' ) === 0 )
{
paragraphCleanup = true;
}
ed.execCommand('mceInsertRawHTML', false, html, {skip_undo : 1} );
newElement = ed.dom.get( id );
if ( paragraphCleanup ) this.paragraphCleanup( ed, newElement );
return newElement;
},
/**
* Only for use for block tags ( appends or prepends tag relative to current tag )
*
* @param ed TinyMCE editor instance
* @param {String} tag Tag Name
* @param {String} content Inner content of tag, can be html, but only tested with plain text
* @param {Array} args Optional parameter that is passed as second parameter to ed.dom.setAttribs() if set.
* @return HtmlElement
*/
insertTagCleanly: function( ed, tag, content, args )
{
var edCurrentNode = eZOEPopupUtils.settings.editorSelectedNode ? eZOEPopupUtils.settings.editorSelectedNode : ed.selection.getNode(),
newElement = edCurrentNode.ownerDocument.createElement( tag );
if ( tag !== 'img' ) newElement.innerHTML = content;
if ( edCurrentNode.nodeName === 'TD' )
edCurrentNode.appendChild( newElement );
else if ( edCurrentNode.nextSibling )
edCurrentNode.parentNode.insertBefore( newElement, edCurrentNode.nextSibling );
else if ( edCurrentNode.nodeName === 'BODY' )// IE when editor is empty
edCurrentNode.appendChild( newElement );
else
edCurrentNode.parentNode.appendChild( newElement );
if ( (tag === 'div' || tag === 'pre') && edCurrentNode && edCurrentNode.nodeName.toLowerCase() === 'p' )
{
this.paragraphCleanup( ed, newElement );
}
if ( args ) ed.dom.setAttribs( newElement, args );
return newElement;
},
/**
* Cleanup broken paragraphs after inserting block tags into paragraphs
*
* @param ed TinyMCE editor instance
* @param {HtmlElement} el
*/
paragraphCleanup: function( ed, el )
{
var emptyContent = [ '', '<br>', '<BR>', ' ', ' ', " " ];
if ( el.previousSibling
&& el.previousSibling.nodeName.toLowerCase() === 'p'
&& ( !el.previousSibling.hasChildNodes() || jQuery.inArray( el.previousSibling.innerHTML, emptyContent ) !== -1 ))
{
el.parentNode.removeChild( el.previousSibling );
}
if ( el.nextSibling
&& el.nextSibling.nodeName.toLowerCase() === 'p'
&& ( !el.nextSibling.hasChildNodes() || jQuery.inArray( el.nextSibling.innerHTML, emptyContent ) !== -1 ))
{
el.parentNode.removeChild( el.nextSibling );
}
},
/**
* Removes some unwanted stuff from attribute values
*
* @param {String} value
* @return {String}
*/
safeHtml: function( value )
{
value = value.replace(/&/g, '&');
value = value.replace(/\"/g, '"');
value = value.replace(/</g, '<');
value = value.replace(/>/g, '>');
return value;
},
xmlToXhtmlHash: {
'paragraph': 'p',
'literal': 'pre',
'anchor': 'a',
'link': 'a'
},
cancel: function()
{
tinyMCEPopup.close();
},
/**
* Removes all children of a node safly (especially needed to clear select options and table data)
* Also disables tag if it was an select
*
* @param {HtmlElement} node
*/
removeChildren: function( node )
{
if ( !node ) return;
while ( node.hasChildNodes() )
{
node.removeChild( node.firstChild );
}
if ( node.nodeName === 'SELECT' ) node.disabled = true;
},
/**
* Adds options to a selection based on object with name / value pairs or array
* and disables select tag if no options where added.
*
* @param {HtmlElement} node
* @param {Object|Array} o
*/
addSelectOptions: function( node, o )
{
if ( !node || node.nodeName !== 'SELECT' ) return;
var opt, c = 0, i;
if ( o.constructor.toString().indexOf('Array') === -1 )
{
for ( key in o )
{
opt = document.createElement("option");
opt.value = key === '0' || key === '-0-' ? '' : key;
opt.innerHTML = o[key]
node.appendChild( opt );
c++;
}
}
else
{
for ( i = 0, c = o.length; i < c; i++ )
{
opt = document.createElement("option");
opt.value = opt.innerHTML = o[i];
node.appendChild( opt );
}
}
node.disabled = c === 0;
},
/**
* Get custom attribute value from form values and map them to style value as well
*
* @param {HtmlElement} node
* @return {Object} Hash of attributes and their values for use on editor elements
*/
getCustomAttributeArgs: function( node )
{
var args = {
'customattributes': '',
'style': ''
}, s = eZOEPopupUtils.settings, handler = s.customAttributeSaveHandler;
var customArr = [];
jQuery( '#' + node + ' input,#' + node + ' select,#' + node + ' textarea' ).each(function( i, el )
{
var o = jQuery( el ), name = o.attr("name"), value, style;
if ( o.hasClass('mceItemSkip') || !name ) return;
if ( o.attr("type") === 'checkbox' && !o.prop("checked") ) return;
// see if there is a save hander that needs to do some work on the value
if ( handler[el.id] !== undefined && handler[el.id].call !== undefined )
value = handler[el.id].call( o, el, o.val() );
else
value = o.val()
// add to styles if custom attibute is defined in customAttributeStyleMap
if ( value !== '' && s.customAttributeStyleMap && s.customAttributeStyleMap[name] !== undefined )
{
// filtered because the browser (ie,ff&opera) convert the tag to font tag in certain circumstances
style = s.customAttributeStyleMap[name];
if ( /[margin|border|padding|width|height]/.test( style ) )
args['style'] += style + ': ' + value + '; ';
}
customArr.push( name + '|' + value );
});
args['customattributes'] = customArr.join('attribute_separation');
return args;
},
/**
* Get general attributes for tag from form values
*
* @param {HtmlElement} node
* @return {Object} Hash of attributes and their values for use on editor elements
*/
getGeneralAttributeArgs: function( node )
{
var args = {}, handler = eZOEPopupUtils.settings.customAttributeSaveHandler;
jQuery( '#' + node + ' input,#' + node + ' select' ).each(function( i, el )
{
var o = jQuery( el ), name = o.attr("name");
if ( o.hasClass('mceItemSkip') || !name ) return;
if ( o.attr("type") === 'checkbox' && !o.prop("checked") ) return;
// see if there is a save hander that needs to do some work on the value
if ( handler[el.id] !== undefined && handler[el.id].call !== undefined )
args[name] = handler[el.id].call( o, el, o.val() );
else
args[name] = o.val()
});
return args;
},
/**
* Get parent tag by tag name with optional class name and type check
*
* @param {HtmlElement} n
* @param {String} tag
* @param {String} className
* @param {String} type
* @param {Boolean} checkElement Checks n as well if true
* @return {HtmlElement|False}
*/
getParentByTag: function( n, tag, className, type, checkElement )
{
if ( className ) className = ' ' + className + ' ';
tag = ',' + tag.toUpperCase() + ',';
while ( n !== undefined && n.nodeName !== undefined && n.nodeName !== 'BODY' )
{
if ( checkElement && tag.indexOf( ',' + n.nodeName + ',' ) !== -1
&& ( !className || (' ' + n.className + ' ').indexOf( className ) !== -1 )
&& ( !type || n.getAttribute('type') === type ) )
{
return n;
}
n = n.parentNode;
checkElement = true;
}
return false;
},
toggleCustomAttributes: function( e )
{
if ( this.each !== undefined )
node = this;
else
node = jQuery( this );
jQuery('table.custom_attributes').each(function( i, el ){
el = jQuery( el );
if ( el.attr('id') === node[0].value + '_customattributes' )
el.show();
else
el.hide();
});
},
/**
* Sets deafult values for based on custom attribute value
* global objects: ez
*
* @param string node Element id of parent node for custom attribute form
* @param string valueString The raw customattributes string from attribute
*/
initCustomAttributeValue: function( node, valueString )
{
if ( valueString === null || !document.getElementById( node ) )
return;
var arr = valueString.split('attribute_separation'), values = {}, t, handler = eZOEPopupUtils.settings.customAttributeInitHandler;
for(var i = 0, l = arr.length; i < l; i++)
{
t = arr[i].split('|');
var key = t.shift();
values[key] = t.join('|');
}
jQuery( '#' + node + ' input,#' + node + ' select,#' + node + ' textarea' ).each(function( i, el )
{
var o = jQuery( el ), name = el.name;
if ( o.hasClass('mceItemSkip') || !name )
return;
if ( values[name] !== undefined )
{
if ( handler[el.id] !== undefined && handler[el.id].call !== undefined )
handler[el.id].call( o, el, values[name] );
else if ( el.type === 'checkbox' )
el.checked = values[name] == el.value;
else if ( el.type === 'select-one' )
{
// Make sure selecion has value before we set it (#014986)
for( var i = 0, l = el.options.length; i < l; i++ )
{
if ( el.options[i].value == values[name] ) el.value = values[name];
}
}
else
el.value = values[name];
try {
el.onchange();
} catch (ex) {
// Try fire event, ignore errors
}
}
});
},
initGeneralmAttributes: function( node, editorElement )
{
// init general attributes form values from tinymce element values
var handler = eZOEPopupUtils.settings.customAttributeInitHandler, cssReplace = function( s ){
s = s.replace(/(webkit-[\w\-]+|Apple-[\w\-]+|mceItem\w+|ezoeItem\w+|mceVisualAid)/g, '');
if ( !eZOEPopupUtils.settings.cssClass )
return s;
jQuery.each(eZOEPopupUtils.settings.cssClass.split(' '), function(index, value){
s = s.replace( value, '' );
});
return s;
};
jQuery( '#' + node + ' input,#' + node + ' select' ).each(function( i, el )
{
var o = jQuery( el ), name = el.name, v;
if ( o.hasClass('mceItemSkip') ) return;
if ( name === 'class' )
v = jQuery.trim( cssReplace( editorElement.className ) );
else {
v = tinyMCEPopup.editor.dom.getAttrib( editorElement, name );
if ( !v && tinymce.DOM.getAttrib(editorElement, 'style') && editorElement.style[name.toLowerCase()] ) {
v = editorElement.style[name.toLowerCase()];
}
}
if ( v !== false && v !== null && v !== undefined )
{
if ( handler[el.id] !== undefined && handler[el.id].call !== undefined )
handler[el.id].call( o, el, v );
else if ( el.type === 'checkbox' )
el.checked = v == el.value;
else if ( el.type === 'select-one' )
{
// Make sure selection has value before we set it (#014986)
for( var i = 0, l = el.options.length; i < l; i++ )
{
if ( el.options[i].value == v ) el.value = v;
}
}
else
el.value = v;
try {
el.onchange();
} catch (ex) {
// Try fire event, ignore errors
}
}
});
},
switchTagTypeIfNeeded: function ( currentNode, targetTag )
{
if ( currentNode && currentNode.nodeName && targetTag !== currentNode.nodeName.toLowerCase() )
{
// changing to a different node type
var ed = tinyMCEPopup.editor, doc = ed.getDoc(), newNode = doc.createElement( targetTag );
// copy children
if ( newNode.nodeName !== 'IMG' )
{
for ( var c = 0; c < currentNode.childNodes.length; c++ )
newNode.appendChild( currentNode.childNodes[c].cloneNode(1) );
}
// copy attributes
for ( var a = 0; a < currentNode.attributes.length; a++ )
ed.dom.setAttrib(newNode, currentNode.attributes[a].name, ed.dom.getAttrib( currentNode, currentNode.attributes[a].name ) );
if ( currentNode.parentNode.nodeName === 'BODY'
&& ( newNode.nodeName === 'SPAN' || newNode.nodeName === 'IMG' )
)
{
// replace node but wrap inside a paragraph first
var p = doc.createElement('p');
p.appendChild( newNode );
currentNode.parentNode.replaceChild( p, currentNode );
}
else
{
// replace node
currentNode.parentNode.replaceChild( newNode, currentNode );
}
return newNode;
}
return currentNode;
},
selectByEmbedId: function( id, node_id, name, useNode )
{
// redirects to embed window of a specific object id
// global objects: ez
if ( id !== undefined )
{
var s = tinyMCEPopup.editor.settings, type = useNode === true && node_id > 0 ? 'eZNode_' + node_id : 'eZObject_' + id ;
window.location = s.ez_extension_url + '/relations/' + s.ez_contentobject_id + '/' + s.ez_contentobject_version + '/auto/' + type;
}
},
BIND: function()
{
// Binds arguments to a function, so when you call the returned wrapper function,
// arguments are intact and arguments passed to the wrapper function is appended.
// first argument is function, second is 'this' and the rest is arguments
var __args = Array.prototype.slice.call( arguments ), __fn = __args.shift(), __obj = __args.shift();
return function(){return __fn.apply( __obj, __args.concat( Array.prototype.slice.call( arguments ) ) )};
},
searchEnter: function( e, isButton )
{
// post search form if enter key is pressed or isButton = true
if ( isButton )
{
eZOEPopupUtils.search();
return false;
}
e = e || window.event;
key = e.which || e.keyCode;
if ( key == 13)
{
eZOEPopupUtils.search(); // enter key
return false;
}
return true;
},
browse: function( nodeId, offset )
{
// browse for a specific node id and a offset on the child elements
var postData = eZOEPopupUtils.jqSafeSerilizer('browse_box'), o = offset ? offset : 0;
jQuery.ez('ezoe::browse::' + nodeId + '::' + o, postData, function( data ){ eZOEPopupUtils.browseCallBack( data, 'browse' ) } );
jQuery('#browse_progress' ).show();
},
search: function( offset )
{
// serach for nodes with input and select form elements inside a 'search_box' container element
if ( jQuery.trim( jQuery('#SearchText').val() ) )
{
var postData = eZOEPopupUtils.jqSafeSerilizer('search_box'), o = offset ? offset : 0;
jQuery.ez('ezjsc::search::x::' + o, postData, eZOEPopupUtils.searchCallBack );
jQuery('#search_progress' ).show();
}
},
jqSafeSerilizer: function( id )
{
// jQuery encodes form names incl [] if you pass an object / array to it, avoid by using string
var postData = '', val;
jQuery.each( jQuery('#' + id + ' input, #' + id + ' select').serializeArray(), function(i, o){
if ( o.value )
postData += ( postData ? '&' : '') + o.name + '=' + o.value;
});
return postData;
},
browseCallBack: function( data, mode, emptyCallBack )
{
// call back function for the browse() ajax call, generates the html markup with paging and path header (if defined)
mode = mode ? mode : 'browse';
jQuery('#' + mode + '_progress' ).hide();
var ed = tinyMCEPopup.editor, tbody = jQuery('#' + mode + '_box_prev tbody')[0], thead = jQuery('#' + mode + '_box_prev thead')[0], tfoot = jQuery('#' + mode + '_box_prev tfoot')[0], tr, td, tag, hasImage, emptyList = true;
eZOEPopupUtils.removeChildren( tbody );
eZOEPopupUtils.removeChildren( thead );
eZOEPopupUtils.removeChildren( tfoot );
if ( data && data.content !== '' )
{
var fn = mode + ( mode === 'browse' ? '('+ data.content['node']['node_id'] + ',' : '(' );
var classGenerator = eZOEPopupUtils.settings.browseClassGenerator, linkGenerator = eZOEPopupUtils.settings.browseLinkGenerator;
if ( data.content['node'] && data.content['node']['name'] )
{
tr = document.createElement("tr"), td = document.createElement("td");
tr.className = 'browse-path-list';
td.className = 'thight';
tr.appendChild( td );
td = document.createElement("td")
td.setAttribute('colspan', '3');
if ( data.content['node']['path'] !== false && data.content['node']['node_id'] != 1 )
{
// Prepend root node so you can browse to the root of the installation
data.content['node']['path'].splice(0,0,{'node_id':1, 'name': ed.getLang('ez.root_node_name'), 'class_name': 'Folder'});
jQuery.each( data.content['node']['path'], function( i, n )
{
tag = document.createElement("a");
tag.setAttribute('href', 'JavaScript:eZOEPopupUtils.' + mode + '(' + n.node_id + ');');
tag.setAttribute('title', ed.getLang('advanced.type') + ': ' + n.class_name );
tag.innerHTML = n.name;
td.appendChild( tag );
tag = document.createElement("span");
tag.innerHTML = ' / ';
td.appendChild( tag );
});
}
tag = document.createElement("span");
tag.innerHTML = data.content['node']['name'];
td.appendChild( tag );
tr.appendChild( td );
thead.appendChild( tr );
}
if ( data.content['list'] )
{
jQuery.each( data.content['list'], function( i, n )
{
tr = document.createElement("tr"), td = document.createElement("td"), tag = document.createElement("input"), isImage = false;
tag.setAttribute('type', 'radio');
tag.setAttribute('name', 'selectembedobject');
tag.className = 'input_noborder';
tag.setAttribute('value', n.contentobject_id);
tag.setAttribute('title', ed.getLang('advanced.select') );
tag.onclick = eZOEPopupUtils.BIND( eZOEPopupUtils.selectByEmbedId, eZOEPopupUtils, n.contentobject_id, n.node_id, n.name );
td.appendChild( tag );
td.className = 'thight';
tr.appendChild( td );
td = document.createElement("td");
if ( linkGenerator.call !== undefined )
{
tag = linkGenerator.call( this, n, mode, ed );
}
else if ( n.children_count )
{
tag = document.createElement("a");
tag.setAttribute('href', 'JavaScript:eZOEPopupUtils.' + mode + '(' + n.node_id + ');');
tag.setAttribute('title', ed.getLang('browse') + ': ' + n.url_alias );
}
else
{
tag = document.createElement("span");
tag.setAttribute('title', n.url_alias );
}
tag.innerHTML = n.name;
td.appendChild( tag );
tr.appendChild( td );
td = document.createElement("td");
tag = document.createElement("span");
tag.innerHTML = n.class_name;
td.appendChild( tag );
tr.appendChild( td );
td = document.createElement("td");
var imageIndex = eZOEPopupUtils.indexOfImage( n, eZOEPopupUtils.settings.browseImageAlias );
if ( imageIndex !== -1 )
{
tag = document.createElement("span");
tag.className = 'image_preview';
var previewUrl = ed.settings.ez_root_url + encodeURI( n.data_map[ n.image_attributes[imageIndex] ].content[eZOEPopupUtils.settings.browseImageAlias].url )
tag.innerHTML += ' <a href="#">' + ed.getLang('preview.preview_desc') + '<img src="' + previewUrl + '" /></a>';
td.appendChild( tag );
hasImage = true;
}
tr.appendChild( td );
tr.className = classGenerator.call( this, n, hasImage, ed );
tbody.appendChild( tr );
emptyList = false;
} );
}
// Make sure int params that needs to be subtracted/added are native int's
var offset = eZOEPopupUtils.Int( data.content['offset'] ), limit = eZOEPopupUtils.Int( data.content['limit'] );
tr = document.createElement("tr"), td = document.createElement("td");
tr.appendChild( document.createElement("td") );
if ( offset > 0 )
{
tag = document.createElement("a");
tag.setAttribute('href', 'JavaScript:eZOEPopupUtils.' + fn + (offset - limit) + ');');
tag.innerHTML = '<< ' + ed.getLang('advanced.previous');
td.appendChild( tag );
}
tr.appendChild( td );
td = document.createElement("td");
td.setAttribute('colspan', '2');
if ( (offset + limit) < data.content['total_count'] )
{
tag = document.createElement("a");
tag.setAttribute('href', 'JavaScript:eZOEPopupUtils.' + fn + (offset + limit) + ');');
tag.innerHTML = ed.getLang('advanced.next') + ' >>';
td.appendChild( tag );
}
tr.appendChild( td );
tfoot.appendChild( tr );
}
if ( emptyList && emptyCallBack !== undefined && emptyCallBack.call !== undefined )
{
emptyCallBack.call( this, tbody, mode, ed );
}
return false;
},
searchCallBack : function( searchData )
{
// wrapper function for browseCallBack, called by ajax call in search()
var data = { 'content': '' };
if ( searchData && searchData.content !== '' )
{
data['content'] = {
'limit': searchData.content.SearchLimit,
'offset': searchData.content.SearchOffset,
'total_count': searchData.content.SearchCount,
'list': searchData.content.SearchResult
};
}
return eZOEPopupUtils.browseCallBack( data, 'search', function( tbody, mode, ed ){
// callback for use when result is empty
var tr = document.createElement("tr"), td = document.createElement("td"), tag = document.createElement("span");
tr.appendChild( document.createElement("td") );
tr.className = 'search-result-empty';
td.setAttribute('colspan', '3');
tag.innerHTML = ed.getLang('ez.empty_search_result').replace('<search_string>', jQuery('#SearchText').val() );
td.appendChild( tag );
tr.appendChild( td );
tbody.appendChild( tr );
} );
},
indexOfImage: function( jsonNode, alias )
{
if ( !alias ) alias = eZOEPopupUtils.settings.browseImageAlias;
var index = -1;
jQuery.each( jsonNode.image_attributes, function( i, attr )
{
if ( index === -1 && jsonNode.data_map[ attr ] && jsonNode.data_map[ attr ].content[ alias ] )
index = i;
});
return index;
},
// some reusable functions from ezcore
ie65: /MSIE [56]/.test( navigator.userAgent ),
Int: function(value, fallBack)
{
// Checks if value is a int, if not fallBack or 0 is returned
value = parseInt( value );
return isNaN( value ) ? ( fallBack !== undefined ? fallBack : 0 ) : value;
},
Float: function(value, fallBack)
{
// Checks if value is float, if not fallBack or 0 is returned
value = parseFloat( value );
return isNaN( value ) ? ( fallBack !== undefined ? fallBack : 0 ) : value;
},
min: function()
{
// Returns the lowest number, or null if none
var min = null;
for (var i = 0, a = arguments, l = a.length; i < l; i++)
if (min === null || min > a[i]) min = a[i];
return min;
}
};
| imadkaf/aYaville | ezpublish_legacy/extension/ezoe/design/standard/javascript/ezoe/popup_utils.js | JavaScript | gpl-2.0 | 39,510 |
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*************************************************************
*
* MathJax/localization/fi/FontWarnings.js
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Localization.addTranslation("fi","FontWarnings",{
version: "2.3",
isLoaded: true,
strings: {
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/fi/FontWarnings.js");
| shayzluf/lazoozweb | wiki/extensions/Math/modules/MathJax/unpacked/localization/fi/FontWarnings.js | JavaScript | gpl-2.0 | 1,060 |
var mkdirp = require('mkdirp');
var path = require('canonical-path');
module.exports = {
create: function(config) {
var currentVersion = config.get('currentVersion');
var docsBase = path.join(config.get('basePath'), config.get('rendering.outputFolder'), 'docs');
var versionDir = path.join(docsBase, currentVersion);
// create the folders for the current version
mkdirp.sync(versionDir);
}
};
| cloud-envy/famous-angular | docs-generation/processors/create-folders.js | JavaScript | mpl-2.0 | 408 |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'indent', 'bn', {
indent: 'ইনডেন্ট বাড়াও',
outdent: 'ইনডেন্ট কমাও'
} );
| nttuyen/task | task-management/src/main/resources/org/exoplatform/task/management/assets/ckeditorCustom/plugins/indent/lang/bn.js | JavaScript | lgpl-3.0 | 300 |
jQuery(function($){
$.supersized({
// Functionality
slideshow : 1, // Slideshow on/off
autoplay : 1, // Slideshow starts playing automatically
start_slide : 1, // Start slide (0 is random)
stop_loop : 0, // Pauses slideshow on last slide
random : 0, // Randomize slide order (Ignores start slide)
slide_interval : 12000, // Length between transitions
transition : 1, // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
transition_speed : 1000, // Speed of transition
new_window : 1, // Image links open in new window/tab
pause_hover : 0, // Pause slideshow on hover
keyboard_nav : 1, // Keyboard navigation on/off
performance : 1, // 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
image_protect : 1, // Disables image dragging and right click with Javascript
// Size & Position
min_width : 0, // Min width allowed (in pixels)
min_height : 0, // Min height allowed (in pixels)
vertical_center : 1, // Vertically center background
horizontal_center : 1, // Horizontally center background
fit_always : 0, // Image will never exceed browser width or height (Ignores min. dimensions)
fit_portrait : 1, // Portrait images will not exceed browser height
fit_landscape : 0, // Landscape images will not exceed browser width
// Components
slide_links : 'blank', // Individual links for each slide (Options: false, 'num', 'name', 'blank')
thumb_links : 0, // Individual thumb links for each slide
thumbnail_navigation : 0, // Thumbnail navigation
slides : [ // Slideshow Images
{image : './images/feat-bg1.jpg', title : '<div class="major">Apollo</div><div class="slidedescription">Quisque non magna ac tortor tincidunt posuere. Vestibulum luctus aliquet gravida. Etiam non dolor sit amet libero porttitor egestas quis sed urna.</div><ul class="footprints"><li><a href="">Our Work</a></li><li><a href="">Our Blog</a></li><li><a href="">Our People</a></li><ul>', thumb : '', url : '#'},
{image : './images/feat-bg6.jpg', title : '<div class="major">LIVE EPIC</div><div class="slidedescription">What a piece of work is a man, how noble in reason, how infinite in faculties, in form and moving how express and admirable, in action how like an angel, in apprehension how like a god.</div>', thumb : '', url : '#'},
{image : './images/feat-bg2.jpg', title : '<div class="major minor">… or lavishly</div><div class="slidedescription">As a space, Work Happy hosts events regularly with the intent to educate and grow our local creative community. From courses on web design and programming, classes on photography, to community meetups to help introduce creatives to other creatives. </div>', thumb : '', url : '#'},
{image : './images/feat-bg3.jpg', title : '<div class="major">Apollo</div><div class="slidedescription">Desks start at $75 a month part time or $125 full time. All Co-workers have access to all Work Happuy events and meetups. Desks are month to month and the facility does have a security system.</div>', thumb : '', url : '#'},
{image : './images/feat-bg4.jpg', title : '<div class="major">Apollo</div><div class="slidedescription">Desks start at $75 a month part time or $125 full time. All Co-workers have access to all Work Happuy events and meetups. Desks are month to month and the facility does have a security system.</div>', thumb : '', url : '#'},
{image : './images/feat-bg5.jpg', title : '<div class="major">Apollo</div><div class="slidedescription">Desks start at $75 a month part time or $125 full time. All Co-workers have access to all Work Happuy events and meetups. Desks are month to month and the facility does have a security system.</div>', thumb : '', url : '#'}
],
// Theme Options
progress_bar : 0, // Timer for each slide
mouse_scrub : 0
});
});
| sphrcl/murrayhillsuites.com | wp-content/themes/ic/scripts/supersized.images.js | JavaScript | mit | 4,420 |
var expect = require("chai").expect;
var sinon = require("sinon");
var chalk = require("chalk");
var ReadlineStub = require("../../helpers/readline");
var Base = require("../../../lib/prompts/base");
describe("`base` prompt (e.g. prompt helpers)", function() {
beforeEach(function() {
this.rl = new ReadlineStub();
this.base = new Base({
message: "foo bar",
name: "name"
}, this.rl );
});
it("`suffix` method should only add ':' if last char is a letter", function() {
expect(this.base.suffix("m:")).to.equal("m: ");
expect(this.base.suffix("m?")).to.equal("m? ");
expect(this.base.suffix("my question?")).to.equal("my question? ");
expect(this.base.suffix(chalk.bold("m"))).to.equal("\u001b[1mm:\u001b[22m ");
expect(chalk.stripColor(this.base.suffix(chalk.bold("m?")))).to.equal("m? ");
expect(this.base.suffix("m")).to.equal("m: ");
expect(this.base.suffix("M")).to.equal("M: ");
expect(this.base.suffix("m ")).to.equal("m ");
expect(this.base.suffix("9")).to.equal("9: ");
expect(this.base.suffix("9~")).to.equal("9~ ");
expect(this.base.suffix()).to.equal(": ");
});
it("should not point by reference to the entry `question` object", function() {
var question = {
message: "foo bar",
name: "name"
};
var base = new Base( question, this.rl );
expect(question).to.not.equal(base.opt);
expect(question.name).to.equal(base.opt.name);
expect(question.message).to.equal(base.opt.message);
});
});
| ehealthafrica-ci/Inquirer.js | test/specs/prompts/base.js | JavaScript | mit | 1,519 |