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
|
---|---|---|---|---|---|
/* -*- tab-width: 2; indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
File Name: 15.8.2.16.js
ECMA Section: 15.8.2.16 sin( x )
Description: return an approximation to the sine of the
argument. argument is expressed in radians
Author: [email protected]
Date: 7 july 1997
*/
var SECTION = "15.8.2.16";
var VERSION = "ECMA_1";
startTest();
var TITLE = "Math.sin(x)";
writeHeaderToLog( SECTION + " "+ TITLE);
new TestCase( SECTION,
"Math.sin.length",
1,
Math.sin.length );
new TestCase( SECTION,
"Math.sin()",
Number.NaN,
Math.sin() );
new TestCase( SECTION,
"Math.sin(null)",
0,
Math.sin(null) );
new TestCase( SECTION,
"Math.sin(void 0)",
Number.NaN,
Math.sin(void 0) );
new TestCase( SECTION,
"Math.sin(false)",
0,
Math.sin(false) );
new TestCase( SECTION,
"Math.sin('2.356194490192')",
0.7071067811865,
Math.sin('2.356194490192') );
new TestCase( SECTION,
"Math.sin(NaN)",
Number.NaN,
Math.sin(Number.NaN) );
new TestCase( SECTION,
"Math.sin(0)",
0,
Math.sin(0) );
new TestCase( SECTION,
"Math.sin(-0)",
-0,
Math.sin(-0));
new TestCase( SECTION,
"Math.sin(Infinity)",
Number.NaN,
Math.sin(Number.POSITIVE_INFINITY));
new TestCase( SECTION,
"Math.sin(-Infinity)",
Number.NaN,
Math.sin(Number.NEGATIVE_INFINITY));
new TestCase( SECTION,
"Math.sin(0.7853981633974)",
0.7071067811865,
Math.sin(0.7853981633974));
new TestCase( SECTION,
"Math.sin(1.570796326795)",
1,
Math.sin(1.570796326795));
new TestCase( SECTION,
"Math.sin(2.356194490192)",
0.7071067811865,
Math.sin(2.356194490192));
new TestCase( SECTION,
"Math.sin(3.14159265359)",
0,
Math.sin(3.14159265359));
test();
| kostaspl/SpiderMonkey38 | js/src/tests/ecma/Math/15.8.2.16.js | JavaScript | mpl-2.0 | 2,192 |
/*
* Copyright (C) 2016 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import TestUtils from 'react-dom/test-utils'
import AppointmentGroupList from 'jsx/calendar/scheduler/components/appointment_groups/AppointmentGroupList'
QUnit.module('AppointmentGroupList')
test('renders the AppointmentGroupList component', () => {
const appointmentGroup = {
appointments: [
{
child_events: [{user: {sortable_name: 'test'}}],
start_at: '2016-10-18T19:00:00Z',
end_at: '2016-10-18T110:00:00Z'
}
],
appointments_count: 1
}
const component = TestUtils.renderIntoDocument(
<AppointmentGroupList appointmentGroup={appointmentGroup} />
)
const appointmentGroupList = TestUtils.findRenderedDOMComponentWithClass(
component,
'AppointmentGroupList__List'
)
ok(appointmentGroupList)
})
test('renders renders reserved badge when someone is signed up in a slot', () => {
const appointmentGroup = {
appointments: [
{
child_events: [
{
user: {sortable_name: test}
}
],
start_at: '2016-10-18T19:00:00Z',
end_at: '2016-10-18T110:00:00Z'
},
{
child_events: [],
start_at: '2016-10-18T16:00:00Z',
end_at: '2016-10-18T17:00:00Z'
}
],
appointments_count: 2
}
const component = TestUtils.renderIntoDocument(
<AppointmentGroupList appointmentGroup={appointmentGroup} />
)
const reservedBadge = TestUtils.scryRenderedDOMComponentsWithClass(
component,
'AppointmentGroupList__Badge--reserved'
)[0]
ok(reservedBadge)
})
test('renders available badge when no one is signed up', () => {
const appointmentGroup = {
appointments: [
{
child_events: [],
start_at: '2016-10-18T19:00:00Z',
end_at: '2016-10-18T110:00:00Z'
},
{
child_events: [],
start_at: '2016-10-18T16:00:00Z',
end_at: '2016-10-18T17:00:00Z'
}
],
appointments_count: 2
}
const component = TestUtils.renderIntoDocument(
<AppointmentGroupList appointmentGroup={appointmentGroup} />
)
const availableBadge = TestUtils.scryRenderedDOMComponentsWithClass(
component,
'AppointmentGroupList__Badge--unreserved'
)[0]
ok(availableBadge)
})
test('renders correct user names', () => {
const appointmentGroup = {
appointments: [
{
child_events: [
{
user: {sortable_name: 'test1'}
}
],
start_at: '2016-10-18T19:00:00Z',
end_at: '2016-10-18T110:00:00Z'
},
{
child_events: [
{
user: {sortable_name: 'test2'}
}
],
start_at: '2016-10-18T16:00:00Z',
end_at: '2016-10-18T17:00:00Z'
}
],
appointments_count: 2,
participants_per_appointment: 1
}
const component = TestUtils.renderIntoDocument(
<AppointmentGroupList appointmentGroup={appointmentGroup} />
)
const appointmentGroupNames = TestUtils.scryRenderedDOMComponentsWithClass(
component,
'AppointmentGroupList__Appointment-label'
)
equal(appointmentGroupNames.length, 2)
equal(appointmentGroupNames[0].textContent, 'test1')
equal(appointmentGroupNames[1].textContent, 'test2')
})
test('renders correct group names', () => {
const appointmentGroup = {
appointments: [
{
child_events: [
{
group: {name: 'test1'}
}
],
start_at: '2016-10-18T19:00:00Z',
end_at: '2016-10-18T110:00:00Z'
},
{
child_events: [
{
group: {name: 'test2'}
}
],
start_at: '2016-10-18T16:00:00Z',
end_at: '2016-10-18T17:00:00Z'
}
],
appointments_count: 2,
participants_per_appointment: 1
}
const component = TestUtils.renderIntoDocument(
<AppointmentGroupList appointmentGroup={appointmentGroup} />
)
const appointmentGroupNames = TestUtils.scryRenderedDOMComponentsWithClass(
component,
'AppointmentGroupList__Appointment-label'
)
equal(appointmentGroupNames.length, 2)
equal(appointmentGroupNames[0].textContent, 'test1')
equal(appointmentGroupNames[1].textContent, 'test2')
})
test('renders "Available" at the end of the user list if more appointments are available for the slot', () => {
const appointmentGroup = {
appointments: [
{
child_events: [
{
user: {sortable_name: 'test1'}
}
],
start_at: '2016-10-18T19:00:00Z',
end_at: '2016-10-18T110:00:00Z',
child_events_count: 1
},
{
child_events: [
{
user: {sortable_name: 'test2'}
},
{
user: {sortable_name: 'test3'}
}
],
start_at: '2016-10-18T16:00:00Z',
end_at: '2016-10-18T17:00:00Z',
child_events_count: 2
}
],
appointments_count: 2,
participants_per_appointment: 2
}
const component = TestUtils.renderIntoDocument(
<AppointmentGroupList appointmentGroup={appointmentGroup} />
)
const appointmentGroupNames = TestUtils.scryRenderedDOMComponentsWithClass(
component,
'AppointmentGroupList__Appointment-label'
)
equal(appointmentGroupNames.length, 2)
equal(appointmentGroupNames[0].textContent, 'test1; Available')
equal(appointmentGroupNames[1].textContent, 'test2; test3')
})
test('renders date at start of datestring to accommodate multi-date events', () => {
const appointmentGroup = {
appointments: [
{
child_events: [
{
user: {sortable_name: 'test1'}
}
],
start_at: '2016-10-18T19:00:00Z',
end_at: '2016-10-19T110:00:00Z',
child_events_count: 1
},
{
child_events: [
{
user: {sortable_name: 'test2'}
},
{
user: {sortable_name: 'test3'}
}
],
start_at: '2016-10-19T16:00:00Z',
end_at: '2016-10-19T17:00:00Z',
child_events_count: 2
}
],
appointments_count: 2,
participants_per_appointment: 2
}
const component = TestUtils.renderIntoDocument(
<AppointmentGroupList appointmentGroup={appointmentGroup} />
)
const appointmentGroupNames = TestUtils.scryRenderedDOMComponentsWithClass(
component,
'AppointmentGroupList__Appointment-timeLabel'
)
equal(appointmentGroupNames.length, 2)
equal(appointmentGroupNames[0].textContent, 'Oct 18, 2016, 7pm to 12am')
equal(appointmentGroupNames[1].textContent, 'Oct 19, 2016, 4pm to 5pm')
})
| djbender/canvas-lms | spec/javascripts/jsx/calendar/scheduler/components/appointment_groups/AppointmentGroupListSpec.js | JavaScript | agpl-3.0 | 7,303 |
/**
* SPDX-FileCopyrightText: © 2014 Liferay, Inc. <https://liferay.com>
* SPDX-License-Identifier: LGPL-3.0-or-later
*/
if (!CKEDITOR.plugins.get('ae_selectionkeystrokes')) {
/**
* CKEditor plugin that simulates editor interaction events based on manual keystrokes. This
* can be used to trigger different reactions in the editor.
*
* @class CKEDITOR.plugins.ae_selectionkeystrokes
*/
CKEDITOR.plugins.add('ae_selectionkeystrokes', {
requires: 'ae_selectionregion',
/**
* Initialization of the plugin, part of CKEditor plugin lifecycle.
* The function adds a command to the editor for every defined selectionKeystroke
* in the configuration and maps it to the specified keystroke.
*
* @method init
* @param {Object} editor The current editor instance
*/
init(editor) {
if (editor.config.selectionKeystrokes) {
editor.config.selectionKeystrokes.forEach(
selectionKeystroke => {
const command = new CKEDITOR.command(editor, {
exec(editor) {
editor.fire('editorInteraction', {
manualSelection:
selectionKeystroke.selection,
nativeEvent: {},
selectionData: editor.getSelectionData(),
});
},
});
const commandName =
'selectionKeystroke' + selectionKeystroke.selection;
editor.addCommand(commandName, command);
editor.setKeystroke(
selectionKeystroke.keys,
commandName
);
}
);
}
},
});
}
| ambrinchaudhary/alloy-editor | src/plugins/selectionkeystrokes.js | JavaScript | lgpl-3.0 | 1,481 |
chrome.devtools.panels.create(
"CatX.FM",
"radio.png",
"panel.html",
function cb(panel) {
panel.onShown.addListener(function(win){ win.focus(); });
}
);
| akfish-archive/fm-terminal | devtool.js | JavaScript | lgpl-3.0 | 189 |
/**
* Created by Mike Pugh on 05/27/2014. MIT License.
*/
(function () {
'use strict';
var AngularGeoFire;
angular.module('angularGeoFire', []).factory('$geofire', [
'$q',
'$timeout',
'$rootScope',
'$log',
function ($q, $timeout, $rootScope, $log) {
return function (geoRef) {
$log.info('Constructing $geofire');
var gf = new AngularGeoFire($q, $timeout, $rootScope, geoRef);
return gf.construct();
};
}
]);
AngularGeoFire = function ($q, $timeout, $rootScope, geoRef) {
this._q = $q;
this._rootScope = $rootScope;
this._timeout = $timeout;
if (typeof geoRef === 'string') {
throw new Error('Please provide a Firebase reference instead of a URL');
}
this._geoRef = geoRef;
this._geoFire = new GeoFire(this._geoRef);
this._onPointsNearLocCallbacks = [];
this._onPointsNearId = [];
};
AngularGeoFire.prototype = {
construct: function () {
var self = this;
var object = {};
object.$set = function (key, location) {
var deferred = self._q.defer();
self._timeout(function () {
self._geoFire.set(key, location).then(function () {
deferred.resolve(null);
}).catch(function (error) {
deferred.reject(error);
});
});
return deferred.promise;
};
object.$remove = function (key) {
var deferred = self._q.defer();
self._timeout(function () {
self._geoFire.remove(key).then(function () {
deferred.resolve(null);
}).catch(function (error) {
deferred.reject(error);
});
});
return deferred.promise;
};
object.$get = function (key) {
var deferred = self._q.defer();
self._timeout(function () {
self._geoFire.get(key).then(function (location) {
deferred.resolve(location);
}).catch(function (error) {
deferred.reject(error);
});
});
return deferred.promise;
};
object.$query = function (queryCriteria) {
var _geoQuery = self._geoFire.query(queryCriteria);
return {
center: function () {
return _geoQuery.center();
},
radius: function () {
return _geoQuery.radius();
},
updateCriteria: function (newQueryCriteria) {
_geoQuery.updateCriteria(newQueryCriteria);
},
on: function (eventType, broadcastName) {
return _geoQuery.on(eventType, function (key, location, distance) {
self._rootScope.$broadcast(broadcastName, key, location, distance);
});
},
cancel: function () {
_geoQuery.cancel();
}
};
};
object.$distance = function (location1, location2) {
return self._geoFire.distance(location1, location2);
};
self._object = object;
return self._object;
}
};
}.call(this)); | alexu84/atmSurfingClient | www/lib/AngularGeoFire/src/angularGeoFire.js | JavaScript | unlicense | 3,043 |
/**
* @author kile / http://kile.stravaganza.org/
*/
var Cylinder = function (numSegs, topRad, botRad, height, topOffset, botOffset) {
THREE.Geometry.call(this);
var scope = this, i;
// VERTICES
// Top circle vertices
for (i = 0; i < numSegs; i++) {
v(
Math.sin(2 * 3.1415 * i / numSegs)*topRad,
Math.cos(2 * 3.1415 * i / numSegs)*topRad,
0);
}
// Bottom circle vertices
for (i = 0; i < numSegs; i++) {
v(
Math.sin(2 * 3.1415 * i / numSegs)*botRad,
Math.cos(2 * 3.1415 * i / numSegs)*botRad,
height);
}
// FACES
// Body
for (i = 0; i < numSegs; i++) {
f4(i, i + numSegs, numSegs + (i + 1) % numSegs, (i + 1) % numSegs, '#ff0000');
}
// Bottom circle
if (botRad != 0) {
v(0, 0, -topOffset);
for (i = numSegs; i < numSegs + (numSegs / 2); i++) {
f4(2 * numSegs,
(2 * i - 2 * numSegs) % numSegs,
(2 * i - 2 * numSegs + 1) % numSegs,
(2 * i - 2 * numSegs + 2) % numSegs);
}
}
// Top circle
if (topRad != 0) {
v(0, 0, height + topOffset);
for (i = numSegs + (numSegs / 2); i < 2 * numSegs; i++) {
f4( (2 * i - 2 * numSegs + 2) % numSegs + numSegs,
(2 * i - 2 * numSegs + 1) % numSegs + numSegs,
(2 * i - 2 * numSegs) % numSegs+numSegs,
2 * numSegs + 1);
}
}
this.computeCentroids();
this.computeNormals();
function v(x, y, z) {
scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
}
function f4(a, b, c, d) {
scope.faces.push( new THREE.Face4( a, b, c, d ) );
}
}
Cylinder.prototype = new THREE.Geometry();
Cylinder.prototype.constructor = Cylinder;
| ehelms/medipa_web | web/three.js/extras/primitives/Cylinder.js | JavaScript | apache-2.0 | 1,590 |
//Create Volume
var libpb=require('libprofitbricks')
libpb.setauth('username','password') // <---- Your username and password
var dcid='f355b51d-1c9c-4150-bc55-a616fe3bf437' // <--- Your data center id
var vol=new libpb.volume( {'name': 'My Favorite Volume',
'size': 80,
'bus': "VIRTIO",
'type': "HDD",
'licenceType': "UNKNOWN"})
libpb.createVolume(dcid,vol)
| StackPointCloud/profitbricks-sdk-nodejs | examples/createvolume.js | JavaScript | apache-2.0 | 465 |
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 7.6.1-4-6
description: >
Allow reserved words as property names by set function within an
object, verified with hasOwnProperty: continue, for, switch
---*/
var test0 = 0, test1 = 1, test2 = 2;
var tokenCodes = {
set continue(value){
test0 = value;
},
get continue(){
return test0;
},
set for(value){
test1 = value;
},
get for(){
return test1;
},
set switch(value){
test2 = value;
},
get switch(){
return test2;
}
};
var arr = [
'continue',
'for',
'switch'
];
for(var p in tokenCodes) {
for(var p1 in arr) {
if(arr[p1] === p) {
assert(tokenCodes.hasOwnProperty(arr[p1]), 'tokenCodes.hasOwnProperty(arr[p1]) !== true');
}
}
}
| m0ppers/arangodb | 3rdParty/V8/V8-5.0.71.39/test/test262/data/test/language/reserved-words/7.6.1-4-6.js | JavaScript | apache-2.0 | 1,258 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The length property of splice does not have the attribute DontDelete
es5id: 15.4.4.12_A5.2
description: Checking use hasOwnProperty, delete
---*/
//CHECK#1
if (Array.prototype.splice.hasOwnProperty('length') !== true) {
$ERROR('#1: Array.prototype.splice.hasOwnProperty(\'length\') === true. Actual: ' + (Array.prototype.splice.hasOwnProperty('length')));
}
delete Array.prototype.splice.length;
//CHECK#2
if (Array.prototype.splice.hasOwnProperty('length') !== false) {
$ERROR('#2: delete Array.prototype.splice.length; Array.prototype.splice.hasOwnProperty(\'length\') === false. Actual: ' + (Array.prototype.splice.hasOwnProperty('length')));
}
//CHECK#3
if (Array.prototype.splice.length === undefined) {
$ERROR('#3: delete Array.prototype.splice.length; Array.prototype.splice.length !== undefined');
}
| m0ppers/arangodb | 3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/Array/prototype/splice/S15.4.4.12_A5.2.js | JavaScript | apache-2.0 | 963 |
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
Vue.config.productionTip = false
Vue.prototype.$http = axios
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
| alexlib/docker-ubuntu-vnc-desktop | web/src/main.js | JavaScript | apache-2.0 | 414 |
foam.CLASS({
package: 'foam.nanos.alarming',
name: 'AlarmConfigOMNameSink',
extends: 'foam.dao.ProxySink',
javaImports: [
'foam.util.SafetyUtil'
],
methods: [
{
name: 'put',
javaCode: `
getDelegate().put(obj, sub);
AlarmConfig config = (AlarmConfig) obj;
if ( config == null ) return;
if ( ! SafetyUtil.isEmpty(config.getPreRequest()) ) {
dao_.put(new OMName(config.getPreRequest()));
}
if ( ! SafetyUtil.isEmpty(config.getPostRequest()) ) {
dao_.put(new OMName(config.getPostRequest()));
}
if ( ! SafetyUtil.isEmpty(config.getTimeOutRequest()) ) {
dao_.put(new OMName(config.getTimeOutRequest()));
}
`
}
],
axioms: [
{
buildJavaClass: function(cls) {
cls.extras.push(`
protected foam.dao.DAO dao_;
public AlarmConfigOMNameSink(foam.core.X x, foam.dao.Sink delegate, foam.dao.DAO dao) {
super(x, delegate);
dao_ = dao;
}
`);
}
}
]
});
| jacksonic/vjlofvhjfgm | src/foam/nanos/alarming/AlarmConfigOMNameSink.js | JavaScript | apache-2.0 | 1,081 |
const pmc = zrequire('pm_conversations');
run_test('partners', () => {
const user1_id = 1;
const user2_id = 2;
const user3_id = 3;
pmc.set_partner(user1_id);
pmc.set_partner(user3_id);
assert.equal(pmc.is_partner(user1_id), true);
assert.equal(pmc.is_partner(user2_id), false);
assert.equal(pmc.is_partner(user3_id), true);
});
zrequire("people");
run_test('insert_recent_private_message', () => {
const params = {
recent_private_conversations: [
{user_ids: [11, 2],
max_message_id: 150,
},
{user_ids: [1],
max_message_id: 111,
},
{user_ids: [],
max_message_id: 7,
},
],
};
people.initialize_current_user(15);
pmc.recent.initialize(params);
assert.deepEqual(pmc.recent.get(), [
{user_ids_string: '2,11', max_message_id: 150},
{user_ids_string: '1', max_message_id: 111},
{user_ids_string: '15', max_message_id: 7},
]);
pmc.recent.insert([1], 1001);
pmc.recent.insert([2], 2001);
pmc.recent.insert([1], 3001);
// try to backdate user1's latest message
pmc.recent.insert([1], 555);
assert.deepEqual(pmc.recent.get(), [
{user_ids_string: '1', max_message_id: 3001},
{user_ids_string: '2', max_message_id: 2001},
{user_ids_string: '2,11', max_message_id: 150},
{user_ids_string: '15', max_message_id: 7},
]);
assert.deepEqual(pmc.recent.get_strings(), ['1', '2', '2,11', '15']);
});
| timabbott/zulip | frontend_tests/node_tests/pm_conversations.js | JavaScript | apache-2.0 | 1,560 |
/**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
foam.CLASS({
package: 'foam.java',
name: 'PropertyInfo',
extends: 'foam.java.Class',
properties: [
['anonymous', true],
'propName',
'propShortName',
'propAliases',
'compare',
'comparePropertyToObject',
'comparePropertyToValue',
{
name: 'getAliasesBody',
expression: function() {
var b = 'new String[] {';
for ( var i = 0 ; i < this.propAliases.length ; i++ ) {
b += '"' + this.propAliases[i] + '"';
if ( i < this.propAliases.length-1 ) b += ', ';
}
return b + '};';
}
},
{
class: 'Boolean',
name: 'networkTransient'
},
{
class: 'Boolean',
name: 'externalTransient'
},
{
class: 'Boolean',
name: 'storageTransient'
},
{
class: 'Boolean',
name: 'storageOptional'
},
{
class: 'Boolean',
name: 'clusterTransient'
},
{
class: 'Boolean',
name: 'readPermissionRequired'
},
{
class: 'Boolean',
name: 'writePermissionRequired'
},
{
class: 'Boolean',
documentation: 'define a property is a XML attribute. eg <foo id="XMLAttribute"></foo>',
name: 'xmlAttribute'
},
{
class: 'Boolean',
documentation: 'define a property is a XML textNode. eg <foo id="1">textNode</foo>',
name: 'xmlTextNode'
},
{
class: 'String',
name: 'sqlType'
},
{
name: 'getterName',
expression: function(propName) {
return 'get' + foam.String.capitalize(propName);
}
},
{
name: 'setterName',
expression: function(propName) {
return 'set' + foam.String.capitalize(propName);
}
},
{
name: 'clearName',
expression: function(propName) {
return 'clear' + foam.String.capitalize(propName);
}
},
{
class: 'Boolean',
name: 'includeInID'
},
{
class: 'Boolean',
name: 'includeInDigest',
value: true
},
{
class: 'Boolean',
name: 'includeInSignature',
value: true
},
{
class: 'Boolean',
name: 'containsPII'
},
{
class: 'Boolean',
name: 'containsDeletablePII'
},
'sourceCls',
'propType',
'propValue',
'propRequired',
'jsonParser',
'csvParser',
'cloneProperty',
'queryParser',
'diffProperty',
'validateObj',
'toCSV',
'toCSVLabel',
'fromCSVLabelMapping',
'formatJSON',
{
class: 'Boolean',
name: 'sheetsOutput',
documentation: 'The sheetsOutput specifies if property shoud be written to Google Sheet on import. eg on Transaction import in case there is Status column transaction\'s status will be written there'
},
{
name: 'methods',
factory: function() {
var fullName = this.sourceCls.package ? this.sourceCls.package + '.' + this.sourceCls.name : this.sourceCls.name;
var m = [
{
name: 'getName',
visibility: 'public',
type: 'String',
body: 'return "' + this.propName + '";'
},
{
name: 'get_',
type: this.propType,
visibility: 'public',
args: [{ name: 'o', type: 'Object' }],
body: 'return ((' + fullName + ') o).' + this.getterName + '();'
},
{
name: 'set',
type: 'void',
visibility: 'public',
args: [{ name: 'o', type: 'Object' }, { name: 'value', type: 'Object' }],
body: '((' + fullName + ') o).' + this.setterName + '(cast(value));'
},
{
name: 'clear',
type: 'void',
visibility: 'public',
args: [{ name: 'o', type: 'Object' }],
body: '((' + fullName + ') o).' + this.clearName + '();'
},
{
name: 'isSet',
visibility: 'public',
type: 'boolean',
args: [{ name: 'o', type: 'Object' }],
body: `return ((${fullName}) o).${this.propName}IsSet_;`
}
];
var primitiveType = ['boolean', 'long', 'byte', 'double','float','short','int'];
if ( this.propType == 'java.util.Date' ||
! ( primitiveType.includes(this.propType) || this.propType == 'Object' || this.propType == 'String') ){
m.push({
name: 'cast',
type: this.propType,
visibility: 'public',
args: [{ name: 'o', type: 'Object' }],
body: 'return ' + ( this.propType == "Object" ? 'o;' : '( ' + this.propType + ') o;')
});
}
if ( this.propType == 'java.util.Date' ||
this.propType == 'String' ||
! ( primitiveType.includes(this.propType)|| this.propType == 'Object' || this.extends == 'foam.core.AbstractFObjectPropertyInfo' || this.extends == 'foam.core.AbstractFObjectArrayPropertyInfo') ){
m.push({
name: 'getSQLType',
visibility: 'public',
type: 'String',
body: 'return "' + this.sqlType + '";'
});
}
if ( this.propType == 'java.util.Date' ||
this.propType == 'String' ||
this.propType == 'Object' ||
! ( primitiveType.includes(this.propType) ) ){
m.push({
name: 'get',
visibility: 'public',
type: 'Object',
args: [{ name: 'o', type: 'Object' }],
body: 'return get_(o);'
});
m.push({
name: 'jsonParser',
type: 'foam.lib.parse.Parser',
visibility: 'public',
body: 'return ' + ( this.jsonParser ? this.jsonParser : null ) + ';'
});
}
if ( ! ( primitiveType.includes(this.propType) || this.propType == 'java.util.Date' || this.propType == 'String' || this.propType == 'Object' ) ) {
//TODO add support for special type.
// || this.propType == 'java.util.Map' || this.propType == 'java.util.List'
//TODO add support for subtype.
// this.propType == 'foam.core.AbstractFObjectPropertyInfo' || this.propType == 'foam.core.AbstractClassPropertyInfo') ||
// this.propType == 'foam.core.AbstractObjectPropertyInfo'
m.push({
name: 'getValueClass',
visibility: 'public',
type: 'Class',
body: `return ${this.propType}.class;`
});
// m.push({
// name: 'jsonParser',
// type: 'foam.lib.parse.Parser',
// visibility: 'public',
// body: 'return ' + ( this.jsonParser ? this.jsonParser : null ) + ';'
// });
m.push({
name: 'queryParser',
type: 'foam.lib.parse.Parser',
visibility: 'public',
body: 'return ' + ( this.queryParser ? this.queryParser : null ) + ';'
});
m.push({
name: 'csvParser',
type: 'foam.lib.parse.Parser',
visibility: 'public',
body: 'return ' + ( this.csvParser ? this.csvParser : null ) + ';'
});
}
if ( this.compare !== '' ) {
m.push({
name: 'compare',
type: 'int',
visibility: 'public',
args: [{ name: 'o1', type: 'Object' }, { name: 'o2', type: 'Object' }],
body: this.compare,
});
}
if ( this.comparePropertyToObject !== '' ) {
m.push({
name: 'comparePropertyToObject',
type: 'int',
visibility: 'public',
args: [{ name: 'key', type: 'Object' }, { name: 'o', type: 'Object' }],
body: this.comparePropertyToObject,
});
}
if ( this.comparePropertyToValue !== '' ) {
m.push({
name: 'comparePropertyToValue',
type: 'int',
visibility: 'public',
args: [{ name: 'key', type: 'Object' }, { name: 'value', type: 'Object' }],
body: this.comparePropertyToValue,
});
}
if ( ! ( primitiveType.includes(this.propType) || this.propType == 'java.util.Date' || this.propType == 'String' || this.propType == 'Object' || this.extends == 'foam.core.AbstractFObjectPropertyInfo' || this.extends == 'foam.core.AbstractFObjectArrayPropertyInfo') ) {
m.push({
name: 'isDefaultValue',
visibility: 'public',
type: 'boolean',
args: [{ name: 'o', type: 'Object' }],
/* TODO: revise when/if expression support is added to Java */
body: `return foam.util.SafetyUtil.compare(get_(o), ${this.propValue}) == 0;`
});
// TODO: We could reduce the amount a Enum PropertyInfo code we output
if ( this.extends != 'foam.core.AbstractEnumPropertyInfo' ) {
m.push({
name: 'format',
visibility: 'public',
type: 'void',
args: [
{
name: 'formatter',
type: 'foam.lib.formatter.FObjectFormatter'
},
{
name: 'obj',
type: 'foam.core.FObject'
}
],
body: 'formatter.output(get_(obj));'
});
}
}
if ( this.networkTransient ) {
m.push({
name: 'getNetworkTransient',
type: 'boolean',
visibility: 'public',
body: 'return ' + this.networkTransient + ';'
});
}
if ( this.externalTransient ) {
m.push({
name: 'getExternalTransient',
type: 'boolean',
visibility: 'public',
body: 'return ' + this.externalTransient + ';'
});
}
if ( this.storageTransient ) {
m.push({
name: 'getStorageTransient',
type: 'boolean',
visibility: 'public',
body: 'return ' + this.storageTransient + ';'
});
}
if ( this.storageOptional ) {
m.push({
name: 'getStorageOptional',
type: 'boolean',
visibility: 'public',
body: 'return ' + this.storageOptional + ';'
});
}
if ( this.clusterTransient ) {
m.push({
name: 'getClusterTransient',
type: 'boolean',
visibility: 'public',
body: 'return ' + this.clusterTransient + ';'
});
}
if ( this.readPermissionRequired ) {
m.push({
name: 'getReadPermissionRequired',
type: 'boolean',
visibility: 'public',
body: 'return ' + this.readPermissionRequired + ';'
});
}
if ( this.writePermissionRequired ) {
m.push({
name: 'getWritePermissionRequired',
type: 'boolean',
visibility: 'public',
body: 'return ' + this.writePermissionRequired + ';'
});
}
if ( this.xmlAttribute ) {
m.push({
name: 'getXMLAttribute',
type: 'boolean',
visibility: 'public',
body: 'return ' + this.xmlAttribute + ';'
});
}
if ( this.xmlTextNode ) {
m.push({
name: 'getXMLTextNode',
type: 'boolean',
visibility: 'public',
body: 'return ' + this.xmlTextNode + ';'
});
}
if ( this.propRequired ) {
m.push({
name: 'getRequired',
visibility: 'public',
type: 'boolean',
body: 'return ' + Boolean(this.propRequired) + ';'
});
}
if ( this.validateObj ) {
m.push({
name: 'validateObj',
visibility: 'public',
type: 'void',
args: [
{ name: 'x', type: 'foam.core.X' },
{ name: 'obj', type: 'foam.core.FObject' }
],
body: this.validateObj
});
}
if ( this.propShortName ) {
m.push({
name: 'getShortName',
visibility: 'public',
type: 'String',
body: this.propShortName ?
'return "' + this.propShortName + '";' :
'return null;'
});
}
if ( this.propAliases.length ) {
m.push({
name: 'getAliases',
visibility: 'public',
type: 'String[]',
body: 'return ' + this.getAliasesBody
});
}
if ( this.cloneProperty != null ) {
m.push({
name: 'cloneProperty',
visibility: 'public',
type: 'void',
args: [{ type: 'foam.core.FObject', name: 'source' },
{ type: 'foam.core.FObject', name: 'dest' }],
body: this.cloneProperty
});
}
if ( this.diffProperty != null ) {
m.push({
name: 'diff',
visibility: 'public',
type: 'void',
args: [{ type: 'foam.core.FObject', name: 'o1' },
{ type: 'foam.core.FObject', name: 'o2' },
{ type: 'java.util.Map', name: 'diff' },
{ type: 'foam.core.PropertyInfo', name: 'prop' }],
body: this.diffProperty
});
}
// default value is true, only generate if value is false
if ( ! this.includeInDigest ) {
m.push({
name: 'includeInDigest',
visibility: 'public',
type: 'boolean',
body: `return ${this.includeInDigest};`
});
}
if ( this.includeInID ) {
m.push({
name: 'includeInID',
visibility: 'public',
type: 'boolean',
body: 'return true;'
});
}
// default value is true, only generate if value is false
if ( ! this.includeInSignature ) {
m.push({
name: 'includeInSignature',
visibility: 'public',
type: 'boolean',
body: `return ${this.includeInSignature};`
});
}
if ( this.containsPII ) {
m.push({
name: 'containsPII',
visibility: 'public',
type: 'boolean',
body: `return ${this.containsPII};`
});
}
if ( this.containsDeletablePII ) {
m.push({
name: 'containsDeletablePII',
visibility: 'public',
type: 'boolean',
body: `return ${this.containsDeletablePII};`
});
}
if ( this.sheetsOutput ) {
m.push({
name: 'getSheetsOutput',
type: 'boolean',
visibility: 'public',
body: 'return ' + this.sheetsOutput + ';'
});
}
if ( this.formatJSON != null ) {
m.push({
name: 'formatJSON',
type: 'void',
visibility: 'public',
args: [
{
name: 'formatter',
type: 'foam.lib.formatter.FObjectFormatter'
},
{
name: 'obj',
type: 'foam.core.FObject'
}
],
body: this.formatJSON + ';'
});
}
return m;
}
}
]
});
| jacksonic/vjlofvhjfgm | src/foam/java/PropertyInfo.js | JavaScript | apache-2.0 | 16,398 |
/// 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.2.3.7-5-b-70",
path: "TestCases/chapter15/15.2/15.2.3/15.2.3.7/15.2.3.7-5-b-70.js",
description: "Object.defineProperties - 'configurable' property of 'descObj' is own accessor property without a get function that overrides an inherited accessor property (8.10.5 step 4.a)",
test: function testcase() {
var obj = {};
var proto = {};
Object.defineProperty(proto, "configurable", {
get: function () {
return true;
}
});
var Con = function () { };
Con.prototype = proto;
var descObj = new Con();
Object.defineProperty(descObj, "configurable", {
set: function () { }
});
Object.defineProperties(obj, {
prop: descObj
});
var result1 = obj.hasOwnProperty("prop");
delete obj.prop;
var result2 = obj.hasOwnProperty("prop");
return result1 === true && result2 === true;
},
precondition: function prereq() {
return fnExists(Object.defineProperties) && fnExists(Object.defineProperty);
}
});
| hnafar/IronJS | Src/Tests/ietestcenter/chapter15/15.2/15.2.3/15.2.3.7/15.2.3.7-5-b-70.js | JavaScript | apache-2.0 | 2,708 |
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var Q = require('q'),
path = require('path'),
rewire = require('rewire'),
platformRoot = '../../template',
testPath = 'testpath',
buildPath = path.join(platformRoot, 'cordova', 'build'),
prepare = require(platformRoot + '/cordova/lib/prepare.js'),
build = rewire(platformRoot + '/cordova/lib/build.js');
var utils = require(platformRoot + '/cordova/lib/utils');
var package = require(platformRoot + '/cordova/lib/package');
var AppxManifest = require(platformRoot + '/cordova/lib/AppxManifest');
var MSBuildTools = require(platformRoot + '/cordova/lib/MSBuildTools');
function createFindAvailableVersionMock(version, path, buildSpy) {
build.__set__('MSBuildTools.findAvailableVersion', function() {
return Q.resolve({
version: version,
path: path,
buildProject: function (solutionFile, buildType, buildArch) {
if (typeof buildSpy === 'function') {
buildSpy(solutionFile, buildType, buildArch);
}
return Q.reject(); // rejecting here to stop build process
}
});
});
}
function createFindAllAvailableVersionsMock(versionSet) {
build.__set__('MSBuildTools.findAllAvailableVersions', function() {
return Q.resolve(versionSet);
});
}
function createConfigParserMock(winVersion, phoneVersion) {
build.__set__('ConfigParser', function() {
return {
getPreference: function(prefName) {
switch (prefName) {
case 'windows-target-version':
return winVersion;
case 'windows-phone-target-version':
return phoneVersion;
}
},
getWindowsTargetVersion: function() {
return winVersion;
},
getWindowsPhoneTargetVersion: function() {
return phoneVersion;
}
};
});
}
describe('run method', function() {
var findAvailableVersionOriginal,
findAllAvailableVersionsOriginal,
configParserOriginal;
beforeEach(function () {
findAvailableVersionOriginal = build.__get__('MSBuildTools.findAvailableVersion');
findAllAvailableVersionsOriginal = build.__get__('MSBuildTools.findAllAvailableVersions');
configParserOriginal = build.__get__('ConfigParser');
var originalBuildMethod = build.run;
spyOn(build, 'run').andCallFake(function () {
// Bind original build to custom 'this' object to mock platform's locations property
return originalBuildMethod.apply({locations: {www: 'some/path'}}, arguments);
});
spyOn(utils, 'isCordovaProject').andReturn(true);
spyOn(prepare, 'applyPlatformConfig');
spyOn(prepare, 'updateBuildConfig');
spyOn(package, 'getPackage').andReturn(Q({}));
spyOn(AppxManifest, 'get').andReturn({
getIdentity: function () {
return { setPublisher: function () {} };
},
write: function () {}
});
});
afterEach(function() {
build.__set__('MSBuildTools.findAvailableVersion', findAvailableVersionOriginal);
build.__set__('MSBuildTools.findAllAvailableVersions', findAllAvailableVersionsOriginal);
build.__set__('ConfigParser', configParserOriginal);
});
it('spec.1 should reject if not launched from project directory', function(done) {
var rejectSpy = jasmine.createSpy(),
buildSpy = jasmine.createSpy();
// utils.isCordovaProject is a spy, so we can call andReturn directly on it
utils.isCordovaProject.andReturn(false);
createFindAllAvailableVersionsMock([{version: '14.0', buildProject: buildSpy, path: testPath }]);
build.run([ 'node', buildPath, '--release', '--debug' ])
.fail(rejectSpy)
.finally(function() {
expect(rejectSpy).toHaveBeenCalled();
expect(buildSpy).not.toHaveBeenCalled();
done();
});
});
it('spec.2 should throw if both debug and release args specified', function() {
var buildSpy = jasmine.createSpy();
createFindAvailableVersionMock('14.0', testPath, buildSpy);
expect(function () {
build.run({release: true, debug: true});
}).toThrow();
});
it('spec.3 should throw if both phone and win args specified', function() {
var buildSpy = jasmine.createSpy();
createFindAvailableVersionMock('14.0', testPath, buildSpy);
expect(function () {
build.run({argv: [ '--phone', '--win' ]});
}).toThrow();
});
it('should respect build configuration from \'buildConfig\' option', function (done) {
createFindAllAvailableVersionsMock([{version: '14.0', buildProject: jasmine.createSpy(), path: testPath }]);
var buildConfigPath = path.resolve(__dirname, 'fixtures/fakeBuildConfig.json');
build.run({ buildConfig: buildConfigPath })
.finally(function() {
expect(prepare.updateBuildConfig).toHaveBeenCalled();
var buildOpts = prepare.updateBuildConfig.calls[0].args[0];
var buildConfig = require(buildConfigPath).windows.debug;
expect(buildOpts.packageCertificateKeyFile).toBeDefined();
expect(buildOpts.packageCertificateKeyFile)
.toEqual(path.resolve(path.dirname(buildConfigPath), buildConfig.packageCertificateKeyFile));
['packageThumbprint', 'publisherId'].forEach(function (key) {
expect(buildOpts[key]).toBeDefined();
expect(buildOpts[key]).toEqual(buildConfig[key]);
});
done();
});
});
it('spec.4 should call buildProject of MSBuildTools with buildType = "release" if called with --release argument', function(done) {
var buildSpy = jasmine.createSpy().andCallFake(function (solutionFile, buildType, buildArch) {
expect(buildType).toBe('release');
});
createFindAllAvailableVersionsMock([{version: '14.0', buildProject: buildSpy, path: testPath }]);
build.run({ release: true })
.finally(function() {
expect(buildSpy).toHaveBeenCalled();
done();
});
});
it('spec.5 should call buildProject of MSBuildTools with buildType = "debug" if called without arguments', function(done) {
var buildSpy = jasmine.createSpy().andCallFake(function (solutionFile, buildType, buildArch) {
expect(buildType).toBe('debug');
});
createFindAllAvailableVersionsMock([{version: '14.0', buildProject: buildSpy, path: testPath }]);
build.run([ 'node', buildPath ])
.finally(function() {
expect(buildSpy).toHaveBeenCalled();
done();
});
});
it('spec.6 should call buildProject of MSBuildTools with buildArch = "arm" if called with --archs="arm" argument', function(done) {
var buildSpy = jasmine.createSpy().andCallFake(function (solutionFile, buildType, buildArch) {
expect(buildArch).toBe('arm');
});
createFindAllAvailableVersionsMock([{version: '14.0', buildProject: buildSpy, path: testPath }]);
build.run({ archs: 'arm' })
.finally(function() {
expect(buildSpy).toHaveBeenCalled();
done();
});
});
it('spec.7 should call buildProject of MSBuildTools once for all architectures if called with --archs="arm x86 x64 anycpu" argument', function(done) {
var armBuild = jasmine.createSpy(),
x86Build = jasmine.createSpy(),
x64Build = jasmine.createSpy(),
anyCpuBuild = jasmine.createSpy();
createFindAllAvailableVersionsMock([
{
version: '14.0',
path: testPath,
buildProject: function(solutionFile, buildType, buildArch) {
expect(buildArch).toMatch(/^arm$|^any\s?cpu$|^x86$|^x64$/);
switch (buildArch) {
case 'arm':
armBuild();
return Q();
case 'x86':
x86Build();
return Q();
case 'anycpu':
case 'any cpu':
anyCpuBuild();
return Q();
case 'x64':
x64Build();
return Q();
default:
return Q.reject();
}
}
}]);
build.run({ archs: 'arm x86 x64 anycpu', argv: ['--phone'] })
.finally(function() {
expect(armBuild).toHaveBeenCalled();
expect(x86Build).toHaveBeenCalled();
expect(x64Build).toHaveBeenCalled();
expect(anyCpuBuild).toHaveBeenCalled();
done();
});
});
it('spec.8 should fail buildProject if built with MSBuildTools version 4.0', function(done) {
var buildSpy = jasmine.createSpy(),
errorSpy = jasmine.createSpy();
createFindAllAvailableVersionsMock([{version: '4.0', buildProject: buildSpy, path: testPath }]);
createConfigParserMock('8.0');
build.run({argv: ['--win']})
.fail(function(error) {
errorSpy();
expect(error).toBeDefined();
})
.finally(function() {
expect(errorSpy).toHaveBeenCalled();
expect(buildSpy).not.toHaveBeenCalled();
done();
});
});
it('spec.9 should call buildProject of MSBuildTools if built for windows 8.1', function(done) {
var buildSpy = jasmine.createSpy();
createFindAllAvailableVersionsMock([{version: '14.0', buildProject: buildSpy, path: testPath }]);
createConfigParserMock('8.1');
build.run({argv: ['--win']})
.finally(function() {
expect(buildSpy).toHaveBeenCalled();
done();
});
});
it('spec.10 should throw an error if windows-target-version has unsupported value', function(done) {
var buildSpy = jasmine.createSpy(),
errorSpy = jasmine.createSpy();
createFindAvailableVersionMock('14.0', testPath, buildSpy);
createConfigParserMock('unsupported value here');
build.run({argv: ['--win']})
.fail(function(error) {
errorSpy();
expect(error).toBeDefined();
})
.finally(function() {
expect(errorSpy).toHaveBeenCalled();
expect(buildSpy).not.toHaveBeenCalled();
done();
});
});
it('spec.11 should call buildProject of MSBuildTools if built for windows phone 8.1', function(done) {
var buildSpy = jasmine.createSpy();
createFindAllAvailableVersionsMock([{version: '14.0', buildProject: buildSpy, path: testPath }]);
createConfigParserMock(null, '8.1');
build.run({argv: ['--phone']})
.finally(function() {
expect(buildSpy).toHaveBeenCalled();
done();
});
});
it('spec.12 should throw an error if windows-phone-target-version has unsupported value', function(done) {
var buildSpy = jasmine.createSpy(),
errorSpy = jasmine.createSpy();
createFindAvailableVersionMock('14.0', testPath, buildSpy);
createConfigParserMock(null, 'unsupported value here');
build.run({argv: ['--phone']})
.fail(function(error) {
errorSpy();
expect(error).toBeDefined();
})
.finally(function() {
expect(errorSpy).toHaveBeenCalled();
expect(buildSpy).not.toHaveBeenCalled();
done();
});
});
it('spec.13 should be able to override target via --appx parameter', function(done) {
var buildSpy = jasmine.createSpy().andCallFake(function(solutionFile, buildType, buildArch) {
// check that we build Windows 10 and not Windows 8.1
expect(solutionFile.toLowerCase()).toMatch('cordovaapp.windows10.jsproj');
});
createFindAllAvailableVersionsMock([{version: '14.0', buildProject: buildSpy, path: testPath }]);
// provision config to target Windows 8.1
createConfigParserMock('8.1', '8.1');
// explicitly specify Windows 10 as target
build.run({argv: ['--appx=uap']})
.finally(function() {
expect(buildSpy).toHaveBeenCalled();
done();
});
});
it('spec.14 should use user-specified msbuild if VSINSTALLDIR variable is set', function (done) {
var customMSBuildPath = '/some/path';
var msBuildBinPath = path.join(customMSBuildPath, 'MSBuild/15.0/Bin');
var customMSBuildVersion = '15.0';
process.env.VSINSTALLDIR = customMSBuildPath;
spyOn(MSBuildTools, 'getMSBuildToolsAt')
.andReturn(Q({
path: customMSBuildPath,
version: customMSBuildVersion,
buildProject: jasmine.createSpy('buildProject').andReturn(Q())
}));
var fail = jasmine.createSpy('fail');
build.run({})
.fail(fail)
.finally(function() {
expect(fail).not.toHaveBeenCalled();
expect(MSBuildTools.getMSBuildToolsAt).toHaveBeenCalledWith(msBuildBinPath);
delete process.env.VSINSTALLDIR;
done();
});
});
it('spec.15 should choose latest version if there are multiple versions available with minor version difference', function(done) {
var fail = jasmine.createSpy('fail');
var buildTools14 = {version: '14.0', buildProject: jasmine.createSpy('buildTools14'), path: testPath };
var buildTools15 = {version: '15.0', buildProject: jasmine.createSpy('buildTools15'), path: testPath };
var buildTools151 = {version: '15.1', buildProject: jasmine.createSpy('buildTools151'), path: testPath };
createFindAllAvailableVersionsMock([buildTools14, buildTools15, buildTools151]);
// explicitly specify Windows 10 as target
build.run({argv: ['--appx=uap']})
.fail(fail)
.finally(function() {
expect(fail).not.toHaveBeenCalled();
expect(buildTools151.buildProject).toHaveBeenCalled();
done();
});
});
});
| dpogue/cordova-windows | spec/unit/build.spec.js | JavaScript | apache-2.0 | 15,415 |
/**
* Copyright (c) 2014, 2016, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
define(["ojs/ojcore","ojs/ojprogressbar","ojs/ojtree","ojs/ojtoolbar","ojs/ojpopup","ojs/ojmenu","ojs/ojradioset","ojs/ojtrain","ojs/ojtabs","ojs/ojcollapsible","ojs/ojdialog","ojs/ojaccordion","ojs/ojcheckboxset","ojs/ojinputtext","ojs/ojradiocheckbox","ojs/ojinputnumber","ojs/ojconveyorbelt","ojs/ojbutton"],function(a){return a}); | charlier-shoe/2fauth | frontend/js/libs/oj/v2.1.0/min/ojcomponents.js | JavaScript | apache-2.0 | 456 |
/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 0.12.0
*/
/**
* Config is a utility used within an Object to allow the implementer to maintain a list of local configuration properties and listen for changes to those properties dynamically using CustomEvent. The initial values are also maintained so that the configuration can be reset at any given point to its initial state.
* @class YAHOO.util.Config
* @constructor
* @param {Object} owner The owner Object to which this Config Object belongs
*/
YAHOO.util.Config = function(owner) {
if (owner) {
this.init(owner);
} else {
YAHOO.log("No owner specified for Config object", "error");
}
};
YAHOO.util.Config.prototype = {
/**
* Object reference to the owner of this Config Object
* @property owner
* @type Object
*/
owner : null,
/**
* Boolean flag that specifies whether a queue is currently being executed
* @property queueInProgress
* @type Boolean
*/
queueInProgress : false,
/**
* Validates that the value passed in is a Boolean.
* @method checkBoolean
* @param {Object} val The value to validate
* @return {Boolean} true, if the value is valid
*/
checkBoolean: function(val) {
if (typeof val == 'boolean') {
return true;
} else {
return false;
}
},
/**
* Validates that the value passed in is a number.
* @method checkNumber
* @param {Object} val The value to validate
* @return {Boolean} true, if the value is valid
*/
checkNumber: function(val) {
if (isNaN(val)) {
return false;
} else {
return true;
}
}
};
/**
* Initializes the configuration Object and all of its local members.
* @method init
* @param {Object} owner The owner Object to which this Config Object belongs
*/
YAHOO.util.Config.prototype.init = function(owner) {
this.owner = owner;
/**
* Object reference to the owner of this Config Object
* @event configChangedEvent
*/
this.configChangedEvent = new YAHOO.util.CustomEvent("configChanged");
this.queueInProgress = false;
/* Private Members */
/**
* Maintains the local collection of configuration property objects and their specified values
* @property config
* @private
* @type Object
*/
var config = {};
/**
* Maintains the local collection of configuration property objects as they were initially applied.
* This object is used when resetting a property.
* @property initialConfig
* @private
* @type Object
*/
var initialConfig = {};
/**
* Maintains the local, normalized CustomEvent queue
* @property eventQueue
* @private
* @type Object
*/
var eventQueue = [];
/**
* Fires a configuration property event using the specified value.
* @method fireEvent
* @private
* @param {String} key The configuration property's name
* @param {value} Object The value of the correct type for the property
*/
var fireEvent = function( key, value ) {
YAHOO.log("Firing Config event: " + key + "=" + value, "info");
key = key.toLowerCase();
var property = config[key];
if (typeof property != 'undefined' && property.event) {
property.event.fire(value);
}
};
/* End Private Members */
/**
* Adds a property to the Config Object's private config hash.
* @method addProperty
* @param {String} key The configuration property's name
* @param {Object} propertyObject The Object containing all of this property's arguments
*/
this.addProperty = function( key, propertyObject ) {
key = key.toLowerCase();
YAHOO.log("Added property: " + key, "info");
config[key] = propertyObject;
propertyObject.event = new YAHOO.util.CustomEvent(key);
propertyObject.key = key;
if (propertyObject.handler) {
propertyObject.event.subscribe(propertyObject.handler, this.owner, true);
}
this.setProperty(key, propertyObject.value, true);
if (! propertyObject.suppressEvent) {
this.queueProperty(key, propertyObject.value);
}
};
/**
* Returns a key-value configuration map of the values currently set in the Config Object.
* @method getConfig
* @return {Object} The current config, represented in a key-value map
*/
this.getConfig = function() {
var cfg = {};
for (var prop in config) {
var property = config[prop];
if (typeof property != 'undefined' && property.event) {
cfg[prop] = property.value;
}
}
return cfg;
};
/**
* Returns the value of specified property.
* @method getProperty
* @param {String} key The name of the property
* @return {Object} The value of the specified property
*/
this.getProperty = function(key) {
key = key.toLowerCase();
var property = config[key];
if (typeof property != 'undefined' && property.event) {
return property.value;
} else {
return undefined;
}
};
/**
* Resets the specified property's value to its initial value.
* @method resetProperty
* @param {String} key The name of the property
* @return {Boolean} True is the property was reset, false if not
*/
this.resetProperty = function(key) {
key = key.toLowerCase();
var property = config[key];
if (typeof property != 'undefined' && property.event) {
if (initialConfig[key] && initialConfig[key] != 'undefined') {
this.setProperty(key, initialConfig[key]);
}
return true;
} else {
return false;
}
};
/**
* Sets the value of a property. If the silent property is passed as true, the property's event will not be fired.
* @method setProperty
* @param {String} key The name of the property
* @param {String} value The value to set the property to
* @param {Boolean} silent Whether the value should be set silently, without firing the property event.
* @return {Boolean} True, if the set was successful, false if it failed.
*/
this.setProperty = function(key, value, silent) {
key = key.toLowerCase();
YAHOO.log("setProperty: " + key + "=" + value, "info");
if (this.queueInProgress && ! silent) {
this.queueProperty(key,value); // Currently running through a queue...
return true;
} else {
var property = config[key];
if (typeof property != 'undefined' && property.event) {
if (property.validator && ! property.validator(value)) { // validator
return false;
} else {
property.value = value;
if (! silent) {
fireEvent(key, value);
this.configChangedEvent.fire([key, value]);
}
return true;
}
} else {
return false;
}
}
};
/**
* Sets the value of a property and queues its event to execute. If the event is already scheduled to execute, it is
* moved from its current position to the end of the queue.
* @method queueProperty
* @param {String} key The name of the property
* @param {String} value The value to set the property to
* @return {Boolean} true, if the set was successful, false if it failed.
*/
this.queueProperty = function(key, value) {
key = key.toLowerCase();
YAHOO.log("queueProperty: " + key + "=" + value, "info");
var property = config[key];
if (typeof property != 'undefined' && property.event) {
if (typeof value != 'undefined' && property.validator && ! property.validator(value)) { // validator
return false;
} else {
if (typeof value != 'undefined') {
property.value = value;
} else {
value = property.value;
}
var foundDuplicate = false;
for (var i=0;i<eventQueue.length;i++) {
var queueItem = eventQueue[i];
if (queueItem) {
var queueItemKey = queueItem[0];
var queueItemValue = queueItem[1];
if (queueItemKey.toLowerCase() == key) {
// found a dupe... push to end of queue, null current item, and break
eventQueue[i] = null;
eventQueue.push([key, (typeof value != 'undefined' ? value : queueItemValue)]);
foundDuplicate = true;
break;
}
}
}
if (! foundDuplicate && typeof value != 'undefined') { // this is a refire, or a new property in the queue
eventQueue.push([key, value]);
}
}
if (property.supercedes) {
for (var s=0;s<property.supercedes.length;s++) {
var supercedesCheck = property.supercedes[s];
for (var q=0;q<eventQueue.length;q++) {
var queueItemCheck = eventQueue[q];
if (queueItemCheck) {
var queueItemCheckKey = queueItemCheck[0];
var queueItemCheckValue = queueItemCheck[1];
if ( queueItemCheckKey.toLowerCase() == supercedesCheck.toLowerCase() ) {
eventQueue.push([queueItemCheckKey, queueItemCheckValue]);
eventQueue[q] = null;
break;
}
}
}
}
}
YAHOO.log("Config event queue: " + this.outputEventQueue(), "info");
return true;
} else {
return false;
}
};
/**
* Fires the event for a property using the property's current value.
* @method refireEvent
* @param {String} key The name of the property
*/
this.refireEvent = function(key) {
key = key.toLowerCase();
var property = config[key];
if (typeof property != 'undefined' && property.event && typeof property.value != 'undefined') {
if (this.queueInProgress) {
this.queueProperty(key);
} else {
fireEvent(key, property.value);
}
}
};
/**
* Applies a key-value Object literal to the configuration, replacing any existing values, and queueing the property events.
* Although the values will be set, fireQueue() must be called for their associated events to execute.
* @method applyConfig
* @param {Object} userConfig The configuration Object literal
* @param {Boolean} init When set to true, the initialConfig will be set to the userConfig passed in, so that calling a reset will reset the properties to the passed values.
*/
this.applyConfig = function(userConfig, init) {
if (init) {
initialConfig = userConfig;
}
for (var prop in userConfig) {
this.queueProperty(prop, userConfig[prop]);
}
};
/**
* Refires the events for all configuration properties using their current values.
* @method refresh
*/
this.refresh = function() {
for (var prop in config) {
this.refireEvent(prop);
}
};
/**
* Fires the normalized list of queued property change events
* @method fireQueue
*/
this.fireQueue = function() {
this.queueInProgress = true;
for (var i=0;i<eventQueue.length;i++) {
var queueItem = eventQueue[i];
if (queueItem) {
var key = queueItem[0];
var value = queueItem[1];
var property = config[key];
property.value = value;
fireEvent(key,value);
}
}
this.queueInProgress = false;
eventQueue = [];
};
/**
* Subscribes an external handler to the change event for any given property.
* @method subscribeToConfigEvent
* @param {String} key The property name
* @param {Function} handler The handler function to use subscribe to the property's event
* @param {Object} obj The Object to use for scoping the event handler (see CustomEvent documentation)
* @param {Boolean} override Optional. If true, will override "this" within the handler to map to the scope Object passed into the method.
* @return {Boolean} True, if the subscription was successful, otherwise false.
*/
this.subscribeToConfigEvent = function(key, handler, obj, override) {
key = key.toLowerCase();
var property = config[key];
if (typeof property != 'undefined' && property.event) {
if (! YAHOO.util.Config.alreadySubscribed(property.event, handler, obj)) {
property.event.subscribe(handler, obj, override);
}
return true;
} else {
return false;
}
};
/**
* Unsubscribes an external handler from the change event for any given property.
* @method unsubscribeFromConfigEvent
* @param {String} key The property name
* @param {Function} handler The handler function to use subscribe to the property's event
* @param {Object} obj The Object to use for scoping the event handler (see CustomEvent documentation)
* @return {Boolean} True, if the unsubscription was successful, otherwise false.
*/
this.unsubscribeFromConfigEvent = function(key, handler, obj) {
key = key.toLowerCase();
var property = config[key];
if (typeof property != 'undefined' && property.event) {
return property.event.unsubscribe(handler, obj);
} else {
return false;
}
};
/**
* Returns a string representation of the Config object
* @method toString
* @return {String} The Config object in string format.
*/
this.toString = function() {
var output = "Config";
if (this.owner) {
output += " [" + this.owner.toString() + "]";
}
return output;
};
/**
* Returns a string representation of the Config object's current CustomEvent queue
* @method outputEventQueue
* @return {String} The string list of CustomEvents currently queued for execution
*/
this.outputEventQueue = function() {
var output = "";
for (var q=0;q<eventQueue.length;q++) {
var queueItem = eventQueue[q];
if (queueItem) {
output += queueItem[0] + "=" + queueItem[1] + ", ";
}
}
return output;
};
};
/**
* Checks to determine if a particular function/Object pair are already subscribed to the specified CustomEvent
* @method YAHOO.util.Config.alreadySubscribed
* @static
* @param {YAHOO.util.CustomEvent} evt The CustomEvent for which to check the subscriptions
* @param {Function} fn The function to look for in the subscribers list
* @param {Object} obj The execution scope Object for the subscription
* @return {Boolean} true, if the function/Object pair is already subscribed to the CustomEvent passed in
*/
YAHOO.util.Config.alreadySubscribed = function(evt, fn, obj) {
for (var e=0;e<evt.subscribers.length;e++) {
var subsc = evt.subscribers[e];
if (subsc && subsc.obj == obj && subsc.fn == fn) {
return true;
}
}
return false;
};
/**
* The Container family of components is designed to enable developers to create different kinds of content-containing modules on the web. Module and Overlay are the most basic containers, and they can be used directly or extended to build custom containers. Also part of the Container family are four UI controls that extend Module and Overlay: Tooltip, Panel, Dialog, and SimpleDialog.
* @module Container
* @requires yahoo,dom,event,dragdrop,animation
*/
/**
* Module is a JavaScript representation of the Standard Module Format. Standard Module Format is a simple standard for markup containers where child nodes representing the header, body, and footer of the content are denoted using the CSS classes "hd", "bd", and "ft" respectively. Module is the base class for all other classes in the YUI Container package.
* @class Module
* @namespace YAHOO.widget
* @constructor
* @param {String} el The element ID representing the Module <em>OR</em>
* @param {HTMLElement} el The element representing the Module
* @param {Object} userConfig The configuration Object literal containing the configuration that should be set for this module. See configuration documentation for more details.
*/
YAHOO.widget.Module = function(el, userConfig) {
if (el) {
this.init(el, userConfig);
} else {
YAHOO.log("No element or element ID specified for Module instantiation", "error");
}
};
/**
* Constant representing the prefix path to use for non-secure images
* @property YAHOO.widget.Module.IMG_ROOT
* @static
* @final
* @type String
*/
YAHOO.widget.Module.IMG_ROOT = "http://us.i1.yimg.com/us.yimg.com/i/";
/**
* Constant representing the prefix path to use for securely served images
* @property YAHOO.widget.Module.IMG_ROOT_SSL
* @static
* @final
* @type String
*/
YAHOO.widget.Module.IMG_ROOT_SSL = "https://a248.e.akamai.net/sec.yimg.com/i/";
/**
* Constant for the default CSS class name that represents a Module
* @property YAHOO.widget.Module.CSS_MODULE
* @static
* @final
* @type String
*/
YAHOO.widget.Module.CSS_MODULE = "module";
/**
* Constant representing the module header
* @property YAHOO.widget.Module.CSS_HEADER
* @static
* @final
* @type String
*/
YAHOO.widget.Module.CSS_HEADER = "hd";
/**
* Constant representing the module body
* @property YAHOO.widget.Module.CSS_BODY
* @static
* @final
* @type String
*/
YAHOO.widget.Module.CSS_BODY = "bd";
/**
* Constant representing the module footer
* @property YAHOO.widget.Module.CSS_FOOTER
* @static
* @final
* @type String
*/
YAHOO.widget.Module.CSS_FOOTER = "ft";
/**
* Constant representing the url for the "src" attribute of the iframe used to monitor changes to the browser's base font size
* @property YAHOO.widget.Module.RESIZE_MONITOR_SECURE_URL
* @static
* @final
* @type String
*/
YAHOO.widget.Module.RESIZE_MONITOR_SECURE_URL = "javascript:false;";
YAHOO.widget.Module.prototype = {
/**
* The class's constructor function
* @property contructor
* @type Function
*/
constructor : YAHOO.widget.Module,
/**
* The main module element that contains the header, body, and footer
* @property element
* @type HTMLElement
*/
element : null,
/**
* The header element, denoted with CSS class "hd"
* @property header
* @type HTMLElement
*/
header : null,
/**
* The body element, denoted with CSS class "bd"
* @property body
* @type HTMLElement
*/
body : null,
/**
* The footer element, denoted with CSS class "ft"
* @property footer
* @type HTMLElement
*/
footer : null,
/**
* The id of the element
* @property id
* @type String
*/
id : null,
/**
* The String representing the image root
* @property imageRoot
* @type String
*/
imageRoot : YAHOO.widget.Module.IMG_ROOT,
/**
* Initializes the custom events for Module which are fired automatically at appropriate times by the Module class.
* @method initEvents
*/
initEvents : function() {
/**
* CustomEvent fired prior to class initalization.
* @event beforeInitEvent
* @param {class} classRef class reference of the initializing class, such as this.beforeInitEvent.fire(YAHOO.widget.Module)
*/
this.beforeInitEvent = new YAHOO.util.CustomEvent("beforeInit");
/**
* CustomEvent fired after class initalization.
* @event initEvent
* @param {class} classRef class reference of the initializing class, such as this.beforeInitEvent.fire(YAHOO.widget.Module)
*/
this.initEvent = new YAHOO.util.CustomEvent("init");
/**
* CustomEvent fired when the Module is appended to the DOM
* @event appendEvent
*/
this.appendEvent = new YAHOO.util.CustomEvent("append");
/**
* CustomEvent fired before the Module is rendered
* @event beforeRenderEvent
*/
this.beforeRenderEvent = new YAHOO.util.CustomEvent("beforeRender");
/**
* CustomEvent fired after the Module is rendered
* @event renderEvent
*/
this.renderEvent = new YAHOO.util.CustomEvent("render");
/**
* CustomEvent fired when the header content of the Module is modified
* @event changeHeaderEvent
* @param {String/HTMLElement} content String/element representing the new header content
*/
this.changeHeaderEvent = new YAHOO.util.CustomEvent("changeHeader");
/**
* CustomEvent fired when the body content of the Module is modified
* @event changeBodyEvent
* @param {String/HTMLElement} content String/element representing the new body content
*/
this.changeBodyEvent = new YAHOO.util.CustomEvent("changeBody");
/**
* CustomEvent fired when the footer content of the Module is modified
* @event changeFooterEvent
* @param {String/HTMLElement} content String/element representing the new footer content
*/
this.changeFooterEvent = new YAHOO.util.CustomEvent("changeFooter");
/**
* CustomEvent fired when the content of the Module is modified
* @event changeContentEvent
*/
this.changeContentEvent = new YAHOO.util.CustomEvent("changeContent");
/**
* CustomEvent fired when the Module is destroyed
* @event destroyEvent
*/
this.destroyEvent = new YAHOO.util.CustomEvent("destroy");
/**
* CustomEvent fired before the Module is shown
* @event beforeShowEvent
*/
this.beforeShowEvent = new YAHOO.util.CustomEvent("beforeShow");
/**
* CustomEvent fired after the Module is shown
* @event showEvent
*/
this.showEvent = new YAHOO.util.CustomEvent("show");
/**
* CustomEvent fired before the Module is hidden
* @event beforeHideEvent
*/
this.beforeHideEvent = new YAHOO.util.CustomEvent("beforeHide");
/**
* CustomEvent fired after the Module is hidden
* @event hideEvent
*/
this.hideEvent = new YAHOO.util.CustomEvent("hide");
},
/**
* String representing the current user-agent platform
* @property platform
* @type String
*/
platform : function() {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1) {
return "windows";
} else if (ua.indexOf("macintosh") != -1) {
return "mac";
} else {
return false;
}
}(),
/**
* String representing the current user-agent browser
* @property browser
* @type String
*/
browser : function() {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('opera')!=-1) { // Opera (check first in case of spoof)
return 'opera';
} else if (ua.indexOf('msie 7')!=-1) { // IE7
return 'ie7';
} else if (ua.indexOf('msie') !=-1) { // IE
return 'ie';
} else if (ua.indexOf('safari')!=-1) { // Safari (check before Gecko because it includes "like Gecko")
return 'safari';
} else if (ua.indexOf('gecko') != -1) { // Gecko
return 'gecko';
} else {
return false;
}
}(),
/**
* Boolean representing whether or not the current browsing context is secure (https)
* @property isSecure
* @type Boolean
*/
isSecure : function() {
if (window.location.href.toLowerCase().indexOf("https") === 0) {
return true;
} else {
return false;
}
}(),
/**
* Initializes the custom events for Module which are fired automatically at appropriate times by the Module class.
*/
initDefaultConfig : function() {
// Add properties //
/**
* Specifies whether the Module is visible on the page.
* @config visible
* @type Boolean
* @default true
*/
this.cfg.addProperty("visible", { value:true, handler:this.configVisible, validator:this.cfg.checkBoolean } );
/**
* Object or array of objects representing the ContainerEffect classes that are active for animating the container.
* @config effect
* @type Object
* @default null
*/
this.cfg.addProperty("effect", { suppressEvent:true, supercedes:["visible"] } );
/**
* Specifies whether to create a special proxy iframe to monitor for user font resizing in the document
* @config monitorresize
* @type Boolean
* @default true
*/
this.cfg.addProperty("monitorresize", { value:true, handler:this.configMonitorResize } );
},
/**
* The Module class's initialization method, which is executed for Module and all of its subclasses. This method is automatically called by the constructor, and sets up all DOM references for pre-existing markup, and creates required markup if it is not already present.
* @method init
* @param {String} el The element ID representing the Module <em>OR</em>
* @param {HTMLElement} el The element representing the Module
* @param {Object} userConfig The configuration Object literal containing the configuration that should be set for this module. See configuration documentation for more details.
*/
init : function(el, userConfig) {
this.initEvents();
this.beforeInitEvent.fire(YAHOO.widget.Module);
/**
* The Module's Config object used for monitoring configuration properties.
* @property cfg
* @type YAHOO.util.Config
*/
this.cfg = new YAHOO.util.Config(this);
if (this.isSecure) {
this.imageRoot = YAHOO.widget.Module.IMG_ROOT_SSL;
}
if (typeof el == "string") {
var elId = el;
el = document.getElementById(el);
if (! el) {
el = document.createElement("DIV");
el.id = elId;
}
}
this.element = el;
if (el.id) {
this.id = el.id;
}
var childNodes = this.element.childNodes;
if (childNodes) {
for (var i=0;i<childNodes.length;i++) {
var child = childNodes[i];
switch (child.className) {
case YAHOO.widget.Module.CSS_HEADER:
this.header = child;
break;
case YAHOO.widget.Module.CSS_BODY:
this.body = child;
break;
case YAHOO.widget.Module.CSS_FOOTER:
this.footer = child;
break;
}
}
}
this.initDefaultConfig();
YAHOO.util.Dom.addClass(this.element, YAHOO.widget.Module.CSS_MODULE);
if (userConfig) {
this.cfg.applyConfig(userConfig, true);
}
// Subscribe to the fireQueue() method of Config so that any queued configuration changes are
// excecuted upon render of the Module
if (! YAHOO.util.Config.alreadySubscribed(this.renderEvent, this.cfg.fireQueue, this.cfg)) {
this.renderEvent.subscribe(this.cfg.fireQueue, this.cfg, true);
}
this.initEvent.fire(YAHOO.widget.Module);
},
/**
* Initialized an empty IFRAME that is placed out of the visible area that can be used to detect text resize.
* @method initResizeMonitor
*/
initResizeMonitor : function() {
if(this.browser != "opera") {
var resizeMonitor = document.getElementById("_yuiResizeMonitor");
if (! resizeMonitor) {
resizeMonitor = document.createElement("iframe");
var bIE = (this.browser.indexOf("ie") === 0);
if(this.isSecure &&
YAHOO.widget.Module.RESIZE_MONITOR_SECURE_URL &&
bIE) {
resizeMonitor.src =
YAHOO.widget.Module.RESIZE_MONITOR_SECURE_URL;
}
resizeMonitor.id = "_yuiResizeMonitor";
resizeMonitor.style.visibility = "hidden";
document.body.appendChild(resizeMonitor);
resizeMonitor.style.width = "10em";
resizeMonitor.style.height = "10em";
resizeMonitor.style.position = "absolute";
var nLeft = -1 * resizeMonitor.offsetWidth,
nTop = -1 * resizeMonitor.offsetHeight;
resizeMonitor.style.top = nTop + "px";
resizeMonitor.style.left = nLeft + "px";
resizeMonitor.style.borderStyle = "none";
resizeMonitor.style.borderWidth = "0";
YAHOO.util.Dom.setStyle(resizeMonitor, "opacity", "0");
resizeMonitor.style.visibility = "visible";
if(!bIE) {
var doc = resizeMonitor.contentWindow.document;
doc.open();
doc.close();
}
}
if(resizeMonitor && resizeMonitor.contentWindow) {
this.resizeMonitor = resizeMonitor;
YAHOO.util.Event.addListener(this.resizeMonitor.contentWindow, "resize", this.onDomResize, this, true);
}
}
},
/**
* Event handler fired when the resize monitor element is resized.
* @method onDomResize
* @param {DOMEvent} e The DOM resize event
* @param {Object} obj The scope object passed to the handler
*/
onDomResize : function(e, obj) {
var nLeft = -1 * this.resizeMonitor.offsetWidth,
nTop = -1 * this.resizeMonitor.offsetHeight;
this.resizeMonitor.style.top = nTop + "px";
this.resizeMonitor.style.left = nLeft + "px";
},
/**
* Sets the Module's header content to the HTML specified, or appends the passed element to the header. If no header is present, one will be automatically created.
* @method setHeader
* @param {String} headerContent The HTML used to set the header <em>OR</em>
* @param {HTMLElement} headerContent The HTMLElement to append to the header
*/
setHeader : function(headerContent) {
if (! this.header) {
this.header = document.createElement("DIV");
this.header.className = YAHOO.widget.Module.CSS_HEADER;
}
if (typeof headerContent == "string") {
this.header.innerHTML = headerContent;
} else {
this.header.innerHTML = "";
this.header.appendChild(headerContent);
}
this.changeHeaderEvent.fire(headerContent);
this.changeContentEvent.fire();
},
/**
* Appends the passed element to the header. If no header is present, one will be automatically created.
* @method appendToHeader
* @param {HTMLElement} element The element to append to the header
*/
appendToHeader : function(element) {
if (! this.header) {
this.header = document.createElement("DIV");
this.header.className = YAHOO.widget.Module.CSS_HEADER;
}
this.header.appendChild(element);
this.changeHeaderEvent.fire(element);
this.changeContentEvent.fire();
},
/**
* Sets the Module's body content to the HTML specified, or appends the passed element to the body. If no body is present, one will be automatically created.
* @method setBody
* @param {String} bodyContent The HTML used to set the body <em>OR</em>
* @param {HTMLElement} bodyContent The HTMLElement to append to the body
*/
setBody : function(bodyContent) {
if (! this.body) {
this.body = document.createElement("DIV");
this.body.className = YAHOO.widget.Module.CSS_BODY;
}
if (typeof bodyContent == "string")
{
this.body.innerHTML = bodyContent;
} else {
this.body.innerHTML = "";
this.body.appendChild(bodyContent);
}
this.changeBodyEvent.fire(bodyContent);
this.changeContentEvent.fire();
},
/**
* Appends the passed element to the body. If no body is present, one will be automatically created.
* @method appendToBody
* @param {HTMLElement} element The element to append to the body
*/
appendToBody : function(element) {
if (! this.body) {
this.body = document.createElement("DIV");
this.body.className = YAHOO.widget.Module.CSS_BODY;
}
this.body.appendChild(element);
this.changeBodyEvent.fire(element);
this.changeContentEvent.fire();
},
/**
* Sets the Module's footer content to the HTML specified, or appends the passed element to the footer. If no footer is present, one will be automatically created.
* @method setFooter
* @param {String} footerContent The HTML used to set the footer <em>OR</em>
* @param {HTMLElement} footerContent The HTMLElement to append to the footer
*/
setFooter : function(footerContent) {
if (! this.footer) {
this.footer = document.createElement("DIV");
this.footer.className = YAHOO.widget.Module.CSS_FOOTER;
}
if (typeof footerContent == "string") {
this.footer.innerHTML = footerContent;
} else {
this.footer.innerHTML = "";
this.footer.appendChild(footerContent);
}
this.changeFooterEvent.fire(footerContent);
this.changeContentEvent.fire();
},
/**
* Appends the passed element to the footer. If no footer is present, one will be automatically created.
* @method appendToFooter
* @param {HTMLElement} element The element to append to the footer
*/
appendToFooter : function(element) {
if (! this.footer) {
this.footer = document.createElement("DIV");
this.footer.className = YAHOO.widget.Module.CSS_FOOTER;
}
this.footer.appendChild(element);
this.changeFooterEvent.fire(element);
this.changeContentEvent.fire();
},
/**
* Renders the Module by inserting the elements that are not already in the main Module into their correct places. Optionally appends the Module to the specified node prior to the render's execution. NOTE: For Modules without existing markup, the appendToNode argument is REQUIRED. If this argument is ommitted and the current element is not present in the document, the function will return false, indicating that the render was a failure.
* @method render
* @param {String} appendToNode The element id to which the Module should be appended to prior to rendering <em>OR</em>
* @param {HTMLElement} appendToNode The element to which the Module should be appended to prior to rendering
* @param {HTMLElement} moduleElement OPTIONAL. The element that represents the actual Standard Module container.
* @return {Boolean} Success or failure of the render
*/
render : function(appendToNode, moduleElement) {
this.beforeRenderEvent.fire();
if (! moduleElement) {
moduleElement = this.element;
}
var me = this;
var appendTo = function(element) {
if (typeof element == "string") {
element = document.getElementById(element);
}
if (element) {
element.appendChild(me.element);
me.appendEvent.fire();
}
};
if (appendToNode) {
appendTo(appendToNode);
} else { // No node was passed in. If the element is not pre-marked up, this fails
if (! YAHOO.util.Dom.inDocument(this.element)) {
YAHOO.log("Render failed. Must specify appendTo node if Module isn't already in the DOM.", "error");
return false;
}
}
// Need to get everything into the DOM if it isn't already
if (this.header && ! YAHOO.util.Dom.inDocument(this.header)) {
// There is a header, but it's not in the DOM yet... need to add it
var firstChild = moduleElement.firstChild;
if (firstChild) { // Insert before first child if exists
moduleElement.insertBefore(this.header, firstChild);
} else { // Append to empty body because there are no children
moduleElement.appendChild(this.header);
}
}
if (this.body && ! YAHOO.util.Dom.inDocument(this.body)) {
// There is a body, but it's not in the DOM yet... need to add it
if (this.footer && YAHOO.util.Dom.isAncestor(this.moduleElement, this.footer)) { // Insert before footer if exists in DOM
moduleElement.insertBefore(this.body, this.footer);
} else { // Append to element because there is no footer
moduleElement.appendChild(this.body);
}
}
if (this.footer && ! YAHOO.util.Dom.inDocument(this.footer)) {
// There is a footer, but it's not in the DOM yet... need to add it
moduleElement.appendChild(this.footer);
}
this.renderEvent.fire();
return true;
},
/**
* Removes the Module element from the DOM and sets all child elements to null.
* @method destroy
*/
destroy : function() {
if (this.element) {
var parent = this.element.parentNode;
}
if (parent) {
parent.removeChild(this.element);
}
this.element = null;
this.header = null;
this.body = null;
this.footer = null;
this.destroyEvent.fire();
},
/**
* Shows the Module element by setting the visible configuration property to true. Also fires two events: beforeShowEvent prior to the visibility change, and showEvent after.
* @method show
*/
show : function() {
this.cfg.setProperty("visible", true);
},
/**
* Hides the Module element by setting the visible configuration property to false. Also fires two events: beforeHideEvent prior to the visibility change, and hideEvent after.
* @method hide
*/
hide : function() {
this.cfg.setProperty("visible", false);
},
// BUILT-IN EVENT HANDLERS FOR MODULE //
/**
* Default event handler for changing the visibility property of a Module. By default, this is achieved by switching the "display" style between "block" and "none".
* This method is responsible for firing showEvent and hideEvent.
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner.
* @method configVisible
*/
configVisible : function(type, args, obj) {
var visible = args[0];
if (visible) {
this.beforeShowEvent.fire();
YAHOO.util.Dom.setStyle(this.element, "display", "block");
this.showEvent.fire();
} else {
this.beforeHideEvent.fire();
YAHOO.util.Dom.setStyle(this.element, "display", "none");
this.hideEvent.fire();
}
},
/**
* Default event handler for the "monitorresize" configuration property
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner.
* @method configMonitorResize
*/
configMonitorResize : function(type, args, obj) {
var monitor = args[0];
if (monitor) {
this.initResizeMonitor();
} else {
YAHOO.util.Event.removeListener(this.resizeMonitor, "resize", this.onDomResize);
this.resizeMonitor = null;
}
}
};
/**
* Returns a String representation of the Object.
* @method toString
* @return {String} The string representation of the Module
*/
YAHOO.widget.Module.prototype.toString = function() {
return "Module " + this.id;
};
/**
* Overlay is a Module that is absolutely positioned above the page flow. It has convenience methods for positioning and sizing, as well as options for controlling zIndex and constraining the Overlay's position to the current visible viewport. Overlay also contains a dynamicly generated IFRAME which is placed beneath it for Internet Explorer 6 and 5.x so that it will be properly rendered above SELECT elements.
* @class Overlay
* @namespace YAHOO.widget
* @extends YAHOO.widget.Module
* @param {String} el The element ID representing the Overlay <em>OR</em>
* @param {HTMLElement} el The element representing the Overlay
* @param {Object} userConfig The configuration object literal containing 10/23/2006the configuration that should be set for this Overlay. See configuration documentation for more details.
* @constructor
*/
YAHOO.widget.Overlay = function(el, userConfig) {
YAHOO.widget.Overlay.superclass.constructor.call(this, el, userConfig);
};
YAHOO.extend(YAHOO.widget.Overlay, YAHOO.widget.Module);
/**
* The URL that will be placed in the iframe
* @property YAHOO.widget.Overlay.IFRAME_SRC
* @static
* @final
* @type String
*/
YAHOO.widget.Overlay.IFRAME_SRC = "javascript:false;"
/**
* Constant representing the top left corner of an element, used for configuring the context element alignment
* @property YAHOO.widget.Overlay.TOP_LEFT
* @static
* @final
* @type String
*/
YAHOO.widget.Overlay.TOP_LEFT = "tl";
/**
* Constant representing the top right corner of an element, used for configuring the context element alignment
* @property YAHOO.widget.Overlay.TOP_RIGHT
* @static
* @final
* @type String
*/
YAHOO.widget.Overlay.TOP_RIGHT = "tr";
/**
* Constant representing the top bottom left corner of an element, used for configuring the context element alignment
* @property YAHOO.widget.Overlay.BOTTOM_LEFT
* @static
* @final
* @type String
*/
YAHOO.widget.Overlay.BOTTOM_LEFT = "bl";
/**
* Constant representing the bottom right corner of an element, used for configuring the context element alignment
* @property YAHOO.widget.Overlay.BOTTOM_RIGHT
* @static
* @final
* @type String
*/
YAHOO.widget.Overlay.BOTTOM_RIGHT = "br";
/**
* Constant representing the default CSS class used for an Overlay
* @property YAHOO.widget.Overlay.CSS_OVERLAY
* @static
* @final
* @type String
*/
YAHOO.widget.Overlay.CSS_OVERLAY = "overlay";
/**
* The Overlay initialization method, which is executed for Overlay and all of its subclasses. This method is automatically called by the constructor, and sets up all DOM references for pre-existing markup, and creates required markup if it is not already present.
* @method init
* @param {String} el The element ID representing the Overlay <em>OR</em>
* @param {HTMLElement} el The element representing the Overlay
* @param {Object} userConfig The configuration object literal containing the configuration that should be set for this Overlay. See configuration documentation for more details.
*/
YAHOO.widget.Overlay.prototype.init = function(el, userConfig) {
YAHOO.widget.Overlay.superclass.init.call(this, el/*, userConfig*/); // Note that we don't pass the user config in here yet because we only want it executed once, at the lowest subclass level
this.beforeInitEvent.fire(YAHOO.widget.Overlay);
YAHOO.util.Dom.addClass(this.element, YAHOO.widget.Overlay.CSS_OVERLAY);
if (userConfig) {
this.cfg.applyConfig(userConfig, true);
}
if (this.platform == "mac" && this.browser == "gecko") {
if (! YAHOO.util.Config.alreadySubscribed(this.showEvent,this.showMacGeckoScrollbars,this)) {
this.showEvent.subscribe(this.showMacGeckoScrollbars,this,true);
}
if (! YAHOO.util.Config.alreadySubscribed(this.hideEvent,this.hideMacGeckoScrollbars,this)) {
this.hideEvent.subscribe(this.hideMacGeckoScrollbars,this,true);
}
}
this.initEvent.fire(YAHOO.widget.Overlay);
};
/**
* Initializes the custom events for Overlay which are fired automatically at appropriate times by the Overlay class.
* @method initEvents
*/
YAHOO.widget.Overlay.prototype.initEvents = function() {
YAHOO.widget.Overlay.superclass.initEvents.call(this);
/**
* CustomEvent fired before the Overlay is moved.
* @event beforeMoveEvent
* @param {Number} x x coordinate
* @param {Number} y y coordinate
*/
this.beforeMoveEvent = new YAHOO.util.CustomEvent("beforeMove", this);
/**
* CustomEvent fired after the Overlay is moved.
* @event moveEvent
* @param {Number} x x coordinate
* @param {Number} y y coordinate
*/
this.moveEvent = new YAHOO.util.CustomEvent("move", this);
};
/**
* Initializes the class's configurable properties which can be changed using the Overlay's Config object (cfg).
* @method initDefaultConfig
*/
YAHOO.widget.Overlay.prototype.initDefaultConfig = function() {
YAHOO.widget.Overlay.superclass.initDefaultConfig.call(this);
// Add overlay config properties //
/**
* The absolute x-coordinate position of the Overlay
* @config x
* @type Number
* @default null
*/
this.cfg.addProperty("x", { handler:this.configX, validator:this.cfg.checkNumber, suppressEvent:true, supercedes:["iframe"] } );
/**
* The absolute y-coordinate position of the Overlay
* @config y
* @type Number
* @default null
*/
this.cfg.addProperty("y", { handler:this.configY, validator:this.cfg.checkNumber, suppressEvent:true, supercedes:["iframe"] } );
/**
* An array with the absolute x and y positions of the Overlay
* @config xy
* @type Number[]
* @default null
*/
this.cfg.addProperty("xy",{ handler:this.configXY, suppressEvent:true, supercedes:["iframe"] } );
/**
* The array of context arguments for context-sensitive positioning. The format is: [id or element, element corner, context corner]. For example, setting this property to ["img1", "tl", "bl"] would align the Overlay's top left corner to the context element's bottom left corner.
* @config context
* @type Array
* @default null
*/
this.cfg.addProperty("context", { handler:this.configContext, suppressEvent:true, supercedes:["iframe"] } );
/**
* True if the Overlay should be anchored to the center of the viewport.
* @config fixedcenter
* @type Boolean
* @default false
*/
this.cfg.addProperty("fixedcenter", { value:false, handler:this.configFixedCenter, validator:this.cfg.checkBoolean, supercedes:["iframe","visible"] } );
/**
* CSS width of the Overlay.
* @config width
* @type String
* @default null
*/
this.cfg.addProperty("width", { handler:this.configWidth, suppressEvent:true, supercedes:["iframe"] } );
/**
* CSS height of the Overlay.
* @config height
* @type String
* @default null
*/
this.cfg.addProperty("height", { handler:this.configHeight, suppressEvent:true, supercedes:["iframe"] } );
/**
* CSS z-index of the Overlay.
* @config zIndex
* @type Number
* @default null
*/
this.cfg.addProperty("zIndex", { value:null, handler:this.configzIndex } );
/**
* True if the Overlay should be prevented from being positioned out of the viewport.
* @config constraintoviewport
* @type Boolean
* @default false
*/
this.cfg.addProperty("constraintoviewport", { value:false, handler:this.configConstrainToViewport, validator:this.cfg.checkBoolean, supercedes:["iframe","x","y","xy"] } );
/**
* True if the Overlay should have an IFRAME shim (for correcting the select z-index bug in IE6 and below).
* @config iframe
* @type Boolean
* @default true for IE6 and below, false for all others
*/
this.cfg.addProperty("iframe", { value:(this.browser == "ie" ? true : false), handler:this.configIframe, validator:this.cfg.checkBoolean, supercedes:["zIndex"] } );
};
/**
* Moves the Overlay to the specified position. This function is identical to calling this.cfg.setProperty("xy", [x,y]);
* @method moveTo
* @param {Number} x The Overlay's new x position
* @param {Number} y The Overlay's new y position
*/
YAHOO.widget.Overlay.prototype.moveTo = function(x, y) {
this.cfg.setProperty("xy",[x,y]);
};
/**
* Adds a special CSS class to the Overlay when Mac/Gecko is in use, to work around a Gecko bug where
* scrollbars cannot be hidden. See https://bugzilla.mozilla.org/show_bug.cgi?id=187435
* @method hideMacGeckoScrollbars
*/
YAHOO.widget.Overlay.prototype.hideMacGeckoScrollbars = function() {
YAHOO.util.Dom.removeClass(this.element, "show-scrollbars");
YAHOO.util.Dom.addClass(this.element, "hide-scrollbars");
};
/**
* Removes a special CSS class from the Overlay when Mac/Gecko is in use, to work around a Gecko bug where
* scrollbars cannot be hidden. See https://bugzilla.mozilla.org/show_bug.cgi?id=187435
* @method showMacGeckoScrollbars
*/
YAHOO.widget.Overlay.prototype.showMacGeckoScrollbars = function() {
YAHOO.util.Dom.removeClass(this.element, "hide-scrollbars");
YAHOO.util.Dom.addClass(this.element, "show-scrollbars");
};
// BEGIN BUILT-IN PROPERTY EVENT HANDLERS //
/**
* The default event handler fired when the "visible" property is changed. This method is responsible for firing showEvent and hideEvent.
* @method configVisible
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner.
*/
YAHOO.widget.Overlay.prototype.configVisible = function(type, args, obj) {
var visible = args[0];
var currentVis = YAHOO.util.Dom.getStyle(this.element, "visibility");
if (currentVis == "inherit") {
var e = this.element.parentNode;
while (e.nodeType != 9 && e.nodeType != 11) {
currentVis = YAHOO.util.Dom.getStyle(e, "visibility");
if (currentVis != "inherit") { break; }
e = e.parentNode;
}
if (currentVis == "inherit") {
currentVis = "visible";
}
}
var effect = this.cfg.getProperty("effect");
var effectInstances = [];
if (effect) {
if (effect instanceof Array) {
for (var i=0;i<effect.length;i++) {
var eff = effect[i];
effectInstances[effectInstances.length] = eff.effect(this, eff.duration);
}
} else {
effectInstances[effectInstances.length] = effect.effect(this, effect.duration);
}
}
var isMacGecko = (this.platform == "mac" && this.browser == "gecko");
if (visible) { // Show
if (isMacGecko) {
this.showMacGeckoScrollbars();
}
if (effect) { // Animate in
if (visible) { // Animate in if not showing
if (currentVis != "visible" || currentVis === "") {
this.beforeShowEvent.fire();
for (var j=0;j<effectInstances.length;j++) {
var ei = effectInstances[j];
if (j === 0 && ! YAHOO.util.Config.alreadySubscribed(ei.animateInCompleteEvent,this.showEvent.fire,this.showEvent)) {
ei.animateInCompleteEvent.subscribe(this.showEvent.fire,this.showEvent,true); // Delegate showEvent until end of animateInComplete
}
ei.animateIn();
}
}
}
} else { // Show
if (currentVis != "visible" || currentVis === "") {
this.beforeShowEvent.fire();
YAHOO.util.Dom.setStyle(this.element, "visibility", "visible");
this.cfg.refireEvent("iframe");
this.showEvent.fire();
}
}
} else { // Hide
if (isMacGecko) {
this.hideMacGeckoScrollbars();
}
if (effect) { // Animate out if showing
if (currentVis == "visible") {
this.beforeHideEvent.fire();
for (var k=0;k<effectInstances.length;k++) {
var h = effectInstances[k];
if (k === 0 && ! YAHOO.util.Config.alreadySubscribed(h.animateOutCompleteEvent,this.hideEvent.fire,this.hideEvent)) {
h.animateOutCompleteEvent.subscribe(this.hideEvent.fire,this.hideEvent,true); // Delegate hideEvent until end of animateOutComplete
}
h.animateOut();
}
} else if (currentVis === "") {
YAHOO.util.Dom.setStyle(this.element, "visibility", "hidden");
}
} else { // Simple hide
if (currentVis == "visible" || currentVis === "") {
this.beforeHideEvent.fire();
YAHOO.util.Dom.setStyle(this.element, "visibility", "hidden");
this.cfg.refireEvent("iframe");
this.hideEvent.fire();
}
}
}
};
/**
* Center event handler used for centering on scroll/resize, but only if the Overlay is visible
* @method doCenterOnDOMEvent
*/
YAHOO.widget.Overlay.prototype.doCenterOnDOMEvent = function() {
if (this.cfg.getProperty("visible")) {
this.center();
}
};
/**
* The default event handler fired when the "fixedcenter" property is changed.
* @method configFixedCenter
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner.
*/
YAHOO.widget.Overlay.prototype.configFixedCenter = function(type, args, obj) {
var val = args[0];
if (val) {
this.center();
if (! YAHOO.util.Config.alreadySubscribed(this.beforeShowEvent, this.center, this)) {
this.beforeShowEvent.subscribe(this.center, this, true);
}
if (! YAHOO.util.Config.alreadySubscribed(YAHOO.widget.Overlay.windowResizeEvent, this.doCenterOnDOMEvent, this)) {
YAHOO.widget.Overlay.windowResizeEvent.subscribe(this.doCenterOnDOMEvent, this, true);
}
if (! YAHOO.util.Config.alreadySubscribed(YAHOO.widget.Overlay.windowScrollEvent, this.doCenterOnDOMEvent, this)) {
YAHOO.widget.Overlay.windowScrollEvent.subscribe( this.doCenterOnDOMEvent, this, true);
}
} else {
YAHOO.widget.Overlay.windowResizeEvent.unsubscribe(this.doCenterOnDOMEvent, this);
YAHOO.widget.Overlay.windowScrollEvent.unsubscribe(this.doCenterOnDOMEvent, this);
}
};
/**
* The default event handler fired when the "height" property is changed.
* @method configHeight
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner.
*/
YAHOO.widget.Overlay.prototype.configHeight = function(type, args, obj) {
var height = args[0];
var el = this.element;
YAHOO.util.Dom.setStyle(el, "height", height);
this.cfg.refireEvent("iframe");
};
/**
* The default event handler fired when the "width" property is changed.
* @method configWidth
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner.
*/
YAHOO.widget.Overlay.prototype.configWidth = function(type, args, obj) {
var width = args[0];
var el = this.element;
YAHOO.util.Dom.setStyle(el, "width", width);
this.cfg.refireEvent("iframe");
};
/**
* The default event handler fired when the "zIndex" property is changed.
* @method configzIndex
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner.
*/
YAHOO.widget.Overlay.prototype.configzIndex = function(type, args, obj) {
var zIndex = args[0];
var el = this.element;
if (! zIndex) {
zIndex = YAHOO.util.Dom.getStyle(el, "zIndex");
if (! zIndex || isNaN(zIndex)) {
zIndex = 0;
}
}
if (this.iframe) {
if (zIndex <= 0) {
zIndex = 1;
}
YAHOO.util.Dom.setStyle(this.iframe, "zIndex", (zIndex-1));
}
YAHOO.util.Dom.setStyle(el, "zIndex", zIndex);
this.cfg.setProperty("zIndex", zIndex, true);
};
/**
* The default event handler fired when the "xy" property is changed.
* @method configXY
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner.
*/
YAHOO.widget.Overlay.prototype.configXY = function(type, args, obj) {
var pos = args[0];
var x = pos[0];
var y = pos[1];
this.cfg.setProperty("x", x);
this.cfg.setProperty("y", y);
this.beforeMoveEvent.fire([x,y]);
x = this.cfg.getProperty("x");
y = this.cfg.getProperty("y");
YAHOO.log("xy: " + [x,y], "iframe");
this.cfg.refireEvent("iframe");
this.moveEvent.fire([x,y]);
};
/**
* The default event handler fired when the "x" property is changed.
* @method configX
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner.
*/
YAHOO.widget.Overlay.prototype.configX = function(type, args, obj) {
var x = args[0];
var y = this.cfg.getProperty("y");
this.cfg.setProperty("x", x, true);
this.cfg.setProperty("y", y, true);
this.beforeMoveEvent.fire([x,y]);
x = this.cfg.getProperty("x");
y = this.cfg.getProperty("y");
YAHOO.util.Dom.setX(this.element, x, true);
this.cfg.setProperty("xy", [x, y], true);
this.cfg.refireEvent("iframe");
this.moveEvent.fire([x, y]);
};
/**
* The default event handler fired when the "y" property is changed.
* @method configY
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner.
*/
YAHOO.widget.Overlay.prototype.configY = function(type, args, obj) {
var x = this.cfg.getProperty("x");
var y = args[0];
this.cfg.setProperty("x", x, true);
this.cfg.setProperty("y", y, true);
this.beforeMoveEvent.fire([x,y]);
x = this.cfg.getProperty("x");
y = this.cfg.getProperty("y");
YAHOO.util.Dom.setY(this.element, y, true);
this.cfg.setProperty("xy", [x, y], true);
this.cfg.refireEvent("iframe");
this.moveEvent.fire([x, y]);
};
/**
* Shows the iframe shim, if it has been enabled
* @method showIframe
*/
YAHOO.widget.Overlay.prototype.showIframe = function() {
if (this.iframe) {
this.iframe.style.display = "block";
}
};
/**
* Hides the iframe shim, if it has been enabled
* @method hideIframe
*/
YAHOO.widget.Overlay.prototype.hideIframe = function() {
if (this.iframe) {
this.iframe.style.display = "none";
}
};
/**
* The default event handler fired when the "iframe" property is changed.
* @method configIframe
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner.
*/
YAHOO.widget.Overlay.prototype.configIframe = function(type, args, obj) {
var val = args[0];
if (val) { // IFRAME shim is enabled
if (! YAHOO.util.Config.alreadySubscribed(this.showEvent, this.showIframe, this)) {
this.showEvent.subscribe(this.showIframe, this, true);
}
if (! YAHOO.util.Config.alreadySubscribed(this.hideEvent, this.hideIframe, this)) {
this.hideEvent.subscribe(this.hideIframe, this, true);
}
var x = this.cfg.getProperty("x");
var y = this.cfg.getProperty("y");
if (! x || ! y) {
this.syncPosition();
x = this.cfg.getProperty("x");
y = this.cfg.getProperty("y");
}
YAHOO.log("iframe positioning to: " + [x,y], "iframe");
if (! isNaN(x) && ! isNaN(y)) {
if (! this.iframe) {
this.iframe = document.createElement("iframe");
if (this.isSecure) {
this.iframe.src = this.imageRoot + YAHOO.widget.Overlay.IFRAME_SRC;
}
var parent = this.element.parentNode;
if (parent) {
parent.appendChild(this.iframe);
} else {
document.body.appendChild(this.iframe);
}
YAHOO.util.Dom.setStyle(this.iframe, "position", "absolute");
YAHOO.util.Dom.setStyle(this.iframe, "border", "none");
YAHOO.util.Dom.setStyle(this.iframe, "margin", "0");
YAHOO.util.Dom.setStyle(this.iframe, "padding", "0");
YAHOO.util.Dom.setStyle(this.iframe, "opacity", "0");
if (this.cfg.getProperty("visible")) {
this.showIframe();
} else {
this.hideIframe();
}
}
var iframeDisplay = YAHOO.util.Dom.getStyle(this.iframe, "display");
if (iframeDisplay == "none") {
this.iframe.style.display = "block";
}
YAHOO.util.Dom.setXY(this.iframe, [x,y]);
var width = this.element.clientWidth;
var height = this.element.clientHeight;
YAHOO.util.Dom.setStyle(this.iframe, "width", (width+2) + "px");
YAHOO.util.Dom.setStyle(this.iframe, "height", (height+2) + "px");
if (iframeDisplay == "none") {
this.iframe.style.display = "none";
}
}
} else {
if (this.iframe) {
this.iframe.style.display = "none";
}
this.showEvent.unsubscribe(this.showIframe, this);
this.hideEvent.unsubscribe(this.hideIframe, this);
}
};
/**
* The default event handler fired when the "constraintoviewport" property is changed.
* @method configConstrainToViewport
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner.
*/
YAHOO.widget.Overlay.prototype.configConstrainToViewport = function(type, args, obj) {
var val = args[0];
if (val) {
if (! YAHOO.util.Config.alreadySubscribed(this.beforeMoveEvent, this.enforceConstraints, this)) {
this.beforeMoveEvent.subscribe(this.enforceConstraints, this, true);
}
} else {
this.beforeMoveEvent.unsubscribe(this.enforceConstraints, this);
}
};
/**
* The default event handler fired when the "context" property is changed.
* @method configContext
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner.
*/
YAHOO.widget.Overlay.prototype.configContext = function(type, args, obj) {
var contextArgs = args[0];
if (contextArgs) {
var contextEl = contextArgs[0];
var elementMagnetCorner = contextArgs[1];
var contextMagnetCorner = contextArgs[2];
if (contextEl) {
if (typeof contextEl == "string") {
this.cfg.setProperty("context", [document.getElementById(contextEl),elementMagnetCorner,contextMagnetCorner], true);
}
if (elementMagnetCorner && contextMagnetCorner) {
this.align(elementMagnetCorner, contextMagnetCorner);
}
}
}
};
// END BUILT-IN PROPERTY EVENT HANDLERS //
/**
* Aligns the Overlay to its context element using the specified corner points (represented by the constants TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, and BOTTOM_RIGHT.
* @method align
* @param {String} elementAlign The String representing the corner of the Overlay that should be aligned to the context element
* @param {String} contextAlign The corner of the context element that the elementAlign corner should stick to.
*/
YAHOO.widget.Overlay.prototype.align = function(elementAlign, contextAlign) {
var contextArgs = this.cfg.getProperty("context");
if (contextArgs) {
var context = contextArgs[0];
var element = this.element;
var me = this;
if (! elementAlign) {
elementAlign = contextArgs[1];
}
if (! contextAlign) {
contextAlign = contextArgs[2];
}
if (element && context) {
var elementRegion = YAHOO.util.Dom.getRegion(element);
var contextRegion = YAHOO.util.Dom.getRegion(context);
var doAlign = function(v,h) {
switch (elementAlign) {
case YAHOO.widget.Overlay.TOP_LEFT:
me.moveTo(h,v);
break;
case YAHOO.widget.Overlay.TOP_RIGHT:
me.moveTo(h-element.offsetWidth,v);
break;
case YAHOO.widget.Overlay.BOTTOM_LEFT:
me.moveTo(h,v-element.offsetHeight);
break;
case YAHOO.widget.Overlay.BOTTOM_RIGHT:
me.moveTo(h-element.offsetWidth,v-element.offsetHeight);
break;
}
};
switch (contextAlign) {
case YAHOO.widget.Overlay.TOP_LEFT:
doAlign(contextRegion.top, contextRegion.left);
break;
case YAHOO.widget.Overlay.TOP_RIGHT:
doAlign(contextRegion.top, contextRegion.right);
break;
case YAHOO.widget.Overlay.BOTTOM_LEFT:
doAlign(contextRegion.bottom, contextRegion.left);
break;
case YAHOO.widget.Overlay.BOTTOM_RIGHT:
doAlign(contextRegion.bottom, contextRegion.right);
break;
}
}
}
};
/**
* The default event handler executed when the moveEvent is fired, if the "constraintoviewport" is set to true.
* @method enforceConstraints
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers, this will usually equal the owner.
*/
YAHOO.widget.Overlay.prototype.enforceConstraints = function(type, args, obj) {
var pos = args[0];
var x = pos[0];
var y = pos[1];
var offsetHeight = this.element.offsetHeight;
var offsetWidth = this.element.offsetWidth;
var viewPortWidth = YAHOO.util.Dom.getViewportWidth();
var viewPortHeight = YAHOO.util.Dom.getViewportHeight();
var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
var topConstraint = scrollY + 10;
var leftConstraint = scrollX + 10;
var bottomConstraint = scrollY + viewPortHeight - offsetHeight - 10;
var rightConstraint = scrollX + viewPortWidth - offsetWidth - 10;
if (x < leftConstraint) {
x = leftConstraint;
} else if (x > rightConstraint) {
x = rightConstraint;
}
if (y < topConstraint) {
y = topConstraint;
} else if (y > bottomConstraint) {
y = bottomConstraint;
}
this.cfg.setProperty("x", x, true);
this.cfg.setProperty("y", y, true);
this.cfg.setProperty("xy", [x,y], true);
};
/**
* Centers the container in the viewport.
* @method center
*/
YAHOO.widget.Overlay.prototype.center = function() {
var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
var viewPortWidth = YAHOO.util.Dom.getClientWidth();
var viewPortHeight = YAHOO.util.Dom.getClientHeight();
var elementWidth = this.element.offsetWidth;
var elementHeight = this.element.offsetHeight;
var x = (viewPortWidth / 2) - (elementWidth / 2) + scrollX;
var y = (viewPortHeight / 2) - (elementHeight / 2) + scrollY;
this.cfg.setProperty("xy", [parseInt(x, 10), parseInt(y, 10)]);
this.cfg.refireEvent("iframe");
};
/**
* Synchronizes the Panel's "xy", "x", and "y" properties with the Panel's position in the DOM. This is primarily used to update position information during drag & drop.
* @method syncPosition
*/
YAHOO.widget.Overlay.prototype.syncPosition = function() {
var pos = YAHOO.util.Dom.getXY(this.element);
this.cfg.setProperty("x", pos[0], true);
this.cfg.setProperty("y", pos[1], true);
this.cfg.setProperty("xy", pos, true);
};
/**
* Event handler fired when the resize monitor element is resized.
* @method onDomResize
* @param {DOMEvent} e The resize DOM event
* @param {Object} obj The scope object
*/
YAHOO.widget.Overlay.prototype.onDomResize = function(e, obj) {
YAHOO.widget.Overlay.superclass.onDomResize.call(this, e, obj);
var me = this;
setTimeout(function() {
me.syncPosition();
me.cfg.refireEvent("iframe");
me.cfg.refireEvent("context");
}, 0);
};
/**
* Removes the Overlay element from the DOM and sets all child elements to null.
* @method destroy
*/
YAHOO.widget.Overlay.prototype.destroy = function() {
if (this.iframe) {
this.iframe.parentNode.removeChild(this.iframe);
}
this.iframe = null;
YAHOO.widget.Overlay.superclass.destroy.call(this);
};
/**
* Returns a String representation of the object.
* @method toString
* @return {String} The string representation of the Overlay.
*/
YAHOO.widget.Overlay.prototype.toString = function() {
return "Overlay " + this.id;
};
/**
* A singleton CustomEvent used for reacting to the DOM event for window scroll
* @event YAHOO.widget.Overlay.windowScrollEvent
*/
YAHOO.widget.Overlay.windowScrollEvent = new YAHOO.util.CustomEvent("windowScroll");
/**
* A singleton CustomEvent used for reacting to the DOM event for window resize
* @event YAHOO.widget.Overlay.windowResizeEvent
*/
YAHOO.widget.Overlay.windowResizeEvent = new YAHOO.util.CustomEvent("windowResize");
/**
* The DOM event handler used to fire the CustomEvent for window scroll
* @method YAHOO.widget.Overlay.windowScrollHandler
* @static
* @param {DOMEvent} e The DOM scroll event
*/
YAHOO.widget.Overlay.windowScrollHandler = function(e) {
if (YAHOO.widget.Module.prototype.browser == "ie" || YAHOO.widget.Module.prototype.browser == "ie7") {
if (! window.scrollEnd) {
window.scrollEnd = -1;
}
clearTimeout(window.scrollEnd);
window.scrollEnd = setTimeout(function() { YAHOO.widget.Overlay.windowScrollEvent.fire(); }, 1);
} else {
YAHOO.widget.Overlay.windowScrollEvent.fire();
}
};
/**
* The DOM event handler used to fire the CustomEvent for window resize
* @method YAHOO.widget.Overlay.windowResizeHandler
* @static
* @param {DOMEvent} e The DOM resize event
*/
YAHOO.widget.Overlay.windowResizeHandler = function(e) {
if (YAHOO.widget.Module.prototype.browser == "ie" || YAHOO.widget.Module.prototype.browser == "ie7") {
if (! window.resizeEnd) {
window.resizeEnd = -1;
}
clearTimeout(window.resizeEnd);
window.resizeEnd = setTimeout(function() { YAHOO.widget.Overlay.windowResizeEvent.fire(); }, 100);
} else {
YAHOO.widget.Overlay.windowResizeEvent.fire();
}
};
/**
* A boolean that indicated whether the window resize and scroll events have already been subscribed to.
* @property YAHOO.widget.Overlay._initialized
* @private
* @type Boolean
*/
YAHOO.widget.Overlay._initialized = null;
if (YAHOO.widget.Overlay._initialized === null) {
YAHOO.util.Event.addListener(window, "scroll", YAHOO.widget.Overlay.windowScrollHandler);
YAHOO.util.Event.addListener(window, "resize", YAHOO.widget.Overlay.windowResizeHandler);
YAHOO.widget.Overlay._initialized = true;
}
/**
* OverlayManager is used for maintaining the focus status of multiple Overlays.* @namespace YAHOO.widget
* @namespace YAHOO.widget
* @class OverlayManager
* @constructor
* @param {Array} overlays Optional. A collection of Overlays to register with the manager.
* @param {Object} userConfig The object literal representing the user configuration of the OverlayManager
*/
YAHOO.widget.OverlayManager = function(userConfig) {
this.init(userConfig);
};
/**
* The CSS class representing a focused Overlay
* @property YAHOO.widget.OverlayManager.CSS_FOCUSED
* @static
* @final
* @type String
*/
YAHOO.widget.OverlayManager.CSS_FOCUSED = "focused";
YAHOO.widget.OverlayManager.prototype = {
/**
* The class's constructor function
* @property contructor
* @type Function
*/
constructor : YAHOO.widget.OverlayManager,
/**
* The array of Overlays that are currently registered
* @property overlays
* @type YAHOO.widget.Overlay[]
*/
overlays : null,
/**
* Initializes the default configuration of the OverlayManager
* @method initDefaultConfig
*/
initDefaultConfig : function() {
/**
* The collection of registered Overlays in use by the OverlayManager
* @config overlays
* @type YAHOO.widget.Overlay[]
* @default null
*/
this.cfg.addProperty("overlays", { suppressEvent:true } );
/**
* The default DOM event that should be used to focus an Overlay
* @config focusevent
* @type String
* @default "mousedown"
*/
this.cfg.addProperty("focusevent", { value:"mousedown" } );
},
/**
* Initializes the OverlayManager
* @method init
* @param {YAHOO.widget.Overlay[]} overlays Optional. A collection of Overlays to register with the manager.
* @param {Object} userConfig The object literal representing the user configuration of the OverlayManager
*/
init : function(userConfig) {
/**
* The OverlayManager's Config object used for monitoring configuration properties.
* @property cfg
* @type YAHOO.util.Config
*/
this.cfg = new YAHOO.util.Config(this);
this.initDefaultConfig();
if (userConfig) {
this.cfg.applyConfig(userConfig, true);
}
this.cfg.fireQueue();
/**
* The currently activated Overlay
* @property activeOverlay
* @private
* @type YAHOO.widget.Overlay
*/
var activeOverlay = null;
/**
* Returns the currently focused Overlay
* @method getActive
* @return {YAHOO.widget.Overlay} The currently focused Overlay
*/
this.getActive = function() {
return activeOverlay;
};
/**
* Focuses the specified Overlay
* @method focus
* @param {YAHOO.widget.Overlay} overlay The Overlay to focus
* @param {String} overlay The id of the Overlay to focus
*/
this.focus = function(overlay) {
var o = this.find(overlay);
if (o) {
this.blurAll();
activeOverlay = o;
YAHOO.util.Dom.addClass(activeOverlay.element, YAHOO.widget.OverlayManager.CSS_FOCUSED);
this.overlays.sort(this.compareZIndexDesc);
var topZIndex = YAHOO.util.Dom.getStyle(this.overlays[0].element, "zIndex");
if (! isNaN(topZIndex) && this.overlays[0] != overlay) {
activeOverlay.cfg.setProperty("zIndex", (parseInt(topZIndex, 10) + 2));
}
this.overlays.sort(this.compareZIndexDesc);
}
};
/**
* Removes the specified Overlay from the manager
* @method remove
* @param {YAHOO.widget.Overlay} overlay The Overlay to remove
* @param {String} overlay The id of the Overlay to remove
*/
this.remove = function(overlay) {
var o = this.find(overlay);
if (o) {
var originalZ = YAHOO.util.Dom.getStyle(o.element, "zIndex");
o.cfg.setProperty("zIndex", -1000, true);
this.overlays.sort(this.compareZIndexDesc);
this.overlays = this.overlays.slice(0, this.overlays.length-1);
o.cfg.setProperty("zIndex", originalZ, true);
o.cfg.setProperty("manager", null);
o.focusEvent = null;
o.blurEvent = null;
o.focus = null;
o.blur = null;
}
};
/**
* Removes focus from all registered Overlays in the manager
* @method blurAll
*/
this.blurAll = function() {
activeOverlay = null;
for (var o=0;o<this.overlays.length;o++) {
YAHOO.util.Dom.removeClass(this.overlays[o].element, YAHOO.widget.OverlayManager.CSS_FOCUSED);
}
};
var overlays = this.cfg.getProperty("overlays");
if (! this.overlays) {
this.overlays = [];
}
if (overlays) {
this.register(overlays);
this.overlays.sort(this.compareZIndexDesc);
}
},
/**
* Registers an Overlay or an array of Overlays with the manager. Upon registration, the Overlay receives functions for focus and blur, along with CustomEvents for each.
* @method register
* @param {YAHOO.widget.Overlay} overlay An Overlay to register with the manager.
* @param {YAHOO.widget.Overlay[]} overlay An array of Overlays to register with the manager.
* @return {Boolean} True if any Overlays are registered.
*/
register : function(overlay) {
if (overlay instanceof YAHOO.widget.Overlay) {
overlay.cfg.addProperty("manager", { value:this } );
overlay.focusEvent = new YAHOO.util.CustomEvent("focus");
overlay.blurEvent = new YAHOO.util.CustomEvent("blur");
var mgr=this;
overlay.focus = function() {
mgr.focus(this);
this.focusEvent.fire();
};
overlay.blur = function() {
mgr.blurAll();
this.blurEvent.fire();
};
var focusOnDomEvent = function(e,obj) {
overlay.focus();
};
var focusevent = this.cfg.getProperty("focusevent");
YAHOO.util.Event.addListener(overlay.element,focusevent,focusOnDomEvent,this,true);
var zIndex = YAHOO.util.Dom.getStyle(overlay.element, "zIndex");
if (! isNaN(zIndex)) {
overlay.cfg.setProperty("zIndex", parseInt(zIndex, 10));
} else {
overlay.cfg.setProperty("zIndex", 0);
}
this.overlays.push(overlay);
return true;
} else if (overlay instanceof Array) {
var regcount = 0;
for (var i=0;i<overlay.length;i++) {
if (this.register(overlay[i])) {
regcount++;
}
}
if (regcount > 0) {
return true;
}
} else {
return false;
}
},
/**
* Attempts to locate an Overlay by instance or ID.
* @method find
* @param {YAHOO.widget.Overlay} overlay An Overlay to locate within the manager
* @param {String} overlay An Overlay id to locate within the manager
* @return {YAHOO.widget.Overlay} The requested Overlay, if found, or null if it cannot be located.
*/
find : function(overlay) {
if (overlay instanceof YAHOO.widget.Overlay) {
for (var o=0;o<this.overlays.length;o++) {
if (this.overlays[o] == overlay) {
return this.overlays[o];
}
}
} else if (typeof overlay == "string") {
for (var p=0;p<this.overlays.length;p++) {
if (this.overlays[p].id == overlay) {
return this.overlays[p];
}
}
}
return null;
},
/**
* Used for sorting the manager's Overlays by z-index.
* @method compareZIndexDesc
* @private
* @return {Number} 0, 1, or -1, depending on where the Overlay should fall in the stacking order.
*/
compareZIndexDesc : function(o1, o2) {
var zIndex1 = o1.cfg.getProperty("zIndex");
var zIndex2 = o2.cfg.getProperty("zIndex");
if (zIndex1 > zIndex2) {
return -1;
} else if (zIndex1 < zIndex2) {
return 1;
} else {
return 0;
}
},
/**
* Shows all Overlays in the manager.
* @method showAll
*/
showAll : function() {
for (var o=0;o<this.overlays.length;o++) {
this.overlays[o].show();
}
},
/**
* Hides all Overlays in the manager.
* @method hideAll
*/
hideAll : function() {
for (var o=0;o<this.overlays.length;o++) {
this.overlays[o].hide();
}
},
/**
* Returns a string representation of the object.
* @method toString
* @return {String} The string representation of the OverlayManager
*/
toString : function() {
return "OverlayManager";
}
};
/**
* KeyListener is a utility that provides an easy interface for listening for keydown/keyup events fired against DOM elements.
* @namespace YAHOO.util
* @class KeyListener
* @constructor
* @param {HTMLElement} attachTo The element or element ID to which the key event should be attached
* @param {String} attachTo The element or element ID to which the key event should be attached
* @param {Object} keyData The object literal representing the key(s) to detect. Possible attributes are shift(boolean), alt(boolean), ctrl(boolean) and keys(either an int or an array of ints representing keycodes).
* @param {Function} handler The CustomEvent handler to fire when the key event is detected
* @param {Object} handler An object literal representing the handler.
* @param {String} event Optional. The event (keydown or keyup) to listen for. Defaults automatically to keydown.
*/
YAHOO.util.KeyListener = function(attachTo, keyData, handler, event) {
if (! attachTo) {
YAHOO.log("No attachTo element specified", "error");
}
if (! keyData) {
YAHOO.log("No keyData specified", "error");
}
if (! handler) {
YAHOO.log("No handler specified", "error");
}
if (! event) {
event = YAHOO.util.KeyListener.KEYDOWN;
}
/**
* The CustomEvent fired internally when a key is pressed
* @event keyEvent
* @private
* @param {Object} keyData The object literal representing the key(s) to detect. Possible attributes are shift(boolean), alt(boolean), ctrl(boolean) and keys(either an int or an array of ints representing keycodes).
*/
var keyEvent = new YAHOO.util.CustomEvent("keyPressed");
/**
* The CustomEvent fired when the KeyListener is enabled via the enable() function
* @event enabledEvent
* @param {Object} keyData The object literal representing the key(s) to detect. Possible attributes are shift(boolean), alt(boolean), ctrl(boolean) and keys(either an int or an array of ints representing keycodes).
*/
this.enabledEvent = new YAHOO.util.CustomEvent("enabled");
/**
* The CustomEvent fired when the KeyListener is disabled via the disable() function
* @event disabledEvent
* @param {Object} keyData The object literal representing the key(s) to detect. Possible attributes are shift(boolean), alt(boolean), ctrl(boolean) and keys(either an int or an array of ints representing keycodes).
*/
this.disabledEvent = new YAHOO.util.CustomEvent("disabled");
if (typeof attachTo == 'string') {
attachTo = document.getElementById(attachTo);
}
if (typeof handler == 'function') {
keyEvent.subscribe(handler);
} else {
keyEvent.subscribe(handler.fn, handler.scope, handler.correctScope);
}
/**
* Handles the key event when a key is pressed.
* @method handleKeyPress
* @param {DOMEvent} e The keypress DOM event
* @param {Object} obj The DOM event scope object
* @private
*/
function handleKeyPress(e, obj) {
if (! keyData.shift) {
keyData.shift = false;
}
if (! keyData.alt) {
keyData.alt = false;
}
if (! keyData.ctrl) {
keyData.ctrl = false;
}
// check held down modifying keys first
if (e.shiftKey == keyData.shift &&
e.altKey == keyData.alt &&
e.ctrlKey == keyData.ctrl) { // if we pass this, all modifiers match
var dataItem;
var keyPressed;
if (keyData.keys instanceof Array) {
for (var i=0;i<keyData.keys.length;i++) {
dataItem = keyData.keys[i];
if (dataItem == e.charCode ) {
keyEvent.fire(e.charCode, e);
break;
} else if (dataItem == e.keyCode) {
keyEvent.fire(e.keyCode, e);
break;
}
}
} else {
dataItem = keyData.keys;
if (dataItem == e.charCode ) {
keyEvent.fire(e.charCode, e);
} else if (dataItem == e.keyCode) {
keyEvent.fire(e.keyCode, e);
}
}
}
}
/**
* Enables the KeyListener by attaching the DOM event listeners to the target DOM element
* @method enable
*/
this.enable = function() {
if (! this.enabled) {
YAHOO.util.Event.addListener(attachTo, event, handleKeyPress);
this.enabledEvent.fire(keyData);
}
/**
* Boolean indicating the enabled/disabled state of the Tooltip
* @property enabled
* @type Boolean
*/
this.enabled = true;
};
/**
* Disables the KeyListener by removing the DOM event listeners from the target DOM element
* @method disable
*/
this.disable = function() {
if (this.enabled) {
YAHOO.util.Event.removeListener(attachTo, event, handleKeyPress);
this.disabledEvent.fire(keyData);
}
this.enabled = false;
};
/**
* Returns a String representation of the object.
* @method toString
* @return {String} The string representation of the KeyListener
*/
this.toString = function() {
return "KeyListener [" + keyData.keys + "] " + attachTo.tagName + (attachTo.id ? "[" + attachTo.id + "]" : "");
};
};
/**
* Constant representing the DOM "keydown" event.
* @property YAHOO.util.KeyListener.KEYDOWN
* @static
* @final
* @type String
*/
YAHOO.util.KeyListener.KEYDOWN = "keydown";
/**
* Constant representing the DOM "keyup" event.
* @property YAHOO.util.KeyListener.KEYUP
* @static
* @final
* @type String
*/
YAHOO.util.KeyListener.KEYUP = "keyup";
/**
* ContainerEffect encapsulates animation transitions that are executed when an Overlay is shown or hidden.
* @namespace YAHOO.widget
* @class ContainerEffect
* @constructor
* @param {YAHOO.widget.Overlay} overlay The Overlay that the animation should be associated with
* @param {Object} attrIn The object literal representing the animation arguments to be used for the animate-in transition. The arguments for this literal are: attributes(object, see YAHOO.util.Anim for description), duration(Number), and method(i.e. YAHOO.util.Easing.easeIn).
* @param {Object} attrOut The object literal representing the animation arguments to be used for the animate-out transition. The arguments for this literal are: attributes(object, see YAHOO.util.Anim for description), duration(Number), and method(i.e. YAHOO.util.Easing.easeIn).
* @param {HTMLElement} targetElement Optional. The target element that should be animated during the transition. Defaults to overlay.element.
* @param {class} Optional. The animation class to instantiate. Defaults to YAHOO.util.Anim. Other options include YAHOO.util.Motion.
*/
YAHOO.widget.ContainerEffect = function(overlay, attrIn, attrOut, targetElement, animClass) {
if (! animClass) {
animClass = YAHOO.util.Anim;
}
/**
* The overlay to animate
* @property overlay
* @type YAHOO.widget.Overlay
*/
this.overlay = overlay;
/**
* The animation attributes to use when transitioning into view
* @property attrIn
* @type Object
*/
this.attrIn = attrIn;
/**
* The animation attributes to use when transitioning out of view
* @property attrOut
* @type Object
*/
this.attrOut = attrOut;
/**
* The target element to be animated
* @property targetElement
* @type HTMLElement
*/
this.targetElement = targetElement || overlay.element;
/**
* The animation class to use for animating the overlay
* @property animClass
* @type class
*/
this.animClass = animClass;
};
/**
* Initializes the animation classes and events.
* @method init
*/
YAHOO.widget.ContainerEffect.prototype.init = function() {
this.beforeAnimateInEvent = new YAHOO.util.CustomEvent("beforeAnimateIn");
this.beforeAnimateOutEvent = new YAHOO.util.CustomEvent("beforeAnimateOut");
this.animateInCompleteEvent = new YAHOO.util.CustomEvent("animateInComplete");
this.animateOutCompleteEvent = new YAHOO.util.CustomEvent("animateOutComplete");
this.animIn = new this.animClass(this.targetElement, this.attrIn.attributes, this.attrIn.duration, this.attrIn.method);
this.animIn.onStart.subscribe(this.handleStartAnimateIn, this);
this.animIn.onTween.subscribe(this.handleTweenAnimateIn, this);
this.animIn.onComplete.subscribe(this.handleCompleteAnimateIn, this);
this.animOut = new this.animClass(this.targetElement, this.attrOut.attributes, this.attrOut.duration, this.attrOut.method);
this.animOut.onStart.subscribe(this.handleStartAnimateOut, this);
this.animOut.onTween.subscribe(this.handleTweenAnimateOut, this);
this.animOut.onComplete.subscribe(this.handleCompleteAnimateOut, this);
};
/**
* Triggers the in-animation.
* @method animateIn
*/
YAHOO.widget.ContainerEffect.prototype.animateIn = function() {
this.beforeAnimateInEvent.fire();
this.animIn.animate();
};
/**
* Triggers the out-animation.
* @method animateOut
*/
YAHOO.widget.ContainerEffect.prototype.animateOut = function() {
this.beforeAnimateOutEvent.fire();
this.animOut.animate();
};
/**
* The default onStart handler for the in-animation.
* @method handleStartAnimateIn
* @param {String} type The CustomEvent type
* @param {Object[]} args The CustomEvent arguments
* @param {Object} obj The scope object
*/
YAHOO.widget.ContainerEffect.prototype.handleStartAnimateIn = function(type, args, obj) { };
/**
* The default onTween handler for the in-animation.
* @method handleTweenAnimateIn
* @param {String} type The CustomEvent type
* @param {Object[]} args The CustomEvent arguments
* @param {Object} obj The scope object
*/
YAHOO.widget.ContainerEffect.prototype.handleTweenAnimateIn = function(type, args, obj) { };
/**
* The default onComplete handler for the in-animation.
* @method handleCompleteAnimateIn
* @param {String} type The CustomEvent type
* @param {Object[]} args The CustomEvent arguments
* @param {Object} obj The scope object
*/
YAHOO.widget.ContainerEffect.prototype.handleCompleteAnimateIn = function(type, args, obj) { };
/**
* The default onStart handler for the out-animation.
* @method handleStartAnimateOut
* @param {String} type The CustomEvent type
* @param {Object[]} args The CustomEvent arguments
* @param {Object} obj The scope object
*/
YAHOO.widget.ContainerEffect.prototype.handleStartAnimateOut = function(type, args, obj) { };
/**
* The default onTween handler for the out-animation.
* @method handleTweenAnimateOut
* @param {String} type The CustomEvent type
* @param {Object[]} args The CustomEvent arguments
* @param {Object} obj The scope object
*/
YAHOO.widget.ContainerEffect.prototype.handleTweenAnimateOut = function(type, args, obj) { };
/**
* The default onComplete handler for the out-animation.
* @method handleCompleteAnimateOut
* @param {String} type The CustomEvent type
* @param {Object[]} args The CustomEvent arguments
* @param {Object} obj The scope object
*/
YAHOO.widget.ContainerEffect.prototype.handleCompleteAnimateOut = function(type, args, obj) { };
/**
* Returns a string representation of the object.
* @method toString
* @return {String} The string representation of the ContainerEffect
*/
YAHOO.widget.ContainerEffect.prototype.toString = function() {
var output = "ContainerEffect";
if (this.overlay) {
output += " [" + this.overlay.toString() + "]";
}
return output;
};
/**
* A pre-configured ContainerEffect instance that can be used for fading an overlay in and out.
* @method FADE
* @static
* @param {Overlay} The Overlay object to animate
* @param {Number} The duration of the animation
* @return {ContainerEffect} The configured ContainerEffect object
*/
YAHOO.widget.ContainerEffect.FADE = function(overlay, dur) {
var fade = new YAHOO.widget.ContainerEffect(overlay, { attributes:{opacity: {from:0, to:1}}, duration:dur, method:YAHOO.util.Easing.easeIn }, { attributes:{opacity: {to:0}}, duration:dur, method:YAHOO.util.Easing.easeOut}, overlay.element );
fade.handleStartAnimateIn = function(type,args,obj) {
YAHOO.util.Dom.addClass(obj.overlay.element, "hide-select");
if (! obj.overlay.underlay) {
obj.overlay.cfg.refireEvent("underlay");
}
if (obj.overlay.underlay) {
obj.initialUnderlayOpacity = YAHOO.util.Dom.getStyle(obj.overlay.underlay, "opacity");
obj.overlay.underlay.style.filter = null;
}
YAHOO.util.Dom.setStyle(obj.overlay.element, "visibility", "visible");
YAHOO.util.Dom.setStyle(obj.overlay.element, "opacity", 0);
};
fade.handleCompleteAnimateIn = function(type,args,obj) {
YAHOO.util.Dom.removeClass(obj.overlay.element, "hide-select");
if (obj.overlay.element.style.filter) {
obj.overlay.element.style.filter = null;
}
if (obj.overlay.underlay) {
YAHOO.util.Dom.setStyle(obj.overlay.underlay, "opacity", obj.initialUnderlayOpacity);
}
obj.overlay.cfg.refireEvent("iframe");
obj.animateInCompleteEvent.fire();
};
fade.handleStartAnimateOut = function(type, args, obj) {
YAHOO.util.Dom.addClass(obj.overlay.element, "hide-select");
if (obj.overlay.underlay) {
obj.overlay.underlay.style.filter = null;
}
};
fade.handleCompleteAnimateOut = function(type, args, obj) {
YAHOO.util.Dom.removeClass(obj.overlay.element, "hide-select");
if (obj.overlay.element.style.filter) {
obj.overlay.element.style.filter = null;
}
YAHOO.util.Dom.setStyle(obj.overlay.element, "visibility", "hidden");
YAHOO.util.Dom.setStyle(obj.overlay.element, "opacity", 1);
obj.overlay.cfg.refireEvent("iframe");
obj.animateOutCompleteEvent.fire();
};
fade.init();
return fade;
};
/**
* A pre-configured ContainerEffect instance that can be used for sliding an overlay in and out.
* @method SLIDE
* @static
* @param {Overlay} The Overlay object to animate
* @param {Number} The duration of the animation
* @return {ContainerEffect} The configured ContainerEffect object
*/
YAHOO.widget.ContainerEffect.SLIDE = function(overlay, dur) {
var x = overlay.cfg.getProperty("x") || YAHOO.util.Dom.getX(overlay.element);
var y = overlay.cfg.getProperty("y") || YAHOO.util.Dom.getY(overlay.element);
var clientWidth = YAHOO.util.Dom.getClientWidth();
var offsetWidth = overlay.element.offsetWidth;
var slide = new YAHOO.widget.ContainerEffect(overlay, {
attributes:{ points: { to:[x, y] } },
duration:dur,
method:YAHOO.util.Easing.easeIn
},
{
attributes:{ points: { to:[(clientWidth+25), y] } },
duration:dur,
method:YAHOO.util.Easing.easeOut
},
overlay.element,
YAHOO.util.Motion);
slide.handleStartAnimateIn = function(type,args,obj) {
obj.overlay.element.style.left = (-25-offsetWidth) + "px";
obj.overlay.element.style.top = y + "px";
};
slide.handleTweenAnimateIn = function(type, args, obj) {
var pos = YAHOO.util.Dom.getXY(obj.overlay.element);
var currentX = pos[0];
var currentY = pos[1];
if (YAHOO.util.Dom.getStyle(obj.overlay.element, "visibility") == "hidden" && currentX < x) {
YAHOO.util.Dom.setStyle(obj.overlay.element, "visibility", "visible");
}
obj.overlay.cfg.setProperty("xy", [currentX,currentY], true);
obj.overlay.cfg.refireEvent("iframe");
};
slide.handleCompleteAnimateIn = function(type, args, obj) {
obj.overlay.cfg.setProperty("xy", [x,y], true);
obj.startX = x;
obj.startY = y;
obj.overlay.cfg.refireEvent("iframe");
obj.animateInCompleteEvent.fire();
};
slide.handleStartAnimateOut = function(type, args, obj) {
var vw = YAHOO.util.Dom.getViewportWidth();
var pos = YAHOO.util.Dom.getXY(obj.overlay.element);
var yso = pos[1];
var currentTo = obj.animOut.attributes.points.to;
obj.animOut.attributes.points.to = [(vw+25), yso];
};
slide.handleTweenAnimateOut = function(type, args, obj) {
var pos = YAHOO.util.Dom.getXY(obj.overlay.element);
var xto = pos[0];
var yto = pos[1];
obj.overlay.cfg.setProperty("xy", [xto,yto], true);
obj.overlay.cfg.refireEvent("iframe");
};
slide.handleCompleteAnimateOut = function(type, args, obj) {
YAHOO.util.Dom.setStyle(obj.overlay.element, "visibility", "hidden");
obj.overlay.cfg.setProperty("xy", [x,y]);
obj.animateOutCompleteEvent.fire();
};
slide.init();
return slide;
}; | richkadel/flip.tv | showfiles/src/main/webapp/lib/YahooUI/container/container_core-debug.js | JavaScript | apache-2.0 | 93,694 |
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var common = require("ui/tab-view/tab-view-common");
var trace = require("trace");
var imageSource = require("image-source");
var VIEWS_STATES = "_viewStates";
require("utils/module-merge").merge(common, exports);
var ViewPagerClass = (function (_super) {
__extends(ViewPagerClass, _super);
function ViewPagerClass(ctx, owner) {
_super.call(this, ctx);
this.owner = owner;
return global.__native(this);
}
ViewPagerClass.prototype.onVisibilityChanged = function (changedView, visibility) {
_super.prototype.onVisibilityChanged.call(this, changedView, visibility);
this.owner._onVisibilityChanged(changedView, visibility);
};
return ViewPagerClass;
})(android.support.v4.view.ViewPager);
;
var PagerAdapterClass = (function (_super) {
__extends(PagerAdapterClass, _super);
function PagerAdapterClass(owner, items) {
_super.call(this);
this.owner = owner;
this.items = items;
return global.__native(this);
}
PagerAdapterClass.prototype.getCount = function () {
return this.items ? this.items.length : 0;
};
PagerAdapterClass.prototype.getPageTitle = function (index) {
if (index < 0 || index >= this.items.length) {
return "";
}
return this.items[index].title;
};
PagerAdapterClass.prototype.instantiateItem = function (container, index) {
trace.write("TabView.PagerAdapter.instantiateItem; container: " + container + "; index: " + index, common.traceCategory);
var item = this.items[index];
if (item.view.parent !== this.owner) {
this.owner._addView(item.view);
}
if (this[VIEWS_STATES]) {
trace.write("TabView.PagerAdapter.instantiateItem; restoreHierarchyState: " + item.view, common.traceCategory);
item.view.android.restoreHierarchyState(this[VIEWS_STATES]);
}
container.addView(item.view.android);
return item.view.android;
};
PagerAdapterClass.prototype.destroyItem = function (container, index, _object) {
trace.write("TabView.PagerAdapter.destroyItem; container: " + container + "; index: " + index + "; _object: " + _object, common.traceCategory);
var item = this.items[index];
var nativeView = item.view.android;
if (nativeView.toString() !== _object.toString()) {
throw new Error("Expected " + nativeView.toString() + " to equal " + _object.toString());
}
if (!this[VIEWS_STATES]) {
this[VIEWS_STATES] = new android.util.SparseArray();
}
nativeView.saveHierarchyState(this[VIEWS_STATES]);
container.removeView(nativeView);
if (item.view.parent === this.owner) {
this.owner._removeView(item.view);
}
};
PagerAdapterClass.prototype.isViewFromObject = function (view, _object) {
return view === _object;
};
PagerAdapterClass.prototype.saveState = function () {
trace.write("TabView.PagerAdapter.saveState", common.traceCategory);
var owner = this.owner;
if (!owner || owner._childrenCount === 0) {
return null;
}
if (!this[VIEWS_STATES]) {
this[VIEWS_STATES] = new android.util.SparseArray();
}
var viewStates = this[VIEWS_STATES];
var childCallback = function (view) {
var nativeView = view.android;
if (nativeView && nativeView.isSaveFromParentEnabled && nativeView.isSaveFromParentEnabled()) {
nativeView.saveHierarchyState(viewStates);
}
return true;
};
owner._eachChildView(childCallback);
var bundle = new android.os.Bundle();
bundle.putSparseParcelableArray(VIEWS_STATES, viewStates);
return bundle;
};
PagerAdapterClass.prototype.restoreState = function (state, loader) {
trace.write("TabView.PagerAdapter.restoreState", common.traceCategory);
var bundle = state;
bundle.setClassLoader(loader);
this[VIEWS_STATES] = bundle.getSparseParcelableArray(VIEWS_STATES);
};
return PagerAdapterClass;
})(android.support.v4.view.PagerAdapter);
;
var TabView = (function (_super) {
__extends(TabView, _super);
function TabView() {
_super.call(this);
this._listenersSuspended = false;
this._tabsAddedByMe = new Array();
this._tabsCache = {};
this._iconsCache = {};
var that = new WeakRef(this);
this._tabListener = new android.app.ActionBar.TabListener({
get owner() {
return that.get();
},
onTabSelected: function (tab, transaction) {
var owner = this.owner;
if (!owner) {
return;
}
if (owner._listenersSuspended || !owner.isLoaded) {
return;
}
var index = owner._tabsCache[tab.hashCode()];
trace.write("TabView.TabListener.onTabSelected(" + index + ");", common.traceCategory);
owner.selectedIndex = index;
},
onTabUnselected: function (tab, transaction) {
},
onTabReselected: function (tab, transaction) {
}
});
this._pageChangeListener = new android.support.v4.view.ViewPager.OnPageChangeListener({
get owner() {
return that.get();
},
onPageSelected: function (index) {
var owner = this.owner;
if (!owner) {
return;
}
if (owner._listenersSuspended || !owner.isLoaded) {
return;
}
trace.write("TabView.OnPageChangeListener.onPageSelected(" + index + ");", common.traceCategory);
owner.selectedIndex = index;
},
onPageScrollStateChanged: function (state) {
},
onPageScrolled: function (index, offset, offsetPixels) {
}
});
}
Object.defineProperty(TabView.prototype, "android", {
get: function () {
return this._android;
},
enumerable: true,
configurable: true
});
TabView.prototype._createUI = function () {
trace.write("TabView._createUI(" + this._android + ");", common.traceCategory);
this._android = new ViewPagerClass(this._context, this);
if (!this._androidViewId) {
this._androidViewId = android.view.View.generateViewId();
}
this._android.setId(this._androidViewId);
this._android.setOnPageChangeListener(this._pageChangeListener);
};
TabView.prototype._onVisibilityChanged = function (changedView, visibility) {
trace.write("TabView._onVisibilityChanged:" + this.android + " isShown():" + this.android.isShown(), common.traceCategory);
if (this.isLoaded && this.android && this.android.isShown()) {
this._addTabsIfNeeded();
this._setNativeSelectedIndex(this.selectedIndex);
}
else {
if (TabView._isProxyOfOrDescendantOfNativeView(this, changedView)) {
this._removeTabsIfNeeded();
}
}
};
TabView._isProxyOfOrDescendantOfNativeView = function (view, nativeView) {
if (view.android === nativeView) {
return true;
}
if (!view.parent) {
return false;
}
return TabView._isProxyOfOrDescendantOfNativeView(view.parent, nativeView);
};
TabView.prototype._onAttached = function (context) {
trace.write("TabView._onAttached(" + context + ");", common.traceCategory);
_super.prototype._onAttached.call(this, context);
};
TabView.prototype._onDetached = function (force) {
trace.write("TabView._onDetached(" + force + ");", common.traceCategory);
_super.prototype._onDetached.call(this, force);
};
TabView.prototype.onLoaded = function () {
trace.write("TabView.onLoaded(); selectedIndex: " + this.selectedIndex + "; items: " + this.items + ";", common.traceCategory);
_super.prototype.onLoaded.call(this);
if (this.android && this.android.isShown()) {
this._addTabsIfNeeded();
}
};
TabView.prototype.onUnloaded = function () {
trace.write("TabView.onUnloaded();", common.traceCategory);
this._removeTabsIfNeeded();
_super.prototype.onUnloaded.call(this);
};
TabView.prototype._addTabsIfNeeded = function () {
if (this.items && this.items.length > 0 && this._tabsAddedByMe.length === 0) {
this._listenersSuspended = true;
this._addTabs(this.items);
this._listenersSuspended = false;
}
};
TabView.prototype._removeTabsIfNeeded = function () {
if (this._tabsAddedByMe.length > 0) {
this._listenersSuspended = true;
this._removeTabs(this.items);
this._listenersSuspended = false;
}
};
TabView.prototype._onItemsPropertyChangedSetNativeValue = function (data) {
trace.write("TabView._onItemsPropertyChangedSetNativeValue(" + data.oldValue + " ---> " + data.newValue + ");", common.traceCategory);
this._listenersSuspended = true;
if (data.oldValue) {
this._removeTabs(data.oldValue);
this._unsetAdapter();
}
if (data.newValue) {
this._addTabs(data.newValue);
this._setAdapter(data.newValue);
}
this._updateSelectedIndexOnItemsPropertyChanged(data.newValue);
this._listenersSuspended = false;
};
TabView.prototype._setAdapter = function (items) {
this._pagerAdapter = new PagerAdapterClass(this, items);
this._android.setAdapter(this._pagerAdapter);
};
TabView.prototype._unsetAdapter = function () {
if (this._pagerAdapter) {
this._android.setAdapter(null);
this._pagerAdapter = null;
}
};
TabView.prototype._addTabs = function (newItems) {
trace.write("TabView._addTabs(" + newItems + ");", common.traceCategory);
_super.prototype._addTabs.call(this, newItems);
var actionBar = this._getActionBar();
if (!actionBar) {
return;
}
if (this._tabsAddedByMe.length > 0) {
throw new Error("TabView has already added its tabs to the ActionBar.");
}
this._originalActionBarNavigationMode = actionBar.getNavigationMode();
actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS);
this._originalActionBarIsShowing = actionBar.isShowing();
actionBar.show();
var i = 0;
var length = newItems.length;
var item;
var tab;
for (i; i < length; i++) {
item = newItems[i];
tab = actionBar.newTab();
tab.setText(item.title);
this._setIcon(item.iconSource, tab);
tab.setTabListener(this._tabListener);
actionBar.addTab(tab);
this._tabsCache[tab.hashCode()] = i;
this._tabsAddedByMe.push(tab);
}
};
TabView.prototype._setIcon = function (iconSource, tab) {
if (!iconSource) {
return;
}
var drawable;
drawable = this._iconsCache[iconSource];
if (!drawable) {
var is = imageSource.fromFileOrResource(iconSource);
if (is) {
drawable = new android.graphics.drawable.BitmapDrawable(is.android);
this._iconsCache[iconSource] = drawable;
}
}
if (drawable) {
tab.setIcon(drawable);
}
};
TabView.prototype._removeTabs = function (oldItems) {
trace.write("TabView._removeTabs(" + oldItems + ");", common.traceCategory);
_super.prototype._removeTabs.call(this, oldItems);
var actionBar = this._getActionBar();
if (!actionBar) {
return;
}
var i = actionBar.getTabCount() - 1;
var tab;
var index;
for (i; i >= 0; i--) {
tab = actionBar.getTabAt(i);
index = this._tabsAddedByMe.indexOf(tab);
if (index > -1) {
actionBar.removeTabAt(i);
tab.setTabListener(null);
delete this._tabsCache[tab.hashCode()];
this._tabsAddedByMe.splice(index, 1);
}
}
if (this._tabsAddedByMe.length > 0) {
throw new Error("TabView did not remove all of its tabs from the ActionBar.");
}
if (this._originalActionBarNavigationMode !== undefined) {
actionBar.setNavigationMode(this._originalActionBarNavigationMode);
}
if (!this._originalActionBarIsShowing) {
actionBar.hide();
}
};
TabView.prototype._onSelectedIndexPropertyChangedSetNativeValue = function (data) {
trace.write("TabView._onSelectedIndexPropertyChangedSetNativeValue(" + data.oldValue + " ---> " + data.newValue + ");", common.traceCategory);
_super.prototype._onSelectedIndexPropertyChangedSetNativeValue.call(this, data);
this._setNativeSelectedIndex(data.newValue);
};
TabView.prototype._setNativeSelectedIndex = function (index) {
if (index === undefined || index === null) {
return;
}
var actionBar = this._getActionBar();
if (actionBar) {
var actionBarSelectedIndex = actionBar.getSelectedNavigationIndex();
if (actionBarSelectedIndex !== index) {
actionBar.setSelectedNavigationItem(index);
}
}
var viewPagerSelectedIndex = this._android.getCurrentItem();
if (viewPagerSelectedIndex !== index) {
this._android.setCurrentItem(index, true);
}
};
TabView.prototype._loadEachChildView = function () {
};
TabView.prototype._unloadEachChildView = function () {
};
TabView.prototype._getActionBar = function () {
if (!this._android) {
return undefined;
}
var activity = this._android.getContext();
return activity.getActionBar();
};
return TabView;
})(common.TabView);
exports.TabView = TabView;
| paveldk/TalkUpp-Repo | tns_modules/ui/tab-view/tab-view.android.js | JavaScript | bsd-2-clause | 14,657 |
if (typeof module !== 'undefined' && module.exports) {
module.exports = jQuery;
}
else if (typeof define !== 'undefined' && define.amd) {
define([], function () {
return jQuery;
});
}
| alkaest2002/gzts-lab | web/app/assets/frameworks/bower_components/r.js/build/tests/pragma/good5.js | JavaScript | bsd-3-clause | 204 |
// 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.
// Shows an updating list of process statistics.
function init() {
chrome.processes.onUpdatedWithMemory.addListener(
function(processes) {
var table = "<table>\n" +
"<tr><td><b>Process</b></td>" +
"<td>OS ID</td>" +
"<td>Title</td>" +
"<td>Type</td>" +
"<td>Tabs</td>" +
"<td>CPU</td>" +
"<td>Network</td>" +
"<td>Private Memory</td>" +
"<td>FPS</td>" +
"<td>JS Memory</td>" +
"<td></td>" +
"</tr>\n";
for (pid in processes) {
table = displayProcessInfo(processes[pid], table);
}
table += "</table>\n";
var div = document.getElementById("process-list");
div.innerHTML = table;
});
document.getElementById("killProcess").onclick = function () {
var procId = parseInt(prompt("Enter process ID"));
chrome.processes.terminate(procId);
}
}
function displayProcessInfo(process, table) {
// Format network string like task manager
var network = process.network;
if (network > 1024) {
network = (network / 1024).toFixed(1) + " kB/s";
} else if (network > 0) {
network += " B/s";
} else if (network == -1) {
network = "N/A";
}
table +=
"<tr><td>" + process.id + "</td>" +
"<td>" + process.osProcessId + "</td>" +
"<td>" + process.title + "</td>" +
"<td>" + process.type + "</td>" +
"<td>" + process.tabs + "</td>" +
"<td>" + process.cpu + "</td>" +
"<td>" + network + "</td>";
if ("privateMemory" in process) {
table += "<td>" + (process.privateMemory / 1024) + "K</td>";
} else {
table += "<td>N/A</td>";
}
if ("fps" in process) {
table += "<td>" + process.fps.toFixed(2) + "</td>";
} else {
table += "<td>N/A</td>";
}
if ("jsMemoryAllocated" in process) {
var allocated = process.jsMemoryAllocated / 1024;
var used = process.jsMemoryUsed / 1024;
table += "<td>" + allocated.toFixed(2) + "K (" + used.toFixed(2) +
"K live)</td>";
} else {
table += "<td>N/A</td>";
}
table +=
"<td></td>" +
"</tr>\n";
return table;
}
document.addEventListener('DOMContentLoaded', init);
| anirudhSK/chromium | chrome/common/extensions/docs/examples/api/processes/process_monitor/popup.js | JavaScript | bsd-3-clause | 2,324 |
function (doc) {
if (doc.doc_type === "ADMReport"
&& (!doc.domain || (doc.domain && doc.is_default))) {
var entry = {
name: doc.name,
description: doc.description
};
if (doc.domain) {
entry['domain'] = doc.domain;
}
emit(["defaults all slug", doc.reporting_section, doc.slug, doc._id], entry);
if (doc.domain) {
emit(["defaults domain slug", doc.domain, doc.reporting_section, doc.slug, doc._id], entry);
} else {
emit(["defaults global slug", doc.reporting_section, doc.slug, doc._id], entry);
}
}
}
| gmimano/commcaretest | corehq/apps/adm/_design/views/all_default_reports/map.js | JavaScript | bsd-3-clause | 641 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var gonzales = require('gonzales');
exports.parse = gonzales.srcToCSSP;
exports.toCSS = gonzales.csspToSrc;
exports.toTree = gonzales.csspToTree;
exports.traverse = require('./lib/traverse.js');
},{"./lib/traverse.js":2,"gonzales":5}],2:[function(require,module,exports){
function tree(node, visitor) {
if (!Array.isArray(node)) {
return node;
}
if (visitor.test && visitor.test(node[0], node[1])) {
node = visitor.process(node);
if (!node) {
return;
}
}
var res = [node[0]];
for (var i = 1; i < node.length; i++) {
var n = tree(node[i], visitor);
n && res.push(n);
}
return res;
}
module.exports = function traverse (ast, visitors) {
visitors.forEach(function(visitor) {
ast = tree(ast, visitor);
});
return ast;
};
},{}],3:[function(require,module,exports){
// version: 1.0.0
function csspToSrc(tree, hasInfo) {
var _m_simple = {
'unary': 1, 'nth': 1, 'combinator': 1, 'ident': 1, 'number': 1, 's': 1,
'string': 1, 'attrselector': 1, 'operator': 1, 'raw': 1, 'unknown': 1
},
_m_composite = {
'simpleselector': 1, 'dimension': 1, 'selector': 1, 'property': 1, 'value': 1,
'filterv': 1, 'progid': 1, 'ruleset': 1, 'atruleb': 1, 'atrulerq': 1, 'atrulers': 1,
'stylesheet': 1
},
_m_primitive = {
'cdo': 'cdo', 'cdc': 'cdc', 'decldelim': ';', 'namespace': '|', 'delim': ','
};
function _t(tree) {
var t = tree[hasInfo? 1 : 0];
if (t in _m_primitive) return _m_primitive[t];
else if (t in _m_simple) return _simple(tree);
else if (t in _m_composite) return _composite(tree);
return _unique[t](tree);
}
function _composite(t, i) {
var s = '';
i = i === undefined ? (hasInfo? 2 : 1) : i;
for (; i < t.length; i++) s += _t(t[i]);
return s;
}
function _simple(t) {
return t[hasInfo? 2 : 1];
}
var _unique = {
percentage: function(t) {
return _t(t[hasInfo? 2 : 1]) + '%';
},
comment: function (t) {
return '/*' + t[hasInfo? 2 : 1] + '*/';
},
clazz: function(t) {
return '.' + _t(t[hasInfo? 2 : 1]);
},
atkeyword: function(t) {
return '@' + _t(t[hasInfo? 2 : 1]);
},
shash: function (t) {
return '#' + t[hasInfo? 2 : 1];
},
vhash: function(t) {
return '#' + t[hasInfo? 2 : 1];
},
attrib: function(t) {
return '[' + _composite(t) + ']';
},
important: function(t) {
return '!' + _composite(t) + 'important';
},
nthselector: function(t) {
return ':' + _simple(t[hasInfo? 2 : 1]) + '(' + _composite(t, hasInfo? 3 : 2) + ')';
},
funktion: function(t) {
return _simple(t[hasInfo? 2 : 1]) + '(' + _composite(t[hasInfo? 3: 2]) + ')';
},
declaration: function(t) {
return _t(t[hasInfo? 2 : 1]) + ':' + _t(t[hasInfo? 3 : 2]);
},
filter: function(t) {
return _t(t[hasInfo? 2 : 1]) + ':' + _t(t[hasInfo? 3 : 2]);
},
block: function(t) {
return '{' + _composite(t) + '}';
},
braces: function(t) {
return t[hasInfo? 2 : 1] + _composite(t, hasInfo? 4 : 3) + t[hasInfo? 3 : 2];
},
atrules: function(t) {
return _composite(t) + ';';
},
atruler: function(t) {
return _t(t[hasInfo? 2 : 1]) + _t(t[hasInfo? 3 : 2]) + '{' + _t(t[hasInfo? 4 : 3]) + '}';
},
pseudoe: function(t) {
return '::' + _t(t[hasInfo? 2 : 1]);
},
pseudoc: function(t) {
return ':' + _t(t[hasInfo? 2 : 1]);
},
uri: function(t) {
return 'url(' + _composite(t) + ')';
},
functionExpression: function(t) {
return 'expression(' + t[hasInfo? 2 : 1] + ')';
}
};
return _t(tree);
}
exports.csspToSrc = csspToSrc;
},{}],4:[function(require,module,exports){
var srcToCSSP = (function() {
var TokenType = {
StringSQ: 'StringSQ',
StringDQ: 'StringDQ',
CommentML: 'CommentML',
CommentSL: 'CommentSL',
Newline: 'Newline',
Space: 'Space',
Tab: 'Tab',
ExclamationMark: 'ExclamationMark', // !
QuotationMark: 'QuotationMark', // "
NumberSign: 'NumberSign', // #
DollarSign: 'DollarSign', // $
PercentSign: 'PercentSign', // %
Ampersand: 'Ampersand', // &
Apostrophe: 'Apostrophe', // '
LeftParenthesis: 'LeftParenthesis', // (
RightParenthesis: 'RightParenthesis', // )
Asterisk: 'Asterisk', // *
PlusSign: 'PlusSign', // +
Comma: 'Comma', // ,
HyphenMinus: 'HyphenMinus', // -
FullStop: 'FullStop', // .
Solidus: 'Solidus', // /
Colon: 'Colon', // :
Semicolon: 'Semicolon', // ;
LessThanSign: 'LessThanSign', // <
EqualsSign: 'EqualsSign', // =
GreaterThanSign: 'GreaterThanSign', // >
QuestionMark: 'QuestionMark', // ?
CommercialAt: 'CommercialAt', // @
LeftSquareBracket: 'LeftSquareBracket', // [
ReverseSolidus: 'ReverseSolidus', // \
RightSquareBracket: 'RightSquareBracket', // ]
CircumflexAccent: 'CircumflexAccent', // ^
LowLine: 'LowLine', // _
LeftCurlyBracket: 'LeftCurlyBracket', // {
VerticalLine: 'VerticalLine', // |
RightCurlyBracket: 'RightCurlyBracket', // }
Tilde: 'Tilde', // ~
Identifier: 'Identifier',
DecimalNumber: 'DecimalNumber'
};
var getTokens = (function() {
var Punctuation,
urlMode = false,
blockMode = 0;
Punctuation = {
' ': TokenType.Space,
'\n': TokenType.Newline,
'\r': TokenType.Newline,
'\t': TokenType.Tab,
'!': TokenType.ExclamationMark,
'"': TokenType.QuotationMark,
'#': TokenType.NumberSign,
'$': TokenType.DollarSign,
'%': TokenType.PercentSign,
'&': TokenType.Ampersand,
'\'': TokenType.Apostrophe,
'(': TokenType.LeftParenthesis,
')': TokenType.RightParenthesis,
'*': TokenType.Asterisk,
'+': TokenType.PlusSign,
',': TokenType.Comma,
'-': TokenType.HyphenMinus,
'.': TokenType.FullStop,
'/': TokenType.Solidus,
':': TokenType.Colon,
';': TokenType.Semicolon,
'<': TokenType.LessThanSign,
'=': TokenType.EqualsSign,
'>': TokenType.GreaterThanSign,
'?': TokenType.QuestionMark,
'@': TokenType.CommercialAt,
'[': TokenType.LeftSquareBracket,
// '\\': TokenType.ReverseSolidus,
']': TokenType.RightSquareBracket,
'^': TokenType.CircumflexAccent,
'_': TokenType.LowLine,
'{': TokenType.LeftCurlyBracket,
'|': TokenType.VerticalLine,
'}': TokenType.RightCurlyBracket,
'~': TokenType.Tilde
};
function isDecimalDigit(c) {
return '0123456789'.indexOf(c) >= 0;
}
function throwError(message) {
throw message;
}
var buffer = '',
tokens = [],
pos,
tn = 0,
ln = 1;
function _getTokens(s) {
if (!s) return [];
tokens = [];
var c, cn;
for (pos = 0; pos < s.length; pos++) {
c = s.charAt(pos);
cn = s.charAt(pos + 1);
if (c === '/' && cn === '*') {
parseMLComment(s);
} else if (!urlMode && c === '/' && cn === '/') {
if (blockMode > 0) parseIdentifier(s);
else parseSLComment(s);
} else if (c === '"' || c === "'") {
parseString(s, c);
} else if (c === ' ') {
parseSpaces(s)
} else if (c in Punctuation) {
pushToken(Punctuation[c], c);
if (c === '\n' || c === '\r') ln++;
if (c === ')') urlMode = false;
if (c === '{') blockMode++;
if (c === '}') blockMode--;
} else if (isDecimalDigit(c)) {
parseDecimalNumber(s);
} else {
parseIdentifier(s);
}
}
mark();
return tokens;
}
function pushToken(type, value) {
tokens.push({ tn: tn++, ln: ln, type: type, value: value });
}
function parseSpaces(s) {
var start = pos;
for (; pos < s.length; pos++) {
if (s.charAt(pos) !== ' ') break;
}
pushToken(TokenType.Space, s.substring(start, pos));
pos--;
}
function parseMLComment(s) {
var start = pos;
for (pos = pos + 2; pos < s.length; pos++) {
if (s.charAt(pos) === '*') {
if (s.charAt(pos + 1) === '/') {
pos++;
break;
}
}
}
pushToken(TokenType.CommentML, s.substring(start, pos + 1));
}
function parseSLComment(s) {
var start = pos;
for (pos = pos + 2; pos < s.length; pos++) {
if (s.charAt(pos) === '\n' || s.charAt(pos) === '\r') {
pos++;
break;
}
}
pushToken(TokenType.CommentSL, s.substring(start, pos));
pos--;
}
function parseString(s, q) {
var start = pos;
for (pos = pos + 1; pos < s.length; pos++) {
if (s.charAt(pos) === '\\') pos++;
else if (s.charAt(pos) === q) break;
}
pushToken(q === '"' ? TokenType.StringDQ : TokenType.StringSQ, s.substring(start, pos + 1));
}
function parseDecimalNumber(s) {
var start = pos;
for (; pos < s.length; pos++) {
if (!isDecimalDigit(s.charAt(pos))) break;
}
pushToken(TokenType.DecimalNumber, s.substring(start, pos));
pos--;
}
function parseIdentifier(s) {
var start = pos;
while (s.charAt(pos) === '/') pos++;
for (; pos < s.length; pos++) {
if (s.charAt(pos) === '\\') pos++;
else if (s.charAt(pos) in Punctuation) break;
}
var ident = s.substring(start, pos);
urlMode = urlMode || ident === 'url';
pushToken(TokenType.Identifier, ident);
pos--;
}
// ====================================
// second run
// ====================================
function mark() {
var ps = [], // Parenthesis
sbs = [], // SquareBracket
cbs = [], // CurlyBracket
t;
for (var i = 0; i < tokens.length; i++) {
t = tokens[i];
switch(t.type) {
case TokenType.LeftParenthesis:
ps.push(i);
break;
case TokenType.RightParenthesis:
if (ps.length) {
t.left = ps.pop();
tokens[t.left].right = i;
}
break;
case TokenType.LeftSquareBracket:
sbs.push(i);
break;
case TokenType.RightSquareBracket:
if (sbs.length) {
t.left = sbs.pop();
tokens[t.left].right = i;
}
break;
case TokenType.LeftCurlyBracket:
cbs.push(i);
break;
case TokenType.RightCurlyBracket:
if (cbs.length) {
t.left = cbs.pop();
tokens[t.left].right = i;
}
break;
}
}
}
return function(s) {
return _getTokens(s);
};
}());
// version: 1.0.0
var getCSSPAST = (function() {
var tokens,
pos,
failLN = 0,
currentBlockLN = 0,
needInfo = false;
var CSSPNodeType,
CSSLevel,
CSSPRules;
CSSPNodeType = {
IdentType: 'ident',
AtkeywordType: 'atkeyword',
StringType: 'string',
ShashType: 'shash',
VhashType: 'vhash',
NumberType: 'number',
PercentageType: 'percentage',
DimensionType: 'dimension',
CdoType: 'cdo',
CdcType: 'cdc',
DecldelimType: 'decldelim',
SType: 's',
AttrselectorType: 'attrselector',
AttribType: 'attrib',
NthType: 'nth',
NthselectorType: 'nthselector',
NamespaceType: 'namespace',
ClazzType: 'clazz',
PseudoeType: 'pseudoe',
PseudocType: 'pseudoc',
DelimType: 'delim',
StylesheetType: 'stylesheet',
AtrulebType: 'atruleb',
AtrulesType: 'atrules',
AtrulerqType: 'atrulerq',
AtrulersType: 'atrulers',
AtrulerType: 'atruler',
BlockType: 'block',
RulesetType: 'ruleset',
CombinatorType: 'combinator',
SimpleselectorType: 'simpleselector',
SelectorType: 'selector',
DeclarationType: 'declaration',
PropertyType: 'property',
ImportantType: 'important',
UnaryType: 'unary',
OperatorType: 'operator',
BracesType: 'braces',
ValueType: 'value',
ProgidType: 'progid',
FiltervType: 'filterv',
FilterType: 'filter',
CommentType: 'comment',
UriType: 'uri',
RawType: 'raw',
FunctionBodyType: 'functionBody',
FunktionType: 'funktion',
FunctionExpressionType: 'functionExpression',
UnknownType: 'unknown'
};
CSSPRules = {
'ident': function() { if (checkIdent(pos)) return getIdent() },
'atkeyword': function() { if (checkAtkeyword(pos)) return getAtkeyword() },
'string': function() { if (checkString(pos)) return getString() },
'shash': function() { if (checkShash(pos)) return getShash() },
'vhash': function() { if (checkVhash(pos)) return getVhash() },
'number': function() { if (checkNumber(pos)) return getNumber() },
'percentage': function() { if (checkPercentage(pos)) return getPercentage() },
'dimension': function() { if (checkDimension(pos)) return getDimension() },
// 'cdo': function() { if (checkCDO()) return getCDO() },
// 'cdc': function() { if (checkCDC()) return getCDC() },
'decldelim': function() { if (checkDecldelim(pos)) return getDecldelim() },
's': function() { if (checkS(pos)) return getS() },
'attrselector': function() { if (checkAttrselector(pos)) return getAttrselector() },
'attrib': function() { if (checkAttrib(pos)) return getAttrib() },
'nth': function() { if (checkNth(pos)) return getNth() },
'nthselector': function() { if (checkNthselector(pos)) return getNthselector() },
'namespace': function() { if (checkNamespace(pos)) return getNamespace() },
'clazz': function() { if (checkClazz(pos)) return getClazz() },
'pseudoe': function() { if (checkPseudoe(pos)) return getPseudoe() },
'pseudoc': function() { if (checkPseudoc(pos)) return getPseudoc() },
'delim': function() { if (checkDelim(pos)) return getDelim() },
'stylesheet': function() { if (checkStylesheet(pos)) return getStylesheet() },
'atruleb': function() { if (checkAtruleb(pos)) return getAtruleb() },
'atrules': function() { if (checkAtrules(pos)) return getAtrules() },
'atrulerq': function() { if (checkAtrulerq(pos)) return getAtrulerq() },
'atrulers': function() { if (checkAtrulers(pos)) return getAtrulers() },
'atruler': function() { if (checkAtruler(pos)) return getAtruler() },
'block': function() { if (checkBlock(pos)) return getBlock() },
'ruleset': function() { if (checkRuleset(pos)) return getRuleset() },
'combinator': function() { if (checkCombinator(pos)) return getCombinator() },
'simpleselector': function() { if (checkSimpleselector(pos)) return getSimpleSelector() },
'selector': function() { if (checkSelector(pos)) return getSelector() },
'declaration': function() { if (checkDeclaration(pos)) return getDeclaration() },
'property': function() { if (checkProperty(pos)) return getProperty() },
'important': function() { if (checkImportant(pos)) return getImportant() },
'unary': function() { if (checkUnary(pos)) return getUnary() },
'operator': function() { if (checkOperator(pos)) return getOperator() },
'braces': function() { if (checkBraces(pos)) return getBraces() },
'value': function() { if (checkValue(pos)) return getValue() },
'progid': function() { if (checkProgid(pos)) return getProgid() },
'filterv': function() { if (checkFilterv(pos)) return getFilterv() },
'filter': function() { if (checkFilter(pos)) return getFilter() },
'comment': function() { if (checkComment(pos)) return getComment() },
'uri': function() { if (checkUri(pos)) return getUri() },
'raw': function() { if (checkRaw(pos)) return getRaw() },
'funktion': function() { if (checkFunktion(pos)) return getFunktion() },
'functionExpression': function() { if (checkFunctionExpression(pos)) return getFunctionExpression() },
'unknown': function() { if (checkUnknown(pos)) return getUnknown() }
};
function fail(token) {
if (token && token.ln > failLN) failLN = token.ln;
}
function throwError() {
throw new Error('Please check the validity of the CSS block starting from the line #' + currentBlockLN);
}
function _getAST(_tokens, rule, _needInfo) {
tokens = _tokens;
needInfo = _needInfo;
pos = 0;
markSC();
return rule ? CSSPRules[rule]() : CSSPRules['stylesheet']();
}
//any = braces | string | percentage | dimension | number | uri | functionExpression | funktion | ident | unary
function checkAny(_i) {
return checkBraces(_i) ||
checkString(_i) ||
checkPercentage(_i) ||
checkDimension(_i) ||
checkNumber(_i) ||
checkUri(_i) ||
checkFunctionExpression(_i) ||
checkFunktion(_i) ||
checkIdent(_i) ||
checkUnary(_i);
}
function getAny() {
if (checkBraces(pos)) return getBraces();
else if (checkString(pos)) return getString();
else if (checkPercentage(pos)) return getPercentage();
else if (checkDimension(pos)) return getDimension();
else if (checkNumber(pos)) return getNumber();
else if (checkUri(pos)) return getUri();
else if (checkFunctionExpression(pos)) return getFunctionExpression();
else if (checkFunktion(pos)) return getFunktion();
else if (checkIdent(pos)) return getIdent();
else if (checkUnary(pos)) return getUnary();
}
//atkeyword = '@' ident:x -> [#atkeyword, x]
function checkAtkeyword(_i) {
var l;
if (tokens[_i++].type !== TokenType.CommercialAt) return fail(tokens[_i - 1]);
if (l = checkIdent(_i)) return l + 1;
return fail(tokens[_i]);
}
function getAtkeyword() {
var startPos = pos;
pos++;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.AtkeywordType, getIdent()]:
[CSSPNodeType.AtkeywordType, getIdent()];
}
//attrib = '[' sc*:s0 ident:x sc*:s1 attrselector:a sc*:s2 (ident | string):y sc*:s3 ']' -> this.concat([#attrib], s0, [x], s1, [a], s2, [y], s3)
// | '[' sc*:s0 ident:x sc*:s1 ']' -> this.concat([#attrib], s0, [x], s1),
function checkAttrib(_i) {
if (tokens[_i].type !== TokenType.LeftSquareBracket) return fail(tokens[_i]);
if (!tokens[_i].right) return fail(tokens[_i]);
return tokens[_i].right - _i + 1;
}
function checkAttrib1(_i) {
var start = _i;
_i++;
var l = checkSC(_i); // s0
if (l) _i += l;
if (l = checkIdent(_i)) _i += l; // x
else return fail(tokens[_i]);
if (l = checkSC(_i)) _i += l; // s1
if (l = checkAttrselector(_i)) _i += l; // a
else return fail(tokens[_i]);
if (l = checkSC(_i)) _i += l; // s2
if ((l = checkIdent(_i)) || (l = checkString(_i))) _i += l; // y
else return fail(tokens[_i]);
if (l = checkSC(_i)) _i += l; // s3
if (tokens[_i].type === TokenType.RightSquareBracket) return _i - start;
return fail(tokens[_i]);
}
function getAttrib1() {
var startPos = pos;
pos++;
var a = (needInfo? [{ ln: tokens[startPos].ln }, CSSPNodeType.AttribType] : [CSSPNodeType.AttribType])
.concat(getSC())
.concat([getIdent()])
.concat(getSC())
.concat([getAttrselector()])
.concat(getSC())
.concat([checkString(pos)? getString() : getIdent()])
.concat(getSC());
pos++;
return a;
}
function checkAttrib2(_i) {
var start = _i;
_i++;
var l = checkSC(_i);
if (l) _i += l;
if (l = checkIdent(_i)) _i += l;
if (l = checkSC(_i)) _i += l;
if (tokens[_i].type === TokenType.RightSquareBracket) return _i - start;
return fail(tokens[_i]);
}
function getAttrib2() {
var startPos = pos;
pos++;
var a = (needInfo? [{ ln: tokens[startPos].ln }, CSSPNodeType.AttribType] : [CSSPNodeType.AttribType])
.concat(getSC())
.concat([getIdent()])
.concat(getSC());
pos++;
return a;
}
function getAttrib() {
if (checkAttrib1(pos)) return getAttrib1();
if (checkAttrib2(pos)) return getAttrib2();
}
//attrselector = (seq('=') | seq('~=') | seq('^=') | seq('$=') | seq('*=') | seq('|=')):x -> [#attrselector, x]
function checkAttrselector(_i) {
if (tokens[_i].type === TokenType.EqualsSign) return 1;
if (tokens[_i].type === TokenType.VerticalLine && (!tokens[_i + 1] || tokens[_i + 1].type !== TokenType.EqualsSign)) return 1;
if (!tokens[_i + 1] || tokens[_i + 1].type !== TokenType.EqualsSign) return fail(tokens[_i]);
switch(tokens[_i].type) {
case TokenType.Tilde:
case TokenType.CircumflexAccent:
case TokenType.DollarSign:
case TokenType.Asterisk:
case TokenType.VerticalLine:
return 2;
}
return fail(tokens[_i]);
}
function getAttrselector() {
var startPos = pos,
s = tokens[pos++].value;
if (tokens[pos] && tokens[pos].type === TokenType.EqualsSign) s += tokens[pos++].value;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.AttrselectorType, s] :
[CSSPNodeType.AttrselectorType, s];
}
//atrule = atruler | atruleb | atrules
function checkAtrule(_i) {
var start = _i,
l;
if (tokens[start].atrule_l !== undefined) return tokens[start].atrule_l;
if (l = checkAtruler(_i)) tokens[_i].atrule_type = 1;
else if (l = checkAtruleb(_i)) tokens[_i].atrule_type = 2;
else if (l = checkAtrules(_i)) tokens[_i].atrule_type = 3;
else return fail(tokens[start]);
tokens[start].atrule_l = l;
return l;
}
function getAtrule() {
switch (tokens[pos].atrule_type) {
case 1: return getAtruler();
case 2: return getAtruleb();
case 3: return getAtrules();
}
}
//atruleb = atkeyword:ak tset*:ap block:b -> this.concat([#atruleb, ak], ap, [b])
function checkAtruleb(_i) {
var start = _i,
l;
if (l = checkAtkeyword(_i)) _i += l;
else return fail(tokens[_i]);
if (l = checkTsets(_i)) _i += l;
if (l = checkBlock(_i)) _i += l;
else return fail(tokens[_i]);
return _i - start;
}
function getAtruleb() {
return (needInfo?
[{ ln: tokens[pos].ln }, CSSPNodeType.AtrulebType, getAtkeyword()] :
[CSSPNodeType.AtrulebType, getAtkeyword()])
.concat(getTsets())
.concat([getBlock()]);
}
//atruler = atkeyword:ak atrulerq:x '{' atrulers:y '}' -> [#atruler, ak, x, y]
function checkAtruler(_i) {
var start = _i,
l;
if (l = checkAtkeyword(_i)) _i += l;
else return fail(tokens[_i]);
if (l = checkAtrulerq(_i)) _i += l;
if (_i < tokens.length && tokens[_i].type === TokenType.LeftCurlyBracket) _i++;
else return fail(tokens[_i]);
if (l = checkAtrulers(_i)) _i += l;
if (_i < tokens.length && tokens[_i].type === TokenType.RightCurlyBracket) _i++;
else return fail(tokens[_i]);
return _i - start;
}
function getAtruler() {
var atruler = needInfo?
[{ ln: tokens[pos].ln }, CSSPNodeType.AtrulerType, getAtkeyword(), getAtrulerq()] :
[CSSPNodeType.AtrulerType, getAtkeyword(), getAtrulerq()];
pos++;
atruler.push(getAtrulers());
pos++;
return atruler;
}
//atrulerq = tset*:ap -> [#atrulerq].concat(ap)
function checkAtrulerq(_i) {
return checkTsets(_i);
}
function getAtrulerq() {
return (needInfo? [{ ln: tokens[pos].ln }, CSSPNodeType.AtrulerqType] : [CSSPNodeType.AtrulerqType]).concat(getTsets());
}
//atrulers = sc*:s0 ruleset*:r sc*:s1 -> this.concat([#atrulers], s0, r, s1)
function checkAtrulers(_i) {
var start = _i,
l;
if (l = checkSC(_i)) _i += l;
while ((l = checkRuleset(_i)) || (l = checkAtrule(_i)) || (l = checkSC(_i))) {
_i += l;
}
tokens[_i].atrulers_end = 1;
if (l = checkSC(_i)) _i += l;
return _i - start;
}
function getAtrulers() {
var atrulers = (needInfo? [{ ln: tokens[pos].ln }, CSSPNodeType.AtrulersType] : [CSSPNodeType.AtrulersType]).concat(getSC()),
x;
while (!tokens[pos].atrulers_end) {
if (checkSC(pos)) {
atrulers = atrulers.concat(getSC());
} else if (checkRuleset(pos)) {
atrulers.push(getRuleset());
} else {
atrulers.push(getAtrule());
}
}
return atrulers.concat(getSC());
}
//atrules = atkeyword:ak tset*:ap ';' -> this.concat([#atrules, ak], ap)
function checkAtrules(_i) {
var start = _i,
l;
if (l = checkAtkeyword(_i)) _i += l;
else return fail(tokens[_i]);
if (l = checkTsets(_i)) _i += l;
if (_i >= tokens.length) return _i - start;
if (tokens[_i].type === TokenType.Semicolon) _i++;
else return fail(tokens[_i]);
return _i - start;
}
function getAtrules() {
var atrules = (needInfo? [{ ln: tokens[pos].ln }, CSSPNodeType.AtrulesType, getAtkeyword()] : [CSSPNodeType.AtrulesType, getAtkeyword()]).concat(getTsets());
pos++;
return atrules;
}
//block = '{' blockdecl*:x '}' -> this.concatContent([#block], x)
function checkBlock(_i) {
if (_i < tokens.length && tokens[_i].type === TokenType.LeftCurlyBracket) return tokens[_i].right - _i + 1;
return fail(tokens[_i]);
}
function getBlock() {
var block = needInfo? [{ ln: tokens[pos].ln }, CSSPNodeType.BlockType] : [CSSPNodeType.BlockType],
end = tokens[pos].right;
pos++;
while (pos < end) {
if (checkBlockdecl(pos)) block = block.concat(getBlockdecl());
else throwError();
}
pos = end + 1;
return block;
}
//blockdecl = sc*:s0 (filter | declaration):x decldelim:y sc*:s1 -> this.concat(s0, [x], [y], s1)
// | sc*:s0 (filter | declaration):x sc*:s1 -> this.concat(s0, [x], s1)
// | sc*:s0 decldelim:x sc*:s1 -> this.concat(s0, [x], s1)
// | sc+:s0 -> s0
function checkBlockdecl(_i) {
var l;
if (l = _checkBlockdecl0(_i)) tokens[_i].bd_type = 1;
else if (l = _checkBlockdecl1(_i)) tokens[_i].bd_type = 2;
else if (l = _checkBlockdecl2(_i)) tokens[_i].bd_type = 3;
else if (l = _checkBlockdecl3(_i)) tokens[_i].bd_type = 4;
else return fail(tokens[_i]);
return l;
}
function getBlockdecl() {
switch (tokens[pos].bd_type) {
case 1: return _getBlockdecl0();
case 2: return _getBlockdecl1();
case 3: return _getBlockdecl2();
case 4: return _getBlockdecl3();
}
}
//sc*:s0 (filter | declaration):x decldelim:y sc*:s1 -> this.concat(s0, [x], [y], s1)
function _checkBlockdecl0(_i) {
var start = _i,
l;
if (l = checkSC(_i)) _i += l;
if (l = checkFilter(_i)) {
tokens[_i].bd_filter = 1;
_i += l;
} else if (l = checkDeclaration(_i)) {
tokens[_i].bd_decl = 1;
_i += l;
} else return fail(tokens[_i]);
if (_i < tokens.length && (l = checkDecldelim(_i))) _i += l;
else return fail(tokens[_i]);
if (l = checkSC(_i)) _i += l;
return _i - start;
}
function _getBlockdecl0() {
return getSC()
.concat([tokens[pos].bd_filter? getFilter() : getDeclaration()])
.concat([getDecldelim()])
.concat(getSC());
}
//sc*:s0 (filter | declaration):x sc*:s1 -> this.concat(s0, [x], s1)
function _checkBlockdecl1(_i) {
var start = _i,
l;
if (l = checkSC(_i)) _i += l;
if (l = checkFilter(_i)) {
tokens[_i].bd_filter = 1;
_i += l;
} else if (l = checkDeclaration(_i)) {
tokens[_i].bd_decl = 1;
_i += l;
} else return fail(tokens[_i]);
if (l = checkSC(_i)) _i += l;
return _i - start;
}
function _getBlockdecl1() {
return getSC()
.concat([tokens[pos].bd_filter? getFilter() : getDeclaration()])
.concat(getSC());
}
//sc*:s0 decldelim:x sc*:s1 -> this.concat(s0, [x], s1)
function _checkBlockdecl2(_i) {
var start = _i,
l;
if (l = checkSC(_i)) _i += l;
if (l = checkDecldelim(_i)) _i += l;
else return fail(tokens[_i]);
if (l = checkSC(_i)) _i += l;
return _i - start;
}
function _getBlockdecl2() {
return getSC()
.concat([getDecldelim()])
.concat(getSC());
}
//sc+:s0 -> s0
function _checkBlockdecl3(_i) {
return checkSC(_i);
}
function _getBlockdecl3() {
return getSC();
}
//braces = '(' tset*:x ')' -> this.concat([#braces, '(', ')'], x)
// | '[' tset*:x ']' -> this.concat([#braces, '[', ']'], x)
function checkBraces(_i) {
if (_i >= tokens.length ||
(tokens[_i].type !== TokenType.LeftParenthesis &&
tokens[_i].type !== TokenType.LeftSquareBracket)
) return fail(tokens[_i]);
return tokens[_i].right - _i + 1;
}
function getBraces() {
var startPos = pos,
left = pos,
right = tokens[pos].right;
pos++;
var tsets = getTsets();
pos++;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.BracesType, tokens[left].value, tokens[right].value].concat(tsets) :
[CSSPNodeType.BracesType, tokens[left].value, tokens[right].value].concat(tsets);
}
function checkCDC(_i) {}
function checkCDO(_i) {}
// node: Clazz
function checkClazz(_i) {
var l;
if (tokens[_i].clazz_l) return tokens[_i].clazz_l;
if (tokens[_i].type === TokenType.FullStop) {
if (l = checkIdent(_i + 1)) {
tokens[_i].clazz_l = l + 1;
return l + 1;
}
}
return fail(tokens[_i]);
}
function getClazz() {
var startPos = pos;
pos++;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.ClazzType, getIdent()] :
[CSSPNodeType.ClazzType, getIdent()];
}
// node: Combinator
function checkCombinator(_i) {
if (tokens[_i].type === TokenType.PlusSign ||
tokens[_i].type === TokenType.GreaterThanSign ||
tokens[_i].type === TokenType.Tilde) return 1;
return fail(tokens[_i]);
}
function getCombinator() {
return needInfo?
[{ ln: tokens[pos].ln }, CSSPNodeType.CombinatorType, tokens[pos++].value] :
[CSSPNodeType.CombinatorType, tokens[pos++].value];
}
// node: Comment
function checkComment(_i) {
if (tokens[_i].type === TokenType.CommentML) return 1;
return fail(tokens[_i]);
}
function getComment() {
var startPos = pos,
s = tokens[pos].value.substring(2),
l = s.length;
if (s.charAt(l - 2) === '*' && s.charAt(l - 1) === '/') s = s.substring(0, l - 2);
pos++;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.CommentType, s] :
[CSSPNodeType.CommentType, s];
}
// declaration = property:x ':' value:y -> [#declaration, x, y]
function checkDeclaration(_i) {
var start = _i,
l;
if (l = checkProperty(_i)) _i += l;
else return fail(tokens[_i]);
if (_i < tokens.length && tokens[_i].type === TokenType.Colon) _i++;
else return fail(tokens[_i]);
if (l = checkValue(_i)) _i += l;
else return fail(tokens[_i]);
return _i - start;
}
function getDeclaration() {
var declaration = needInfo?
[{ ln: tokens[pos].ln }, CSSPNodeType.DeclarationType, getProperty()] :
[CSSPNodeType.DeclarationType, getProperty()];
pos++;
declaration.push(getValue());
return declaration;
}
// node: Decldelim
function checkDecldelim(_i) {
if (_i < tokens.length && tokens[_i].type === TokenType.Semicolon) return 1;
return fail(tokens[_i]);
}
function getDecldelim() {
var startPos = pos;
pos++;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.DecldelimType] :
[CSSPNodeType.DecldelimType];
}
// node: Delim
function checkDelim(_i) {
if (_i < tokens.length && tokens[_i].type === TokenType.Comma) return 1;
if (_i >= tokens.length) return fail(tokens[tokens.length - 1]);
return fail(tokens[_i]);
}
function getDelim() {
var startPos = pos;
pos++;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.DelimType] :
[CSSPNodeType.DelimType];
}
// node: Dimension
function checkDimension(_i) {
var ln = checkNumber(_i),
li;
if (!ln || (ln && _i + ln >= tokens.length)) return fail(tokens[_i]);
if (li = checkNmName2(_i + ln)) return ln + li;
return fail(tokens[_i]);
}
function getDimension() {
var startPos = pos,
n = getNumber(),
dimension = needInfo ?
[{ ln: tokens[pos].ln }, CSSPNodeType.IdentType, getNmName2()] :
[CSSPNodeType.IdentType, getNmName2()];
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.DimensionType, n, dimension] :
[CSSPNodeType.DimensionType, n, dimension];
}
//filter = filterp:x ':' filterv:y -> [#filter, x, y]
function checkFilter(_i) {
var start = _i,
l;
if (l = checkFilterp(_i)) _i += l;
else return fail(tokens[_i]);
if (tokens[_i].type === TokenType.Colon) _i++;
else return fail(tokens[_i]);
if (l = checkFilterv(_i)) _i += l;
else return fail(tokens[_i]);
return _i - start;
}
function getFilter() {
var filter = needInfo?
[{ ln: tokens[pos].ln }, CSSPNodeType.FilterType, getFilterp()] :
[CSSPNodeType.FilterType, getFilterp()];
pos++;
filter.push(getFilterv());
return filter;
}
//filterp = (seq('-filter') | seq('_filter') | seq('*filter') | seq('-ms-filter') | seq('filter')):t sc*:s0 -> this.concat([#property, [#ident, t]], s0)
function checkFilterp(_i) {
var start = _i,
l,
x;
if (_i < tokens.length) {
if (tokens[_i].value === 'filter') l = 1;
else {
x = joinValues2(_i, 2);
if (x === '-filter' || x === '_filter' || x === '*filter') l = 2;
else {
x = joinValues2(_i, 4);
if (x === '-ms-filter') l = 4;
else return fail(tokens[_i]);
}
}
tokens[start].filterp_l = l;
_i += l;
if (checkSC(_i)) _i += l;
return _i - start;
}
return fail(tokens[_i]);
}
function getFilterp() {
var startPos = pos,
x = joinValues2(pos, tokens[pos].filterp_l),
ident = needInfo? [{ ln: tokens[startPos].ln }, CSSPNodeType.IdentType, x] : [CSSPNodeType.IdentType, x];
pos += tokens[pos].filterp_l;
return (needInfo? [{ ln: tokens[startPos].ln }, CSSPNodeType.PropertyType, ident] : [CSSPNodeType.PropertyType, ident])
.concat(getSC());
}
//filterv = progid+:x -> [#filterv].concat(x)
function checkFilterv(_i) {
var start = _i,
l;
if (l = checkProgid(_i)) _i += l;
else return fail(tokens[_i]);
while (l = checkProgid(_i)) {
_i += l;
}
tokens[start].last_progid = _i;
if (_i < tokens.length && (l = checkSC(_i))) _i += l;
if (_i < tokens.length && (l = checkImportant(_i))) _i += l;
return _i - start;
}
function getFilterv() {
var filterv = needInfo? [{ ln: tokens[pos].ln }, CSSPNodeType.FiltervType] : [CSSPNodeType.FiltervType],
last_progid = tokens[pos].last_progid;
while (pos < last_progid) {
filterv.push(getProgid());
}
filterv = filterv.concat(checkSC(pos) ? getSC() : []);
if (pos < tokens.length && checkImportant(pos)) filterv.push(getImportant());
return filterv;
}
//functionExpression = ``expression('' functionExpressionBody*:x ')' -> [#functionExpression, x.join('')],
function checkFunctionExpression(_i) {
var start = _i;
if (!tokens[_i] || tokens[_i++].value !== 'expression') return fail(tokens[_i - 1]);
if (!tokens[_i] || tokens[_i].type !== TokenType.LeftParenthesis) return fail(tokens[_i]);
return tokens[_i].right - start + 1;
}
function getFunctionExpression() {
var startPos = pos;
pos++;
var e = joinValues(pos + 1, tokens[pos].right - 1);
pos = tokens[pos].right + 1;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.FunctionExpressionType, e] :
[CSSPNodeType.FunctionExpressionType, e];
}
//funktion = ident:x '(' functionBody:y ')' -> [#funktion, x, y]
function checkFunktion(_i) {
var start = _i,
l = checkIdent(_i);
if (!l) return fail(tokens[_i]);
_i += l;
if (_i >= tokens.length || tokens[_i].type !== TokenType.LeftParenthesis) return fail(tokens[_i - 1]);
return tokens[_i].right - start + 1;
}
function getFunktion() {
var startPos = pos,
ident = getIdent();
pos++;
var body = ident[needInfo? 2 : 1] !== 'not'?
getFunctionBody() :
getNotFunctionBody(); // ok, here we have CSS3 initial draft: http://dev.w3.org/csswg/selectors3/#negation
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.FunktionType, ident, body] :
[CSSPNodeType.FunktionType, ident, body];
}
function getFunctionBody() {
var startPos = pos,
body = [],
x;
while (tokens[pos].type !== TokenType.RightParenthesis) {
if (checkTset(pos)) {
x = getTset();
if ((needInfo && typeof x[1] === 'string') || typeof x[0] === 'string') body.push(x);
else body = body.concat(x);
} else if (checkClazz(pos)) {
body.push(getClazz());
} else {
throwError();
}
}
pos++;
return (needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.FunctionBodyType] :
[CSSPNodeType.FunctionBodyType]
).concat(body);
}
function getNotFunctionBody() {
var startPos = pos,
body = [],
x;
while (tokens[pos].type !== TokenType.RightParenthesis) {
if (checkSimpleselector(pos)) {
body.push(getSimpleSelector());
} else {
throwError();
}
}
pos++;
return (needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.FunctionBodyType] :
[CSSPNodeType.FunctionBodyType]
).concat(body);
}
// node: Ident
function checkIdent(_i) {
if (_i >= tokens.length) return fail(tokens[_i]);
var start = _i,
wasIdent = false;
if (tokens[_i].type === TokenType.LowLine) return checkIdentLowLine(_i);
// start char / word
if (tokens[_i].type === TokenType.HyphenMinus ||
tokens[_i].type === TokenType.Identifier ||
tokens[_i].type === TokenType.DollarSign ||
tokens[_i].type === TokenType.Asterisk) _i++;
else return fail(tokens[_i]);
wasIdent = tokens[_i - 1].type === TokenType.Identifier;
for (; _i < tokens.length; _i++) {
if (tokens[_i].type !== TokenType.HyphenMinus &&
tokens[_i].type !== TokenType.LowLine) {
if (tokens[_i].type !== TokenType.Identifier &&
(tokens[_i].type !== TokenType.DecimalNumber || !wasIdent)
) break;
else wasIdent = true;
}
}
if (!wasIdent && tokens[start].type !== TokenType.Asterisk) return fail(tokens[_i]);
tokens[start].ident_last = _i - 1;
return _i - start;
}
function checkIdentLowLine(_i) {
var start = _i;
_i++;
for (; _i < tokens.length; _i++) {
if (tokens[_i].type !== TokenType.HyphenMinus &&
tokens[_i].type !== TokenType.DecimalNumber &&
tokens[_i].type !== TokenType.LowLine &&
tokens[_i].type !== TokenType.Identifier) break;
}
tokens[start].ident_last = _i - 1;
return _i - start;
}
function getIdent() {
var startPos = pos,
s = joinValues(pos, tokens[pos].ident_last);
pos = tokens[pos].ident_last + 1;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.IdentType, s] :
[CSSPNodeType.IdentType, s];
}
//important = '!' sc*:s0 seq('important') -> [#important].concat(s0)
function checkImportant(_i) {
var start = _i,
l;
if (tokens[_i++].type !== TokenType.ExclamationMark) return fail(tokens[_i - 1]);
if (l = checkSC(_i)) _i += l;
if (tokens[_i].value !== 'important') return fail(tokens[_i]);
return _i - start + 1;
}
function getImportant() {
var startPos = pos;
pos++;
var sc = getSC();
pos++;
return (needInfo? [{ ln: tokens[startPos].ln }, CSSPNodeType.ImportantType] : [CSSPNodeType.ImportantType]).concat(sc);
}
// node: Namespace
function checkNamespace(_i) {
if (tokens[_i].type === TokenType.VerticalLine) return 1;
return fail(tokens[_i]);
}
function getNamespace() {
var startPos = pos;
pos++;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.NamespaceType] :
[CSSPNodeType.NamespaceType];
}
//nth = (digit | 'n')+:x -> [#nth, x.join('')]
// | (seq('even') | seq('odd')):x -> [#nth, x]
function checkNth(_i) {
return checkNth1(_i) || checkNth2(_i);
}
function checkNth1(_i) {
var start = _i;
for (; _i < tokens.length; _i++) {
if (tokens[_i].type !== TokenType.DecimalNumber && tokens[_i].value !== 'n') break;
}
if (_i !== start) {
tokens[start].nth_last = _i - 1;
return _i - start;
}
return fail(tokens[_i]);
}
function getNth() {
var startPos = pos;
if (tokens[pos].nth_last) {
var n = needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.NthType, joinValues(pos, tokens[pos].nth_last)] :
[CSSPNodeType.NthType, joinValues(pos, tokens[pos].nth_last)];
pos = tokens[pos].nth_last + 1;
return n;
}
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.NthType, tokens[pos++].value] :
[CSSPNodeType.NthType, tokens[pos++].value];
}
function checkNth2(_i) {
if (tokens[_i].value === 'even' || tokens[_i].value === 'odd') return 1;
return fail(tokens[_i]);
}
//nthf = ':' seq('nth-'):x (seq('child') | seq('last-child') | seq('of-type') | seq('last-of-type')):y -> (x + y)
function checkNthf(_i) {
var start = _i,
l = 0;
if (tokens[_i++].type !== TokenType.Colon) return fail(tokens[_i - 1]); l++;
if (tokens[_i++].value !== 'nth' || tokens[_i++].value !== '-') return fail(tokens[_i - 1]); l += 2;
if ('child' === tokens[_i].value) {
l += 1;
} else if ('last-child' === tokens[_i].value +
tokens[_i + 1].value +
tokens[_i + 2].value) {
l += 3;
} else if ('of-type' === tokens[_i].value +
tokens[_i + 1].value +
tokens[_i + 2].value) {
l += 3;
} else if ('last-of-type' === tokens[_i].value +
tokens[_i + 1].value +
tokens[_i + 2].value +
tokens[_i + 3].value +
tokens[_i + 4].value) {
l += 5;
} else return fail(tokens[_i]);
tokens[start + 1].nthf_last = start + l - 1;
return l;
}
function getNthf() {
pos++;
var s = joinValues(pos, tokens[pos].nthf_last);
pos = tokens[pos].nthf_last + 1;
return s;
}
//nthselector = nthf:x '(' (sc | unary | nth)*:y ')' -> [#nthselector, [#ident, x]].concat(y)
function checkNthselector(_i) {
var start = _i,
l;
if (l = checkNthf(_i)) _i += l;
else return fail(tokens[_i]);
if (tokens[_i].type !== TokenType.LeftParenthesis || !tokens[_i].right) return fail(tokens[_i]);
l++;
var rp = tokens[_i++].right;
while (_i < rp) {
if (l = checkSC(_i)) _i += l;
else if (l = checkUnary(_i)) _i += l;
else if (l = checkNth(_i)) _i += l;
else return fail(tokens[_i]);
}
return rp - start + 1;
}
function getNthselector() {
var startPos = pos,
nthf = needInfo?
[{ ln: tokens[pos].ln }, CSSPNodeType.IdentType, getNthf()] :
[CSSPNodeType.IdentType, getNthf()],
ns = needInfo?
[{ ln: tokens[pos].ln }, CSSPNodeType.NthselectorType, nthf] :
[CSSPNodeType.NthselectorType, nthf];
pos++;
while (tokens[pos].type !== TokenType.RightParenthesis) {
if (checkSC(pos)) ns = ns.concat(getSC());
else if (checkUnary(pos)) ns.push(getUnary());
else if (checkNth(pos)) ns.push(getNth());
}
pos++;
return ns;
}
// node: Number
function checkNumber(_i) {
if (_i < tokens.length && tokens[_i].number_l) return tokens[_i].number_l;
if (_i < tokens.length && tokens[_i].type === TokenType.DecimalNumber &&
(!tokens[_i + 1] ||
(tokens[_i + 1] && tokens[_i + 1].type !== TokenType.FullStop))
) return (tokens[_i].number_l = 1, tokens[_i].number_l); // 10
if (_i < tokens.length &&
tokens[_i].type === TokenType.DecimalNumber &&
tokens[_i + 1] && tokens[_i + 1].type === TokenType.FullStop &&
(!tokens[_i + 2] || (tokens[_i + 2].type !== TokenType.DecimalNumber))
) return (tokens[_i].number_l = 2, tokens[_i].number_l); // 10.
if (_i < tokens.length &&
tokens[_i].type === TokenType.FullStop &&
tokens[_i + 1].type === TokenType.DecimalNumber
) return (tokens[_i].number_l = 2, tokens[_i].number_l); // .10
if (_i < tokens.length &&
tokens[_i].type === TokenType.DecimalNumber &&
tokens[_i + 1] && tokens[_i + 1].type === TokenType.FullStop &&
tokens[_i + 2] && tokens[_i + 2].type === TokenType.DecimalNumber
) return (tokens[_i].number_l = 3, tokens[_i].number_l); // 10.10
return fail(tokens[_i]);
}
function getNumber() {
var s = '',
startPos = pos,
l = tokens[pos].number_l;
for (var i = 0; i < l; i++) {
s += tokens[pos + i].value;
}
pos += l;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.NumberType, s] :
[CSSPNodeType.NumberType, s];
}
// node: Operator
function checkOperator(_i) {
if (_i < tokens.length &&
(tokens[_i].type === TokenType.Solidus ||
tokens[_i].type === TokenType.Comma ||
tokens[_i].type === TokenType.Colon ||
tokens[_i].type === TokenType.EqualsSign)) return 1;
return fail(tokens[_i]);
}
function getOperator() {
return needInfo?
[{ ln: tokens[pos].ln }, CSSPNodeType.OperatorType, tokens[pos++].value] :
[CSSPNodeType.OperatorType, tokens[pos++].value];
}
// node: Percentage
function checkPercentage(_i) {
var x = checkNumber(_i);
if (!x || (x && _i + x >= tokens.length)) return fail(tokens[_i]);
if (tokens[_i + x].type === TokenType.PercentSign) return x + 1;
return fail(tokens[_i]);
}
function getPercentage() {
var startPos = pos,
n = getNumber();
pos++;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.PercentageType, n] :
[CSSPNodeType.PercentageType, n];
}
//progid = sc*:s0 seq('progid:DXImageTransform.Microsoft.'):x letter+:y '(' (m_string | m_comment | ~')' char)+:z ')' sc*:s1
// -> this.concat([#progid], s0, [[#raw, x + y.join('') + '(' + z.join('') + ')']], s1),
function checkProgid(_i) {
var start = _i,
l,
x;
if (l = checkSC(_i)) _i += l;
if ((x = joinValues2(_i, 6)) === 'progid:DXImageTransform.Microsoft.') {
_start = _i;
_i += 6;
} else return fail(tokens[_i - 1]);
if (l = checkIdent(_i)) _i += l;
else return fail(tokens[_i]);
if (l = checkSC(_i)) _i += l;
if (tokens[_i].type === TokenType.LeftParenthesis) {
tokens[start].progid_end = tokens[_i].right;
_i = tokens[_i].right + 1;
} else return fail(tokens[_i]);
if (l = checkSC(_i)) _i += l;
return _i - start;
}
function getProgid() {
var startPos = pos,
progid_end = tokens[pos].progid_end;
return (needInfo? [{ ln: tokens[startPos].ln }, CSSPNodeType.ProgidType] : [CSSPNodeType.ProgidType])
.concat(getSC())
.concat([_getProgid(progid_end)])
.concat(getSC());
}
function _getProgid(progid_end) {
var startPos = pos,
x = joinValues(pos, progid_end);
pos = progid_end + 1;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.RawType, x] :
[CSSPNodeType.RawType, x];
}
//property = ident:x sc*:s0 -> this.concat([#property, x], s0)
function checkProperty(_i) {
var start = _i,
l;
if (l = checkIdent(_i)) _i += l;
else return fail(tokens[_i]);
if (l = checkSC(_i)) _i += l;
return _i - start;
}
function getProperty() {
var startPos = pos;
return (needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.PropertyType, getIdent()] :
[CSSPNodeType.PropertyType, getIdent()])
.concat(getSC());
}
function checkPseudo(_i) {
return checkPseudoe(_i) ||
checkPseudoc(_i);
}
function getPseudo() {
if (checkPseudoe(pos)) return getPseudoe();
if (checkPseudoc(pos)) return getPseudoc();
}
function checkPseudoe(_i) {
var l;
if (tokens[_i++].type !== TokenType.Colon) return fail(tokens[_i - 1]);
if (tokens[_i++].type !== TokenType.Colon) return fail(tokens[_i - 1]);
if (l = checkIdent(_i)) return l + 2;
return fail(tokens[_i]);
}
function getPseudoe() {
var startPos = pos;
pos += 2;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.PseudoeType, getIdent()] :
[CSSPNodeType.PseudoeType, getIdent()];
}
//pseudoc = ':' (funktion | ident):x -> [#pseudoc, x]
function checkPseudoc(_i) {
var l;
if (tokens[_i++].type !== TokenType.Colon) return fail(tokens[_i - 1]);
if ((l = checkFunktion(_i)) || (l = checkIdent(_i))) return l + 1;
return fail(tokens[_i]);
}
function getPseudoc() {
var startPos = pos;
pos++;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.PseudocType, checkFunktion(pos)? getFunktion() : getIdent()] :
[CSSPNodeType.PseudocType, checkFunktion(pos)? getFunktion() : getIdent()];
}
//ruleset = selector*:x block:y -> this.concat([#ruleset], x, [y])
function checkRuleset(_i) {
var start = _i,
l;
if (tokens[start].ruleset_l !== undefined) return tokens[start].ruleset_l;
while (l = checkSelector(_i)) {
_i += l;
}
if (l = checkBlock(_i)) _i += l;
else return fail(tokens[_i]);
tokens[start].ruleset_l = _i - start;
return _i - start;
}
function getRuleset() {
var ruleset = needInfo? [{ ln: tokens[pos].ln }, CSSPNodeType.RulesetType] : [CSSPNodeType.RulesetType];
while (!checkBlock(pos)) {
ruleset.push(getSelector());
}
ruleset.push(getBlock());
return ruleset;
}
// node: S
function checkS(_i) {
if (tokens[_i].ws) return tokens[_i].ws_last - _i + 1;
return fail(tokens[_i]);
}
function getS() {
var startPos = pos,
s = joinValues(pos, tokens[pos].ws_last);
pos = tokens[pos].ws_last + 1;
return needInfo? [{ ln: tokens[startPos].ln }, CSSPNodeType.SType, s] : [CSSPNodeType.SType, s];
}
function checkSC(_i) {
var l,
lsc = 0;
while (_i < tokens.length) {
if (!(l = checkS(_i)) && !(l = checkComment(_i))) break;
_i += l;
lsc += l;
}
if (lsc) return lsc;
if (_i >= tokens.length) return fail(tokens[tokens.length - 1]);
return fail(tokens[_i]);
}
function getSC() {
var sc = [];
while (pos < tokens.length) {
if (checkS(pos)) sc.push(getS());
else if (checkComment(pos)) sc.push(getComment());
else break;
}
return sc;
}
//selector = (simpleselector | delim)+:x -> this.concat([#selector], x)
function checkSelector(_i) {
var start = _i,
l;
if (_i < tokens.length) {
while (l = checkSimpleselector(_i) || checkDelim(_i)) {
_i += l;
}
tokens[start].selector_end = _i - 1;
return _i - start;
}
}
function getSelector() {
var selector = needInfo? [{ ln: tokens[pos].ln }, CSSPNodeType.SelectorType] : [CSSPNodeType.SelectorType],
selector_end = tokens[pos].selector_end;
while (pos <= selector_end) {
selector.push(checkDelim(pos) ? getDelim() : getSimpleSelector());
}
return selector;
}
// node: Shash
function checkShash(_i) {
if (tokens[_i].type !== TokenType.NumberSign) return fail(tokens[_i]);
var l = checkNmName(_i + 1);
if (l) return l + 1;
return fail(tokens[_i]);
}
function getShash() {
var startPos = pos;
pos++;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.ShashType, getNmName()] :
[CSSPNodeType.ShashType, getNmName()];
}
//simpleselector = (nthselector | combinator | attrib | pseudo | clazz | shash | any | sc | namespace)+:x -> this.concatContent([#simpleselector], [x])
function checkSimpleselector(_i) {
var start = _i,
l;
while (_i < tokens.length) {
if (l = _checkSimpleSelector(_i)) _i += l;
else break;
}
if (_i - start) return _i - start;
if (_i >= tokens.length) return fail(tokens[tokens.length - 1]);
return fail(tokens[_i]);
}
function _checkSimpleSelector(_i) {
return checkNthselector(_i) ||
checkCombinator(_i) ||
checkAttrib(_i) ||
checkPseudo(_i) ||
checkClazz(_i) ||
checkShash(_i) ||
checkAny(_i) ||
checkSC(_i) ||
checkNamespace(_i);
}
function getSimpleSelector() {
var ss = needInfo? [{ ln: tokens[pos].ln }, CSSPNodeType.SimpleselectorType] : [CSSPNodeType.SimpleselectorType],
t;
while (pos < tokens.length && _checkSimpleSelector(pos)) {
t = _getSimpleSelector();
if ((needInfo && typeof t[1] === 'string') || typeof t[0] === 'string') ss.push(t);
else ss = ss.concat(t);
}
return ss;
}
function _getSimpleSelector() {
if (checkNthselector(pos)) return getNthselector();
else if (checkCombinator(pos)) return getCombinator();
else if (checkAttrib(pos)) return getAttrib();
else if (checkPseudo(pos)) return getPseudo();
else if (checkClazz(pos)) return getClazz();
else if (checkShash(pos)) return getShash();
else if (checkAny(pos)) return getAny();
else if (checkSC(pos)) return getSC();
else if (checkNamespace(pos)) return getNamespace();
}
// node: String
function checkString(_i) {
if (_i < tokens.length &&
(tokens[_i].type === TokenType.StringSQ || tokens[_i].type === TokenType.StringDQ)
) return 1;
return fail(tokens[_i]);
}
function getString() {
var startPos = pos;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.StringType, tokens[pos++].value] :
[CSSPNodeType.StringType, tokens[pos++].value];
}
//stylesheet = (cdo | cdc | sc | statement)*:x -> this.concat([#stylesheet], x)
function checkStylesheet(_i) {
var start = _i,
l;
while (_i < tokens.length) {
if (l = checkSC(_i)) _i += l;
else {
currentBlockLN = tokens[_i].ln;
if (l = checkAtrule(_i)) _i += l;
else if (l = checkRuleset(_i)) _i += l;
else if (l = checkUnknown(_i)) _i += l;
else throwError();
}
}
return _i - start;
}
function getStylesheet(_i) {
var t,
stylesheet = needInfo? [{ ln: tokens[pos].ln }, CSSPNodeType.StylesheetType] : [CSSPNodeType.StylesheetType];
while (pos < tokens.length) {
if (checkSC(pos)) stylesheet = stylesheet.concat(getSC());
else {
currentBlockLN = tokens[pos].ln;
if (checkRuleset(pos)) stylesheet.push(getRuleset());
else if (checkAtrule(pos)) stylesheet.push(getAtrule());
else if (checkUnknown(pos)) stylesheet.push(getUnknown());
else throwError();
}
}
return stylesheet;
}
//tset = vhash | any | sc | operator
function checkTset(_i) {
return checkVhash(_i) ||
checkAny(_i) ||
checkSC(_i) ||
checkOperator(_i);
}
function getTset() {
if (checkVhash(pos)) return getVhash();
else if (checkAny(pos)) return getAny();
else if (checkSC(pos)) return getSC();
else if (checkOperator(pos)) return getOperator();
}
function checkTsets(_i) {
var start = _i,
l;
while (l = checkTset(_i)) {
_i += l;
}
return _i - start;
}
function getTsets() {
var tsets = [],
x;
while (x = getTset()) {
if ((needInfo && typeof x[1] === 'string') || typeof x[0] === 'string') tsets.push(x);
else tsets = tsets.concat(x);
}
return tsets;
}
// node: Unary
function checkUnary(_i) {
if (_i < tokens.length &&
(tokens[_i].type === TokenType.HyphenMinus ||
tokens[_i].type === TokenType.PlusSign)
) return 1;
return fail(tokens[_i]);
}
function getUnary() {
var startPos = pos;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.UnaryType, tokens[pos++].value] :
[CSSPNodeType.UnaryType, tokens[pos++].value];
}
// node: Unknown
function checkUnknown(_i) {
if (_i < tokens.length && tokens[_i].type === TokenType.CommentSL) return 1;
return fail(tokens[_i]);
}
function getUnknown() {
var startPos = pos;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.UnknownType, tokens[pos++].value] :
[CSSPNodeType.UnknownType, tokens[pos++].value];
}
// uri = seq('url(') sc*:s0 string:x sc*:s1 ')' -> this.concat([#uri], s0, [x], s1)
// | seq('url(') sc*:s0 (~')' ~m_w char)*:x sc*:s1 ')' -> this.concat([#uri], s0, [[#raw, x.join('')]], s1),
function checkUri(_i) {
var start = _i,
l;
if (_i < tokens.length && tokens[_i++].value !== 'url') return fail(tokens[_i - 1]);
if (!tokens[_i] || tokens[_i].type !== TokenType.LeftParenthesis) return fail(tokens[_i]);
return tokens[_i].right - start + 1;
}
function getUri() {
var startPos = pos,
uriExcluding = {};
pos += 2;
uriExcluding[TokenType.Space] = 1;
uriExcluding[TokenType.Tab] = 1;
uriExcluding[TokenType.Newline] = 1;
uriExcluding[TokenType.LeftParenthesis] = 1;
uriExcluding[TokenType.RightParenthesis] = 1;
if (checkUri1(pos)) {
var uri = (needInfo? [{ ln: tokens[startPos].ln }, CSSPNodeType.UriType] : [CSSPNodeType.UriType])
.concat(getSC())
.concat([getString()])
.concat(getSC());
pos++;
return uri;
} else {
var uri = (needInfo? [{ ln: tokens[startPos].ln }, CSSPNodeType.UriType] : [CSSPNodeType.UriType])
.concat(getSC()),
l = checkExcluding(uriExcluding, pos),
raw = needInfo?
[{ ln: tokens[pos].ln }, CSSPNodeType.RawType, joinValues(pos, pos + l)] :
[CSSPNodeType.RawType, joinValues(pos, pos + l)];
uri.push(raw);
pos += l + 1;
uri = uri.concat(getSC());
pos++;
return uri;
}
}
function checkUri1(_i) {
var start = _i,
l = checkSC(_i);
if (l) _i += l;
if (tokens[_i].type !== TokenType.StringDQ && tokens[_i].type !== TokenType.StringSQ) return fail(tokens[_i]);
_i++;
if (l = checkSC(_i)) _i += l;
return _i - start;
}
// value = (sc | vhash | any | block | atkeyword | operator | important)+:x -> this.concat([#value], x)
function checkValue(_i) {
var start = _i,
l;
while (_i < tokens.length) {
if (l = _checkValue(_i)) _i += l;
else break;
}
if (_i - start) return _i - start;
return fail(tokens[_i]);
}
function _checkValue(_i) {
return checkSC(_i) ||
checkVhash(_i) ||
checkAny(_i) ||
checkBlock(_i) ||
checkAtkeyword(_i) ||
checkOperator(_i) ||
checkImportant(_i);
}
function getValue() {
var ss = needInfo? [{ ln: tokens[pos].ln }, CSSPNodeType.ValueType] : [CSSPNodeType.ValueType],
t;
while (pos < tokens.length && _checkValue(pos)) {
t = _getValue();
if ((needInfo && typeof t[1] === 'string') || typeof t[0] === 'string') ss.push(t);
else ss = ss.concat(t);
}
return ss;
}
function _getValue() {
if (checkSC(pos)) return getSC();
else if (checkVhash(pos)) return getVhash();
else if (checkAny(pos)) return getAny();
else if (checkBlock(pos)) return getBlock();
else if (checkAtkeyword(pos)) return getAtkeyword();
else if (checkOperator(pos)) return getOperator();
else if (checkImportant(pos)) return getImportant();
}
// node: Vhash
function checkVhash(_i) {
if (_i >= tokens.length || tokens[_i].type !== TokenType.NumberSign) return fail(tokens[_i]);
var l = checkNmName2(_i + 1);
if (l) return l + 1;
return fail(tokens[_i]);
}
function getVhash() {
var startPos = pos;
pos++;
return needInfo?
[{ ln: tokens[startPos].ln }, CSSPNodeType.VhashType, getNmName2()] :
[CSSPNodeType.VhashType, getNmName2()];
}
function checkNmName(_i) {
var start = _i;
// start char / word
if (tokens[_i].type === TokenType.HyphenMinus ||
tokens[_i].type === TokenType.LowLine ||
tokens[_i].type === TokenType.Identifier ||
tokens[_i].type === TokenType.DecimalNumber) _i++;
else return fail(tokens[_i]);
for (; _i < tokens.length; _i++) {
if (tokens[_i].type !== TokenType.HyphenMinus &&
tokens[_i].type !== TokenType.LowLine &&
tokens[_i].type !== TokenType.Identifier &&
tokens[_i].type !== TokenType.DecimalNumber) break;
}
tokens[start].nm_name_last = _i - 1;
return _i - start;
}
function getNmName() {
var s = joinValues(pos, tokens[pos].nm_name_last);
pos = tokens[pos].nm_name_last + 1;
return s;
}
function checkNmName2(_i) {
var start = _i;
if (tokens[_i].type === TokenType.Identifier) return 1;
else if (tokens[_i].type !== TokenType.DecimalNumber) return fail(tokens[_i]);
_i++;
if (!tokens[_i] || tokens[_i].type !== TokenType.Identifier) return 1;
return 2;
}
function getNmName2() {
var s = tokens[pos].value;
if (tokens[pos++].type === TokenType.DecimalNumber &&
pos < tokens.length &&
tokens[pos].type === TokenType.Identifier
) s += tokens[pos++].value;
return s;
}
function checkExcluding(exclude, _i) {
var start = _i;
while(_i < tokens.length) {
if (exclude[tokens[_i++].type]) break;
}
return _i - start - 2;
}
function joinValues(start, finish) {
var s = '';
for (var i = start; i < finish + 1; i++) {
s += tokens[i].value;
}
return s;
}
function joinValues2(start, num) {
if (start + num - 1 >= tokens.length) return;
var s = '';
for (var i = 0; i < num; i++) {
s += tokens[start + i].value;
}
return s;
}
function markSC() {
var ws = -1, // whitespaces
sc = -1, // ws and comments
t;
for (var i = 0; i < tokens.length; i++) {
t = tokens[i];
switch (t.type) {
case TokenType.Space:
case TokenType.Tab:
case TokenType.Newline:
t.ws = true;
t.sc = true;
if (ws === -1) ws = i;
if (sc === -1) sc = i;
break;
case TokenType.CommentML:
if (ws !== -1) {
tokens[ws].ws_last = i - 1;
ws = -1;
}
t.sc = true;
break;
default:
if (ws !== -1) {
tokens[ws].ws_last = i - 1;
ws = -1;
}
if (sc !== -1) {
tokens[sc].sc_last = i - 1;
sc = -1;
}
}
}
if (ws !== -1) tokens[ws].ws_last = i - 1;
if (sc !== -1) tokens[sc].sc_last = i - 1;
}
return function(_tokens, rule, _needInfo) {
return _getAST(_tokens, rule, _needInfo);
}
}());
return function(s, rule, _needInfo) {
return getCSSPAST(getTokens(s), rule, _needInfo);
}
}());
exports.srcToCSSP = srcToCSSP;
},{}],5:[function(require,module,exports){
// CSSP
exports.srcToCSSP = require('./gonzales.cssp.node.js').srcToCSSP;
exports.csspToSrc = require('./cssp.translator.node.js').csspToSrc;
exports.csspToTree = function(tree, level) {
var spaces = dummySpaces(level),
level = level ? level : 0,
s = (level ? '\n' + spaces : '') + '[';
tree.forEach(function(e) {
if (e.ln === undefined) {
s += (Array.isArray(e) ? exports.csspToTree(e, level + 1) : ('\'' + e.toString() + '\'')) + ', ';
}
});
return s.substr(0, s.length - 2) + ']';
}
function dummySpaces(num) {
return ' '.substr(0, num * 2);
}
},{"./cssp.translator.node.js":3,"./gonzales.cssp.node.js":4}],6:[function(require,module,exports){
var gonzo = require('gonzales-ast');
parse = function(css) {
var ast = gonzo.parse(css);
return gonzo.toTree(ast);
}
},{"gonzales-ast":1}]},{},[6]) | tanbo800/ourjs | node_modules/cssshrink/node_modules/gonzales-ast/demo/bundle.js | JavaScript | bsd-3-clause | 73,261 |
var
async = require('async'),
token = require('./token/'),
response = require('./../util/response.js'),
error = require('./../error'),
emitter = require('./../events');
/**
* Token endpoint controller
* Used for: "authorization_code", "password", "client_credentials", "refresh_token" flows
*
* @see http://tools.ietf.org/html/rfc6749#section-3.2
* @param req Request object
* @param res Response object
*/
module.exports = function(req, res) {
req.oauth2.logger.debug('Invoking token endpoint');
var clientId,
clientSecret,
grantType,
client;
async.waterfall([
// Parse client credentials from request body
// if credentials are not exist in request body,
// then check client credentials from BasicAuth header
function(cb) {
if (req.body.client_id && req.body.client_secret) {
clientId = req.body.client_id;
clientSecret = req.body.client_secret;
req.oauth2.logger.debug('Client credentials parsed from body parameters: ', clientId, clientSecret);
cb();
} else {
if (!req.headers || !req.headers.authorization)
return cb(new error.invalidRequest('No authorization header passed'));
var pieces = req.headers.authorization.split(' ', 2);
if (!pieces || pieces.length !== 2)
return cb(new error.invalidRequest('Authorization header is corrupted'));
if (pieces[0] !== 'Basic')
return cb(new error.invalidRequest('Unsupported authorization method: ', pieces[0]));
pieces = new Buffer(pieces[1], 'base64').toString('ascii').split(':', 2);
if (!pieces || pieces.length !== 2)
return cb(new error.invalidRequest('Authorization header has corrupted data'));
clientId = pieces[0];
clientSecret = pieces[1];
req.oauth2.logger.debug('Client credentials parsed from basic auth header: ', clientId, clientSecret);
cb();
}
},
// Check grant type for server support
function(cb) {
if (!req.body.grant_type)
cb(new error.invalidRequest('Body does not contain grant_type parameter'));
grantType = req.body.grant_type;
req.oauth2.logger.debug('Parameter grant_type passed: ', grantType);
cb();
},
// Fetch client and check credentials
function(cb) {
req.oauth2.model.client.fetchById(clientId, function(err, obj) {
if (err)
cb(new error.serverError('Failed to call client::fetchById method'));
else if (!obj)
cb(new error.invalidClient('Client not found'));
else {
req.oauth2.logger.debug('Client fetched: ', obj);
client = obj;
cb();
}
});
},
function(cb){
req.oauth2.model.client.checkSecret(client, clientSecret, function(err, valid){
if(err)
cb(new error.serverError('Failed to call client::checkSecret method'));
else if (!valid)
cb(new error.invalidClient('Wrong client secret provided'));
else
cb();
});
},
// Check grant type against client available
function(cb) {
if (!req.oauth2.model.client.checkGrantType(client, grantType) && grantType !== 'refresh_token')
cb(new error.unauthorizedClient('Grant type is not available for the client'));
else {
req.oauth2.logger.debug('Grant type check passed');
cb();
}
},
function(cb) {
switch (grantType) {
case 'authorization_code':
token.authorizationCode(req.oauth2, client, req.body.code, req.body.redirect_uri, cb);
break;
case 'password':
token.password(req.oauth2, client, req.body.username, req.body.password, req.body.scope, cb);
break;
case 'client_credentials':
token.clientCredentials(req.oauth2, client, req.body.scope, cb);
break;
case 'refresh_token':
token.refreshToken(req.oauth2, client, req.body.refresh_token, req.body.scope, cb);
break;
default:
cb(new error.unsupportedGrantType('Grant type does not match any supported type'));
break;
}
}
],
function(err, data) {
if (err) response.error(req, res, err);
else {
emitter.token_granted(data.event, req, data.data);
response.data(req, res, data.data);
}
});
};
| DawoonC/node-oauth20-provider | lib/controller/token.js | JavaScript | mit | 5,066 |
define(function (require) {
var zrUtil = require('zrender/core/util');
return require('../../echarts').extendComponentView({
type: 'marker',
init: function () {
/**
* Markline grouped by series
* @private
* @type {module:zrender/core/util.HashMap}
*/
this.markerGroupMap = zrUtil.createHashMap();
},
render: function (markerModel, ecModel, api) {
var markerGroupMap = this.markerGroupMap;
markerGroupMap.each(function (item) {
item.__keep = false;
});
var markerModelKey = this.type + 'Model';
ecModel.eachSeries(function (seriesModel) {
var markerModel = seriesModel[markerModelKey];
markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
}, this);
markerGroupMap.each(function (item) {
!item.__keep && this.group.remove(item.group);
}, this);
},
renderSeries: function () {}
});
}); | yjwz0428/yjwz0428.github.io | 作业(1)/echarts-master/src/component/marker/MarkerView.js | JavaScript | mit | 1,107 |
(function($) {
var
$console = $("#dm_console"),
$command = $("#dm_command"),
$lines = $console.find(".dm_content_command"),
$wait = $console.find(".dm_console_wait");
scroll();
$lines.bind("click", function()
{
$command.focus();
}).trigger("click");
$("#dm_command_wrap form").ajaxForm({
beforeSubmit: function(data)
{
if ($("#dm_command").val() == "") return false;
if($("#dm_command").val() == "clear")
{
$lines.html('<li> </li>');
$("#dm_command").val("");
return false;
}
$("#dm_command").val("Loading...");
return true;
},
success: function(data)
{
$lines.append(data);
scroll();
$("#dm_command").val("");
}
});
function scroll()
{
$console[0].scrollTop = 16*$console.find("li").length;
}
$(window).bind('resize', function()
{
$console.height($(window).height() - 90);
}).trigger('resize');
})(jQuery);
| octavioalapizco/diem | dmAdminPlugin/web/js/dmAdminConsole.js | JavaScript | mit | 900 |
'use strict';
let path = require('path');
let webpack = require('webpack');
module.exports = {
entry: {
popover_defaultfunctionality: './app/popover/defaultfunctionality/main.ts',
popover_positioning: './app/popover/positioning/main.ts',
popover_bottompositioning: './app/popover/bottompositioning/main.ts',
popover_modalpopover: './app/popover/modalpopover/main.ts',
popover_righttoleftlayout: './app/popover/righttoleftlayout/main.ts',
progressbar_defaultfunctionality: './app/progressbar/defaultfunctionality/main.ts',
progressbar_colorranges: './app/progressbar/colorranges/main.ts',
progressbar_templates: './app/progressbar/templates/main.ts',
progressbar_layout: './app/progressbar/layout/main.ts',
progressbar_righttoleftlayout: './app/progressbar/righttoleftlayout/main.ts',
rangeselector_defaultfunctionality: './app/rangeselector/defaultfunctionality/main.ts',
rangeselector_datascale: './app/rangeselector/datascale/main.ts',
rangeselector_timescale: './app/rangeselector/timescale/main.ts',
rangeselector_numericscale: './app/rangeselector/numericscale/main.ts',
rangeselector_negativescale: './app/rangeselector/negativescale/main.ts',
rangeselector_decimalscale: './app/rangeselector/decimalscale/main.ts',
rangeselector_backgroundimage: './app/rangeselector/backgroundimage/main.ts',
rangeselector_chartonbackground: './app/rangeselector/chartonbackground/main.ts',
rangeselector_rangeselectorasafilter: './app/rangeselector/rangeselectorasafilter/main.ts',
rangeselector_fluidsize: './app/rangeselector/fluidsize/main.ts',
rangeselector_customizedmarkers: './app/rangeselector/customizedmarkers/main.ts',
rangeselector_righttoleftlayout: './app/rangeselector/righttoleftlayout/main.ts',
rating_defaultfunctionality: './app/rating/defaultfunctionality/main.ts',
rating_twowaydatabinding: './app/rating/twowaydatabinding/main.ts',
responsivepanel_defaultfunctionality: './app/responsivepanel/defaultfunctionality/main.ts',
responsivepanel_integrationwithjqxmenu: './app/responsivepanel/integrationwithjqxmenu/main.ts',
responsivepanel_fluidsize: './app/responsivepanel/fluidsize/main.ts',
responsivepanel_righttoleftlayout: './app/responsivepanel/righttoleftlayout/main.ts',
ribbon_defaultfunctionality: './app/ribbon/defaultfunctionality/main.ts',
ribbon_collapsible: './app/ribbon/collapsible/main.ts',
ribbon_ribbonatthebottom: './app/ribbon/ribbonatthebottom/main.ts',
ribbon_verticalribbon: './app/ribbon/verticalribbon/main.ts',
ribbon_verticalrightposition: './app/ribbon/verticalrightposition/main.ts',
ribbon_popuplayout: './app/ribbon/popuplayout/main.ts',
ribbon_integrationwithotherwidgets: './app/ribbon/integrationwithotherwidgets/main.ts',
ribbon_scrolling: './app/ribbon/scrolling/main.ts',
ribbon_events: './app/ribbon/events/main.ts',
ribbon_fluidsize: './app/ribbon/fluidsize/main.ts',
ribbon_righttoleftlayout: './app/ribbon/righttoleftlayout/main.ts'
},
output: {
path: path.resolve(__dirname + '/aot'),
filename: '[name].bundle.js'
},
module: {
loaders:
[
{
test: /\.ts$/,
loaders: ['awesome-typescript-loader', 'angular2-template-loader?keepUrl=true'],
exclude: [/\.(spec|e2e)\.ts$/]
},
{
test: /\.html$/,
use: 'raw-loader'
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader']
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: [
'raw-loader',
'img-loader'
]
}
]
},
plugins: [
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.ProgressPlugin(),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)@angular/,
path.join(process.cwd(), 'app')
)
],
resolve: {
extensions: ['.ts', '.js']
}
};
| luissancheza/sice | js/jqwidgets/demos/angular/webpack.config9.js | JavaScript | mit | 4,312 |
module.exports = {
getSubscribers: function(cb) {
return cb( null, [
{
rowid: 1001,
phone: '3125555555',
createdAt: '2015-04-26 20:08:45'
},{
rowid: 1002,
phone: '3125555556',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1003,
phone: '3125555557',
createdAt: '2015-04-22 20:08:45'
},{
rowid: 1004,
phone: '3125555558',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1005,
phone: '3125555559',
createdAt: '2015-04-22 20:08:45'
},{
rowid: 1006,
phone: '3125555551',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1007,
phone: '5005550001', // twilio magic number: invalid
createdAt: '2015-04-22 20:08:45'
},{
rowid: 1008,
phone: '3125555553',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1009,
phone: '3125555555',
createdAt: '2015-04-26 20:08:45'
},{
rowid: 1010,
phone: '3125555556',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1011,
phone: '3125555557',
createdAt: '2015-04-22 20:08:45'
},{
rowid: 1012,
phone: '3125555558',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1013,
phone: '3125555559',
createdAt: '2015-04-22 20:08:45'
},{
rowid: 1014,
phone: '3125555551',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1015,
phone: '3125555552',
createdAt: '2015-04-22 20:08:45'
},{
rowid: 1016,
phone: '3125555553',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1017,
phone: '3125555555',
createdAt: '2015-04-26 20:08:45'
},{
rowid: 1018,
phone: '3125555556',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1019,
phone: '3125555557',
createdAt: '2015-04-22 20:08:45'
},{
rowid: 1020,
phone: '3125555558',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1021,
phone: '3125555559',
createdAt: '2015-04-22 20:08:45'
},{
rowid: 1022,
phone: '3125555551',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1023,
phone: '3125555552',
createdAt: '2015-04-22 20:08:45'
},{
rowid: 1024,
phone: '3125555553',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1025,
phone: '3125555555',
createdAt: '2015-04-26 20:08:45'
},{
rowid: 1026,
phone: '3125555556',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1027,
phone: '3125555557',
createdAt: '2015-04-22 20:08:45'
},{
rowid: 1028,
phone: '3125555558',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1029,
phone: '3125555559',
createdAt: '2015-04-22 20:08:45'
},{
rowid: 1030,
phone: '3125555551',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1031,
phone: '3125555552',
createdAt: '2015-04-22 20:08:45'
},{
rowid: 1032,
phone: '3125555553',
createdAt: '2015-04-23 20:08:45'
},{
rowid: 1033,
phone: '3125555554',
createdAt: '2015-04-22 20:08:45'
}
]);
}
}
| benwilhelm/kcbx-petcoke | test/stubs/smsSubscriberService.js | JavaScript | mit | 3,460 |
var utilities = require("./utilities");
var querySelectorForHeadingsToNativize = 'h1.section_heading, h2.section_heading, h3.section_heading';
function getSectionHeadersArray(){
var nodeList = document.querySelectorAll(querySelectorForHeadingsToNativize);
var nodeArray = Array.prototype.slice.call(nodeList);
nodeArray = nodeArray.map(function(n){
return {
anchor:n.getAttribute('id'),
sectionId:n.getAttribute('sectionId'),
text:n.textContent
};
});
return nodeArray;
}
function getSectionHeaderLocationsArray(){
var nodeList = document.querySelectorAll(querySelectorForHeadingsToNativize);
var nodeArray = Array.prototype.slice.call(nodeList);
nodeArray = nodeArray.map(function(n){
return n.getBoundingClientRect().top;
});
return nodeArray;
}
function getSectionHeaderForId(id){
var sectionHeadingParent = utilities.findClosest(document.getElementById(id), 'div[id^="section_heading_and_content_block_"]');
var sectionHeading = sectionHeadingParent.querySelector(querySelectorForHeadingsToNativize);
return sectionHeading;
}
exports.getSectionHeaderForId = getSectionHeaderForId;
global.getSectionHeadersArray = getSectionHeadersArray;
global.getSectionHeaderLocationsArray = getSectionHeaderLocationsArray;
| soppysonny/wikipedia-ios | www/js/sectionHeaders.js | JavaScript | mit | 1,330 |
/**
* A general sheet class. This renderable container provides base support for orientation-aware transitions for popup or
* side-anchored sliding Panels.
*
* In most cases, you should use {@link Ext.ActionSheet}, {@link Ext.MessageBox}, {@link Ext.picker.Picker}, or {@link Ext.picker.Date}.
*/
Ext.define('Ext.Sheet', {
extend: 'Ext.Panel',
xtype: 'sheet',
alternateClassName: ['widget.crosscut'],
requires: ['Ext.Button', 'Ext.fx.Animation'],
config: {
/**
* @cfg
* @inheritdoc
*/
baseCls: Ext.baseCSSPrefix + 'sheet',
/**
* @cfg
* @inheritdoc
*/
modal: true,
/**
* @cfg {Boolean} centered
* Whether or not this component is absolutely centered inside its container.
* @accessor
* @evented
*/
centered: true,
/**
* @cfg {Boolean} stretchX `true` to stretch this sheet horizontally.
*/
stretchX: null,
/**
* @cfg {Boolean} stretchY `true` to stretch this sheet vertically.
*/
stretchY: null,
/**
* @cfg {String} enter
* The viewport side used as the enter point when shown. Valid values are 'top', 'bottom', 'left', and 'right'.
* Applies to sliding animation effects only.
*/
enter: 'bottom',
/**
* @cfg {String} exit
* The viewport side used as the exit point when hidden. Valid values are 'top', 'bottom', 'left', and 'right'.
* Applies to sliding animation effects only.
*/
exit: 'bottom',
/**
* @cfg
* @inheritdoc
*/
showAnimation: !Ext.browser.is.AndroidStock2 ? {
type: 'slideIn',
duration: 250,
easing: 'ease-out'
} : null,
/**
* @cfg
* @inheritdoc
*/
hideAnimation: !Ext.browser.is.AndroidStock2 ? {
type: 'slideOut',
duration: 250,
easing: 'ease-in'
} : null
},
platformConfig: [{
theme: ['Windows'],
enter: 'top',
exit: 'top'
}],
applyHideAnimation: function(config) {
var exit = this.getExit(),
direction = exit;
if (exit === null) {
return null;
}
if (config === true) {
config = {
type: 'slideOut'
};
}
if (Ext.isString(config)) {
config = {
type: config
};
}
var anim = Ext.factory(config, Ext.fx.Animation);
if (anim) {
if (exit == 'bottom') {
direction = 'down';
}
if (exit == 'top') {
direction = 'up';
}
anim.setDirection(direction);
}
return anim;
},
applyShowAnimation: function(config) {
var enter = this.getEnter(),
direction = enter;
if (enter === null) {
return null;
}
if (config === true) {
config = {
type: 'slideIn'
};
}
if (Ext.isString(config)) {
config = {
type: config
};
}
var anim = Ext.factory(config, Ext.fx.Animation);
if (anim) {
if (enter == 'bottom') {
direction = 'down';
}
if (enter == 'top') {
direction = 'up';
}
anim.setBefore({
display: null
});
anim.setReverse(true);
anim.setDirection(direction);
}
return anim;
},
updateStretchX: function(newStretchX) {
this.getLeft();
this.getRight();
if (newStretchX) {
this.setLeft(0);
this.setRight(0);
}
},
updateStretchY: function(newStretchY) {
this.getTop();
this.getBottom();
if (newStretchY) {
this.setTop(0);
this.setBottom(0);
}
}
});
| flrent/livre-sencha-touch-exemples | touch/src/Sheet.js | JavaScript | mit | 4,176 |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'preview', 'fr-ca', {
preview: 'Prévisualiser'
} );
| ninsuo/touchscreen-video-player | src/BaseBundle/Resources/public/ckeditor/plugins/preview/lang/fr-ca.js | JavaScript | mit | 223 |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.messages = exports.ruleName = undefined;
exports.default = function (expectation) {
var checker = (0, _utils.whitespaceChecker)("space", expectation, messages);
return function (root, result) {
var validOptions = _stylelint.utils.validateOptions(result, ruleName, {
actual: expectation,
possible: ["always", "never", "always-single-line"]
});
if (!validOptions) {
return;
}
variableColonSpaceChecker({
root: root,
result: result,
locationChecker: checker.after,
checkedRuleName: ruleName
});
};
};
exports.variableColonSpaceChecker = variableColonSpaceChecker;
var _utils = require("../../utils");
var _stylelint = require("stylelint");
var ruleName = exports.ruleName = (0, _utils.namespace)("dollar-variable-colon-space-after");
var messages = exports.messages = _stylelint.utils.ruleMessages(ruleName, {
expectedAfter: function expectedAfter() {
return "Expected single space after \":\"";
},
rejectedAfter: function rejectedAfter() {
return "Unexpected whitespace after \":\"";
},
expectedAfterSingleLine: function expectedAfterSingleLine() {
return "Expected single space after \":\" with a single-line value";
}
});
function variableColonSpaceChecker(_ref) {
var locationChecker = _ref.locationChecker,
root = _ref.root,
result = _ref.result,
checkedRuleName = _ref.checkedRuleName;
root.walkDecls(function (decl) {
if (decl.prop === undefined || decl.prop[0] !== "$") {
return;
}
// Get the raw $var, and only that
var endOfPropIndex = (0, _utils.declarationValueIndex)(decl) + decl.raw("between").length - 1;
// `$var:`, `$var :`
var propPlusColon = decl.toString().slice(0, endOfPropIndex);
var _loop = function _loop(i) {
if (propPlusColon[i] !== ":") {
return "continue";
}
locationChecker({
source: propPlusColon,
index: i,
lineCheckStr: decl.value,
err: function err(m) {
_stylelint.utils.report({
message: m,
node: decl,
index: i,
result: result,
ruleName: checkedRuleName
});
}
});
return "break";
};
_loop2: for (var i = 0; i < propPlusColon.length; i++) {
var _ret = _loop(i);
switch (_ret) {
case "continue":
continue;
case "break":
break _loop2;}
}
});
} | pmarsceill/stately | node_modules/stylelint-scss/dist/rules/dollar-variable-colon-space-after/index.js | JavaScript | mit | 2,548 |
/* global angular */
angular.module('storm.directives')
.directive('stSeasonList', ['$timeout', '$window', '$state', 'Navigation', function($timeout, $window, $state, Navigation) {
return {
restrict: 'A',
scope: true,
link: function(scope, element, attr) {
scope.seasonsList = null;
scope.selectedSeason = null;
// Update list
scope.$watch(attr.seasonsList, function(value) {
if (!value) return;
// Load list
scope.seasonsList = value;
});
// Watch for seasons list trigger
scope.$watch('showSeasonsList', function(value) {
if (!value) return;
if (typeof scope.seasonsList === undefined) return;
Navigation.setActiveElement(scope.seasonsList.length>0 ? 'season' : 'hide-seasons', true);
});
//
// SEASONS
//
scope.prevSeason = function() {
var index = getSelectedSeasonIndex();
if (index > 0) {
return true;
}
return false;
};
scope.nextSeason = function() {
return true;
};
scope.selectSeason = function(index) {
scope.selectedSeason = index !== undefined ? index : getSelectedSeasonIndex();
updateSelectedSeason();
return false;
};
// Get selected season
function getSelectedSeasonIndex() {
var focusedElement = element[0].querySelector('[nav-focus="true"]');
if (focusedElement === null) return -1;
var selectedSeason = parseInt(focusedElement.getAttribute('season-number'));
var n = 0;
for (var i in scope.seasonsList) {
if (scope.seasonsList[i].number === selectedSeason) {
break;
}
n++;
}
return n;
}
function updateSelectedSeason() {
element.scrollTop(0);
Navigation.setActiveElement(scope.selectedSeason === null ? 'season' : 'episode', true);
}
//
// EPISODES
//
scope.hideEpisodes = function() {
scope.selectedSeason = null;
updateSelectedSeason();
return false;
};
scope.prevEpisode = function() {
return true;
};
scope.nextEpisode = function() {
var index = getSelectedEpisodeIndex();
if (index < scope.seasonsList[scope.selectedSeason].episodes.length-1) {
return true;
}
return false;
};
scope.selectEpisode = function(index) {
index = index !== undefined ? index : getSelectedEpisodeIndex();
var episode = scope.seasonsList[scope.selectedSeason].episodes[index];
// Go to episode
$state.go('^.episode', {id: episode.id});
return false;
};
// Get selected episode
function getSelectedEpisodeIndex() {
var focusedElement = element[0].querySelector('[nav-focus="true"]');
if (focusedElement === null) return -1;
var selectedEpisode = parseInt(focusedElement.getAttribute('episode-number'));
var n = 0;
for (var i in scope.seasonsList[scope.selectedSeason].episodes) {
if (scope.seasonsList[scope.selectedSeason].episodes[i].number === selectedEpisode) {
break;
}
n++;
}
return n;
}
}
};
}]); | pazipazita/storm-master | app/js/directives/stSeasonList.js | JavaScript | mit | 2,967 |
lychee.define('lychee.ui.Entity').includes([
'lychee.event.Emitter'
]).exports(function(lychee, global) {
var _default_state = 'default';
var _default_states = { 'default': null, 'active': null };
var Class = function(data) {
var settings = lychee.extend({}, data);
this.width = typeof settings.width === 'number' ? settings.width : 0;
this.height = typeof settings.height === 'number' ? settings.height : 0;
this.depth = 0;
this.radius = typeof settings.radius === 'number' ? settings.radius : 0;
this.shape = Class.SHAPE.rectangle;
this.state = _default_state;
this.position = { x: 0, y: 0 };
this.visible = true;
this.__clock = null;
this.__states = _default_states;
if (settings.states instanceof Object) {
this.__states = { 'default': null, 'active': null };
for (var id in settings.states) {
if (settings.states.hasOwnProperty(id)) {
this.__states[id] = settings.states[id];
}
}
}
this.setShape(settings.shape);
this.setState(settings.state);
this.setPosition(settings.position);
this.setVisible(settings.visible);
lychee.event.Emitter.call(this);
settings = null;
};
// Same ENUM values as lychee.game.Entity
Class.SHAPE = {
circle: 0,
rectangle: 2
};
Class.prototype = {
/*
* ENTITY API
*/
serialize: function() {
var settings = {};
if (this.width !== 0) settings.width = this.width;
if (this.height !== 0) settings.height = this.height;
if (this.radius !== 0) settings.radius = this.radius;
if (this.shape !== Class.SHAPE.rectangle) settings.shape = this.shape;
if (this.state !== _default_state) settings.state = this.state;
if (this.__states !== _default_states) settings.states = this.__states;
if (this.visible !== true) settings.visible = this.visible;
if (
this.position.x !== 0
|| this.position.y !== 0
) {
settings.position = {};
if (this.position.x !== 0) settings.position.x = this.position.x;
if (this.position.y !== 0) settings.position.y = this.position.y;
}
return {
'constructor': 'lychee.ui.Entity',
'arguments': [ settings ]
};
},
// Allows sync(null, true) for reset
sync: function(clock, force) {
force = force === true;
if (force === true) {
this.__clock = clock;
}
if (this.__clock === null) {
this.__clock = clock;
}
},
// HINT: Renderer skips if no render() method exists
// render: function(renderer, offsetX, offsetY) {},
update: function(clock, delta) {
// 1. Sync clocks initially
// (if Entity was created before loop started)
if (this.__clock === null) {
this.sync(clock);
}
this.__clock = clock;
},
/*
* CUSTOM API
*/
setPosition: function(position) {
if (position instanceof Object) {
this.position.x = typeof position.x === 'number' ? position.x : this.position.x;
this.position.y = typeof position.y === 'number' ? position.y : this.position.y;
return true;
}
return false;
},
getStateMap: function() {
return this.__states[this.state];
},
setState: function(id) {
id = typeof id === 'string' ? id : null;
if (id !== null && this.__states[id] !== undefined) {
this.state = id;
return true;
}
return false;
},
setShape: function(shape) {
if (typeof shape !== 'number') return false;
var found = false;
for (var id in Class.SHAPE) {
if (shape === Class.SHAPE[id]) {
found = true;
break;
}
}
if (found === true) {
this.shape = shape;
}
return found;
},
setVisible: function(visible) {
if (visible === true || visible === false) {
this.visible = visible;
return true;
}
return false;
}
};
return Class;
});
| nspforever/lycheeJS | lychee/ui/Entity.js | JavaScript | mit | 3,836 |
'use strict'
let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js')
let { dirname, resolve, relative, sep } = require('path')
let { pathToFileURL } = require('url')
let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator)
let pathAvailable = Boolean(dirname && resolve && relative && sep)
class MapGenerator {
constructor(stringify, root, opts) {
this.stringify = stringify
this.mapOpts = opts.map || {}
this.root = root
this.opts = opts
}
isMap() {
if (typeof this.opts.map !== 'undefined') {
return !!this.opts.map
}
return this.previous().length > 0
}
previous() {
if (!this.previousMaps) {
this.previousMaps = []
this.root.walk(node => {
if (node.source && node.source.input.map) {
let map = node.source.input.map
if (!this.previousMaps.includes(map)) {
this.previousMaps.push(map)
}
}
})
}
return this.previousMaps
}
isInline() {
if (typeof this.mapOpts.inline !== 'undefined') {
return this.mapOpts.inline
}
let annotation = this.mapOpts.annotation
if (typeof annotation !== 'undefined' && annotation !== true) {
return false
}
if (this.previous().length) {
return this.previous().some(i => i.inline)
}
return true
}
isSourcesContent() {
if (typeof this.mapOpts.sourcesContent !== 'undefined') {
return this.mapOpts.sourcesContent
}
if (this.previous().length) {
return this.previous().some(i => i.withContent())
}
return true
}
clearAnnotation() {
if (this.mapOpts.annotation === false) return
let node
for (let i = this.root.nodes.length - 1; i >= 0; i--) {
node = this.root.nodes[i]
if (node.type !== 'comment') continue
if (node.text.indexOf('# sourceMappingURL=') === 0) {
this.root.removeChild(i)
}
}
}
setSourcesContent() {
let already = {}
this.root.walk(node => {
if (node.source) {
let from = node.source.input.from
if (from && !already[from]) {
already[from] = true
this.map.setSourceContent(
this.toUrl(this.path(from)),
node.source.input.css
)
}
}
})
}
applyPrevMaps() {
for (let prev of this.previous()) {
let from = this.toUrl(this.path(prev.file))
let root = prev.root || dirname(prev.file)
let map
if (this.mapOpts.sourcesContent === false) {
map = new SourceMapConsumer(prev.text)
if (map.sourcesContent) {
map.sourcesContent = map.sourcesContent.map(() => null)
}
} else {
map = prev.consumer()
}
this.map.applySourceMap(map, from, this.toUrl(this.path(root)))
}
}
isAnnotation() {
if (this.isInline()) {
return true
}
if (typeof this.mapOpts.annotation !== 'undefined') {
return this.mapOpts.annotation
}
if (this.previous().length) {
return this.previous().some(i => i.annotation)
}
return true
}
toBase64(str) {
if (Buffer) {
return Buffer.from(str).toString('base64')
} else {
// istanbul ignore next
return window.btoa(unescape(encodeURIComponent(str)))
}
}
addAnnotation() {
let content
if (this.isInline()) {
content =
'data:application/json;base64,' + this.toBase64(this.map.toString())
} else if (typeof this.mapOpts.annotation === 'string') {
content = this.mapOpts.annotation
} else if (typeof this.mapOpts.annotation === 'function') {
content = this.mapOpts.annotation(this.opts.to, this.root)
} else {
content = this.outputFile() + '.map'
}
let eol = '\n'
if (this.css.includes('\r\n')) eol = '\r\n'
this.css += eol + '/*# sourceMappingURL=' + content + ' */'
}
outputFile() {
if (this.opts.to) {
return this.path(this.opts.to)
}
if (this.opts.from) {
return this.path(this.opts.from)
}
return 'to.css'
}
generateMap() {
this.generateString()
if (this.isSourcesContent()) this.setSourcesContent()
if (this.previous().length > 0) this.applyPrevMaps()
if (this.isAnnotation()) this.addAnnotation()
if (this.isInline()) {
return [this.css]
}
return [this.css, this.map]
}
path(file) {
if (file.indexOf('<') === 0) return file
if (/^\w+:\/\//.test(file)) return file
if (this.mapOpts.absolute) return file
let from = this.opts.to ? dirname(this.opts.to) : '.'
if (typeof this.mapOpts.annotation === 'string') {
from = dirname(resolve(from, this.mapOpts.annotation))
}
file = relative(from, file)
return file
}
toUrl(path) {
if (sep === '\\') {
// istanbul ignore next
path = path.replace(/\\/g, '/')
}
return encodeURI(path).replace(/[#?]/g, encodeURIComponent)
}
sourcePath(node) {
if (this.mapOpts.from) {
return this.toUrl(this.mapOpts.from)
} else if (this.mapOpts.absolute) {
if (pathToFileURL) {
return pathToFileURL(node.source.input.from).toString()
} else {
// istanbul ignore next
throw new Error(
'`map.absolute` option is not available in this PostCSS build'
)
}
} else {
return this.toUrl(this.path(node.source.input.from))
}
}
generateString() {
this.css = ''
this.map = new SourceMapGenerator({ file: this.outputFile() })
let line = 1
let column = 1
let noSource = '<no source>'
let mapping = {
source: '',
generated: { line: 0, column: 0 },
original: { line: 0, column: 0 }
}
let lines, last
this.stringify(this.root, (str, node, type) => {
this.css += str
if (node && type !== 'end') {
mapping.generated.line = line
mapping.generated.column = column - 1
if (node.source && node.source.start) {
mapping.source = this.sourcePath(node)
mapping.original.line = node.source.start.line
mapping.original.column = node.source.start.column - 1
this.map.addMapping(mapping)
} else {
mapping.source = noSource
mapping.original.line = 1
mapping.original.column = 0
this.map.addMapping(mapping)
}
}
lines = str.match(/\n/g)
if (lines) {
line += lines.length
last = str.lastIndexOf('\n')
column = str.length - last
} else {
column += str.length
}
if (node && type !== 'start') {
let p = node.parent || { raws: {} }
if (node.type !== 'decl' || node !== p.last || p.raws.semicolon) {
if (node.source && node.source.end) {
mapping.source = this.sourcePath(node)
mapping.original.line = node.source.end.line
mapping.original.column = node.source.end.column - 1
mapping.generated.line = line
mapping.generated.column = column - 2
this.map.addMapping(mapping)
} else {
mapping.source = noSource
mapping.original.line = 1
mapping.original.column = 0
mapping.generated.line = line
mapping.generated.column = column - 1
this.map.addMapping(mapping)
}
}
}
})
}
generate() {
this.clearAnnotation()
if (pathAvailable && sourceMapAvailable && this.isMap()) {
return this.generateMap()
}
let result = ''
this.stringify(this.root, i => {
result += i
})
return [result]
}
}
module.exports = MapGenerator
| kipid/blog | nodejs/web1_html_internet-master/node_modules/postcss/lib/map-generator.js | JavaScript | mit | 7,682 |
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* jshint maxlen: false */
'use strict';
var createAPIRequest = require('../../lib/apirequest');
/**
* TaskQueue API
*
* Lets you access a Google App Engine Pull Task Queue over REST.
*
* @example
* var google = require('googleapis');
* var taskqueue = google.taskqueue('v1beta2');
*
* @namespace taskqueue
* @type {Function}
* @version v1beta2
* @variation v1beta2
* @param {object=} options Options for Taskqueue
*/
function Taskqueue(options) { // eslint-disable-line
var self = this;
self._options = options || {};
self.taskqueues = {
/**
* taskqueue.taskqueues.get
*
* @desc Get detailed information about a TaskQueue.
*
* @alias taskqueue.taskqueues.get
* @memberOf! taskqueue(v1beta2)
*
* @param {object} params Parameters for request
* @param {boolean=} params.getStats Whether to get stats. Optional.
* @param {string} params.project The project under which the queue lies.
* @param {string} params.taskqueue The id of the taskqueue to get the properties of.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get: function (params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}',
method: 'GET'
},
params: params,
requiredParams: ['project', 'taskqueue'],
pathParams: ['project', 'taskqueue'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
self.tasks = {
/**
* taskqueue.tasks.delete
*
* @desc Delete a task from a TaskQueue.
*
* @alias taskqueue.tasks.delete
* @memberOf! taskqueue(v1beta2)
*
* @param {object} params Parameters for request
* @param {string} params.project The project under which the queue lies.
* @param {string} params.task The id of the task to delete.
* @param {string} params.taskqueue The taskqueue to delete a task from.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
delete: function (params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}/tasks/{task}',
method: 'DELETE'
},
params: params,
requiredParams: ['project', 'taskqueue', 'task'],
pathParams: ['project', 'task', 'taskqueue'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* taskqueue.tasks.get
*
* @desc Get a particular task from a TaskQueue.
*
* @alias taskqueue.tasks.get
* @memberOf! taskqueue(v1beta2)
*
* @param {object} params Parameters for request
* @param {string} params.project The project under which the queue lies.
* @param {string} params.task The task to get properties of.
* @param {string} params.taskqueue The taskqueue in which the task belongs.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get: function (params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}/tasks/{task}',
method: 'GET'
},
params: params,
requiredParams: ['project', 'taskqueue', 'task'],
pathParams: ['project', 'task', 'taskqueue'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* taskqueue.tasks.insert
*
* @desc Insert a new task in a TaskQueue
*
* @alias taskqueue.tasks.insert
* @memberOf! taskqueue(v1beta2)
*
* @param {object} params Parameters for request
* @param {string} params.project The project under which the queue lies
* @param {string} params.taskqueue The taskqueue to insert the task into
* @param {object} params.resource Request body data
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
insert: function (params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}/tasks',
method: 'POST'
},
params: params,
requiredParams: ['project', 'taskqueue'],
pathParams: ['project', 'taskqueue'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* taskqueue.tasks.lease
*
* @desc Lease 1 or more tasks from a TaskQueue.
*
* @alias taskqueue.tasks.lease
* @memberOf! taskqueue(v1beta2)
*
* @param {object} params Parameters for request
* @param {boolean=} params.groupByTag When true, all returned tasks will have the same tag
* @param {integer} params.leaseSecs The lease in seconds.
* @param {integer} params.numTasks The number of tasks to lease.
* @param {string} params.project The project under which the queue lies.
* @param {string=} params.tag The tag allowed for tasks in the response. Must only be specified if group_by_tag is true. If group_by_tag is true and tag is not specified the tag will be that of the oldest task by eta, i.e. the first available tag
* @param {string} params.taskqueue The taskqueue to lease a task from.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
lease: function (params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}/tasks/lease',
method: 'POST'
},
params: params,
requiredParams: ['project', 'taskqueue', 'numTasks', 'leaseSecs'],
pathParams: ['project', 'taskqueue'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* taskqueue.tasks.list
*
* @desc List Tasks in a TaskQueue
*
* @alias taskqueue.tasks.list
* @memberOf! taskqueue(v1beta2)
*
* @param {object} params Parameters for request
* @param {string} params.project The project under which the queue lies.
* @param {string} params.taskqueue The id of the taskqueue to list tasks from.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list: function (params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}/tasks',
method: 'GET'
},
params: params,
requiredParams: ['project', 'taskqueue'],
pathParams: ['project', 'taskqueue'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* taskqueue.tasks.patch
*
* @desc Update tasks that are leased out of a TaskQueue. This method supports patch semantics.
*
* @alias taskqueue.tasks.patch
* @memberOf! taskqueue(v1beta2)
*
* @param {object} params Parameters for request
* @param {integer} params.newLeaseSeconds The new lease in seconds.
* @param {string} params.project The project under which the queue lies.
* @param {string} params.task
* @param {string} params.taskqueue
* @param {object} params.resource Request body data
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
patch: function (params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}/tasks/{task}',
method: 'PATCH'
},
params: params,
requiredParams: ['project', 'taskqueue', 'task', 'newLeaseSeconds'],
pathParams: ['project', 'task', 'taskqueue'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* taskqueue.tasks.update
*
* @desc Update tasks that are leased out of a TaskQueue.
*
* @alias taskqueue.tasks.update
* @memberOf! taskqueue(v1beta2)
*
* @param {object} params Parameters for request
* @param {integer} params.newLeaseSeconds The new lease in seconds.
* @param {string} params.project The project under which the queue lies.
* @param {string} params.task
* @param {string} params.taskqueue
* @param {object} params.resource Request body data
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
update: function (params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}/tasks/{task}',
method: 'POST'
},
params: params,
requiredParams: ['project', 'taskqueue', 'task', 'newLeaseSeconds'],
pathParams: ['project', 'task', 'taskqueue'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
}
module.exports = Taskqueue;
| Poornakiruthika/Test | node_modules/youtube-api/node_modules/googleapis/apis/taskqueue/v1beta2.js | JavaScript | mit | 10,120 |
/*
ByteBuffer.js (c) 2015 Daniel Wirtz <[email protected]>
[BUILD] ByteBufferAB - Backing buffer: ArrayBuffer, Accessor: Uint8Array
Released under the Apache License, Version 2.0
see: https://github.com/dcodeIO/ByteBuffer.js for details
*/
function u(k){function g(a,b,c){"undefined"===typeof a&&(a=g.DEFAULT_CAPACITY);"undefined"===typeof b&&(b=g.DEFAULT_ENDIAN);"undefined"===typeof c&&(c=g.DEFAULT_NOASSERT);if(!c){a|=0;if(0>a)throw RangeError("Illegal capacity");b=!!b;c=!!c}this.buffer=0===a?v:new ArrayBuffer(a);this.view=0===a?null:new Uint8Array(this.buffer);this.offset=0;this.markedOffset=-1;this.limit=a;this.littleEndian="undefined"!==typeof b?!!b:!1;this.noAssert=!!c}function m(a){var b=0;return function(){return b<a.length?a.charCodeAt(b++):
null}}function s(){var a=[],b=[];return function(){if(0===arguments.length)return b.join("")+w.apply(String,a);1024<a.length+arguments.length&&(b.push(w.apply(String,a)),a.length=0);Array.prototype.push.apply(a,arguments)}}function x(a,b,c,d,e){var n;n=8*e-d-1;var h=(1<<n)-1,f=h>>1,g=-7;e=c?e-1:0;var q=c?-1:1,k=a[b+e];e+=q;c=k&(1<<-g)-1;k>>=-g;for(g+=n;0<g;c=256*c+a[b+e],e+=q,g-=8);n=c&(1<<-g)-1;c>>=-g;for(g+=d;0<g;n=256*n+a[b+e],e+=q,g-=8);if(0===c)c=1-f;else{if(c===h)return n?NaN:Infinity*(k?-1:
1);n+=Math.pow(2,d);c-=f}return(k?-1:1)*n*Math.pow(2,c-d)}function z(a,b,c,d,e,n){var f,g=8*n-e-1,t=(1<<g)-1,k=t>>1,y=23===e?Math.pow(2,-24)-Math.pow(2,-77):0;n=d?0:n-1;var l=d?1:-1,m=0>b||0===b&&0>1/b?1:0;b=Math.abs(b);isNaN(b)||Infinity===b?(b=isNaN(b)?1:0,d=t):(d=Math.floor(Math.log(b)/Math.LN2),1>b*(f=Math.pow(2,-d))&&(d--,f*=2),b=1<=d+k?b+y/f:b+y*Math.pow(2,1-k),2<=b*f&&(d++,f/=2),d+k>=t?(b=0,d=t):1<=d+k?(b=(b*f-1)*Math.pow(2,e),d+=k):(b=b*Math.pow(2,k-1)*Math.pow(2,e),d=0));for(;8<=e;a[c+n]=
b&255,n+=l,b/=256,e-=8);d=d<<e|b;for(g+=e;0<g;a[c+n]=d&255,n+=l,d/=256,g-=8);a[c+n-l]|=128*m}g.VERSION="4.0.0";g.LITTLE_ENDIAN=!0;g.BIG_ENDIAN=!1;g.DEFAULT_CAPACITY=16;g.DEFAULT_ENDIAN=g.BIG_ENDIAN;g.DEFAULT_NOASSERT=!1;g.Long=k||null;var f=g.prototype;Object.defineProperty(f,"__isByteBuffer__",{value:!0,enumerable:!1,configurable:!1});var v=new ArrayBuffer(0),w=String.fromCharCode;g.accessor=function(){return Uint8Array};g.allocate=function(a,b,c){return new g(a,b,c)};g.concat=function(a,b,c,d){if("boolean"===
typeof b||"string"!==typeof b)d=c,c=b,b=void 0;for(var e=0,f=0,h=a.length,p;f<h;++f)g.isByteBuffer(a[f])||(a[f]=g.wrap(a[f],b)),p=a[f].limit-a[f].offset,0<p&&(e+=p);if(0===e)return new g(0,c,d);b=new g(e,c,d);for(f=0;f<h;)c=a[f++],p=c.limit-c.offset,0>=p||(b.view.set(c.view.subarray(c.offset,c.limit),b.offset),b.offset+=p);b.limit=b.offset;b.offset=0;return b};g.isByteBuffer=function(a){return!0===(a&&a.__isByteBuffer__)};g.type=function(){return ArrayBuffer};g.wrap=function(a,b,c,d){"string"!==typeof b&&
(d=c,c=b,b=void 0);if("string"===typeof a)switch("undefined"===typeof b&&(b="utf8"),b){case "base64":return g.fromBase64(a,c);case "hex":return g.fromHex(a,c);case "binary":return g.fromBinary(a,c);case "utf8":return g.fromUTF8(a,c);case "debug":return g.fromDebug(a,c);default:throw Error("Unsupported encoding: "+b);}if(null===a||"object"!==typeof a)throw TypeError("Illegal buffer");if(g.isByteBuffer(a))return b=f.clone.call(a),b.markedOffset=-1,b;if(a instanceof Uint8Array)b=new g(0,c,d),0<a.length&&
(b.buffer=a.buffer,b.offset=a.byteOffset,b.limit=a.byteOffset+a.byteLength,b.view=new Uint8Array(a.buffer));else if(a instanceof ArrayBuffer)b=new g(0,c,d),0<a.byteLength&&(b.buffer=a,b.offset=0,b.limit=a.byteLength,b.view=0<a.byteLength?new Uint8Array(a):null);else if("[object Array]"===Object.prototype.toString.call(a))for(b=new g(a.length,c,d),b.limit=a.length,c=0;c<a.length;++c)b.view[c]=a[c];else throw TypeError("Illegal buffer");return b};f.readBytes=function(a,b){var c="undefined"===typeof b;
c&&(b=this.offset);if(!this.noAssert){if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;if(0>b||b+a>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+a+") <= "+this.buffer.byteLength);}var d=this.slice(b,b+a);c&&(this.offset+=a);return d};f.writeBytes=f.append;f.writeInt8=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");
a|=0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);}b+=1;var d=this.buffer.byteLength;b>d&&this.resize((d*=2)>b?d:b);this.view[b-1]=a;c&&(this.offset+=1);return this};f.writeByte=f.writeInt8;f.readInt8=function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+
a+" (not an integer)");a>>>=0;if(0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+1) <= "+this.buffer.byteLength);}a=this.view[a];128===(a&128)&&(a=-(255-a+1));b&&(this.offset+=1);return a};f.readByte=f.readInt8;f.writeUint8=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");a>>>=0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+
" (not an integer)");b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);}b+=1;var d=this.buffer.byteLength;b>d&&this.resize((d*=2)>b?d:b);this.view[b-1]=a;c&&(this.offset+=1);return this};f.writeUInt8=f.writeUint8;f.readUint8=function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");a>>>=0;if(0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+
a+" (+1) <= "+this.buffer.byteLength);}a=this.view[a];b&&(this.offset+=1);return a};f.readUInt8=f.readUint8;f.writeInt16=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");a|=0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);
}b+=2;var d=this.buffer.byteLength;b>d&&this.resize((d*=2)>b?d:b);b-=2;this.littleEndian?(this.view[b+1]=(a&65280)>>>8,this.view[b]=a&255):(this.view[b]=(a&65280)>>>8,this.view[b+1]=a&255);c&&(this.offset+=2);return this};f.writeShort=f.writeInt16;f.readInt16=function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");a>>>=0;if(0>a||a+2>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+
a+" (+2) <= "+this.buffer.byteLength);}var c=0;this.littleEndian?(c=this.view[a],c|=this.view[a+1]<<8):(c=this.view[a]<<8,c|=this.view[a+1]);32768===(c&32768)&&(c=-(65535-c+1));b&&(this.offset+=2);return c};f.readShort=f.readInt16;f.writeUint16=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");a>>>=0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");
b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);}b+=2;var d=this.buffer.byteLength;b>d&&this.resize((d*=2)>b?d:b);b-=2;this.littleEndian?(this.view[b+1]=(a&65280)>>>8,this.view[b]=a&255):(this.view[b]=(a&65280)>>>8,this.view[b+1]=a&255);c&&(this.offset+=2);return this};f.writeUInt16=f.writeUint16;f.readUint16=function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+
a+" (not an integer)");a>>>=0;if(0>a||a+2>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+2) <= "+this.buffer.byteLength);}var c=0;this.littleEndian?(c=this.view[a],c|=this.view[a+1]<<8):(c=this.view[a]<<8,c|=this.view[a+1]);b&&(this.offset+=2);return c};f.readUInt16=f.readUint16;f.writeInt32=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");a|=0;if("number"!==
typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);}b+=4;var d=this.buffer.byteLength;b>d&&this.resize((d*=2)>b?d:b);b-=4;this.littleEndian?(this.view[b+3]=a>>>24&255,this.view[b+2]=a>>>16&255,this.view[b+1]=a>>>8&255,this.view[b]=a&255):(this.view[b]=a>>>24&255,this.view[b+1]=a>>>16&255,this.view[b+2]=a>>>8&255,this.view[b+3]=a&255);c&&(this.offset+=4);
return this};f.writeInt=f.writeInt32;f.readInt32=function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");a>>>=0;if(0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+4) <= "+this.buffer.byteLength);}var c=0;this.littleEndian?(c=this.view[a+2]<<16,c|=this.view[a+1]<<8,c|=this.view[a],c+=this.view[a+3]<<24>>>0):(c=this.view[a+1]<<16,c|=this.view[a+2]<<8,c|=this.view[a+
3],c+=this.view[a]<<24>>>0);b&&(this.offset+=4);return c|0};f.readInt=f.readInt32;f.writeUint32=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");a>>>=0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);}b+=4;var d=this.buffer.byteLength;
b>d&&this.resize((d*=2)>b?d:b);b-=4;this.littleEndian?(this.view[b+3]=a>>>24&255,this.view[b+2]=a>>>16&255,this.view[b+1]=a>>>8&255,this.view[b]=a&255):(this.view[b]=a>>>24&255,this.view[b+1]=a>>>16&255,this.view[b+2]=a>>>8&255,this.view[b+3]=a&255);c&&(this.offset+=4);return this};f.writeUInt32=f.writeUint32;f.readUint32=function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");a>>>=0;if(0>
a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+4) <= "+this.buffer.byteLength);}var c=0;this.littleEndian?(c=this.view[a+2]<<16,c|=this.view[a+1]<<8,c|=this.view[a],c+=this.view[a+3]<<24>>>0):(c=this.view[a+1]<<16,c|=this.view[a+2]<<8,c|=this.view[a+3],c+=this.view[a]<<24>>>0);b&&(this.offset+=4);return c};f.readUInt32=f.readUint32;k&&(f.writeInt64=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);if(!this.noAssert){if("number"===typeof a)a=k.fromNumber(a);
else if("string"===typeof a)a=k.fromString(a);else if(!(a&&a instanceof k))throw TypeError("Illegal value: "+a+" (not an integer or Long)");if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);}"number"===typeof a?a=k.fromNumber(a):"string"===typeof a&&(a=k.fromString(a));b+=8;var d=this.buffer.byteLength;b>d&&this.resize((d*=2)>b?d:b);b-=8;
var d=a.low,e=a.high;this.littleEndian?(this.view[b+3]=d>>>24&255,this.view[b+2]=d>>>16&255,this.view[b+1]=d>>>8&255,this.view[b]=d&255,b+=4,this.view[b+3]=e>>>24&255,this.view[b+2]=e>>>16&255,this.view[b+1]=e>>>8&255,this.view[b]=e&255):(this.view[b]=e>>>24&255,this.view[b+1]=e>>>16&255,this.view[b+2]=e>>>8&255,this.view[b+3]=e&255,b+=4,this.view[b]=d>>>24&255,this.view[b+1]=d>>>16&255,this.view[b+2]=d>>>8&255,this.view[b+3]=d&255);c&&(this.offset+=8);return this},f.writeLong=f.writeInt64,f.readInt64=
function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");a>>>=0;if(0>a||a+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+8) <= "+this.buffer.byteLength);}var c=0,d=0;this.littleEndian?(c=this.view[a+2]<<16,c|=this.view[a+1]<<8,c|=this.view[a],c+=this.view[a+3]<<24>>>0,a+=4,d=this.view[a+2]<<16,d|=this.view[a+1]<<8,d|=this.view[a],d+=this.view[a+3]<<24>>>0):(d=this.view[a+
1]<<16,d|=this.view[a+2]<<8,d|=this.view[a+3],d+=this.view[a]<<24>>>0,a+=4,c=this.view[a+1]<<16,c|=this.view[a+2]<<8,c|=this.view[a+3],c+=this.view[a]<<24>>>0);a=new k(c,d,!1);b&&(this.offset+=8);return a},f.readLong=f.readInt64,f.writeUint64=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);if(!this.noAssert){if("number"===typeof a)a=k.fromNumber(a);else if("string"===typeof a)a=k.fromString(a);else if(!(a&&a instanceof k))throw TypeError("Illegal value: "+a+" (not an integer or Long)");
if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);}"number"===typeof a?a=k.fromNumber(a):"string"===typeof a&&(a=k.fromString(a));b+=8;var d=this.buffer.byteLength;b>d&&this.resize((d*=2)>b?d:b);b-=8;var d=a.low,e=a.high;this.littleEndian?(this.view[b+3]=d>>>24&255,this.view[b+2]=d>>>16&255,this.view[b+1]=d>>>8&255,this.view[b]=d&255,b+=4,
this.view[b+3]=e>>>24&255,this.view[b+2]=e>>>16&255,this.view[b+1]=e>>>8&255,this.view[b]=e&255):(this.view[b]=e>>>24&255,this.view[b+1]=e>>>16&255,this.view[b+2]=e>>>8&255,this.view[b+3]=e&255,b+=4,this.view[b]=d>>>24&255,this.view[b+1]=d>>>16&255,this.view[b+2]=d>>>8&255,this.view[b+3]=d&255);c&&(this.offset+=8);return this},f.writeUInt64=f.writeUint64,f.readUint64=function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+
a+" (not an integer)");a>>>=0;if(0>a||a+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+8) <= "+this.buffer.byteLength);}var c=0,d=0;this.littleEndian?(c=this.view[a+2]<<16,c|=this.view[a+1]<<8,c|=this.view[a],c+=this.view[a+3]<<24>>>0,a+=4,d=this.view[a+2]<<16,d|=this.view[a+1]<<8,d|=this.view[a],d+=this.view[a+3]<<24>>>0):(d=this.view[a+1]<<16,d|=this.view[a+2]<<8,d|=this.view[a+3],d+=this.view[a]<<24>>>0,a+=4,c=this.view[a+1]<<16,c|=this.view[a+2]<<8,c|=this.view[a+3],c+=
this.view[a]<<24>>>0);a=new k(c,d,!0);b&&(this.offset+=8);return a},f.readUInt64=f.readUint64);f.writeFloat32=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);if(!this.noAssert){if("number"!==typeof a)throw TypeError("Illegal value: "+a+" (not a number)");if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);}b+=4;var d=this.buffer.byteLength;
b>d&&this.resize((d*=2)>b?d:b);z(this.view,a,b-4,this.littleEndian,23,4);c&&(this.offset+=4);return this};f.writeFloat=f.writeFloat32;f.readFloat32=function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");a>>>=0;if(0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+4) <= "+this.buffer.byteLength);}a=x(this.view,a,this.littleEndian,23,4);b&&(this.offset+=4);return a};
f.readFloat=f.readFloat32;f.writeFloat64=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);if(!this.noAssert){if("number"!==typeof a)throw TypeError("Illegal value: "+a+" (not a number)");if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);}b+=8;var d=this.buffer.byteLength;b>d&&this.resize((d*=2)>b?d:b);z(this.view,a,b-8,this.littleEndian,
52,8);c&&(this.offset+=8);return this};f.writeDouble=f.writeFloat64;f.readFloat64=function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");a>>>=0;if(0>a||a+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+8) <= "+this.buffer.byteLength);}a=x(this.view,a,this.littleEndian,52,8);b&&(this.offset+=8);return a};f.readDouble=f.readFloat64;g.MAX_VARINT32_BYTES=5;g.calculateVarint32=
function(a){a>>>=0;return 128>a?1:16384>a?2:2097152>a?3:268435456>a?4:5};g.zigZagEncode32=function(a){return((a|=0)<<1^a>>31)>>>0};g.zigZagDecode32=function(a){return a>>>1^-(a&1)|0};f.writeVarint32=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");a|=0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+
b+" (+0) <= "+this.buffer.byteLength);}var d=g.calculateVarint32(a);b+=d;var e=this.buffer.byteLength;b>e&&this.resize((e*=2)>b?e:b);b-=d;this.view[b]=d=a|128;a>>>=0;128<=a?(d=a>>7|128,this.view[b+1]=d,16384<=a?(d=a>>14|128,this.view[b+2]=d,2097152<=a?(d=a>>21|128,this.view[b+3]=d,268435456<=a?(this.view[b+4]=a>>28&15,d=5):(this.view[b+3]=d&127,d=4)):(this.view[b+2]=d&127,d=3)):(this.view[b+1]=d&127,d=2)):(this.view[b]=d&127,d=1);return c?(this.offset+=d,this):d};f.writeVarint32ZigZag=function(a,
b){return this.writeVarint32(g.zigZagEncode32(a),b)};f.readVarint32=function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");a>>>=0;if(0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+1) <= "+this.buffer.byteLength);}var c=0,d=0,e;do{e=a+c;if(!this.noAssert&&e>this.limit)throw a=Error("Truncated"),a.truncated=!0,a;e=this.view[e];5>c&&(d|=(e&127)<<7*c>>>0);++c}while(128===
(e&128));d|=0;return b?(this.offset+=c,d):{value:d,length:c}};f.readVarint32ZigZag=function(a){a=this.readVarint32(a);"object"===typeof a?a.value=g.zigZagDecode32(a.value):a=g.zigZagDecode32(a);return a};k&&(g.MAX_VARINT64_BYTES=10,g.calculateVarint64=function(a){"number"===typeof a?a=k.fromNumber(a):"string"===typeof a&&(a=k.fromString(a));var b=a.toInt()>>>0,c=a.shiftRightUnsigned(28).toInt()>>>0;a=a.shiftRightUnsigned(56).toInt()>>>0;return 0==a?0==c?16384>b?128>b?1:2:2097152>b?3:4:16384>c?128>
c?5:6:2097152>c?7:8:128>a?9:10},g.zigZagEncode64=function(a){"number"===typeof a?a=k.fromNumber(a,!1):"string"===typeof a?a=k.fromString(a,!1):!1!==a.unsigned&&(a=a.toSigned());return a.shiftLeft(1).xor(a.shiftRight(63)).toUnsigned()},g.zigZagDecode64=function(a){"number"===typeof a?a=k.fromNumber(a,!1):"string"===typeof a?a=k.fromString(a,!1):!1!==a.unsigned&&(a=a.toSigned());return a.shiftRightUnsigned(1).xor(a.and(k.ONE).toSigned().negate()).toSigned()},f.writeVarint64=function(a,b){var c="undefined"===
typeof b;c&&(b=this.offset);if(!this.noAssert){if("number"===typeof a)a=k.fromNumber(a);else if("string"===typeof a)a=k.fromString(a);else if(!(a&&a instanceof k))throw TypeError("Illegal value: "+a+" (not an integer or Long)");if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);}"number"===typeof a?a=k.fromNumber(a,!1):"string"===typeof a?
a=k.fromString(a,!1):!1!==a.unsigned&&(a=a.toSigned());var d=g.calculateVarint64(a),e=a.toInt()>>>0,f=a.shiftRightUnsigned(28).toInt()>>>0,h=a.shiftRightUnsigned(56).toInt()>>>0;b+=d;var p=this.buffer.byteLength;b>p&&this.resize((p*=2)>b?p:b);b-=d;switch(d){case 10:this.view[b+9]=h>>>7&1;case 9:this.view[b+8]=9!==d?h|128:h&127;case 8:this.view[b+7]=8!==d?f>>>21|128:f>>>21&127;case 7:this.view[b+6]=7!==d?f>>>14|128:f>>>14&127;case 6:this.view[b+5]=6!==d?f>>>7|128:f>>>7&127;case 5:this.view[b+4]=5!==
d?f|128:f&127;case 4:this.view[b+3]=4!==d?e>>>21|128:e>>>21&127;case 3:this.view[b+2]=3!==d?e>>>14|128:e>>>14&127;case 2:this.view[b+1]=2!==d?e>>>7|128:e>>>7&127;case 1:this.view[b]=1!==d?e|128:e&127}return c?(this.offset+=d,this):d},f.writeVarint64ZigZag=function(a,b){return this.writeVarint64(g.zigZagEncode64(a),b)},f.readVarint64=function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");
a>>>=0;if(0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+1) <= "+this.buffer.byteLength);}var c=a,d=0,e=0,f=0,h=0,h=this.view[a++],d=h&127;if(h&128&&(h=this.view[a++],d|=(h&127)<<7,h&128||this.noAssert&&"undefined"===typeof h)&&(h=this.view[a++],d|=(h&127)<<14,h&128||this.noAssert&&"undefined"===typeof h)&&(h=this.view[a++],d|=(h&127)<<21,h&128||this.noAssert&&"undefined"===typeof h)&&(h=this.view[a++],e=h&127,h&128||this.noAssert&&"undefined"===typeof h)&&(h=this.view[a++],
e|=(h&127)<<7,h&128||this.noAssert&&"undefined"===typeof h)&&(h=this.view[a++],e|=(h&127)<<14,h&128||this.noAssert&&"undefined"===typeof h)&&(h=this.view[a++],e|=(h&127)<<21,h&128||this.noAssert&&"undefined"===typeof h)&&(h=this.view[a++],f=h&127,h&128||this.noAssert&&"undefined"===typeof h)&&(h=this.view[a++],f|=(h&127)<<7,h&128||this.noAssert&&"undefined"===typeof h))throw Error("Buffer overrun");d=k.fromBits(d|e<<28,e>>>4|f<<24,!1);return b?(this.offset=a,d):{value:d,length:a-c}},f.readVarint64ZigZag=
function(a){(a=this.readVarint64(a))&&a.value instanceof k?a.value=g.zigZagDecode64(a.value):a=g.zigZagDecode64(a);return a});f.writeCString=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);var d,e=a.length;if(!this.noAssert){if("string"!==typeof a)throw TypeError("Illegal str: Not a string");for(d=0;d<e;++d)if(0===a.charCodeAt(d))throw RangeError("Illegal str: Contains NULL-characters");if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;
if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);}e=l.a(m(a))[1];b+=e+1;d=this.buffer.byteLength;b>d&&this.resize((d*=2)>b?d:b);b-=e+1;l.c(m(a),function(a){this.view[b++]=a}.bind(this));this.view[b++]=0;return c?(this.offset=b,this):e};f.readCString=function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");a>>>=0;if(0>a||a+
1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+1) <= "+this.buffer.byteLength);}var c=a,d,e=-1;l.b(function(){if(0===e)return null;if(a>=this.limit)throw RangeError("Illegal range: Truncated data, "+a+" < "+this.limit);e=this.view[a++];return 0===e?null:e}.bind(this),d=s(),!0);return b?(this.offset=a,d()):{string:d(),length:a-c}};f.writeIString=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);if(!this.noAssert){if("string"!==typeof a)throw TypeError("Illegal str: Not a string");
if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);}var d=b,e;e=l.a(m(a),this.noAssert)[1];b+=4+e;var f=this.buffer.byteLength;b>f&&this.resize((f*=2)>b?f:b);b-=4+e;this.littleEndian?(this.view[b+3]=e>>>24&255,this.view[b+2]=e>>>16&255,this.view[b+1]=e>>>8&255,this.view[b]=e&255):(this.view[b]=e>>>24&255,this.view[b+1]=e>>>16&255,this.view[b+
2]=e>>>8&255,this.view[b+3]=e&255);b+=4;l.c(m(a),function(a){this.view[b++]=a}.bind(this));if(b!==d+4+e)throw RangeError("Illegal range: Truncated data, "+b+" == "+(b+4+e));return c?(this.offset=b,this):b-d};f.readIString=function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");a>>>=0;if(0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+4) <= "+this.buffer.byteLength);
}var c=0,d=a;this.littleEndian?(c=this.view[a+2]<<16,c|=this.view[a+1]<<8,c|=this.view[a],c+=this.view[a+3]<<24>>>0):(c=this.view[a+1]<<16,c|=this.view[a+2]<<8,c|=this.view[a+3],c+=this.view[a]<<24>>>0);a+=4;var e=a+c;l.b(function(){return a<e?this.view[a++]:null}.bind(this),c=s(),this.noAssert);c=c();return b?(this.offset=a,c):{string:c,length:a-d}};g.METRICS_CHARS="c";g.METRICS_BYTES="b";f.writeUTF8String=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);if(!this.noAssert){if("number"!==
typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);}var d,e=b;d=l.a(m(a))[1];b+=d;var f=this.buffer.byteLength;b>f&&this.resize((f*=2)>b?f:b);b-=d;l.c(m(a),function(a){this.view[b++]=a}.bind(this));return c?(this.offset=b,this):b-e};f.writeString=f.writeUTF8String;g.calculateUTF8Chars=function(a){return l.a(m(a))[0]};g.calculateUTF8Bytes=function(a){return l.a(m(a))[1]};
g.calculateString=g.calculateUTF8Bytes;f.readUTF8String=function(a,b,c){"number"===typeof b&&(c=b,b=void 0);var d="undefined"===typeof c;d&&(c=this.offset);"undefined"===typeof b&&(b=g.METRICS_CHARS);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal length: "+a+" (not an integer)");a|=0;if("number"!==typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");c>>>=0;if(0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+0) <= "+
this.buffer.byteLength);}var e=0,f=c,h;if(b===g.METRICS_CHARS){h=s();l.f(function(){return e<a&&c<this.limit?this.view[c++]:null}.bind(this),function(a){++e;l.e(a,h)});if(e!==a)throw RangeError("Illegal range: Truncated data, "+e+" == "+a);return d?(this.offset=c,h()):{string:h(),length:c-f}}if(b===g.METRICS_BYTES){if(!this.noAssert){if("number"!==typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");c>>>=0;if(0>c||c+a>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+
c+" (+"+a+") <= "+this.buffer.byteLength);}var p=c+a;l.b(function(){return c<p?this.view[c++]:null}.bind(this),h=s(),this.noAssert);if(c!==p)throw RangeError("Illegal range: Truncated data, "+c+" == "+p);return d?(this.offset=c,h()):{string:h(),length:c-f}}throw TypeError("Unsupported metrics: "+b);};f.readString=f.readUTF8String;f.writeVString=function(a,b){var c="undefined"===typeof b;c&&(b=this.offset);if(!this.noAssert){if("string"!==typeof a)throw TypeError("Illegal str: Not a string");if("number"!==
typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");b>>>=0;if(0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+0) <= "+this.buffer.byteLength);}var d=b,e,f;e=l.a(m(a),this.noAssert)[1];f=g.calculateVarint32(e);b+=f+e;var h=this.buffer.byteLength;b>h&&this.resize((h*=2)>b?h:b);b-=f+e;b+=this.writeVarint32(e,b);l.c(m(a),function(a){this.view[b++]=a}.bind(this));if(b!==d+e+f)throw RangeError("Illegal range: Truncated data, "+b+" == "+(b+e+f));return c?
(this.offset=b,this):b-d};f.readVString=function(a){var b="undefined"===typeof a;b&&(a=this.offset);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");a>>>=0;if(0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+1) <= "+this.buffer.byteLength);}var c=this.readVarint32(a),d=a;a+=c.length;var c=c.value,e=a+c,c=s();l.b(function(){return a<e?this.view[a++]:null}.bind(this),c,this.noAssert);c=c();return b?(this.offset=
a,c):{string:c,length:a-d}};f.append=function(a,b,c){if("number"===typeof b||"string"!==typeof b)c=b,b=void 0;var d="undefined"===typeof c;d&&(c=this.offset);if(!this.noAssert){if("number"!==typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");c>>>=0;if(0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+0) <= "+this.buffer.byteLength);}a instanceof g||(a=g.wrap(a,b));b=a.limit-a.offset;if(0>=b)return this;c+=b;var e=this.buffer.byteLength;c>e&&this.resize((e*=
2)>c?e:c);this.view.set(a.view.subarray(a.offset,a.limit),c-b);a.offset+=b;d&&(this.offset+=b);return this};f.appendTo=function(a,b){a.append(this,b);return this};f.assert=function(a){this.noAssert=!a;return this};f.capacity=function(){return this.buffer.byteLength};f.clear=function(){this.offset=0;this.limit=this.buffer.byteLength;this.markedOffset=-1;return this};f.clone=function(a){var b=new g(0,this.littleEndian,this.noAssert);a?(b.buffer=new ArrayBuffer(this.buffer.byteLength),b.view=new Uint8Array(b.buffer)):
(b.buffer=this.buffer,b.view=this.view);b.offset=this.offset;b.markedOffset=this.markedOffset;b.limit=this.limit;return b};f.compact=function(a,b){"undefined"===typeof a&&(a=this.offset);"undefined"===typeof b&&(b=this.limit);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");a>>>=0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");b>>>=0;if(0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+
b+" <= "+this.buffer.byteLength);}if(0===a&&b===this.buffer.byteLength)return this;var c=b-a;if(0===c)return this.buffer=v,this.view=null,0<=this.markedOffset&&(this.markedOffset-=a),this.limit=this.offset=0,this;var d=new ArrayBuffer(c),e=new Uint8Array(d);e.set(this.view.subarray(a,b));this.buffer=d;this.view=e;0<=this.markedOffset&&(this.markedOffset-=a);this.offset=0;this.limit=c;return this};f.copy=function(a,b){"undefined"===typeof a&&(a=this.offset);"undefined"===typeof b&&(b=this.limit);if(!this.noAssert){if("number"!==
typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");a>>>=0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");b>>>=0;if(0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength);}if(a===b)return new g(0,this.littleEndian,this.noAssert);var c=b-a,d=new g(c,this.littleEndian,this.noAssert);d.offset=0;d.limit=c;0<=d.markedOffset&&(d.markedOffset-=a);this.copyTo(d,0,a,b);return d};f.copyTo=function(a,
b,c,d){var e,f;if(!this.noAssert&&!g.isByteBuffer(a))throw TypeError("Illegal target: Not a ByteBuffer");b=(f="undefined"===typeof b)?a.offset:b|0;c=(e="undefined"===typeof c)?this.offset:c|0;d="undefined"===typeof d?this.limit:d|0;if(0>b||b>a.buffer.byteLength)throw RangeError("Illegal target range: 0 <= "+b+" <= "+a.buffer.byteLength);if(0>c||d>this.buffer.byteLength)throw RangeError("Illegal source range: 0 <= "+c+" <= "+this.buffer.byteLength);var h=d-c;if(0===h)return a;a.ensureCapacity(b+h);
a.view.set(this.view.subarray(c,d),b);e&&(this.offset+=h);f&&(a.offset+=h);return this};f.ensureCapacity=function(a){var b=this.buffer.byteLength;return b<a?this.resize((b*=2)>a?b:a):this};f.fill=function(a,b,c){var d="undefined"===typeof b;d&&(b=this.offset);"string"===typeof a&&0<a.length&&(a=a.charCodeAt(0));"undefined"===typeof b&&(b=this.offset);"undefined"===typeof c&&(c=this.limit);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");a|=
0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal begin: Not an integer");b>>>=0;if("number"!==typeof c||0!==c%1)throw TypeError("Illegal end: Not an integer");c>>>=0;if(0>b||b>c||c>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+b+" <= "+c+" <= "+this.buffer.byteLength);}if(b>=c)return this;for(;b<c;)this.view[b++]=a;d&&(this.offset=b);return this};f.flip=function(){this.limit=this.offset;this.offset=0;return this};f.mark=function(a){a="undefined"===typeof a?this.offset:a;
if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");a>>>=0;if(0>a||a+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+0) <= "+this.buffer.byteLength);}this.markedOffset=a;return this};f.order=function(a){if(!this.noAssert&&"boolean"!==typeof a)throw TypeError("Illegal littleEndian: Not a boolean");this.littleEndian=!!a;return this};f.LE=function(a){this.littleEndian="undefined"!==typeof a?!!a:!0;return this};f.BE=function(a){this.littleEndian=
"undefined"!==typeof a?!a:!1;return this};f.prepend=function(a,b,c){if("number"===typeof b||"string"!==typeof b)c=b,b=void 0;var d="undefined"===typeof c;d&&(c=this.offset);if(!this.noAssert){if("number"!==typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");c>>>=0;if(0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+0) <= "+this.buffer.byteLength);}a instanceof g||(a=g.wrap(a,b));b=a.limit-a.offset;if(0>=b)return this;var e=b-c;if(0<e){var f=new ArrayBuffer(this.buffer.byteLength+
e),h=new Uint8Array(f);h.set(this.view.subarray(c,this.buffer.byteLength),b);this.buffer=f;this.view=h;this.offset+=e;0<=this.markedOffset&&(this.markedOffset+=e);this.limit+=e;c+=e}else new Uint8Array(this.buffer);this.view.set(a.view.subarray(a.offset,a.limit),c-b);a.offset=a.limit;d&&(this.offset-=b);return this};f.prependTo=function(a,b){a.prepend(this,b);return this};f.printDebug=function(a){"function"!==typeof a&&(a=console.log.bind(console));a(this.toString()+"\n-------------------------------------------------------------------\n"+
this.toDebug(!0))};f.remaining=function(){return this.limit-this.offset};f.reset=function(){0<=this.markedOffset?(this.offset=this.markedOffset,this.markedOffset=-1):this.offset=0;return this};f.resize=function(a){if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal capacity: "+a+" (not an integer)");a|=0;if(0>a)throw RangeError("Illegal capacity: 0 <= "+a);}if(this.buffer.byteLength<a){a=new ArrayBuffer(a);var b=new Uint8Array(a);b.set(this.view);this.buffer=a;this.view=b}return this};
f.reverse=function(a,b){"undefined"===typeof a&&(a=this.offset);"undefined"===typeof b&&(b=this.limit);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");a>>>=0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");b>>>=0;if(0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength);}if(a===b)return this;Array.prototype.reverse.call(this.view.subarray(a,b));return this};
f.skip=function(a){if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal length: "+a+" (not an integer)");a|=0}var b=this.offset+a;if(!this.noAssert&&(0>b||b>this.buffer.byteLength))throw RangeError("Illegal length: 0 <= "+this.offset+" + "+a+" <= "+this.buffer.byteLength);this.offset=b;return this};f.slice=function(a,b){"undefined"===typeof a&&(a=this.offset);"undefined"===typeof b&&(b=this.limit);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");
a>>>=0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");b>>>=0;if(0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength);}var c=this.clone();c.offset=a;c.limit=b;return c};f.toBuffer=function(a){var b=this.offset,c=this.limit;if(!this.noAssert){if("number"!==typeof b||0!==b%1)throw TypeError("Illegal offset: Not an integer");b>>>=0;if("number"!==typeof c||0!==c%1)throw TypeError("Illegal limit: Not an integer");
c>>>=0;if(0>b||b>c||c>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+b+" <= "+c+" <= "+this.buffer.byteLength);}if(!a&&0===b&&c===this.buffer.byteLength)return this.buffer;if(b===c)return v;a=new ArrayBuffer(c-b);(new Uint8Array(a)).set((new Uint8Array(this.buffer)).subarray(b,c),0);return a};f.toArrayBuffer=f.toBuffer;f.toString=function(a,b,c){if("undefined"===typeof a)return"ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+
")";"number"===typeof a&&(c=b=a="utf8");switch(a){case "utf8":return this.toUTF8(b,c);case "base64":return this.toBase64(b,c);case "hex":return this.toHex(b,c);case "binary":return this.toBinary(b,c);case "debug":return this.toDebug();case "columns":return this.m();default:throw Error("Unsupported encoding: "+a);}};var A=function(){for(var a={},b=[65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,
116,117,118,119,120,121,122,48,49,50,51,52,53,54,55,56,57,43,47],c=[],d=0,e=b.length;d<e;++d)c[b[d]]=d;a.h=function(a,c){for(var d,e;null!==(d=a());)c(b[d>>2&63]),e=(d&3)<<4,null!==(d=a())?(e|=d>>4&15,c(b[(e|d>>4&15)&63]),e=(d&15)<<2,null!==(d=a())?(c(b[(e|d>>6&3)&63]),c(b[d&63])):(c(b[e&63]),c(61))):(c(b[e&63]),c(61),c(61))};a.g=function(a,b){function d(a){throw Error("Illegal character code: "+a);}for(var e,f,g;null!==(e=a());)if(f=c[e],"undefined"===typeof f&&d(e),null!==(e=a())&&(g=c[e],"undefined"===
typeof g&&d(e),b(f<<2>>>0|(g&48)>>4),null!==(e=a()))){f=c[e];if("undefined"===typeof f)if(61===e)break;else d(e);b((g&15)<<4>>>0|(f&60)>>2);if(null!==(e=a())){g=c[e];if("undefined"===typeof g)if(61===e)break;else d(e);b((f&3)<<6>>>0|g)}}};a.test=function(a){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a)};return a}();f.toBase64=function(a,b){"undefined"===typeof a&&(a=this.offset);"undefined"===typeof b&&(b=this.limit);if(!this.noAssert){if("number"!==typeof a||0!==
a%1)throw TypeError("Illegal begin: Not an integer");a>>>=0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");b>>>=0;if(0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength);}var c;A.h(function(){return a<b?this.view[a++]:null}.bind(this),c=s());return c()};g.fromBase64=function(a,b,c){if(!c){if("string"!==typeof a)throw TypeError("Illegal str: Not a string");if(0!==a.length%4)throw TypeError("Illegal str: Length not a multiple of 4");
}var d=new g(a.length/4*3,b,c),e=0;A.g(m(a),function(a){d.view[e++]=a});d.limit=e;return d};g.btoa=function(a){return g.fromBinary(a).toBase64()};g.atob=function(a){return g.fromBase64(a).toBinary()};f.toBinary=function(a,b){a="undefined"===typeof a?this.offset:a;b="undefined"===typeof b?this.limit:b;if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");a>>>=0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");b>>>=0;if(0>a||
a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength);}if(a===b)return"";for(var c=[],d=[];a<b;)c.push(this.view[a++]),1024<=c.length&&(d.push(String.fromCharCode.apply(String,c)),c=[]);return d.join("")+String.fromCharCode.apply(String,c)};g.fromBinary=function(a,b,c){if(!c&&"string"!==typeof a)throw TypeError("Illegal str: Not a string");for(var d=0,e=a.length,f=new g(e,b,c);d<e;){b=a.charCodeAt(d);if(!c&&255<b)throw RangeError("Illegal charCode at "+
d+": 0 <= "+b+" <= 255");f.view[d++]=b}f.limit=e;return f};f.toDebug=function(a){for(var b=-1,c=this.buffer.byteLength,d,e="",f="",g="";b<c;){-1!==b&&(d=this.view[b],e=16>d?e+("0"+d.toString(16).toUpperCase()):e+d.toString(16).toUpperCase(),a&&(f+=32<d&&127>d?String.fromCharCode(d):"."));++b;if(a&&0<b&&0===b%16&&b!==c){for(;51>e.length;)e+=" ";g+=e+f+"\n";e=f=""}e=b===this.offset&&b===this.limit?e+(b===this.markedOffset?"!":"|"):b===this.offset?e+(b===this.markedOffset?"[":"<"):b===this.limit?e+(b===
this.markedOffset?"]":">"):e+(b===this.markedOffset?"'":a||0!==b&&b!==c?" ":"")}if(a&&" "!==e){for(;51>e.length;)e+=" ";g+=e+f+"\n"}return a?g:e};g.fromDebug=function(a,b,c){var d=a.length;b=new g((d+1)/3|0,b,c);for(var e=0,f=0,h,k=!1,l=!1,q=!1,m=!1,r=!1;e<d;){switch(h=a.charAt(e++)){case "!":if(!c){if(l||q||m){r=!0;break}l=q=m=!0}b.offset=b.markedOffset=b.limit=f;k=!1;break;case "|":if(!c){if(l||m){r=!0;break}l=m=!0}b.offset=b.limit=f;k=!1;break;case "[":if(!c){if(l||q){r=!0;break}l=q=!0}b.offset=
b.markedOffset=f;k=!1;break;case "<":if(!c){if(l){r=!0;break}l=!0}b.offset=f;k=!1;break;case "]":if(!c){if(m||q){r=!0;break}m=q=!0}b.limit=b.markedOffset=f;k=!1;break;case ">":if(!c){if(m){r=!0;break}m=!0}b.limit=f;k=!1;break;case "'":if(!c){if(q){r=!0;break}q=!0}b.markedOffset=f;k=!1;break;case " ":k=!1;break;default:if(!c&&k){r=!0;break}h=parseInt(h+a.charAt(e++),16);if(!c&&(isNaN(h)||0>h||255<h))throw TypeError("Illegal str: Not a debug encoded string");b.view[f++]=h;k=!0}if(r)throw TypeError("Illegal str: Invalid symbol at "+
e);}if(!c){if(!l||!m)throw TypeError("Illegal str: Missing offset or limit");if(f<b.buffer.byteLength)throw TypeError("Illegal str: Not a debug encoded string (is it hex?) "+f+" < "+d);}return b};f.toHex=function(a,b){a="undefined"===typeof a?this.offset:a;b="undefined"===typeof b?this.limit:b;if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");a>>>=0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");b>>>=0;if(0>a||a>b||
b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength);}for(var c=Array(b-a),d;a<b;)d=this.view[a++],16>d?c.push("0",d.toString(16)):c.push(d.toString(16));return c.join("")};g.fromHex=function(a,b,c){if(!c){if("string"!==typeof a)throw TypeError("Illegal str: Not a string");if(0!==a.length%2)throw TypeError("Illegal str: Length not a multiple of 2");}var d=a.length;b=new g(d/2|0,b);for(var e,f=0,h=0;f<d;f+=2){e=parseInt(a.substring(f,f+2),16);if(!c&&
(!isFinite(e)||0>e||255<e))throw TypeError("Illegal str: Contains non-hex characters");b.view[h++]=e}b.limit=h;return b};var l=function(){var a={j:1114111,i:function(a,c){var d=null;"number"===typeof a&&(d=a,a=function(){return null});for(;null!==d||null!==(d=a());)128>d?c(d&127):(2048>d?c(d>>6&31|192):(65536>d?c(d>>12&15|224):(c(d>>18&7|240),c(d>>12&63|128)),c(d>>6&63|128)),c(d&63|128)),d=null},f:function(a,c){function d(a){a=a.slice(0,a.indexOf(null));var b=Error(a.toString());b.name="TruncatedError";
b.bytes=a;throw b;}for(var e,f,g,k;null!==(e=a());)if(0===(e&128))c(e);else if(192===(e&224))null===(f=a())&&d([e,f]),c((e&31)<<6|f&63);else if(224===(e&240))null!==(f=a())&&null!==(g=a())||d([e,f,g]),c((e&15)<<12|(f&63)<<6|g&63);else if(240===(e&248))null!==(f=a())&&null!==(g=a())&&null!==(k=a())||d([e,f,g,k]),c((e&7)<<18|(f&63)<<12|(g&63)<<6|k&63);else throw RangeError("Illegal starting byte: "+e);},d:function(a,c){for(var d,e=null;null!==(d=null!==e?e:a());)55296<=d&&57343>=d&&null!==(e=a())&&
56320<=e&&57343>=e?(c(1024*(d-55296)+e-56320+65536),e=null):c(d);null!==e&&c(e)},e:function(a,c){var d=null;"number"===typeof a&&(d=a,a=function(){return null});for(;null!==d||null!==(d=a());)65535>=d?c(d):(d-=65536,c((d>>10)+55296),c(d%1024+56320)),d=null},c:function(b,c){a.d(b,function(b){a.i(b,c)})},b:function(b,c){a.f(b,function(b){a.e(b,c)})},k:function(a){return 128>a?1:2048>a?2:65536>a?3:4},l:function(a){for(var c,d=0;null!==(c=a());)d+=128>c?1:2048>c?2:65536>c?3:4;return d},a:function(b){var c=
0,d=0;a.d(b,function(a){++c;d+=128>a?1:2048>a?2:65536>a?3:4});return[c,d]}};return a}();f.toUTF8=function(a,b){"undefined"===typeof a&&(a=this.offset);"undefined"===typeof b&&(b=this.limit);if(!this.noAssert){if("number"!==typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");a>>>=0;if("number"!==typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");b>>>=0;if(0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength);
}var c;try{l.b(function(){return a<b?this.view[a++]:null}.bind(this),c=s())}catch(d){if(a!==b)throw RangeError("Illegal range: Truncated data, "+a+" != "+b);}return c()};g.fromUTF8=function(a,b,c){if(!c&&"string"!==typeof a)throw TypeError("Illegal str: Not a string");var d=new g(l.a(m(a),!0)[1],b,c),e=0;l.c(m(a),function(a){d.view[e++]=a});d.limit=e;return d};return g}
if("function"===typeof define&&define.amd)define(["Long"],u);else if("function"===typeof require&&"object"===typeof module&&module&&module.exports){var B=module,C,D;try{D=require("long")}catch(E){}C=u(D);B.exports=C}else(this.dcodeIO=this.dcodeIO||{}).ByteBuffer=u(this.dcodeIO.Long);
| luop90/LuopsSteamBot | node_modules/steam/node_modules/bytebuffer/dist/ByteBufferAB.min.js | JavaScript | mit | 44,406 |
import * as React from 'react';
import ApiPage from 'docs/src/modules/components/ApiPage';
import mapApiPageTranslations from 'docs/src/modules/utils/mapApiPageTranslations';
import jsonPageContent from './skeleton.json';
export default function Page(props) {
const { descriptions, pageContent } = props;
return <ApiPage descriptions={descriptions} pageContent={pageContent} />;
}
Page.getInitialProps = () => {
const req = require.context('docs/translations/api-docs/skeleton', false, /skeleton.*.json$/);
const descriptions = mapApiPageTranslations(req);
return {
descriptions,
pageContent: jsonPageContent,
};
};
| oliviertassinari/material-ui | docs/pages/material/api/skeleton.js | JavaScript | mit | 639 |
var combinations = require('combinations');
var data = require('../data');
var versions = false;
module.exports = function() {
if (versions) {
return versions;
}
versions = data.versions;
for (var version in versions) {
versions[version] = combinations(versions[version].sort());
versions[version].push([]);
}
return versions;
};
| michael829/jquery-builder | lib/combinations.js | JavaScript | mit | 356 |
var fs = require('fs');
var path = require('path');
var vm = require('vm');
var coffee = require('coffee-script');
var log = require('./logger').create('config');
var helper = require('./helper');
var constant = require('./constants');
var Pattern = function(pattern, served, included, watched) {
this.pattern = pattern;
this.served = helper.isDefined(served) ? served : true;
this.included = helper.isDefined(included) ? included : true;
this.watched = helper.isDefined(watched) ? watched : true;
};
var UrlPattern = function(url) {
Pattern.call(this, url, false, true, false);
};
var createPatternObject = function(pattern) {
if (helper.isString(pattern)) {
return helper.isUrlAbsolute(pattern) ? new UrlPattern(pattern) : new Pattern(pattern);
}
if (helper.isObject(pattern)) {
if (!helper.isDefined(pattern.pattern)) {
log.warn('Invalid pattern %s!\n\tObject is missing "pattern" property".', pattern);
}
return helper.isUrlAbsolute(pattern.pattern) ?
new UrlPattern(pattern.pattern) :
new Pattern(pattern.pattern, pattern.served, pattern.included, pattern.watched);
}
log.warn('Invalid pattern %s!\n\tExpected string or object with "pattern" property.', pattern);
return new Pattern(null, false, false, false);
};
var normalizeConfig = function(config) {
var basePathResolve = function(relativePath) {
if (helper.isUrlAbsolute(relativePath)) {
return relativePath;
}
if (!helper.isDefined(config.basePath) || !helper.isDefined(relativePath)) {
return '';
}
return path.resolve(config.basePath, relativePath);
};
var createPatternMapper = function(resolve) {
return function(objectPattern) {
objectPattern.pattern = resolve(objectPattern.pattern);
return objectPattern;
};
};
config.files = config.files.map(createPatternObject).map(createPatternMapper(basePathResolve));
config.exclude = config.exclude.map(basePathResolve);
config.junitReporter.outputFile = basePathResolve(config.junitReporter.outputFile);
config.coverageReporter.dir = basePathResolve(config.coverageReporter.dir);
// normalize paths on windows
config.basePath = helper.normalizeWinPath(config.basePath);
config.files = config.files.map(createPatternMapper(helper.normalizeWinPath));
config.exclude = config.exclude.map(helper.normalizeWinPath);
config.junitReporter.outputFile = helper.normalizeWinPath(config.junitReporter.outputFile);
config.coverageReporter.dir = helper.normalizeWinPath(config.coverageReporter.dir);
// normalize urlRoot
var urlRoot = config.urlRoot;
if (urlRoot.charAt(0) !== '/') {
urlRoot = '/' + urlRoot;
}
if (urlRoot.charAt(urlRoot.length - 1) !== '/') {
urlRoot = urlRoot + '/';
}
if (urlRoot !== config.urlRoot) {
log.warn('urlRoot normalized to "%s"', urlRoot);
config.urlRoot = urlRoot;
}
if (config.proxies && config.proxies.hasOwnProperty(config.urlRoot)) {
log.warn('"%s" is proxied, you should probably change urlRoot to avoid conflicts',
config.urlRoot);
}
if (config.singleRun && config.autoWatch) {
log.debug('autoWatch set to false, because of singleRun');
config.autoWatch = false;
}
if (helper.isString(config.reporters)) {
config.reporters = config.reporters.split(',');
}
// TODO(vojta): remove
if (helper.isDefined(config.reporter)) {
log.warn('"reporter" is deprecated, use "reporters" instead');
}
// normalize preprocessors
var preprocessors = config.preprocessors || {};
var normalizedPreprocessors = config.preprocessors = Object.create(null);
Object.keys(preprocessors).forEach(function(pattern) {
var normalizedPattern = helper.normalizeWinPath(basePathResolve(pattern));
normalizedPreprocessors[normalizedPattern] = helper.isString(preprocessors[pattern]) ?
[preprocessors[pattern]] : preprocessors[pattern];
});
return config;
};
var readConfigFile = function(filepath) {
var configEnv = {
// constants
LOG_DISABLE: constant.LOG_DISABLE,
LOG_ERROR: constant.LOG_ERROR,
LOG_WARN: constant.LOG_WARN,
LOG_INFO: constant.LOG_INFO,
LOG_DEBUG: constant.LOG_DEBUG,
// access to globals
console: console,
require: require,
process: process,
__filename: filepath,
__dirname: path.dirname(filepath)
};
// TODO(vojta): remove
var CONST_ERR = '%s is not supported anymore.\n\tPlease use `frameworks = ["%s"];` instead.';
['JASMINE', 'MOCHA', 'QUNIT'].forEach(function(framework) {
[framework, framework + '_ADAPTER'].forEach(function(name) {
Object.defineProperty(configEnv, name, {get: function() {
log.warn(CONST_ERR, name, framework.toLowerCase());
}});
});
});
['REQUIRE', 'REQUIRE_ADAPTER'].forEach(function(name) {
Object.defineProperty(configEnv, name, {get: function() {
log.warn(CONST_ERR, name, 'requirejs');
}});
});
['ANGULAR_SCENARIO', 'ANGULAR_SCENARIO_ADAPTER'].forEach(function(name) {
Object.defineProperty(configEnv, name, {get: function() {
log.warn(CONST_ERR, name, 'requirejs');
}});
});
try {
var configSrc = fs.readFileSync(filepath);
// if the configuration file is coffeescript compile it
if (path.extname(filepath) === '.coffee') {
configSrc = coffee.compile(configSrc.toString(), {bare: true});
}
vm.runInNewContext(configSrc, configEnv);
} catch(e) {
if (e.name === 'SyntaxError') {
log.error('Syntax error in config file!\n' + e.message);
} else if (e.code === 'ENOENT' || e.code === 'EISDIR') {
log.error('Config file does not exist!');
} else {
log.error('Invalid config file!\n', e);
}
process.exit(1);
}
return configEnv;
};
var parseConfig = function(configFilePath, cliOptions) {
var configFromFile = configFilePath ? readConfigFile(configFilePath) : {};
// default config
var config = {
frameworks: [],
port: constant.DEFAULT_PORT,
runnerPort: constant.DEFAULT_RUNNER_PORT,
hostname: constant.DEFAULT_HOSTNAME,
basePath: '',
files: [],
exclude: [],
logLevel: constant.LOG_INFO,
colors: true,
autoWatch: false,
reporters: ['progress'],
singleRun: false,
browsers: [],
captureTimeout: 60000,
proxies: {},
preprocessors: {'**/*.coffee': 'coffee'},
urlRoot: '/',
reportSlowerThan: 0,
junitReporter: {
outputFile: 'test-results.xml',
suite: ''
},
coverageReporter: {
type: 'html',
dir: 'coverage/'
},
loggers: [ constant.CONSOLE_APPENDER ],
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-phantomjs-launcher'
]
};
// merge the config from config file and cliOptions (precendense)
Object.getOwnPropertyNames(config).forEach(function(key) {
if (cliOptions.hasOwnProperty(key)) {
config[key] = cliOptions[key];
} else if (configFromFile.hasOwnProperty(key)) {
config[key] = configFromFile[key];
}
});
// resolve basePath
config.basePath = path.resolve(path.dirname(configFilePath), config.basePath);
// always ignore the config file itself
config.exclude.push(configFilePath);
return normalizeConfig(config);
};
// PUBLIC API
exports.parseConfig = parseConfig;
exports.Pattern = Pattern;
exports.createPatternObject = createPatternObject;
| jgrowl/karma | lib/config.js | JavaScript | mit | 7,419 |
/*jshint camelcase:true, plusplus:true, forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, curly:true, browser:true, devel:true, maxerr:100, white:false, onevar:false */
/*global jQuery:true $:true */
(function ($, undefined) {
"use strict";
$(document).ready(function() {
module("key-combo", {
setup: function() {
tests.testSetup();
$('#textInput').val("");
},
teardown: function() {
tests.testTearDown();
}
});
//####### Test Functions #######
test("simple combo", function() {
var $testElement = $('#textInput');
tests.expectedEvents = [
/* a */ {type: "keydown", keyCode: 65}, {type: "keypress", which: "a".charCodeAt(0)},
/* S */ {type: "keydown", keyCode: 83}, {type: "keypress", which: "S".charCodeAt(0)},
/* d */ {type: "keydown", keyCode: 68}, {type: "keypress", which: "d".charCodeAt(0)},
/* F */ {type: "keydown", keyCode: 70}, {type: "keypress", which: "F".charCodeAt(0)},
/* F */ {type: "keyup", keyCode: 70},
/* d */ {type: "keyup", keyCode: 68},
/* S */ {type: "keyup", keyCode: 83},
/* a */ {type: "keyup", keyCode: 65}
];
$testElement.simulate("key-combo", {combo: "a+S+d+F"});
strictEqual($testElement.val(), "aSdF", "Verify result of sequence");
});
test("events only", function() {
var $testElement = $('#textInput');
tests.expectedEvents = [
/* a */ {type: "keydown", keyCode: 65}, {type: "keypress", which: "a".charCodeAt(0)},
/* S */ {type: "keydown", keyCode: 83}, {type: "keypress", which: "S".charCodeAt(0)},
/* d */ {type: "keydown", keyCode: 68}, {type: "keypress", which: "d".charCodeAt(0)},
/* F */ {type: "keydown", keyCode: 70}, {type: "keypress", which: "F".charCodeAt(0)},
/* F */ {type: "keyup", keyCode: 70},
/* d */ {type: "keyup", keyCode: 68},
/* S */ {type: "keyup", keyCode: 83},
/* a */ {type: "keyup", keyCode: 65}
];
$testElement.simulate("key-combo", {combo: "a+S+d+F", eventsOnly: true});
strictEqual($testElement.val(), "", "Verify result of sequence");
});
test("modifiers", function() {
var $testElement = $('#textInput');
tests.expectedEvents = [
/* ctrl */ {type: "keydown", keyCode: 17, ctrlKey: true, shiftKey: false, altKey: false, metaKey: false},
/* shift */ {type: "keydown", keyCode: 16, ctrlKey: true, shiftKey: true, altKey: false, metaKey: false},
/* alt */ {type: "keydown", keyCode: 18, ctrlKey: true, shiftKey: true, altKey: true, metaKey: false},
/* meta */ {type: "keydown", keyCode: 91, ctrlKey: true, shiftKey: true, altKey: true, metaKey: true},
/* a */ {type: "keydown", keyCode: 65, ctrlKey: true, shiftKey: true, altKey: true, metaKey: true}, {type: "keypress", which: 65, ctrlKey: true, shiftKey: true, altKey: true, metaKey: true},
/* a */ {type: "keyup", keyCode: 65, ctrlKey: true, shiftKey: true, altKey: true, metaKey: true},
/* meta */ {type: "keyup", keyCode: 91, ctrlKey: true, shiftKey: true, altKey: true, metaKey: false},
/* alt */ {type: "keyup", keyCode: 18, ctrlKey: true, shiftKey: true, altKey: false, metaKey: false},
/* shift */ {type: "keyup", keyCode: 16, ctrlKey: true, shiftKey: false, altKey: false, metaKey: false},
/* ctrl */ {type: "keyup", keyCode: 17, ctrlKey: false, shiftKey: false, altKey: false, metaKey: false}
];
$testElement.simulate("key-combo", {combo: "ctrl+shift+alt+meta+a"});
strictEqual($testElement.val(), "", "Verify result of sequence");
});
test("shift", function() {
var $testElement = $('#textInput');
tests.expectedEvents = [
/* shift */ {type: "keydown", keyCode: 16, ctrlKey: false, shiftKey: true, altKey: false, metaKey: false},
/* a */ {type: "keydown", keyCode: 65, ctrlKey: false, shiftKey: true, altKey: false, metaKey: false}, {type: "keypress", which: "A".charCodeAt(0), ctrlKey: false, shiftKey: true, altKey: false, metaKey: false},
/* a */ {type: "keyup", keyCode: 65, ctrlKey: false, shiftKey: true, altKey: false, metaKey: false},
/* shift */ {type: "keyup", keyCode: 16, ctrlKey: false, shiftKey: false, altKey: false, metaKey: false}
];
$testElement.simulate("key-combo", {combo: "shift+a"});
strictEqual($testElement.val(), "A", "Verify result of sequence");
});
test("modifier without shift", function() {
var $testElement = $('#textInput');
tests.expectedEvents = [
/* ctrl */ {type: "keydown", keyCode: 17, ctrlKey: true, shiftKey: false, altKey: false, metaKey: false},
/* a */ {type: "keydown", keyCode: 65, ctrlKey: true, shiftKey: false, altKey: false, metaKey: false}, {type: "keypress", which: "a".charCodeAt(0), ctrlKey: true, shiftKey: false, altKey: false, metaKey: false},
/* a */ {type: "keyup", keyCode: 65, ctrlKey: true, shiftKey: false, altKey: false, metaKey: false},
/* ctrl */ {type: "keyup", keyCode: 17, ctrlKey: false, shiftKey: false, altKey: false, metaKey: false}
];
$testElement.simulate("key-combo", {combo: "ctrl+a"});
strictEqual($testElement.val(), "", "Verify result of sequence");
});
test("special character combo", function() {
var $testElement = $('#textInput');
tests.expectedEvents = [
/* ctrl */ {type: "keydown", keyCode: 17, ctrlKey: true, shiftKey: false, altKey: false, metaKey: false},
/* + */ {type: "keydown", keyCode: 187, ctrlKey: true, shiftKey: false, altKey: false, metaKey: false}, {type: "keypress", which: "+".charCodeAt(0), ctrlKey: true, shiftKey: false, altKey: false, metaKey: false},
/* + */ {type: "keyup", keyCode: 187, ctrlKey: true, shiftKey: false, altKey: false, metaKey: false},
/* ctrl */ {type: "keyup", keyCode: 17, ctrlKey: false, shiftKey: false, altKey: false, metaKey: false}
];
$testElement.simulate("key-combo", {combo: "ctrl++"});
strictEqual($testElement.val(), "", "Verify result of sequence");
});
test("special key combo", function() {
var $testElement = $('#textInput');
tests.expectedEvents = [
/* ctrl */ {type: "keydown", keyCode: 17, ctrlKey: true, shiftKey: false, altKey: false, metaKey: false},
/* left-arrow */ {type: "keydown", keyCode: 37, ctrlKey: true, shiftKey: false, altKey: false, metaKey: false},
/* left-arrow */ {type: "keyup", keyCode: 37, ctrlKey: true, shiftKey: false, altKey: false, metaKey: false},
/* ctrl */ {type: "keyup", keyCode: 17, ctrlKey: false, shiftKey: false, altKey: false, metaKey: false}
];
$testElement.simulate("key-combo", {combo: "ctrl+left-arrow"});
strictEqual($testElement.val(), "", "Verify result of sequence");
});
test("simple combo with eventProps", function() {
var $testElement = $('#textInput'),
customProp = "test!";
tests.expectedEvents = [
/* a */ {type: "keydown", keyCode: 65, myCustomProp: customProp},
{type: "keypress", which: "a".charCodeAt(0), myCustomProp: customProp},
/* S */ {type: "keydown", keyCode: 83, myCustomProp: customProp},
{type: "keypress", which: "S".charCodeAt(0), myCustomProp: customProp},
/* d */ {type: "keydown", keyCode: 68, myCustomProp: customProp},
{type: "keypress", which: "d".charCodeAt(0), myCustomProp: customProp},
/* F */ {type: "keydown", keyCode: 70, myCustomProp: customProp},
{type: "keypress", which: "F".charCodeAt(0), myCustomProp: customProp},
/* F */ {type: "keyup", keyCode: 70, myCustomProp: customProp},
/* d */ {type: "keyup", keyCode: 68, myCustomProp: customProp},
/* S */ {type: "keyup", keyCode: 83, myCustomProp: customProp},
/* a */ {type: "keyup", keyCode: 65, myCustomProp: customProp}
];
$testElement.simulate("key-combo", {combo: "a+S+d+F", eventProps: {jQueryTrigger: true, myCustomProp: customProp}});
strictEqual($testElement.val(), "aSdF", "Verify result of sequence");
});
test("simple combo with eventProps without jQueryTrigger", function() {
var $testElement = $('#textInput'),
customProp = "test!";
tests.expectedEvents = [
/* a */ {type: "keydown", keyCode: 65, myCustomProp: undefined},
{type: "keypress", which: "a".charCodeAt(0), myCustomProp: undefined},
/* S */ {type: "keydown", keyCode: 83, myCustomProp: undefined},
{type: "keypress", which: "S".charCodeAt(0), myCustomProp: undefined},
/* d */ {type: "keydown", keyCode: 68, myCustomProp: undefined},
{type: "keypress", which: "d".charCodeAt(0), myCustomProp: undefined},
/* F */ {type: "keydown", keyCode: 70, myCustomProp: undefined},
{type: "keypress", which: "F".charCodeAt(0), myCustomProp: undefined},
/* F */ {type: "keyup", keyCode: 70, myCustomProp: undefined},
/* d */ {type: "keyup", keyCode: 68, myCustomProp: undefined},
/* S */ {type: "keyup", keyCode: 83, myCustomProp: undefined},
/* a */ {type: "keyup", keyCode: 65, myCustomProp: undefined}
];
$testElement.simulate("key-combo", {combo: "a+S+d+F", eventProps: {jQueryTrigger: false, myCustomProp: customProp}});
strictEqual($testElement.val(), "aSdF", "Verify result of sequence");
});
});
}(jQuery));
| Endika/jquery-simulate-ext | tests/key-combo.js | JavaScript | mit | 9,178 |
PANDA.text.DatasetSearch = function() {
return {
search_dataset: gettext("Search <strong>%(dataset)s</strong>"),
search_placeholder: gettext("Enter a search query"),
search: gettext("Search"),
more_options: gettext("More search options"),
back_to_dataset: gettext("Back to dataset details"),
wildcards: gettext("Wildcards"),
wildcards_help: gettext('Use an asterisk to match part of a word: <code>coff*</code> will match "coffee", "Coffer" or "coffins".'),
exact_phrases: gettext("Exact phrases"),
exact_phrases_help: gettext('Put phrases in quotes: <code>"Chicago Bears"</code> will not match "Chicago Panda Bears".'),
and_or: "AND/OR", // Not translated as these are Solr keywords
and_or_help: gettext('Use AND and OR to find combinations of terms: <code>homicide AND first</code> will match "first degree homicide" or "homicide, first degree", but not just "homicide".'),
grouping: gettext("Grouping"),
grouping_help: gettext('Group words with parantheses: <code>homicide AND (first OR 1st)</code> will match "1st degree homicide", "first degree homicide", or "homicide, first degree".'),
alternate_names: gettext("Alternate names"),
alternate_names_help: gettext('PANDA will attempt to match informal and alternate English first names: <code>bill</code> will match "Bill", "Billy", "William", etc. It will not match mispellings.'),
error_title: gettext("Error importing data"),
error_body: gettext("<p>The import failed with the following exception:</p><code>%(traceback)s</code>"),
close: gettext("Close")
}
}
| PalmBeachPost/panda | client/static/js/text/dataset_search.js | JavaScript | mit | 1,667 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Utils_1 = require("../Utils/Utils");
var Constants_1 = require("../Utils/Constants");
var Grabber = (function () {
function Grabber() {
}
Grabber.grab = function (particle, container) {
var options = container.options;
var interactivity = options.interactivity;
if (interactivity.events.onHover.enable && container.interactivity.status === Constants_1.Constants.mouseMoveEvent) {
var mousePos = container.interactivity.mouse.position || { x: 0, y: 0 };
var distMouse = Utils_1.Utils.getDistanceBetweenCoordinates(particle.position, mousePos);
if (distMouse <= container.retina.grabModeDistance) {
var lineOpacity = interactivity.modes.grab.lineLinked.opacity;
var grabDistance = container.retina.grabModeDistance;
var opacityLine = lineOpacity - (distMouse * lineOpacity) / grabDistance;
if (opacityLine > 0) {
container.canvas.drawGrabLine(particle, opacityLine, mousePos);
}
}
}
};
return Grabber;
}());
exports.Grabber = Grabber;
| cdnjs/cdnjs | ajax/libs/tsparticles/1.13.0-alpha.4/Classes/Particle/Grabber.js | JavaScript | mit | 1,214 |
/* [ ---- Gebo Admin Panel - calendar ---- ] */
$(document).ready(function() {
gebo_calendar.regular();
gebo_calendar.google();
//* resize elements on window resize
var lastWindowHeight = $(window).height();
var lastWindowWidth = $(window).width();
$(window).on("debouncedresize",function() {
if($(window).height()!=lastWindowHeight || $(window).width()!=lastWindowWidth){
lastWindowHeight = $(window).height();
lastWindowWidth = $(window).width();
//* rebuild calendar
$('#calendar').fullCalendar('render');
$('#calendar_google').fullCalendar('render');
}
});
});
//* calendar
gebo_calendar = {
regular: function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev next',
center: 'title,today',
right: 'month,agendaWeek,agendaDay'
},
buttonText: {
prev: '<i class="icon-chevron-left cal_prev" />',
next: '<i class="icon-chevron-right cal_next" />'
},
aspectRatio: 2,
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
var title = prompt('Event Title:');
if (title) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
editable: true,
theme: false,
events: [
{
title: 'All Day Event',
start: new Date(y, m, 1),
color: '#aedb97',
textColor: '#3d641b'
},
{
title: 'Long Event',
start: new Date(y, m, d-5),
end: new Date(y, m, d-2)
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d+8, 16, 0),
allDay: false
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d+15, 16, 0),
allDay: false
},
{
title: 'Meeting',
start: new Date(y, m, d+12, 15, 0),
allDay: false,
color: '#aedb97',
textColor: '#3d641b'
},
{
title: 'Lunch',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
allDay: false
},
{
title: 'Birthday Party',
start: new Date(y, m, d+1, 19, 0),
end: new Date(y, m, d+1, 22, 30),
allDay: false,
color: '#cea97e',
textColor: '#5e4223'
},
{
title: 'Click for Google',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
url: 'http://google.com/'
}
],
eventColor: '#bcdeee'
})
},
google: function() {
var calendar = $('#calendar_google').fullCalendar({
header: {
left: 'prev next',
center: 'title,today',
right: 'month,agendaWeek,agendaDay'
},
buttonText: {
prev: '<i class="icon-chevron-left cal_prev" />',
next: '<i class="icon-chevron-right cal_next" />'
},
aspectRatio: 3,
theme: false,
events: {
url:'http://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/basic',
title: 'US Holidays',
color: '#bcdeee'
},
eventClick: function(event) {
// opens events in a popup window
window.open(event.url, 'gcalevent', 'width=700,height=600');
return false;
}
})
}
}; | mtaki/UchumiERP | themes/gebo/js/gebo_calendar.js | JavaScript | epl-1.0 | 3,660 |
'use strict';
var React = require('react');
var PureRenderMixin = require('react-addons-pure-render-mixin');
var SvgIcon = require('../../svg-icon');
var NotificationVoiceChat = React.createClass({
displayName: 'NotificationVoiceChat',
mixins: [PureRenderMixin],
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12l-4-3.2V14H6V6h8v3.2L18 6v8z' })
);
}
});
module.exports = NotificationVoiceChat; | fernando-jascovich/vagrant-manager | node_modules/material-ui/lib/svg-icons/notification/voice-chat.js | JavaScript | gpl-2.0 | 574 |
/**
* appendix page
*/
( function( window ) {
'use strict';
var ID = window.ID;
var transitionProp = getStyleProperty('transition');
var transitionEndEvent = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'otransitionend',
transition: 'transitionend'
}[ transitionProp ];
// -------------------------- appendix -------------------------- //
ID.appendix = function() {
// ----- animate item size ----- //
( function() {
var $container = $('#animate-item-size .isotope').isotope({
masonry: {
columnWidth: 60
}
});
$container.on( 'click', '.item', function() {
$(this).toggleClass('is-expanded');
$container.isotope('layout');
});
})();
// ----- animate item size responsive ----- //
( function() {
var $container = $('#animate-item-size-responsive .isotope').isotope({
itemSelector: '.item',
masonry: {
columnWidth: '.grid-sizer'
}
});
$container.on( 'click', '.item-content', function() {
var target = this;
var previousContentSize = getSize( target );
// disable transition
target.style[ transitionProp ] = 'none';
// set current size
target.style.width = previousContentSize.width + 'px';
target.style.height = previousContentSize.height + 'px';
var itemElem = target.parentNode;
classie.toggleClass( itemElem, 'is-expanded' );
// force redraw
var redraw = target.offsetWidth;
// renable default transition
target.style[ transitionProp ] = '';
// reset 100%/100% sizing after transition end
if ( transitionProp ) {
var onTransitionEnd = function() {
target.style.width = '';
target.style.height = '';
target.removeEventListener( transitionEndEvent, onTransitionEnd, false );
};
target.addEventListener( transitionEndEvent, onTransitionEnd, false );
}
// set new size
var size = getSize( itemElem );
target.style.width = size.width + 'px';
target.style.height = size.height + 'px';
redraw = null; // for JSHint
$container.isotope('layout');
});
})();
};
})( window );
| delvethemes/Free.Delve | wp-content/themes/delve/plugins/isotope-docs/js/pages/appendix.js | JavaScript | gpl-2.0 | 2,233 |
/**
* @license Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @fileOverview Justify commands.
*/
( function() {
function getAlignment( element, useComputedState ) {
useComputedState = useComputedState === undefined || useComputedState;
var align;
if ( useComputedState )
align = element.getComputedStyle( 'text-align' );
else {
while ( !element.hasAttribute || !( element.hasAttribute( 'align' ) || element.getStyle( 'text-align' ) ) ) {
var parent = element.getParent();
if ( !parent )
break;
element = parent;
}
align = element.getStyle( 'text-align' ) || element.getAttribute( 'align' ) || '';
}
// Sometimes computed values doesn't tell.
align && ( align = align.replace( /(?:-(?:moz|webkit)-)?(?:start|auto)/i, '' ) );
!align && useComputedState && ( align = element.getComputedStyle( 'direction' ) == 'rtl' ? 'right' : 'left' );
return align;
}
function justifyCommand( editor, name, value ) {
this.editor = editor;
this.name = name;
this.value = value;
this.context = 'p';
var classes = editor.config.justifyClasses,
blockTag = editor.config.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div';
if ( classes ) {
switch ( value ) {
case 'left':
this.cssClassName = classes[ 0 ];
break;
case 'center':
this.cssClassName = classes[ 1 ];
break;
case 'right':
this.cssClassName = classes[ 2 ];
break;
case 'justify':
this.cssClassName = classes[ 3 ];
break;
}
this.cssClassRegex = new RegExp( '(?:^|\\s+)(?:' + classes.join( '|' ) + ')(?=$|\\s)' );
this.requiredContent = blockTag + '(' + this.cssClassName + ')';
}
else {
this.requiredContent = blockTag + '{text-align}';
}
this.allowedContent = {
'caption div h1 h2 h3 h4 h5 h6 p pre td th li': {
// Do not add elements, but only text-align style if element is validated by other rule.
propertiesOnly: true,
styles: this.cssClassName ? null : 'text-align',
classes: this.cssClassName || null
}
};
// In enter mode BR we need to allow here for div, because when non other
// feature allows div justify is the only plugin that uses it.
if ( editor.config.enterMode == CKEDITOR.ENTER_BR )
this.allowedContent.div = true;
}
function onDirChanged( e ) {
var editor = e.editor;
var range = editor.createRange();
range.setStartBefore( e.data.node );
range.setEndAfter( e.data.node );
var walker = new CKEDITOR.dom.walker( range ),
node;
while ( ( node = walker.next() ) ) {
if ( node.type == CKEDITOR.NODE_ELEMENT ) {
// A child with the defined dir is to be ignored.
if ( !node.equals( e.data.node ) && node.getDirection() ) {
range.setStartAfter( node );
walker = new CKEDITOR.dom.walker( range );
continue;
}
// Switch the alignment.
var classes = editor.config.justifyClasses;
if ( classes ) {
// The left align class.
if ( node.hasClass( classes[ 0 ] ) ) {
node.removeClass( classes[ 0 ] );
node.addClass( classes[ 2 ] );
}
// The right align class.
else if ( node.hasClass( classes[ 2 ] ) ) {
node.removeClass( classes[ 2 ] );
node.addClass( classes[ 0 ] );
}
}
// Always switch CSS margins.
var style = 'text-align';
var align = node.getStyle( style );
if ( align == 'left' )
node.setStyle( style, 'right' );
else if ( align == 'right' )
node.setStyle( style, 'left' );
}
}
}
justifyCommand.prototype = {
exec: function( editor ) {
var selection = editor.getSelection(),
enterMode = editor.config.enterMode;
if ( !selection )
return;
var bookmarks = selection.createBookmarks(),
ranges = selection.getRanges();
var cssClassName = this.cssClassName,
iterator, block;
var useComputedState = editor.config.useComputedState;
useComputedState = useComputedState === undefined || useComputedState;
for ( var i = ranges.length - 1; i >= 0; i-- ) {
iterator = ranges[ i ].createIterator();
iterator.enlargeBr = enterMode != CKEDITOR.ENTER_BR;
while ( ( block = iterator.getNextParagraph( enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ) ) ) {
if ( block.isReadOnly() )
continue;
// Check if style or class might be applied to currently processed element (#455).
var tag = block.getName(),
isAllowedTextAlign, isAllowedCssClass;
isAllowedTextAlign = editor.activeFilter.check( tag + '{text-align}' );
isAllowedCssClass = editor.activeFilter.check( tag + '(' + cssClassName + ')' );
if ( !isAllowedCssClass && !isAllowedTextAlign ) {
continue;
}
block.removeAttribute( 'align' );
block.removeStyle( 'text-align' );
// Remove any of the alignment classes from the className.
var className = cssClassName && ( block.$.className = CKEDITOR.tools.ltrim( block.$.className.replace( this.cssClassRegex, '' ) ) );
var apply = ( this.state == CKEDITOR.TRISTATE_OFF ) && ( !useComputedState || ( getAlignment( block, true ) != this.value ) );
if ( cssClassName && isAllowedCssClass ) {
// Append the desired class name.
if ( apply )
block.addClass( cssClassName );
else if ( !className )
block.removeAttribute( 'class' );
} else if ( apply && isAllowedTextAlign ) {
block.setStyle( 'text-align', this.value );
}
}
}
editor.focus();
editor.forceNextSelectionCheck();
selection.selectBookmarks( bookmarks );
},
refresh: function( editor, path ) {
var firstBlock = path.block || path.blockLimit,
name = firstBlock.getName(),
isEditable = firstBlock.equals( editor.editable() ),
isStylable = this.cssClassName ? editor.activeFilter.check( name + '(' + this.cssClassName + ')' ) :
editor.activeFilter.check( name + '{text-align}' );
// #455
// 1. Check if we are directly in editbale. Justification should be always allowed, and not highlighted.
// Checking situation `body > ul` where ul is selected and path.blockLimit returns editable.
// 2. Check if current element can have applied specific class.
// 3. Check if current element can have applied text-align style.
if ( isEditable && !CKEDITOR.dtd.$list[ path.lastElement.getName() ] ) {
this.setState( CKEDITOR.TRISTATE_OFF );
} else if ( !isEditable && isStylable ) {
// 2 & 3 in one condition.
this.setState( getAlignment( firstBlock, this.editor.config.useComputedState ) == this.value ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
} else {
this.setState( CKEDITOR.TRISTATE_DISABLED );
}
}
};
CKEDITOR.plugins.add( 'justify', {
icons: 'justifyblock,justifycenter,justifyleft,justifyright', // %REMOVE_LINE_CORE%
hidpi: true, // %REMOVE_LINE_CORE%
init: function( editor ) {
if ( editor.blockless )
return;
var left = new justifyCommand( editor, 'justifyleft', 'left' ),
center = new justifyCommand( editor, 'justifycenter', 'center' ),
right = new justifyCommand( editor, 'justifyright', 'right' ),
justify = new justifyCommand( editor, 'justifyblock', 'justify' );
editor.addCommand( 'justifyleft', left );
editor.addCommand( 'justifycenter', center );
editor.addCommand( 'justifyright', right );
editor.addCommand( 'justifyblock', justify );
if ( editor.ui.addButton ) {
editor.ui.addButton( 'JustifyLeft', {
label: editor.lang.common.alignLeft,
command: 'justifyleft',
toolbar: 'align,10'
} );
editor.ui.addButton( 'JustifyCenter', {
label: editor.lang.common.center,
command: 'justifycenter',
toolbar: 'align,20'
} );
editor.ui.addButton( 'JustifyRight', {
label: editor.lang.common.alignRight,
command: 'justifyright',
toolbar: 'align,30'
} );
editor.ui.addButton( 'JustifyBlock', {
label: editor.lang.common.justify,
command: 'justifyblock',
toolbar: 'align,40'
} );
}
editor.on( 'dirChanged', onDirChanged );
}
} );
} )();
/**
* List of classes to use for aligning the contents. If it's `null`, no classes will be used
* and instead the corresponding CSS values will be used.
*
* The array should contain 4 members, in the following order: left, center, right, justify.
*
* // Use the classes 'AlignLeft', 'AlignCenter', 'AlignRight', 'AlignJustify'
* config.justifyClasses = [ 'AlignLeft', 'AlignCenter', 'AlignRight', 'AlignJustify' ];
*
* @cfg {Array} [justifyClasses=null]
* @member CKEDITOR.config
*/
| WBCE/WebsiteBaker_CommunityEdition | wbce/modules/ckeditor/ckeditor/plugins/justify/plugin.js | JavaScript | gpl-2.0 | 8,624 |
/**
* @author cormac1
*/
$(document).ready(function(){
var flag=0;
var color;
$('.edit-button a').addClass('button').wrapInner('<span></span>');
$('.odd').children().css("background-color","#ffffff");
$('.actor-link').parent().parent().click(function(){
//document.location = this.children(0).attr('href');
if(flag==0){
$(this).children().css("background-color","#C9E8FF").children().css("background-color","#C9E8FF");
flag++;
document.location = ($(this).children('td').children('.actor-link').attr("href"));
}
});
$('.actor-link').parent().parent().hover(function(){
if (flag == 0) {
color = $(this).children().css("background-color");
$(this).children().css("background-color","#daEbFF").children().css("background-color","#daEbFF");
$(this).siblings('.even').css("background-color","#eeeeee").children().css("background-color","#eeeeee").children().css("background-color","#eeeeee");
$(this).siblings('.odd').css("background-color","#ffffff").children().css("background-color","#ffffff").children().css("background-color","#ffffff");
}
});
}); | equalitie/rightscase | sites/all/themes/ninesixty/js/button.js | JavaScript | gpl-2.0 | 1,107 |
/*
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 3.0.0pr1
*/
YUI.add('dd-ddm-base', function(Y) {
/**
* Provides the base Drag Drop Manger required for making a Node draggable.
* @module dd
* @submodule dd-ddm-base
*/
/**
* Provides the base Drag Drop Manger required for making a Node draggable.
* @class DDM
* @extends Base
* @constructor
*/
var DDMBase = function() {
//debugger;
DDMBase.superclass.constructor.apply(this, arguments);
};
DDMBase.NAME = 'DragDropMgr';
DDMBase.ATTRS = {
/**
* @attribute clickPixelThresh
* @description The number of pixels to move to start a drag operation, default is 3.
* @type Number
*/
clickPixelThresh: {
value: 3
},
/**
* @attribute clickTimeThresh
* @description The number of milliseconds a mousedown has to pass to start a drag operation, default is 1000.
* @type Number
*/
clickTimeThresh: {
value: 1000
},
/**
* @attribute dragMode
* @description This attribute only works if the dd-drop module is active. It will set the dragMode (point, intersect, strict) of all future Drag instances.
* @type String
*/
dragMode: {
value: 'point',
set: function(mode) {
this._setDragMode(mode);
}
}
};
Y.extend(DDMBase, Y.Base, {
/**
* @private
* @method _setDragMode
* @description Handler for dragMode attribute setter.
* @param String/Number The Number value or the String for the DragMode to default all future drag instances to.
* @return Number The Mode to be set
*/
_setDragMode: function(mode) {
if (mode === null) {
mode = Y.DD.DDM.get('dragMode');
}
switch (mode) {
case 1:
case 'intersect':
return 1;
case 2:
case 'strict':
return 2;
case 0:
case 'point':
return 0;
}
return 0;
},
/**
* @property CSS_PREFIX
* @description The PREFIX to attach to all DD CSS class names
* @type {String}
*/
CSS_PREFIX: 'yui-dd',
_activateTargets: function() {},
/**
* @private
* @property _drags
* @description Holder for all registered drag elements.
* @type {Array}
*/
_drags: [],
/**
* @property activeDrag
* @description A reference to the currently active draggable object.
* @type {Drag}
*/
activeDrag: false,
/**
* @private
* @method _regDrag
* @description Adds a reference to the drag object to the DDM._drags array, called in the constructor of Drag.
* @param {Drag} d The Drag object
*/
_regDrag: function(d) {
this._drags[this._drags.length] = d;
},
/**
* @private
* @method _unregDrag
* @description Remove this drag object from the DDM._drags array.
* @param {Drag} d The drag object.
*/
_unregDrag: function(d) {
var tmp = [];
Y.each(this._drags, function(n, i) {
if (n !== d) {
tmp[tmp.length] = n;
}
});
this._drags = tmp;
},
/**
* @private
* @method _init
* @description DDM's init method
*/
initializer: function() {
Y.Node.get('document').on('mousemove', this._move, this, true);
Y.Node.get('document').on('mouseup', this._end, this, true);
//Y.Event.Target.apply(this);
},
/**
* @private
* @method _start
* @description Internal method used by Drag to signal the start of a drag operation
* @param {Number} x The x position of the drag element
* @param {Number} y The y position of the drag element
* @param {Number} w The width of the drag element
* @param {Number} h The height of the drag element
*/
_start: function(x, y, w, h) {
this._startDrag.apply(this, arguments);
},
/**
* @private
* @method _startDrag
* @description Factory method to be overwritten by other DDM's
* @param {Number} x The x position of the drag element
* @param {Number} y The y position of the drag element
* @param {Number} w The width of the drag element
* @param {Number} h The height of the drag element
*/
_startDrag: function() {},
/**
* @private
* @method _endDrag
* @description Factory method to be overwritten by other DDM's
*/
_endDrag: function() {},
_dropMove: function() {},
/**
* @private
* @method _end
* @description Internal method used by Drag to signal the end of a drag operation
*/
_end: function() {
//@TODO - Here we can get a (click - drag - click - release) interaction instead of a (mousedown - drag - mouseup - release) interaction
//Add as a config option??
if (this.activeDrag) {
this._endDrag();
this.activeDrag.end.call(this.activeDrag);
this.activeDrag = null;
}
},
/**
* @method stopDrag
* @description Method will forcefully stop a drag operation. For example calling this from inside an ESC keypress handler will stop this drag.
* @return {Self}
* @chainable
*/
stopDrag: function() {
if (this.activeDrag) {
this._end();
}
return this;
},
/**
* @private
* @method _move
* @description Internal listener for the mousemove DOM event to pass to the Drag's move method.
* @param {Event} ev The Dom mousemove Event
*/
_move: function(ev) {
if (this.activeDrag) {
this.activeDrag._move.apply(this.activeDrag, arguments);
this._dropMove();
}
},
/**
* @method setXY
* @description A simple method to set the top and left position from offsets instead of page coordinates
* @param {Object} node The node to set the position of
* @param {Array} xy The Array of left/top position to be set.
*/
setXY: function(node, xy) {
var t = parseInt(node.getStyle('top'), 10),
l = parseInt(node.getStyle('left'), 10),
pos = node.getStyle('position');
if (pos === 'static') {
node.setStyle('position', 'relative');
}
// in case of 'auto'
if (isNaN(t)) { t = 0; }
if (isNaN(l)) { l = 0; }
node.setStyle('top', (xy[1] + t) + 'px');
node.setStyle('left', (xy[0] + l) + 'px');
},
/**
* //TODO Private, rename??...
* @private
* @method cssSizestoObject
* @description Helper method to use to set the gutter from the attribute setter.
* @param {String} gutter CSS style string for gutter: '5 0' (sets top and bottom to 5px, left and right to 0px), '1 2 3 4' (top 1px, right 2px, bottom 3px, left 4px)
* @return {Object} The gutter Object Literal.
*/
cssSizestoObject: function(gutter) {
var p = gutter.split(' '),
g = {
top: 0,
bottom: 0,
right: 0,
left: 0
};
if (p.length) {
g.top = parseInt(p[0], 10);
if (p[1]) {
g.right = parseInt(p[1], 10);
} else {
g.right = g.top;
}
if (p[2]) {
g.bottom = parseInt(p[2], 10);
} else {
g.bottom = g.top;
}
if (p[3]) {
g.left = parseInt(p[3], 10);
} else if (p[1]) {
g.left = g.right;
} else {
g.left = g.top;
}
}
return g;
},
/**
* @method getDrag
* @description Get a valid Drag instance back from a Node or a selector string, false otherwise
* @param {String/Object} node The Node instance or Selector string to check for a valid Drag Object
* @return {Object}
*/
getDrag: function(node) {
var drag = false,
n = Y.Node.get(node);
if (n instanceof Y.Node) {
Y.each(this._drags, function(v, k) {
if (n.compareTo(v.get('node'))) {
drag = v;
}
});
}
return drag;
}
});
Y.namespace('DD');
Y.DD.DDM = new DDMBase();
}, '3.0.0pr1' ,{requires:['node', 'base'], skinnable:false});
| NERC-CEH/jules-jasmin | majic/joj/public/js/yui/build/dd/dd-ddm-base.js | JavaScript | gpl-2.0 | 9,568 |
/****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* ignore
*/
/**
* @constant
* @type {number}
*/
cc.UIInterfaceOrientationLandscapeLeft = -90;
/**
* @constant
* @type {number}
*/
cc.UIInterfaceOrientationLandscapeRight = 90;
/**
* @constant
* @type {number}
*/
cc.UIInterfaceOrientationPortraitUpsideDown = 180;
/**
* @constant
* @type {number}
*/
cc.UIInterfaceOrientationPortrait = 0;
/**
* <p>
* This class manages all events of input. include: touch, mouse, accelerometer, keyboard <br/>
* </p>
* @class
* @name cc.inputManager
*/
cc.inputManager = /** @lends cc.inputManager# */{
TOUCH_TIMEOUT: 5000,
_mousePressed: false,
_isRegisterEvent: false,
_preTouchPoint: cc.p(0, 0),
_prevMousePoint: cc.p(0, 0),
_preTouchPool: [],
_preTouchPoolPointer: 0,
_touches: [],
_touchesIntegerDict: {},
_indexBitsUsed: 0,
_maxTouches: 5,
_accelEnabled: false,
_accelInterval: 1 / 30,
_accelMinus: 1,
_accelCurTime: 0,
_acceleration: null,
_accelDeviceEvent: null,
_getUnUsedIndex: function () {
var temp = this._indexBitsUsed;
var now = cc.sys.now();
for (var i = 0; i < this._maxTouches; i++) {
if (!(temp & 0x00000001)) {
this._indexBitsUsed |= (1 << i);
return i;
}
else {
var touch = this._touches[i];
if (now - touch._lastModified > this.TOUCH_TIMEOUT) {
this._removeUsedIndexBit(i);
delete this._touchesIntegerDict[touch.getID()];
return i;
}
}
temp >>= 1;
}
// all bits are used
return -1;
},
_removeUsedIndexBit: function (index) {
if (index < 0 || index >= this._maxTouches)
return;
var temp = 1 << index;
temp = ~temp;
this._indexBitsUsed &= temp;
},
_glView: null,
/**
* @function
* @param {Array} touches
*/
handleTouchesBegin: function (touches) {
var selTouch, index, curTouch, touchID,
handleTouches = [], locTouchIntDict = this._touchesIntegerDict,
now = cc.sys.now();
for (var i = 0, len = touches.length; i < len; i++) {
selTouch = touches[i];
touchID = selTouch.getID();
index = locTouchIntDict[touchID];
if (index == null) {
var unusedIndex = this._getUnUsedIndex();
if (unusedIndex === -1) {
cc.log(cc._LogInfos.inputManager_handleTouchesBegin, unusedIndex);
continue;
}
//curTouch = this._touches[unusedIndex] = selTouch;
curTouch = this._touches[unusedIndex] = new cc.Touch(selTouch._point.x, selTouch._point.y, selTouch.getID());
curTouch._lastModified = now;
curTouch._setPrevPoint(selTouch._prevPoint);
locTouchIntDict[touchID] = unusedIndex;
handleTouches.push(curTouch);
}
}
if (handleTouches.length > 0) {
this._glView._convertTouchesWithScale(handleTouches);
var touchEvent = new cc.EventTouch(handleTouches);
touchEvent._eventCode = cc.EventTouch.EventCode.BEGAN;
cc.eventManager.dispatchEvent(touchEvent);
}
},
/**
* @function
* @param {Array} touches
*/
handleTouchesMove: function (touches) {
var selTouch, index, touchID,
handleTouches = [], locTouches = this._touches,
now = cc.sys.now();
for (var i = 0, len = touches.length; i < len; i++) {
selTouch = touches[i];
touchID = selTouch.getID();
index = this._touchesIntegerDict[touchID];
if (index == null) {
//cc.log("if the index doesn't exist, it is an error");
continue;
}
if (locTouches[index]) {
locTouches[index]._setPoint(selTouch._point);
locTouches[index]._setPrevPoint(selTouch._prevPoint);
locTouches[index]._lastModified = now;
handleTouches.push(locTouches[index]);
}
}
if (handleTouches.length > 0) {
this._glView._convertTouchesWithScale(handleTouches);
var touchEvent = new cc.EventTouch(handleTouches);
touchEvent._eventCode = cc.EventTouch.EventCode.MOVED;
cc.eventManager.dispatchEvent(touchEvent);
}
},
/**
* @function
* @param {Array} touches
*/
handleTouchesEnd: function (touches) {
var handleTouches = this.getSetOfTouchesEndOrCancel(touches);
if (handleTouches.length > 0) {
this._glView._convertTouchesWithScale(handleTouches);
var touchEvent = new cc.EventTouch(handleTouches);
touchEvent._eventCode = cc.EventTouch.EventCode.ENDED;
cc.eventManager.dispatchEvent(touchEvent);
}
},
/**
* @function
* @param {Array} touches
*/
handleTouchesCancel: function (touches) {
var handleTouches = this.getSetOfTouchesEndOrCancel(touches);
if (handleTouches.length > 0) {
this._glView._convertTouchesWithScale(handleTouches);
var touchEvent = new cc.EventTouch(handleTouches);
touchEvent._eventCode = cc.EventTouch.EventCode.CANCELLED;
cc.eventManager.dispatchEvent(touchEvent);
}
},
/**
* @function
* @param {Array} touches
* @returns {Array}
*/
getSetOfTouchesEndOrCancel: function (touches) {
var selTouch, index, touchID, handleTouches = [], locTouches = this._touches, locTouchesIntDict = this._touchesIntegerDict;
for (var i = 0, len = touches.length; i < len; i++) {
selTouch = touches[i];
touchID = selTouch.getID();
index = locTouchesIntDict[touchID];
if (index == null) {
continue; //cc.log("if the index doesn't exist, it is an error");
}
if (locTouches[index]) {
locTouches[index]._setPoint(selTouch._point);
locTouches[index]._setPrevPoint(selTouch._prevPoint);
handleTouches.push(locTouches[index]);
this._removeUsedIndexBit(index);
delete locTouchesIntDict[touchID];
}
}
return handleTouches;
},
/**
* @function
* @param {HTMLElement} element
* @return {Object}
*/
getHTMLElementPosition: function (element) {
var docElem = document.documentElement;
var win = window;
var box = null;
if (cc.isFunction(element.getBoundingClientRect)) {
box = element.getBoundingClientRect();
} else {
box = {
left: 0,
top: 0,
width: parseInt(element.style.width),
height: parseInt(element.style.height)
};
}
return {
left: box.left + win.pageXOffset - docElem.clientLeft,
top: box.top + win.pageYOffset - docElem.clientTop,
width: box.width,
height: box.height
};
},
/**
* @function
* @param {cc.Touch} touch
* @return {cc.Touch}
*/
getPreTouch: function (touch) {
var preTouch = null;
var locPreTouchPool = this._preTouchPool;
var id = touch.getID();
for (var i = locPreTouchPool.length - 1; i >= 0; i--) {
if (locPreTouchPool[i].getID() === id) {
preTouch = locPreTouchPool[i];
break;
}
}
if (!preTouch)
preTouch = touch;
return preTouch;
},
/**
* @function
* @param {cc.Touch} touch
*/
setPreTouch: function (touch) {
var find = false;
var locPreTouchPool = this._preTouchPool;
var id = touch.getID();
for (var i = locPreTouchPool.length - 1; i >= 0; i--) {
if (locPreTouchPool[i].getID() === id) {
locPreTouchPool[i] = touch;
find = true;
break;
}
}
if (!find) {
if (locPreTouchPool.length <= 50) {
locPreTouchPool.push(touch);
} else {
locPreTouchPool[this._preTouchPoolPointer] = touch;
this._preTouchPoolPointer = (this._preTouchPoolPointer + 1) % 50;
}
}
},
/**
* @function
* @param {Number} tx
* @param {Number} ty
* @param {cc.Point} pos
* @return {cc.Touch}
*/
getTouchByXY: function (tx, ty, pos) {
var locPreTouch = this._preTouchPoint;
var location = this._glView.convertToLocationInView(tx, ty, pos);
var touch = new cc.Touch(location.x, location.y);
touch._setPrevPoint(locPreTouch.x, locPreTouch.y);
locPreTouch.x = location.x;
locPreTouch.y = location.y;
return touch;
},
/**
* @function
* @param {cc.Point} location
* @param {cc.Point} pos
* @param {Number} eventType
* @returns {cc.EventMouse}
*/
getMouseEvent: function (location, pos, eventType) {
var locPreMouse = this._prevMousePoint;
this._glView._convertMouseToLocationInView(location, pos);
var mouseEvent = new cc.EventMouse(eventType);
mouseEvent.setLocation(location.x, location.y);
mouseEvent._setPrevCursor(locPreMouse.x, locPreMouse.y);
locPreMouse.x = location.x;
locPreMouse.y = location.y;
return mouseEvent;
},
/**
* @function
* @param {Touch} event
* @param {cc.Point} pos
* @return {cc.Point}
*/
getPointByEvent: function (event, pos) {
if (event.pageX != null) //not available in <= IE8
return {x: event.pageX, y: event.pageY};
pos.left -= document.body.scrollLeft;
pos.top -= document.body.scrollTop;
return {x: event.clientX, y: event.clientY};
},
/**
* @function
* @param {Touch} event
* @param {cc.Point} pos
* @returns {Array}
*/
getTouchesByEvent: function (event, pos) {
var touchArr = [], locView = this._glView;
var touch_event, touch, preLocation;
var locPreTouch = this._preTouchPoint;
var length = event.changedTouches.length;
for (var i = 0; i < length; i++) {
touch_event = event.changedTouches[i];
if (touch_event) {
var location;
if (cc.sys.BROWSER_TYPE_FIREFOX === cc.sys.browserType)
location = locView.convertToLocationInView(touch_event.pageX, touch_event.pageY, pos);
else
location = locView.convertToLocationInView(touch_event.clientX, touch_event.clientY, pos);
if (touch_event.identifier != null) {
touch = new cc.Touch(location.x, location.y, touch_event.identifier);
//use Touch Pool
preLocation = this.getPreTouch(touch).getLocation();
touch._setPrevPoint(preLocation.x, preLocation.y);
this.setPreTouch(touch);
} else {
touch = new cc.Touch(location.x, location.y);
touch._setPrevPoint(locPreTouch.x, locPreTouch.y);
}
locPreTouch.x = location.x;
locPreTouch.y = location.y;
touchArr.push(touch);
}
}
return touchArr;
},
/**
* @function
* @param {HTMLElement} element
*/
registerSystemEvent: function (element) {
if (this._isRegisterEvent) return;
var locView = this._glView = cc.view;
var selfPointer = this;
var supportMouse = ('mouse' in cc.sys.capabilities), supportTouches = ('touches' in cc.sys.capabilities);
//HACK
// - At the same time to trigger the ontouch event and onmouse event
// - The function will execute 2 times
//The known browser:
// liebiao
// miui
// WECHAT
var prohibition = false;
if (cc.sys.isMobile)
prohibition = true;
//register touch event
if (supportMouse) {
window.addEventListener('mousedown', function () {
selfPointer._mousePressed = true;
}, false);
window.addEventListener('mouseup', function (event) {
if (prohibition) return;
var savePressed = selfPointer._mousePressed;
selfPointer._mousePressed = false;
if (!savePressed)
return;
var pos = selfPointer.getHTMLElementPosition(element);
var location = selfPointer.getPointByEvent(event, pos);
if (!cc.rectContainsPoint(new cc.Rect(pos.left, pos.top, pos.width, pos.height), location)) {
selfPointer.handleTouchesEnd([selfPointer.getTouchByXY(location.x, location.y, pos)]);
var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.UP);
mouseEvent.setButton(event.button);
cc.eventManager.dispatchEvent(mouseEvent);
}
}, false);
//register canvas mouse event
element.addEventListener("mousedown", function (event) {
if (prohibition) return;
selfPointer._mousePressed = true;
var pos = selfPointer.getHTMLElementPosition(element);
var location = selfPointer.getPointByEvent(event, pos);
selfPointer.handleTouchesBegin([selfPointer.getTouchByXY(location.x, location.y, pos)]);
var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.DOWN);
mouseEvent.setButton(event.button);
cc.eventManager.dispatchEvent(mouseEvent);
event.stopPropagation();
event.preventDefault();
element.focus();
}, false);
element.addEventListener("mouseup", function (event) {
if (prohibition) return;
selfPointer._mousePressed = false;
var pos = selfPointer.getHTMLElementPosition(element);
var location = selfPointer.getPointByEvent(event, pos);
selfPointer.handleTouchesEnd([selfPointer.getTouchByXY(location.x, location.y, pos)]);
var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.UP);
mouseEvent.setButton(event.button);
cc.eventManager.dispatchEvent(mouseEvent);
event.stopPropagation();
event.preventDefault();
}, false);
element.addEventListener("mousemove", function (event) {
if (prohibition) return;
var pos = selfPointer.getHTMLElementPosition(element);
var location = selfPointer.getPointByEvent(event, pos);
selfPointer.handleTouchesMove([selfPointer.getTouchByXY(location.x, location.y, pos)]);
var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.MOVE);
if (selfPointer._mousePressed)
mouseEvent.setButton(event.button);
else
mouseEvent.setButton(null);
cc.eventManager.dispatchEvent(mouseEvent);
event.stopPropagation();
event.preventDefault();
}, false);
element.addEventListener("mousewheel", function (event) {
var pos = selfPointer.getHTMLElementPosition(element);
var location = selfPointer.getPointByEvent(event, pos);
var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.SCROLL);
mouseEvent.setButton(event.button);
mouseEvent.setScrollData(0, event.wheelDelta);
cc.eventManager.dispatchEvent(mouseEvent);
event.stopPropagation();
event.preventDefault();
}, false);
/* firefox fix */
element.addEventListener("DOMMouseScroll", function (event) {
var pos = selfPointer.getHTMLElementPosition(element);
var location = selfPointer.getPointByEvent(event, pos);
var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.SCROLL);
mouseEvent.setButton(event.button);
mouseEvent.setScrollData(0, event.detail * -120);
cc.eventManager.dispatchEvent(mouseEvent);
event.stopPropagation();
event.preventDefault();
}, false);
}
if (window.navigator.msPointerEnabled) {
var _pointerEventsMap = {
"MSPointerDown": selfPointer.handleTouchesBegin,
"MSPointerMove": selfPointer.handleTouchesMove,
"MSPointerUp": selfPointer.handleTouchesEnd,
"MSPointerCancel": selfPointer.handleTouchesCancel
};
for (var eventName in _pointerEventsMap) {
(function (_pointerEvent, _touchEvent) {
element.addEventListener(_pointerEvent, function (event) {
var pos = selfPointer.getHTMLElementPosition(element);
pos.left -= document.documentElement.scrollLeft;
pos.top -= document.documentElement.scrollTop;
_touchEvent.call(selfPointer, [selfPointer.getTouchByXY(event.clientX, event.clientY, pos)]);
event.stopPropagation();
}, false);
})(eventName, _pointerEventsMap[eventName]);
}
}
if (supportTouches) {
//register canvas touch event
element.addEventListener("touchstart", function (event) {
if (!event.changedTouches) return;
var pos = selfPointer.getHTMLElementPosition(element);
pos.left -= document.body.scrollLeft;
pos.top -= document.body.scrollTop;
selfPointer.handleTouchesBegin(selfPointer.getTouchesByEvent(event, pos));
event.stopPropagation();
event.preventDefault();
element.focus();
}, false);
element.addEventListener("touchmove", function (event) {
if (!event.changedTouches) return;
var pos = selfPointer.getHTMLElementPosition(element);
pos.left -= document.body.scrollLeft;
pos.top -= document.body.scrollTop;
selfPointer.handleTouchesMove(selfPointer.getTouchesByEvent(event, pos));
event.stopPropagation();
event.preventDefault();
}, false);
element.addEventListener("touchend", function (event) {
if (!event.changedTouches) return;
var pos = selfPointer.getHTMLElementPosition(element);
pos.left -= document.body.scrollLeft;
pos.top -= document.body.scrollTop;
selfPointer.handleTouchesEnd(selfPointer.getTouchesByEvent(event, pos));
event.stopPropagation();
event.preventDefault();
}, false);
element.addEventListener("touchcancel", function (event) {
if (!event.changedTouches) return;
var pos = selfPointer.getHTMLElementPosition(element);
pos.left -= document.body.scrollLeft;
pos.top -= document.body.scrollTop;
selfPointer.handleTouchesCancel(selfPointer.getTouchesByEvent(event, pos));
event.stopPropagation();
event.preventDefault();
}, false);
}
//register keyboard event
this._registerKeyboardEvent();
//register Accelerometer event
this._registerAccelerometerEvent();
this._isRegisterEvent = true;
},
_registerKeyboardEvent: function () {
},
_registerAccelerometerEvent: function () {
},
/**
* @function
* @param {Number} dt
*/
update: function (dt) {
if (this._accelCurTime > this._accelInterval) {
this._accelCurTime -= this._accelInterval;
cc.eventManager.dispatchEvent(new cc.EventAcceleration(this._acceleration));
}
this._accelCurTime += dt;
}
};
| zero5566/super_mahjong | mahjong/super_mahjong/frameworks/cocos2d-html5/cocos2d/core/platform/CCInputManager.js | JavaScript | gpl-2.0 | 22,201 |
$(function () {
$("a.submit").click(function (ev) {
ev.preventDefault();
var f = $(this).closest("form");
f.attr("action", this.href);
bootbox.confirm("Are you sure you want do this? There is no undo button.", function (result) {
if (result) {
$.block();
f.submit();
}
});
});
$("a.toggledup").click(function (ev) {
ev.preventDefault();
var f = $(this).closest("form");
f.attr("action", this.href);
$.block();
f.submit();
});
$("#usefrom").change(function (ev) {
ev.preventDefault();
$("input:radio[value=0]").attr("checked", "checked");
});
$("#usetarget").change(function (ev) {
ev.preventDefault();
$("input:radio[value=1]").attr("checked", "checked");
});
});
| nehresma/bvcms | CmsWeb/Content/touchpoint/js/people/merge.js | JavaScript | gpl-2.0 | 867 |
/*
* Copyright (C) 2011 Flamingo Project (http://www.cloudine.io).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
Ext.define('Flamingo2.view.designer.DesignerModel', {
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.designerModel',
data: {
title: message.msg('workflow.title')
}
}); | chiwanpark/flamingo2 | flamingo2-web/src/main/webapp/resources/app/view/designer/DesignerModel.js | JavaScript | gpl-3.0 | 913 |
module.exports = {
entry: './client/index.js',
output: {
path: __dirname,
filename: './public/bundle.js'
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader'
},
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /\.svg$|\.ttf?|\.woff$|\.woff2|\.eof|\.eot/,
loader: 'file-loader'
}
]
}
}
| coinsTracker/coinTracker | webpack.config.js | JavaScript | gpl-3.0 | 555 |
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/*eslint max-nested-callbacks: 0*/
/*jscs:disable requirePaddingNewLinesInObjects*/
/*jscs:disable jsDoc*/
define([
'underscore',
'uiRegistry',
'Magento_Ui/js/form/components/collection/item'
], function (_, registry, Constr) {
'use strict';
describe('Magento_Ui/js/form/components/collection/item', function () {
var obj = new Constr({
provider: 'provName',
name: '',
index: ''
});
registry.set('provName', {
on: function () {
},
get: function () {
},
set: function () {
}
});
describe('"initProperties" method', function () {
it('Check for defined ', function () {
expect(obj.hasOwnProperty('initProperties')).toBeDefined();
});
it('Check answer type', function () {
var type = typeof obj.initProperties;
expect(type).toEqual('function');
});
it('Check returned value if method called without arguments', function () {
expect(obj.initProperties()).toBeDefined();
});
it('Check returned value type if method called without arguments', function () {
var type = typeof obj.initProperties();
expect(type).toEqual('object');
});
it('Check "displayed" property', function () {
obj.displayed = null;
obj.initProperties();
expect(obj.displayed).toEqual([]);
});
});
describe('"initObservable" method', function () {
it('Check for defined ', function () {
expect(obj.hasOwnProperty('initObservable')).toBeDefined();
});
it('Check answer type', function () {
var type = typeof obj.initObservable;
expect(type).toEqual('function');
});
it('Check returned value if method called without arguments', function () {
expect(obj.initObservable()).toBeDefined();
});
it('Check returned value type if method called without arguments', function () {
var type = typeof obj.initObservable();
expect(type).toEqual('object');
});
it('Check called "this.observe" method', function () {
obj.observe = jasmine.createSpy();
obj.initObservable();
expect(obj.observe).toHaveBeenCalled();
});
});
describe('"initElement" method', function () {
it('Check for defined ', function () {
expect(obj.hasOwnProperty('initElement')).toBeDefined();
});
it('Check answer type', function () {
var type = typeof obj.initElement;
expect(type).toEqual('function');
});
it('Check returned value if method called with object argument', function () {
var arg = {
initContainer: function () {
}
};
expect(obj.initElement(arg)).toBeDefined();
});
it('Check returned value type if method called with object argument', function () {
var arg = {
initContainer: function () {
}
},
type = typeof obj.initElement(arg);
expect(type).toEqual('object');
});
it('Check called "this.insertToIndexed" method with object argument', function () {
var arg = {
initContainer: function () {
}
};
obj.insertToIndexed = jasmine.createSpy();
obj.initElement(arg);
expect(obj.insertToIndexed).toHaveBeenCalledWith(arg);
});
});
describe('"insertToIndexed" method', function () {
it('Check for defined ', function () {
expect(obj.hasOwnProperty('insertToIndexed')).toBeDefined();
});
it('Check answer type', function () {
var type = typeof obj.insertToIndexed;
expect(type).toEqual('function');
});
it('Check called "insertToIndexed" method with object argument', function () {
var arg = {
initContainer: function () {
}
};
obj.insertToIndexed(arg);
expect(obj.insertToIndexed).toHaveBeenCalledWith(arg);
});
});
describe('"formatPreviews" method', function () {
it('Check for defined ', function () {
expect(obj.hasOwnProperty('formatPreviews')).toBeDefined();
});
it('Check answer type', function () {
var type = typeof obj.formatPreviews;
expect(type).toEqual('function');
});
it('Check returned value if call method with array arguments', function () {
expect(obj.formatPreviews(['1', '2', '3'])).toEqual(
[
{
'items': ['1'],
'separator': ' ',
'prefix': ''
},
{
'items': ['2'],
'separator': ' ',
'prefix': ''
},
{
'items': ['3'],
'separator': ' ',
'prefix': ''
}
]
);
});
});
describe('"buildPreview" method', function () {
it('Check for defined ', function () {
expect(obj.hasOwnProperty('buildPreview')).toBeDefined();
});
it('Check answer type', function () {
var type = typeof obj.buildPreview;
expect(type).toEqual('function');
});
it('Check returned value if method called with object argument', function () {
var arg = {
items: [],
prefix: 'magento'
};
expect(obj.buildPreview(arg)).toBeDefined();
});
it('Check returned value type if method called with object argument', function () {
var arg = {
items: [],
prefix: 'magento'
},
type = typeof obj.buildPreview(arg);
expect(type).toEqual('string');
});
it('Check called "this.getPreview" method with object argument', function () {
var arg = {
items: [],
prefix: 'magento'
};
obj.getPreview = jasmine.createSpy().and.callFake(function () {
return [];
});
obj.buildPreview(arg);
expect(obj.getPreview).toHaveBeenCalledWith(arg.items);
});
});
describe('"hasPreview" method', function () {
it('Check for defined ', function () {
expect(obj.hasOwnProperty('hasPreview')).toBeDefined();
});
it('Check answer type', function () {
var type = typeof obj.hasPreview;
expect(type).toEqual('function');
});
it('Check returned value type if method called with object argument', function () {
var arg = {
items: [],
prefix: 'magento'
},
type = typeof obj.hasPreview(arg);
expect(type).toEqual('boolean');
});
it('Check called "this.getPreview" method with object argument', function () {
var arg = {
items: [],
prefix: 'magento'
};
obj.getPreview = jasmine.createSpy().and.callFake(function () {
return [];
});
obj.hasPreview(arg);
expect(obj.getPreview).toHaveBeenCalledWith(arg.items);
});
});
describe('"getPreview" method', function () {
it('Check for defined ', function () {
expect(obj.hasOwnProperty('getPreview')).toBeDefined();
});
it('Check answer type', function () {
var type = typeof obj.getPreview;
expect(type).toEqual('function');
});
it('Check returned value type if method called with object argument', function () {
var arg = {
items: [],
prefix: 'magento'
},
type = typeof obj.getPreview(arg);
expect(type).toEqual('object');
});
});
});
});
| rajmahesh/magento2-master | vendor/magento/magento2-base/dev/tests/js/jasmine/tests/app/code/Magento/Ui/base/js/form/components/collection/item.test.js | JavaScript | gpl-3.0 | 9,385 |
// LICENCE https://github.com/adaptlearning/adapt_authoring/blob/master/LICENSE
define(function(require) {
var Origin = require('coreJS/app/origin');
var SidebarContainerView = require('coreJS/sidebar/views/sidebarView');
var Sidebar = {};
Sidebar.addView = function($el, options) {
// Trigger to remove current views
Origin.trigger('sidebar:views:remove');
// Check if element is a view element
if (_.isElement($el[0]) !== true) {
return console.log("Sidebar - Cannot add this object to the sidebar view. Please make sure it's the views $el");
}
// Trigger update of views
Origin.trigger('sidebar:sidebarContainer:update', $el, options);
}
// Append sidebar to body
Origin.once('app:dataReady', function() {
$('body').append(new SidebarContainerView().$el);
});
// Push sidebar to Origin object
Origin.sidebar = Sidebar;
}) | AmitGolhar/adapt_authoring | frontend/src/core/sidebar/sidebar.js | JavaScript | gpl-3.0 | 949 |
/*
* Copyright (C) 2005-2013 University of Sydney
*
* Licensed under the GNU License, Version 3.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.gnu.org/licenses/gpl-3.0.txt
*
* 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.
*/
/**
* OpenLayer Map viewer
*
* @author Kim Jackson
* @author Stephen White <[email protected]>
* @author Artem Osmakov <[email protected]>
* @copyright (C) 2005-2013 University of Sydney
* @link http://Sydney.edu.au/Heurist
* @version 3.1.0
* @license http://www.gnu.org/licenses/gpl-3.0.txt GNU License 3.0
* @package Heurist academic knowledge management system
* @subpackage Viewwers/Map
* @deprecated
*/
var map;
var iconsByrectype = [];
var onclickfn;
function loadMap(options) {
if (! options) options = {};
if (options["onclick"])
onclickfn = options["onclick"];
//var startView = calculateGoodMapView(options["startobjects"]);
map = new OpenLayers.Map("map");
var google = new OpenLayers.Layer.Google("Google Terrain" , {type: G_PHYSICAL_MAP });
var wms = new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} );
var ve = new OpenLayers.Layer.VirtualEarth( "VE");
var yahoo = new OpenLayers.Layer.Yahoo( "Yahoo");
map.addLayers([wms, google, ve, yahoo]);
var markerLayer = new OpenLayers.Layer.Markers("markers");
map.addLayer(markerLayer);
var vectorLayer = new OpenLayers.Layer.Vector("vector");
map.addLayer(vectorLayer);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.addControl(new OpenLayers.Control.MousePosition());
map.addControl(new OpenLayers.Control.NavToolbar());
map.setCenter(new OpenLayers.LonLat(0, 0), 3);
/* add objects to the map */
var url = top.HEURIST.iconDir+"questionmark.gif"; // todo: needs to load top.heurist
var sz = new OpenLayers.Size(16, 16);
var calculateOffset = function(size) {
return new OpenLayers.Pixel(-(size.w/2), -size.h);
};
var baseIcon = new OpenLayers.Icon(url, sz, null, calculateOffset);
for (var i in HEURIST.tmap.geoObjects) {
var geo = HEURIST.tmap.geoObjects[i];
var record = HEURIST.tmap.records[geo.bibID];
var highlight = false;
if (options["highlight"]) {
for (var h in options["highlight"]) {
if (geo.bibID == options["highlight"][h]) highlight = true;
}
}
if (! iconsByrectype[record.rectype]) {
iconsByrectype[record.rectype] = baseIcon.clone();
iconsByrectype[record.rectype].setUrl(top.HEURIST.iconDir + record.rectype + ".png");
// todo: 14/11/11 need to set top.HEURIST
}
var marker = null;
var polygon = null;
switch (geo.type) {
case "point":
marker = new OpenLayers.Marker(new OpenLayers.LonLat(geo.geo.x, geo.geo.y), getIcon(record).clone());
markerLayer.addMarker(marker);
break;
case "circle":
if (window.heurist_useLabelledMapIcons) {
addPointMarker(new GLatLng(geo.geo.y, geo.geo.x), record);
}
var points = [];
for (var i=0; i < 40; ++i) {
var x = geo.geo.x + geo.geo.radius * Math.cos(i * 2*Math.PI / 40);
var y = geo.geo.y + geo.geo.radius * Math.sin(i * 2*Math.PI / 40);
points.push(new OpenLayers.Geometry.Point(x, y));
}
polygon = new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(points));
if (highlight) {
vectorLayer.addFeatures([new OpenLayers.Feature.Vector(polygon)]); //, "#ff0000", 1, 0.5, "#ffaaaa", 0.3);
} else {
vectorLayer.addFeatures([new OpenLayers.Feature.Vector(polygon)]); //, "#0000ff", 1, 0.5, "#aaaaff", 0.3);
}
break;
case "rect":
if (window.heurist_useLabelledMapIcons) {
addPointMarker(new GLatLng((geo.geo.y0+geo.geo.y1)/2, (geo.geo.x0+geo.geo.x1)/2), record);
}
var points = [];
points.push(new OpenLayers.Geometry.Point(geo.geo.x0, geo.geo.y0));
points.push(new OpenLayers.Geometry.Point(geo.geo.x0, geo.geo.y1));
points.push(new OpenLayers.Geometry.Point(geo.geo.x1, geo.geo.y1));
points.push(new OpenLayers.Geometry.Point(geo.geo.x1, geo.geo.y0));
polygon = new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(points));
if (highlight) {
vectorLayer.addFeatures([new OpenLayers.Feature.Vector(polygon)]); //, "#ff0000", 1, 0.5, "#ffaaaa", 0.3);
} else {
vectorLayer.addFeatures([new OpenLayers.Feature.Vector(polygon)]); //, "#0000ff", 1, 0.5, "#aaaaff", 0.3);
}
break;
case "polygon":
if (window.heurist_useLabelledMapIcons) {
addPointMarker(new GLatLng(geo.geo.points[1].y, geo.geo.points[1].x), record);
}
var points = [];
for (var i=0; i < geo.geo.points.length; ++i) {
points.push(new OpenLayers.Geometry.Point(geo.geo.points[i].x, geo.geo.points[i].y));
}
polygon = new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(points));
if (highlight) {
vectorLayer.addFeatures([new OpenLayers.Feature.Vector(polygon)]); //, "#ff0000", 1, 0.5, "#ffaaaa", 0.3);
} else {
vectorLayer.addFeatures([new OpenLayers.Feature.Vector(polygon)]); //, "#0000ff", 1, 0.5, "#aaaaff", 0.3);
}
break;
case "path":
//var points = [];
//for (var i=0; i < geo.geo.points.length; ++i)
// points.push(new GLatLng(geo.geo.points[i].y, geo.geo.points[i].x));
if (highlight) {
polygon = new GPolyline.fromEncoded({ color: "#ff0000", weight: 3, opacity: 0.8, points: geo.geo.points, zoomFactor: 3, levels: geo.geo.levels, numLevels: 21 });
} else {
polygon = new GPolyline.fromEncoded({ color: "#0000ff", weight: 3, opacity: 0.8, points: geo.geo.points, zoomFactor: 3, levels: geo.geo.levels, numLevels: 21 });
}
if (window.heurist_useLabelledMapIcons) {
addPointMarker(polygon.getVertex(Math.floor(polygon.getVertexCount() / 2)), record);
}
break;
}
/*
if (marker) {
marker.record = record;
if (! record.overlays) record.overlays = [];
record.overlays.push(marker);
map.addOverlay(marker);
GEvent.addListener(marker, "click", markerClick);
}
else if (polygon) {
polygon.record = record;
if (! record.overlays) record.overlays = [];
record.overlays.push(polygon);
map.addOverlay(polygon);
GEvent.addListener(polygon, "click", polygonClick);
}
*/
}
}
function calculateGoodMapView(geoObjects) {
var minX, minY, maxX, maxY;
if (! geoObjects) geoObjects = HEURIST.tmap.geoObjects;
for (var i=0; i < geoObjects.length; ++i) {
var geo = geoObjects[i];
var bbox = (geo.type == "point")? { n: geo.geo.y, s: geo.geo.y, w: geo.geo.x, e: geo.geo.x } : geo.geo.bounds;
if (i > 0) {
if (bbox.w < minX) minX = bbox.w;
if (bbox.e > maxX) maxX = bbox.e;
if (bbox.s < minY) minY = bbox.s;
if (bbox.n > maxY) maxY = bbox.n;
}
else {
minX = bbox.w;
maxX = bbox.e;
minY = bbox.s;
maxY = bbox.n;
}
}
var centre = new GLatLng(0.5 * (minY + maxY), 0.5 * (minX + maxX));
if (maxX-minX < 0.000001 && maxY-minY < 0.000001) { // single point, or very close points
var sw = new GLatLng(minY - 0.1, minX - 0.1);
var ne = new GLatLng(maxY + 0.1, maxX + 0.1);
}
else {
var sw = new GLatLng(minY - 0.1*(maxY - minY), minX - 0.1*(maxX - minX));
var ne = new GLatLng(maxY + 0.1*(maxY - minY), maxX + 0.1*(maxX - minX));
}
var zoom = map.getBoundsZoomLevel(new GLatLngBounds(sw, ne));
return { latlng: centre, zoom: zoom };
}
function markerClick() {
var record = this.record;
if (onclickfn) {
onclickfn(record, this, this.getPoint());
} else {
var html = "<b>" + record.title + " </b>";
if (record.description) html += "<p style='height: 128px; overflow: auto;'>" + record.description + "</p>";
html += "<p><a target=_new href='../../records/view/viewRecord.php?recID=" + record.bibID + "'>heurist record #" + record.bibID + "</a></p>";
this.openInfoWindowHtml(html);
}
}
function polygonClick(point) {
var record = this.record;
if (onclickfn) {
onclickfn(record, this, point);
} else {
var html = "<b>" + record.title + " </b>";
if (record.description) html += "<p style='height: 128px; overflow: auto;'>" + record.description + "</p>";
html += "<p><a target=_new href='../../records/view/viewRecord.php?recID=" + record.bibID + "'>heurist record #" + record.bibID + "</a></p>";
map.openInfoWindowHtml(point, html);
}
}
var iconNumber = 0;
var legendIcons;
function getIcon(record) {
if (! window.heurist_useLabelledMapIcons) {
return iconsByrectype[record.rectype];
}
if (! legendIcons) {
var protoLegendImgs = document.getElementsByTagName("img");
var legendImgs = [];
legendIcons = {};
var mainLegendImg;
for (var i=0; i < protoLegendImgs.length; ++i) {
if (protoLegendImgs[i].className === "main-map-icon") {
mainLegendImg = protoLegendImgs[i];
}
else if (protoLegendImgs[i].className === "map-icons") {
legendImgs.push(protoLegendImgs[i]);
}
}
var baseIcon = new GIcon();
baseIcon.image = url;
baseIcon.shadow = "../../common/images/maps-icons/circle-shadow.png";
baseIcon.iconAnchor = new GPoint(10, 10);
baseIcon.iconWindowAnchor = new GPoint(10, 10);
baseIcon.iconSize = new GSize(20, 20);
baseIcon.shadowSize = new GSize(29, 21);
if (mainLegendImg) {
var icon = new GIcon(baseIcon);
icon.image = "../../common/images/maps-icons/circleStar.png";
var bibID = (mainLegendImg.id + "").replace(/icon-/, "");
legendIcons[bibID] = icon;
icon.associatedLegendImage = mainLegendImg;
mainLegendImg.style.backgroundImage = "url(" + icon.image + ")";
}
for (i=0; i < legendImgs.length; ++i) {
var iconLetter;
if (i < 26) {
iconLetter = String.fromCharCode(0x41 + i);
}
else {
iconLetter = "Dot";
}
var url = "../../common/images/maps-icons/circle" + iconLetter + ".png";
var icon = new GIcon(baseIcon);
icon.image = url;
var bibID = (legendImgs[i].id + "").replace(/icon-/, "");
legendIcons[ bibID ] = icon;
legendImgs[i].style.backgroundImage = "url(" + url + ")";
}
}
if (legendIcons[ record.bibID ]) {
if (legendIcons[record.bibID].associatedLegendImage) {
legendIcons[record.bibID].associatedLegendImage.style.display = "";
}
return legendIcons[ record.bibID ];
}
else {
return iconsByrectype[record.rectype];
}
}
function addPointMarker(latlng, record) {
var marker = new GMarker(latlng, getIcon(record));
if (! record.overlays) { record.overlays = []; }
record.overlays.push(marker);
map.addOverlay(marker);
}
| thegooglecodearchive/heurist | viewers/map/loadOLMap.js | JavaScript | gpl-3.0 | 10,789 |
define([
'intern!object',
'intern/chai!assert',
'base/lib/config',
'base/lib/login',
'base/lib/assert',
'base/lib/poll',
'base/lib/POM'
], function(registerSuite, assert, config, libLogin, libAssert, poll, POM) {
// Create this page's specific POM
var Page = new POM({
// Any functions used multiple times or important properties of the page
});
registerSuite({
name: 'auth',
before: function() {
Page.init(this.remote, config.homepageUrl);
},
beforeEach: function() {
return Page.setup().then(function() {
return libLogin.openLoginWidget(Page.remote);
});
},
after: function() {
return Page.teardown();
},
'Hovering over the header nav widget opens submenu': libAssert.elementExistsAndDisplayed('.oauth-login-picker'),
'Clicking Persona link opens new window': function() {
var remote = this.remote;
return remote
.findByCssSelector('.oauth-login-picker .launch-persona-login')
.click()
.end()
.getAllWindowHandles()
.then(function(handles) {
assert.equal(handles.length, 2);
return remote.switchToWindow(handles[1])
.getPageTitle()
.then(function(title) {
assert.ok(title.toLowerCase().indexOf('persona') != -1, 'Persona window opens upon login click');
return remote.closeCurrentWindow().switchToWindow(handles[0]);
});
});
},
'Logging in with Persona for the first time sends user to registration page': function() {
var dfd = this.async(config.testTimeout);
var remote = this.remote;
libLogin.getTestPersonaLoginCredentials(function(credentials) {
return libLogin.completePersonaWindow(remote, credentials.email, credentials.password).then(function() {
return remote
.then(function() {
return remote
.getCurrentUrl()
.then(function(url) {
assert.isTrue(url.indexOf('/account/signup') != -1);
return libLogin.completePersonaLogout(remote).then(dfd.resolve);
});
});
});
});
return dfd;
},
'[requires-login] Logging in with Persona with real credentials works': function() {
var dfd = this.async(config.testTimeout);
var remote = this.remote;
libLogin.completePersonaWindow(remote).then(function() {
return remote
.findByCssSelector('.oauth-logged-in-profile')
.then(function(element) {
poll.until(element, 'isDisplayed')
.then(function() {
return element
.click()
.then(function() {
return remote
.findById('edit-profile')
.click()
.end()
.findByCssSelector('.fm-submit button[type=submit]')
.click()
.end()
.findByCssSelector('.memberSince')
.click() // Just ensuring the element is there
.end()
.findByCssSelector('.oauth-logged-in-signout')
.click()
.end()
.findByCssSelector('.oauth-login-container')
.then(dfd.callback(function() {
assert.isTrue(true, 'User can sign out without problems');
}));
});
});
});
});
return dfd;
},
'Clicking on the GitHub icon initializes GitHub login process': function() {
return this.remote
.findByCssSelector('.oauth-login-picker a[data-service="GitHub"]')
.click()
.getCurrentUrl()
.then(function(url) {
assert.ok(url.toLowerCase().indexOf('github.com') != -1, 'Clicking GitHub login link goes to GitHub.com. (Requires working GitHub login.)');
})
.goBack(); // Cleanup to go back to MDN from GitHub sign in page
},
'Sign in icons are hidden from header widget on smaller screens': function() {
return this.remote
.setWindowSize(config.mediaQueries.tablet, 400)
.findByCssSelector('.oauth-login-options .oauth-icon')
.moveMouseTo(5, 5)
.isDisplayed()
.then(function(bool) {
assert.isFalse(bool);
});
}
});
});
| davehunt/kuma | tests/ui/tests/auth.js | JavaScript | mpl-2.0 | 6,271 |
/**
* Less - Leaner CSS v3.11.1
* http://lesscss.org
*
* Copyright (c) 2009-2020, Alexis Sellier <[email protected]>
* Licensed under the Apache-2.0 License.
*
* @license Apache-2.0
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.less = factory());
}(this, (function () { 'use strict';
// Export a new default each time
var defaultOptions = (function () { return ({
/* Inline Javascript - @plugin still allowed */
javascriptEnabled: false,
/* Outputs a makefile import dependency list to stdout. */
depends: false,
/* (DEPRECATED) Compress using less built-in compression.
* This does an okay job but does not utilise all the tricks of
* dedicated css compression. */
compress: false,
/* Runs the less parser and just reports errors without any output. */
lint: false,
/* Sets available include paths.
* If the file in an @import rule does not exist at that exact location,
* less will look for it at the location(s) passed to this option.
* You might use this for instance to specify a path to a library which
* you want to be referenced simply and relatively in the less files. */
paths: [],
/* color output in the terminal */
color: true,
/* The strictImports controls whether the compiler will allow an @import inside of either
* @media blocks or (a later addition) other selector blocks.
* See: https://github.com/less/less.js/issues/656 */
strictImports: false,
/* Allow Imports from Insecure HTTPS Hosts */
insecure: false,
/* Allows you to add a path to every generated import and url in your css.
* This does not affect less import statements that are processed, just ones
* that are left in the output css. */
rootpath: '',
/* By default URLs are kept as-is, so if you import a file in a sub-directory
* that references an image, exactly the same URL will be output in the css.
* This option allows you to re-write URL's in imported files so that the
* URL is always relative to the base imported file */
rewriteUrls: false,
/* How to process math
* 0 always - eagerly try to solve all operations
* 1 parens-division - require parens for division "/"
* 2 parens | strict - require parens for all operations
* 3 strict-legacy - legacy strict behavior (super-strict)
*/
math: 0,
/* Without this option, less attempts to guess at the output unit when it does maths. */
strictUnits: false,
/* Effectively the declaration is put at the top of your base Less file,
* meaning it can be used but it also can be overridden if this variable
* is defined in the file. */
globalVars: null,
/* As opposed to the global variable option, this puts the declaration at the
* end of your base file, meaning it will override anything defined in your Less file. */
modifyVars: null,
/* This option allows you to specify a argument to go on to every URL. */
urlArgs: ''
}); });
function extractId(href) {
return href.replace(/^[a-z-]+:\/+?[^\/]+/, '') // Remove protocol & domain
.replace(/[\?\&]livereload=\w+/, '') // Remove LiveReload cachebuster
.replace(/^\//, '') // Remove root /
.replace(/\.[a-zA-Z]+$/, '') // Remove simple extension
.replace(/[^\.\w-]+/g, '-') // Replace illegal characters
.replace(/\./g, ':'); // Replace dots with colons(for valid id)
}
function addDataAttr(options, tag) {
for (var opt in tag.dataset) {
if (tag.dataset.hasOwnProperty(opt)) {
if (opt === 'env' || opt === 'dumpLineNumbers' || opt === 'rootpath' || opt === 'errorReporting') {
options[opt] = tag.dataset[opt];
}
else {
try {
options[opt] = JSON.parse(tag.dataset[opt]);
}
catch (_) { }
}
}
}
}
var browser = {
createCSS: function (document, styles, sheet) {
// Strip the query-string
var href = sheet.href || '';
// If there is no title set, use the filename, minus the extension
var id = "less:" + (sheet.title || extractId(href));
// If this has already been inserted into the DOM, we may need to replace it
var oldStyleNode = document.getElementById(id);
var keepOldStyleNode = false;
// Create a new stylesheet node for insertion or (if necessary) replacement
var styleNode = document.createElement('style');
styleNode.setAttribute('type', 'text/css');
if (sheet.media) {
styleNode.setAttribute('media', sheet.media);
}
styleNode.id = id;
if (!styleNode.styleSheet) {
styleNode.appendChild(document.createTextNode(styles));
// If new contents match contents of oldStyleNode, don't replace oldStyleNode
keepOldStyleNode = (oldStyleNode !== null && oldStyleNode.childNodes.length > 0 && styleNode.childNodes.length > 0 &&
oldStyleNode.firstChild.nodeValue === styleNode.firstChild.nodeValue);
}
var head = document.getElementsByTagName('head')[0];
// If there is no oldStyleNode, just append; otherwise, only append if we need
// to replace oldStyleNode with an updated stylesheet
if (oldStyleNode === null || keepOldStyleNode === false) {
var nextEl = sheet && sheet.nextSibling || null;
if (nextEl) {
nextEl.parentNode.insertBefore(styleNode, nextEl);
}
else {
head.appendChild(styleNode);
}
}
if (oldStyleNode && keepOldStyleNode === false) {
oldStyleNode.parentNode.removeChild(oldStyleNode);
}
// For IE.
// This needs to happen *after* the style element is added to the DOM, otherwise IE 7 and 8 may crash.
// See http://social.msdn.microsoft.com/Forums/en-US/7e081b65-878a-4c22-8e68-c10d39c2ed32/internet-explorer-crashes-appending-style-element-to-head
if (styleNode.styleSheet) {
try {
styleNode.styleSheet.cssText = styles;
}
catch (e) {
throw new Error('Couldn\'t reassign styleSheet.cssText.');
}
}
},
currentScript: function (window) {
var document = window.document;
return document.currentScript || (function () {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();
}
};
var addDefaultOptions = (function (window, options) {
// use options from the current script tag data attribues
addDataAttr(options, browser.currentScript(window));
if (options.isFileProtocol === undefined) {
options.isFileProtocol = /^(file|(chrome|safari)(-extension)?|resource|qrc|app):/.test(window.location.protocol);
}
// Load styles asynchronously (default: false)
//
// This is set to `false` by default, so that the body
// doesn't start loading before the stylesheets are parsed.
// Setting this to `true` can result in flickering.
//
options.async = options.async || false;
options.fileAsync = options.fileAsync || false;
// Interval between watch polls
options.poll = options.poll || (options.isFileProtocol ? 1000 : 1500);
options.env = options.env || (window.location.hostname == '127.0.0.1' ||
window.location.hostname == '0.0.0.0' ||
window.location.hostname == 'localhost' ||
(window.location.port &&
window.location.port.length > 0) ||
options.isFileProtocol ? 'development'
: 'production');
var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(window.location.hash);
if (dumpLineNumbers) {
options.dumpLineNumbers = dumpLineNumbers[1];
}
if (options.useFileCache === undefined) {
options.useFileCache = true;
}
if (options.onReady === undefined) {
options.onReady = true;
}
if (options.relativeUrls) {
options.rewriteUrls = 'all';
}
});
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
var colors = {
'aliceblue': '#f0f8ff',
'antiquewhite': '#faebd7',
'aqua': '#00ffff',
'aquamarine': '#7fffd4',
'azure': '#f0ffff',
'beige': '#f5f5dc',
'bisque': '#ffe4c4',
'black': '#000000',
'blanchedalmond': '#ffebcd',
'blue': '#0000ff',
'blueviolet': '#8a2be2',
'brown': '#a52a2a',
'burlywood': '#deb887',
'cadetblue': '#5f9ea0',
'chartreuse': '#7fff00',
'chocolate': '#d2691e',
'coral': '#ff7f50',
'cornflowerblue': '#6495ed',
'cornsilk': '#fff8dc',
'crimson': '#dc143c',
'cyan': '#00ffff',
'darkblue': '#00008b',
'darkcyan': '#008b8b',
'darkgoldenrod': '#b8860b',
'darkgray': '#a9a9a9',
'darkgrey': '#a9a9a9',
'darkgreen': '#006400',
'darkkhaki': '#bdb76b',
'darkmagenta': '#8b008b',
'darkolivegreen': '#556b2f',
'darkorange': '#ff8c00',
'darkorchid': '#9932cc',
'darkred': '#8b0000',
'darksalmon': '#e9967a',
'darkseagreen': '#8fbc8f',
'darkslateblue': '#483d8b',
'darkslategray': '#2f4f4f',
'darkslategrey': '#2f4f4f',
'darkturquoise': '#00ced1',
'darkviolet': '#9400d3',
'deeppink': '#ff1493',
'deepskyblue': '#00bfff',
'dimgray': '#696969',
'dimgrey': '#696969',
'dodgerblue': '#1e90ff',
'firebrick': '#b22222',
'floralwhite': '#fffaf0',
'forestgreen': '#228b22',
'fuchsia': '#ff00ff',
'gainsboro': '#dcdcdc',
'ghostwhite': '#f8f8ff',
'gold': '#ffd700',
'goldenrod': '#daa520',
'gray': '#808080',
'grey': '#808080',
'green': '#008000',
'greenyellow': '#adff2f',
'honeydew': '#f0fff0',
'hotpink': '#ff69b4',
'indianred': '#cd5c5c',
'indigo': '#4b0082',
'ivory': '#fffff0',
'khaki': '#f0e68c',
'lavender': '#e6e6fa',
'lavenderblush': '#fff0f5',
'lawngreen': '#7cfc00',
'lemonchiffon': '#fffacd',
'lightblue': '#add8e6',
'lightcoral': '#f08080',
'lightcyan': '#e0ffff',
'lightgoldenrodyellow': '#fafad2',
'lightgray': '#d3d3d3',
'lightgrey': '#d3d3d3',
'lightgreen': '#90ee90',
'lightpink': '#ffb6c1',
'lightsalmon': '#ffa07a',
'lightseagreen': '#20b2aa',
'lightskyblue': '#87cefa',
'lightslategray': '#778899',
'lightslategrey': '#778899',
'lightsteelblue': '#b0c4de',
'lightyellow': '#ffffe0',
'lime': '#00ff00',
'limegreen': '#32cd32',
'linen': '#faf0e6',
'magenta': '#ff00ff',
'maroon': '#800000',
'mediumaquamarine': '#66cdaa',
'mediumblue': '#0000cd',
'mediumorchid': '#ba55d3',
'mediumpurple': '#9370d8',
'mediumseagreen': '#3cb371',
'mediumslateblue': '#7b68ee',
'mediumspringgreen': '#00fa9a',
'mediumturquoise': '#48d1cc',
'mediumvioletred': '#c71585',
'midnightblue': '#191970',
'mintcream': '#f5fffa',
'mistyrose': '#ffe4e1',
'moccasin': '#ffe4b5',
'navajowhite': '#ffdead',
'navy': '#000080',
'oldlace': '#fdf5e6',
'olive': '#808000',
'olivedrab': '#6b8e23',
'orange': '#ffa500',
'orangered': '#ff4500',
'orchid': '#da70d6',
'palegoldenrod': '#eee8aa',
'palegreen': '#98fb98',
'paleturquoise': '#afeeee',
'palevioletred': '#d87093',
'papayawhip': '#ffefd5',
'peachpuff': '#ffdab9',
'peru': '#cd853f',
'pink': '#ffc0cb',
'plum': '#dda0dd',
'powderblue': '#b0e0e6',
'purple': '#800080',
'rebeccapurple': '#663399',
'red': '#ff0000',
'rosybrown': '#bc8f8f',
'royalblue': '#4169e1',
'saddlebrown': '#8b4513',
'salmon': '#fa8072',
'sandybrown': '#f4a460',
'seagreen': '#2e8b57',
'seashell': '#fff5ee',
'sienna': '#a0522d',
'silver': '#c0c0c0',
'skyblue': '#87ceeb',
'slateblue': '#6a5acd',
'slategray': '#708090',
'slategrey': '#708090',
'snow': '#fffafa',
'springgreen': '#00ff7f',
'steelblue': '#4682b4',
'tan': '#d2b48c',
'teal': '#008080',
'thistle': '#d8bfd8',
'tomato': '#ff6347',
'turquoise': '#40e0d0',
'violet': '#ee82ee',
'wheat': '#f5deb3',
'white': '#ffffff',
'whitesmoke': '#f5f5f5',
'yellow': '#ffff00',
'yellowgreen': '#9acd32'
};
var unitConversions = {
length: {
'm': 1,
'cm': 0.01,
'mm': 0.001,
'in': 0.0254,
'px': 0.0254 / 96,
'pt': 0.0254 / 72,
'pc': 0.0254 / 72 * 12
},
duration: {
's': 1,
'ms': 0.001
},
angle: {
'rad': 1 / (2 * Math.PI),
'deg': 1 / 360,
'grad': 1 / 400,
'turn': 1
}
};
var data = { colors: colors, unitConversions: unitConversions };
var Node = /** @class */ (function () {
function Node() {
this.parent = null;
this.visibilityBlocks = undefined;
this.nodeVisible = undefined;
this.rootNode = null;
this.parsed = null;
var self = this;
Object.defineProperty(this, 'currentFileInfo', {
get: function () { return self.fileInfo(); }
});
Object.defineProperty(this, 'index', {
get: function () { return self.getIndex(); }
});
}
Node.prototype.setParent = function (nodes, parent) {
function set(node) {
if (node && node instanceof Node) {
node.parent = parent;
}
}
if (Array.isArray(nodes)) {
nodes.forEach(set);
}
else {
set(nodes);
}
};
Node.prototype.getIndex = function () {
return this._index || (this.parent && this.parent.getIndex()) || 0;
};
Node.prototype.fileInfo = function () {
return this._fileInfo || (this.parent && this.parent.fileInfo()) || {};
};
Node.prototype.isRulesetLike = function () {
return false;
};
Node.prototype.toCSS = function (context) {
var strs = [];
this.genCSS(context, {
add: function (chunk, fileInfo, index) {
strs.push(chunk);
},
isEmpty: function () {
return strs.length === 0;
}
});
return strs.join('');
};
Node.prototype.genCSS = function (context, output) {
output.add(this.value);
};
Node.prototype.accept = function (visitor) {
this.value = visitor.visit(this.value);
};
Node.prototype.eval = function () { return this; };
Node.prototype._operate = function (context, op, a, b) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
};
Node.prototype.fround = function (context, value) {
var precision = context && context.numPrecision;
// add "epsilon" to ensure numbers like 1.000000005 (represented as 1.000000004999...) are properly rounded:
return (precision) ? Number((value + 2e-16).toFixed(precision)) : value;
};
// Returns true if this node represents root of ast imported by reference
Node.prototype.blocksVisibility = function () {
if (this.visibilityBlocks == null) {
this.visibilityBlocks = 0;
}
return this.visibilityBlocks !== 0;
};
Node.prototype.addVisibilityBlock = function () {
if (this.visibilityBlocks == null) {
this.visibilityBlocks = 0;
}
this.visibilityBlocks = this.visibilityBlocks + 1;
};
Node.prototype.removeVisibilityBlock = function () {
if (this.visibilityBlocks == null) {
this.visibilityBlocks = 0;
}
this.visibilityBlocks = this.visibilityBlocks - 1;
};
// Turns on node visibility - if called node will be shown in output regardless
// of whether it comes from import by reference or not
Node.prototype.ensureVisibility = function () {
this.nodeVisible = true;
};
// Turns off node visibility - if called node will NOT be shown in output regardless
// of whether it comes from import by reference or not
Node.prototype.ensureInvisibility = function () {
this.nodeVisible = false;
};
// return values:
// false - the node must not be visible
// true - the node must be visible
// undefined or null - the node has the same visibility as its parent
Node.prototype.isVisible = function () {
return this.nodeVisible;
};
Node.prototype.visibilityInfo = function () {
return {
visibilityBlocks: this.visibilityBlocks,
nodeVisible: this.nodeVisible
};
};
Node.prototype.copyVisibilityInfo = function (info) {
if (!info) {
return;
}
this.visibilityBlocks = info.visibilityBlocks;
this.nodeVisible = info.nodeVisible;
};
return Node;
}());
Node.compare = function (a, b) {
/* returns:
-1: a < b
0: a = b
1: a > b
and *any* other value for a != b (e.g. undefined, NaN, -2 etc.) */
if ((a.compare) &&
// for "symmetric results" force toCSS-based comparison
// of Quoted or Anonymous if either value is one of those
!(b.type === 'Quoted' || b.type === 'Anonymous')) {
return a.compare(b);
}
else if (b.compare) {
return -b.compare(a);
}
else if (a.type !== b.type) {
return undefined;
}
a = a.value;
b = b.value;
if (!Array.isArray(a)) {
return a === b ? 0 : undefined;
}
if (a.length !== b.length) {
return undefined;
}
for (var i_1 = 0; i_1 < a.length; i_1++) {
if (Node.compare(a[i_1], b[i_1]) !== 0) {
return undefined;
}
}
return 0;
};
Node.numericCompare = function (a, b) { return a < b ? -1
: a === b ? 0
: a > b ? 1 : undefined; };
//
// RGB Colors - #ff0014, #eee
//
var Color = /** @class */ (function (_super) {
__extends(Color, _super);
function Color(rgb, a, originalForm) {
var _this = _super.call(this) || this;
var self = _this;
//
// The end goal here, is to parse the arguments
// into an integer triplet, such as `128, 255, 0`
//
// This facilitates operations and conversions.
//
if (Array.isArray(rgb)) {
_this.rgb = rgb;
}
else if (rgb.length >= 6) {
_this.rgb = [];
rgb.match(/.{2}/g).map(function (c, i) {
if (i < 3) {
self.rgb.push(parseInt(c, 16));
}
else {
self.alpha = (parseInt(c, 16)) / 255;
}
});
}
else {
_this.rgb = [];
rgb.split('').map(function (c, i) {
if (i < 3) {
self.rgb.push(parseInt(c + c, 16));
}
else {
self.alpha = (parseInt(c + c, 16)) / 255;
}
});
}
_this.alpha = _this.alpha || (typeof a === 'number' ? a : 1);
if (typeof originalForm !== 'undefined') {
_this.value = originalForm;
}
return _this;
}
Color.prototype.luma = function () {
var r = this.rgb[0] / 255;
var g = this.rgb[1] / 255;
var b = this.rgb[2] / 255;
r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4);
g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4);
b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4);
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
};
Color.prototype.genCSS = function (context, output) {
output.add(this.toCSS(context));
};
Color.prototype.toCSS = function (context, doNotCompress) {
var compress = context && context.compress && !doNotCompress;
var color;
var alpha;
var colorFunction;
var args = [];
// `value` is set if this color was originally
// converted from a named color string so we need
// to respect this and try to output named color too.
alpha = this.fround(context, this.alpha);
if (this.value) {
if (this.value.indexOf('rgb') === 0) {
if (alpha < 1) {
colorFunction = 'rgba';
}
}
else if (this.value.indexOf('hsl') === 0) {
if (alpha < 1) {
colorFunction = 'hsla';
}
else {
colorFunction = 'hsl';
}
}
else {
return this.value;
}
}
else {
if (alpha < 1) {
colorFunction = 'rgba';
}
}
switch (colorFunction) {
case 'rgba':
args = this.rgb.map(function (c) { return clamp(Math.round(c), 255); }).concat(clamp(alpha, 1));
break;
case 'hsla':
args.push(clamp(alpha, 1));
case 'hsl':
color = this.toHSL();
args = [
this.fround(context, color.h),
this.fround(context, color.s * 100) + "%",
this.fround(context, color.l * 100) + "%"
].concat(args);
}
if (colorFunction) {
// Values are capped between `0` and `255`, rounded and zero-padded.
return colorFunction + "(" + args.join("," + (compress ? '' : ' ')) + ")";
}
color = this.toRGB();
if (compress) {
var splitcolor = color.split('');
// Convert color to short format
if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
color = "#" + splitcolor[1] + splitcolor[3] + splitcolor[5];
}
}
return color;
};
//
// Operations have to be done per-channel, if not,
// channels will spill onto each other. Once we have
// our result, in the form of an integer triplet,
// we create a new Color node to hold the result.
//
Color.prototype.operate = function (context, op, other) {
var rgb = new Array(3);
var alpha = this.alpha * (1 - other.alpha) + other.alpha;
for (var c = 0; c < 3; c++) {
rgb[c] = this._operate(context, op, this.rgb[c], other.rgb[c]);
}
return new Color(rgb, alpha);
};
Color.prototype.toRGB = function () {
return toHex(this.rgb);
};
Color.prototype.toHSL = function () {
var r = this.rgb[0] / 255;
var g = this.rgb[1] / 255;
var b = this.rgb[2] / 255;
var a = this.alpha;
var max = Math.max(r, g, b);
var min = Math.min(r, g, b);
var h;
var s;
var l = (max + min) / 2;
var d = max - min;
if (max === min) {
h = s = 0;
}
else {
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return { h: h * 360, s: s, l: l, a: a };
};
// Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
Color.prototype.toHSV = function () {
var r = this.rgb[0] / 255;
var g = this.rgb[1] / 255;
var b = this.rgb[2] / 255;
var a = this.alpha;
var max = Math.max(r, g, b);
var min = Math.min(r, g, b);
var h;
var s;
var v = max;
var d = max - min;
if (max === 0) {
s = 0;
}
else {
s = d / max;
}
if (max === min) {
h = 0;
}
else {
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return { h: h * 360, s: s, v: v, a: a };
};
Color.prototype.toARGB = function () {
return toHex([this.alpha * 255].concat(this.rgb));
};
Color.prototype.compare = function (x) {
return (x.rgb &&
x.rgb[0] === this.rgb[0] &&
x.rgb[1] === this.rgb[1] &&
x.rgb[2] === this.rgb[2] &&
x.alpha === this.alpha) ? 0 : undefined;
};
return Color;
}(Node));
Color.prototype.type = 'Color';
function clamp(v, max) {
return Math.min(Math.max(v, 0), max);
}
function toHex(v) {
return "#" + v.map(function (c) {
c = clamp(Math.round(c), 255);
return (c < 16 ? '0' : '') + c.toString(16);
}).join('');
}
Color.fromKeyword = function (keyword) {
var c;
var key = keyword.toLowerCase();
if (colors.hasOwnProperty(key)) {
c = new Color(colors[key].slice(1));
}
else if (key === 'transparent') {
c = new Color([0, 0, 0], 0);
}
if (c) {
c.value = keyword;
return c;
}
};
var Paren = /** @class */ (function (_super) {
__extends(Paren, _super);
function Paren(node) {
var _this = _super.call(this) || this;
_this.value = node;
return _this;
}
Paren.prototype.genCSS = function (context, output) {
output.add('(');
this.value.genCSS(context, output);
output.add(')');
};
Paren.prototype.eval = function (context) {
return new Paren(this.value.eval(context));
};
return Paren;
}(Node));
Paren.prototype.type = 'Paren';
var _noSpaceCombinators = {
'': true,
' ': true,
'|': true
};
var Combinator = /** @class */ (function (_super) {
__extends(Combinator, _super);
function Combinator(value) {
var _this = _super.call(this) || this;
if (value === ' ') {
_this.value = ' ';
_this.emptyOrWhitespace = true;
}
else {
_this.value = value ? value.trim() : '';
_this.emptyOrWhitespace = _this.value === '';
}
return _this;
}
Combinator.prototype.genCSS = function (context, output) {
var spaceOrEmpty = (context.compress || _noSpaceCombinators[this.value]) ? '' : ' ';
output.add(spaceOrEmpty + this.value + spaceOrEmpty);
};
return Combinator;
}(Node));
Combinator.prototype.type = 'Combinator';
var Element = /** @class */ (function (_super) {
__extends(Element, _super);
function Element(combinator, value, isVariable, index, currentFileInfo, visibilityInfo) {
var _this = _super.call(this) || this;
_this.combinator = combinator instanceof Combinator ?
combinator : new Combinator(combinator);
if (typeof value === 'string') {
_this.value = value.trim();
}
else if (value) {
_this.value = value;
}
else {
_this.value = '';
}
_this.isVariable = isVariable;
_this._index = index;
_this._fileInfo = currentFileInfo;
_this.copyVisibilityInfo(visibilityInfo);
_this.setParent(_this.combinator, _this);
return _this;
}
Element.prototype.accept = function (visitor) {
var value = this.value;
this.combinator = visitor.visit(this.combinator);
if (typeof value === 'object') {
this.value = visitor.visit(value);
}
};
Element.prototype.eval = function (context) {
return new Element(this.combinator, this.value.eval ? this.value.eval(context) : this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
};
Element.prototype.clone = function () {
return new Element(this.combinator, this.value, this.isVariable, this.getIndex(), this.fileInfo(), this.visibilityInfo());
};
Element.prototype.genCSS = function (context, output) {
output.add(this.toCSS(context), this.fileInfo(), this.getIndex());
};
Element.prototype.toCSS = function (context) {
if (context === void 0) { context = {}; }
var value = this.value;
var firstSelector = context.firstSelector;
if (value instanceof Paren) {
// selector in parens should not be affected by outer selector
// flags (breaks only interpolated selectors - see #1973)
context.firstSelector = true;
}
value = value.toCSS ? value.toCSS(context) : value;
context.firstSelector = firstSelector;
if (value === '' && this.combinator.value.charAt(0) === '&') {
return '';
}
else {
return this.combinator.toCSS(context) + value;
}
};
return Element;
}(Node));
Element.prototype.type = 'Element';
var Math$1 = {
ALWAYS: 0,
PARENS_DIVISION: 1,
PARENS: 2,
STRICT_LEGACY: 3
};
var RewriteUrls = {
OFF: 0,
LOCAL: 1,
ALL: 2
};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var clone_1 = createCommonjsModule(function (module) {
var clone = (function () {
function _instanceof(obj, type) {
return type != null && obj instanceof type;
}
var nativeMap;
try {
nativeMap = Map;
}
catch (_) {
// maybe a reference error because no `Map`. Give it a dummy value that no
// value will ever be an instanceof.
nativeMap = function () { };
}
var nativeSet;
try {
nativeSet = Set;
}
catch (_) {
nativeSet = function () { };
}
var nativePromise;
try {
nativePromise = Promise;
}
catch (_) {
nativePromise = function () { };
}
/**
* Clones (copies) an Object using deep copying.
*
* This function supports circular references by default, but if you are certain
* there are no circular references in your object, you can save some CPU time
* by calling clone(obj, false).
*
* Caution: if `circular` is false and `parent` contains circular references,
* your program may enter an infinite loop and crash.
*
* @param `parent` - the object to be cloned
* @param `circular` - set to true if the object to be cloned may contain
* circular references. (optional - true by default)
* @param `depth` - set to a number if the object is only to be cloned to
* a particular depth. (optional - defaults to Infinity)
* @param `prototype` - sets the prototype to be used when cloning an object.
* (optional - defaults to parent prototype).
* @param `includeNonEnumerable` - set to true if the non-enumerable properties
* should be cloned as well. Non-enumerable properties on the prototype
* chain will be ignored. (optional - false by default)
*/
function clone(parent, circular, depth, prototype, includeNonEnumerable) {
if (typeof circular === 'object') {
depth = circular.depth;
prototype = circular.prototype;
includeNonEnumerable = circular.includeNonEnumerable;
circular = circular.circular;
}
// maintain two arrays for circular references, where corresponding parents
// and children have the same index
var allParents = [];
var allChildren = [];
var useBuffer = typeof Buffer != 'undefined';
if (typeof circular == 'undefined')
circular = true;
if (typeof depth == 'undefined')
depth = Infinity;
// recurse this function so we don't reset allParents and allChildren
function _clone(parent, depth) {
// cloning null always returns null
if (parent === null)
return null;
if (depth === 0)
return parent;
var child;
var proto;
if (typeof parent != 'object') {
return parent;
}
if (_instanceof(parent, nativeMap)) {
child = new nativeMap();
}
else if (_instanceof(parent, nativeSet)) {
child = new nativeSet();
}
else if (_instanceof(parent, nativePromise)) {
child = new nativePromise(function (resolve, reject) {
parent.then(function (value) {
resolve(_clone(value, depth - 1));
}, function (err) {
reject(_clone(err, depth - 1));
});
});
}
else if (clone.__isArray(parent)) {
child = [];
}
else if (clone.__isRegExp(parent)) {
child = new RegExp(parent.source, __getRegExpFlags(parent));
if (parent.lastIndex)
child.lastIndex = parent.lastIndex;
}
else if (clone.__isDate(parent)) {
child = new Date(parent.getTime());
}
else if (useBuffer && Buffer.isBuffer(parent)) {
if (Buffer.allocUnsafe) {
// Node.js >= 4.5.0
child = Buffer.allocUnsafe(parent.length);
}
else {
// Older Node.js versions
child = new Buffer(parent.length);
}
parent.copy(child);
return child;
}
else if (_instanceof(parent, Error)) {
child = Object.create(parent);
}
else {
if (typeof prototype == 'undefined') {
proto = Object.getPrototypeOf(parent);
child = Object.create(proto);
}
else {
child = Object.create(prototype);
proto = prototype;
}
}
if (circular) {
var index = allParents.indexOf(parent);
if (index != -1) {
return allChildren[index];
}
allParents.push(parent);
allChildren.push(child);
}
if (_instanceof(parent, nativeMap)) {
parent.forEach(function (value, key) {
var keyChild = _clone(key, depth - 1);
var valueChild = _clone(value, depth - 1);
child.set(keyChild, valueChild);
});
}
if (_instanceof(parent, nativeSet)) {
parent.forEach(function (value) {
var entryChild = _clone(value, depth - 1);
child.add(entryChild);
});
}
for (var i in parent) {
var attrs;
if (proto) {
attrs = Object.getOwnPropertyDescriptor(proto, i);
}
if (attrs && attrs.set == null) {
continue;
}
child[i] = _clone(parent[i], depth - 1);
}
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(parent);
for (var i = 0; i < symbols.length; i++) {
// Don't need to worry about cloning a symbol because it is a primitive,
// like a number or string.
var symbol = symbols[i];
var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
continue;
}
child[symbol] = _clone(parent[symbol], depth - 1);
if (!descriptor.enumerable) {
Object.defineProperty(child, symbol, {
enumerable: false
});
}
}
}
if (includeNonEnumerable) {
var allPropertyNames = Object.getOwnPropertyNames(parent);
for (var i = 0; i < allPropertyNames.length; i++) {
var propertyName = allPropertyNames[i];
var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);
if (descriptor && descriptor.enumerable) {
continue;
}
child[propertyName] = _clone(parent[propertyName], depth - 1);
Object.defineProperty(child, propertyName, {
enumerable: false
});
}
}
return child;
}
return _clone(parent, depth);
}
/**
* Simple flat clone using prototype, accepts only objects, usefull for property
* override on FLAT configuration object (no nested props).
*
* USE WITH CAUTION! This may not behave as you wish if you do not know how this
* works.
*/
clone.clonePrototype = function clonePrototype(parent) {
if (parent === null)
return null;
var c = function () { };
c.prototype = parent;
return new c();
};
// private utility functions
function __objToStr(o) {
return Object.prototype.toString.call(o);
}
clone.__objToStr = __objToStr;
function __isDate(o) {
return typeof o === 'object' && __objToStr(o) === '[object Date]';
}
clone.__isDate = __isDate;
function __isArray(o) {
return typeof o === 'object' && __objToStr(o) === '[object Array]';
}
clone.__isArray = __isArray;
function __isRegExp(o) {
return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
}
clone.__isRegExp = __isRegExp;
function __getRegExpFlags(re) {
var flags = '';
if (re.global)
flags += 'g';
if (re.ignoreCase)
flags += 'i';
if (re.multiline)
flags += 'm';
return flags;
}
clone.__getRegExpFlags = __getRegExpFlags;
return clone;
})();
if ( module.exports) {
module.exports = clone;
}
});
/* jshint proto: true */
function getLocation(index, inputStream) {
var n = index + 1;
var line = null;
var column = -1;
while (--n >= 0 && inputStream.charAt(n) !== '\n') {
column++;
}
if (typeof index === 'number') {
line = (inputStream.slice(0, index).match(/\n/g) || '').length;
}
return {
line: line,
column: column
};
}
function copyArray(arr) {
var i;
var length = arr.length;
var copy = new Array(length);
for (i = 0; i < length; i++) {
copy[i] = arr[i];
}
return copy;
}
function clone(obj) {
var cloned = {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
cloned[prop] = obj[prop];
}
}
return cloned;
}
function defaults(obj1, obj2) {
var newObj = obj2 || {};
if (!obj2._defaults) {
newObj = {};
var defaults_1 = clone_1(obj1);
newObj._defaults = defaults_1;
var cloned = obj2 ? clone_1(obj2) : {};
Object.assign(newObj, defaults_1, cloned);
}
return newObj;
}
function copyOptions(obj1, obj2) {
if (obj2 && obj2._defaults) {
return obj2;
}
var opts = defaults(obj1, obj2);
if (opts.strictMath) {
opts.math = Math$1.STRICT_LEGACY;
}
// Back compat with changed relativeUrls option
if (opts.relativeUrls) {
opts.rewriteUrls = RewriteUrls.ALL;
}
if (typeof opts.math === 'string') {
switch (opts.math.toLowerCase()) {
case 'always':
opts.math = Math$1.ALWAYS;
break;
case 'parens-division':
opts.math = Math$1.PARENS_DIVISION;
break;
case 'strict':
case 'parens':
opts.math = Math$1.PARENS;
break;
case 'strict-legacy':
opts.math = Math$1.STRICT_LEGACY;
}
}
if (typeof opts.rewriteUrls === 'string') {
switch (opts.rewriteUrls.toLowerCase()) {
case 'off':
opts.rewriteUrls = RewriteUrls.OFF;
break;
case 'local':
opts.rewriteUrls = RewriteUrls.LOCAL;
break;
case 'all':
opts.rewriteUrls = RewriteUrls.ALL;
break;
}
}
return opts;
}
function merge(obj1, obj2) {
for (var prop in obj2) {
if (obj2.hasOwnProperty(prop)) {
obj1[prop] = obj2[prop];
}
}
return obj1;
}
function flattenArray(arr, result) {
if (result === void 0) { result = []; }
for (var i_1 = 0, length_1 = arr.length; i_1 < length_1; i_1++) {
var value = arr[i_1];
if (Array.isArray(value)) {
flattenArray(value, result);
}
else {
if (value !== undefined) {
result.push(value);
}
}
}
return result;
}
var utils = /*#__PURE__*/Object.freeze({
__proto__: null,
getLocation: getLocation,
copyArray: copyArray,
clone: clone,
defaults: defaults,
copyOptions: copyOptions,
merge: merge,
flattenArray: flattenArray
});
var anonymousFunc = /(<anonymous>|Function):(\d+):(\d+)/;
/**
* This is a centralized class of any error that could be thrown internally (mostly by the parser).
* Besides standard .message it keeps some additional data like a path to the file where the error
* occurred along with line and column numbers.
*
* @class
* @extends Error
* @type {module.LessError}
*
* @prop {string} type
* @prop {string} filename
* @prop {number} index
* @prop {number} line
* @prop {number} column
* @prop {number} callLine
* @prop {number} callExtract
* @prop {string[]} extract
*
* @param {Object} e - An error object to wrap around or just a descriptive object
* @param {Object} fileContentMap - An object with file contents in 'contents' property (like importManager) @todo - move to fileManager?
* @param {string} [currentFilename]
*/
var LessError = function LessError(e, fileContentMap, currentFilename) {
Error.call(this);
var filename = e.filename || currentFilename;
this.message = e.message;
this.stack = e.stack;
if (fileContentMap && filename) {
var input = fileContentMap.contents[filename];
var loc = getLocation(e.index, input);
var line = loc.line;
var col = loc.column;
var callLine = e.call && getLocation(e.call, input).line;
var lines = input ? input.split('\n') : '';
this.type = e.type || 'Syntax';
this.filename = filename;
this.index = e.index;
this.line = typeof line === 'number' ? line + 1 : null;
this.column = col;
if (!this.line && this.stack) {
var found = this.stack.match(anonymousFunc);
/**
* We have to figure out how this environment stringifies anonymous functions
* so we can correctly map plugin errors.
*
* Note, in Node 8, the output of anonymous funcs varied based on parameters
* being present or not, so we inject dummy params.
*/
var func = new Function('a', 'throw new Error()');
var lineAdjust = 0;
try {
func();
}
catch (e) {
var match = e.stack.match(anonymousFunc);
var line_1 = parseInt(match[2]);
lineAdjust = 1 - line_1;
}
if (found) {
if (found[2]) {
this.line = parseInt(found[2]) + lineAdjust;
}
if (found[3]) {
this.column = parseInt(found[3]);
}
}
}
this.callLine = callLine + 1;
this.callExtract = lines[callLine];
this.extract = [
lines[this.line - 2],
lines[this.line - 1],
lines[this.line]
];
}
};
if (typeof Object.create === 'undefined') {
var F = function () { };
F.prototype = Error.prototype;
LessError.prototype = new F();
}
else {
LessError.prototype = Object.create(Error.prototype);
}
LessError.prototype.constructor = LessError;
/**
* An overridden version of the default Object.prototype.toString
* which uses additional information to create a helpful message.
*
* @param {Object} options
* @returns {string}
*/
LessError.prototype.toString = function (options) {
if (options === void 0) { options = {}; }
var message = '';
var extract = this.extract || [];
var error = [];
var stylize = function (str) { return str; };
if (options.stylize) {
var type = typeof options.stylize;
if (type !== 'function') {
throw Error("options.stylize should be a function, got a " + type + "!");
}
stylize = options.stylize;
}
if (this.line !== null) {
if (typeof extract[0] === 'string') {
error.push(stylize(this.line - 1 + " " + extract[0], 'grey'));
}
if (typeof extract[1] === 'string') {
var errorTxt = this.line + " ";
if (extract[1]) {
errorTxt += extract[1].slice(0, this.column) +
stylize(stylize(stylize(extract[1].substr(this.column, 1), 'bold') +
extract[1].slice(this.column + 1), 'red'), 'inverse');
}
error.push(errorTxt);
}
if (typeof extract[2] === 'string') {
error.push(stylize(this.line + 1 + " " + extract[2], 'grey'));
}
error = error.join('\n') + stylize('', 'reset') + "\n";
}
message += stylize(this.type + "Error: " + this.message, 'red');
if (this.filename) {
message += stylize(' in ', 'red') + this.filename;
}
if (this.line) {
message += stylize(" on line " + this.line + ", column " + (this.column + 1) + ":", 'grey');
}
message += "\n" + error;
if (this.callLine) {
message += stylize('from ', 'red') + (this.filename || '') + "/n";
message += stylize(this.callLine, 'grey') + " " + this.callExtract + "/n";
}
return message;
};
var Selector = /** @class */ (function (_super) {
__extends(Selector, _super);
function Selector(elements, extendList, condition, index, currentFileInfo, visibilityInfo) {
var _this = _super.call(this) || this;
_this.extendList = extendList;
_this.condition = condition;
_this.evaldCondition = !condition;
_this._index = index;
_this._fileInfo = currentFileInfo;
_this.elements = _this.getElements(elements);
_this.mixinElements_ = undefined;
_this.copyVisibilityInfo(visibilityInfo);
_this.setParent(_this.elements, _this);
return _this;
}
Selector.prototype.accept = function (visitor) {
if (this.elements) {
this.elements = visitor.visitArray(this.elements);
}
if (this.extendList) {
this.extendList = visitor.visitArray(this.extendList);
}
if (this.condition) {
this.condition = visitor.visit(this.condition);
}
};
Selector.prototype.createDerived = function (elements, extendList, evaldCondition) {
elements = this.getElements(elements);
var newSelector = new Selector(elements, extendList || this.extendList, null, this.getIndex(), this.fileInfo(), this.visibilityInfo());
newSelector.evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition;
newSelector.mediaEmpty = this.mediaEmpty;
return newSelector;
};
Selector.prototype.getElements = function (els) {
if (!els) {
return [new Element('', '&', false, this._index, this._fileInfo)];
}
if (typeof els === 'string') {
this.parse.parseNode(els, ['selector'], this._index, this._fileInfo, function (err, result) {
if (err) {
throw new LessError({
index: err.index,
message: err.message
}, this.parse.imports, this._fileInfo.filename);
}
els = result[0].elements;
});
}
return els;
};
Selector.prototype.createEmptySelectors = function () {
var el = new Element('', '&', false, this._index, this._fileInfo);
var sels = [new Selector([el], null, null, this._index, this._fileInfo)];
sels[0].mediaEmpty = true;
return sels;
};
Selector.prototype.match = function (other) {
var elements = this.elements;
var len = elements.length;
var olen;
var i;
other = other.mixinElements();
olen = other.length;
if (olen === 0 || len < olen) {
return 0;
}
else {
for (i = 0; i < olen; i++) {
if (elements[i].value !== other[i]) {
return 0;
}
}
}
return olen; // return number of matched elements
};
Selector.prototype.mixinElements = function () {
if (this.mixinElements_) {
return this.mixinElements_;
}
var elements = this.elements.map(function (v) { return v.combinator.value + (v.value.value || v.value); }).join('').match(/[,&#\*\.\w-]([\w-]|(\\.))*/g);
if (elements) {
if (elements[0] === '&') {
elements.shift();
}
}
else {
elements = [];
}
return (this.mixinElements_ = elements);
};
Selector.prototype.isJustParentSelector = function () {
return !this.mediaEmpty &&
this.elements.length === 1 &&
this.elements[0].value === '&' &&
(this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
};
Selector.prototype.eval = function (context) {
var evaldCondition = this.condition && this.condition.eval(context);
var elements = this.elements;
var extendList = this.extendList;
elements = elements && elements.map(function (e) { return e.eval(context); });
extendList = extendList && extendList.map(function (extend) { return extend.eval(context); });
return this.createDerived(elements, extendList, evaldCondition);
};
Selector.prototype.genCSS = function (context, output) {
var i;
var element;
if ((!context || !context.firstSelector) && this.elements[0].combinator.value === '') {
output.add(' ', this.fileInfo(), this.getIndex());
}
for (i = 0; i < this.elements.length; i++) {
element = this.elements[i];
element.genCSS(context, output);
}
};
Selector.prototype.getIsOutput = function () {
return this.evaldCondition;
};
return Selector;
}(Node));
Selector.prototype.type = 'Selector';
var Value = /** @class */ (function (_super) {
__extends(Value, _super);
function Value(value) {
var _this = _super.call(this) || this;
if (!value) {
throw new Error('Value requires an array argument');
}
if (!Array.isArray(value)) {
_this.value = [value];
}
else {
_this.value = value;
}
return _this;
}
Value.prototype.accept = function (visitor) {
if (this.value) {
this.value = visitor.visitArray(this.value);
}
};
Value.prototype.eval = function (context) {
if (this.value.length === 1) {
return this.value[0].eval(context);
}
else {
return new Value(this.value.map(function (v) { return v.eval(context); }));
}
};
Value.prototype.genCSS = function (context, output) {
var i;
for (i = 0; i < this.value.length; i++) {
this.value[i].genCSS(context, output);
if (i + 1 < this.value.length) {
output.add((context && context.compress) ? ',' : ', ');
}
}
};
return Value;
}(Node));
Value.prototype.type = 'Value';
var Keyword = /** @class */ (function (_super) {
__extends(Keyword, _super);
function Keyword(value) {
var _this = _super.call(this) || this;
_this.value = value;
return _this;
}
Keyword.prototype.genCSS = function (context, output) {
if (this.value === '%') {
throw { type: 'Syntax', message: 'Invalid % without number' };
}
output.add(this.value);
};
return Keyword;
}(Node));
Keyword.prototype.type = 'Keyword';
Keyword.True = new Keyword('true');
Keyword.False = new Keyword('false');
var Anonymous = /** @class */ (function (_super) {
__extends(Anonymous, _super);
function Anonymous(value, index, currentFileInfo, mapLines, rulesetLike, visibilityInfo) {
var _this = _super.call(this) || this;
_this.value = value;
_this._index = index;
_this._fileInfo = currentFileInfo;
_this.mapLines = mapLines;
_this.rulesetLike = (typeof rulesetLike === 'undefined') ? false : rulesetLike;
_this.allowRoot = true;
_this.copyVisibilityInfo(visibilityInfo);
return _this;
}
Anonymous.prototype.eval = function () {
return new Anonymous(this.value, this._index, this._fileInfo, this.mapLines, this.rulesetLike, this.visibilityInfo());
};
Anonymous.prototype.compare = function (other) {
return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
};
Anonymous.prototype.isRulesetLike = function () {
return this.rulesetLike;
};
Anonymous.prototype.genCSS = function (context, output) {
this.nodeVisible = Boolean(this.value);
if (this.nodeVisible) {
output.add(this.value, this._fileInfo, this._index, this.mapLines);
}
};
return Anonymous;
}(Node));
Anonymous.prototype.type = 'Anonymous';
var MATH = Math$1;
var Declaration = /** @class */ (function (_super) {
__extends(Declaration, _super);
function Declaration(name, value, important, merge, index, currentFileInfo, inline, variable) {
var _this = _super.call(this) || this;
_this.name = name;
_this.value = (value instanceof Node) ? value : new Value([value ? new Anonymous(value) : null]);
_this.important = important ? " " + important.trim() : '';
_this.merge = merge;
_this._index = index;
_this._fileInfo = currentFileInfo;
_this.inline = inline || false;
_this.variable = (variable !== undefined) ? variable
: (name.charAt && (name.charAt(0) === '@'));
_this.allowRoot = true;
_this.setParent(_this.value, _this);
return _this;
}
Declaration.prototype.genCSS = function (context, output) {
output.add(this.name + (context.compress ? ':' : ': '), this.fileInfo(), this.getIndex());
try {
this.value.genCSS(context, output);
}
catch (e) {
e.index = this._index;
e.filename = this._fileInfo.filename;
throw e;
}
output.add(this.important + ((this.inline || (context.lastRule && context.compress)) ? '' : ';'), this._fileInfo, this._index);
};
Declaration.prototype.eval = function (context) {
var mathBypass = false;
var prevMath;
var name = this.name;
var evaldValue;
var variable = this.variable;
if (typeof name !== 'string') {
// expand 'primitive' name directly to get
// things faster (~10% for benchmark.less):
name = (name.length === 1) && (name[0] instanceof Keyword) ?
name[0].value : evalName(context, name);
variable = false; // never treat expanded interpolation as new variable name
}
// @todo remove when parens-division is default
if (name === 'font' && context.math === MATH.ALWAYS) {
mathBypass = true;
prevMath = context.math;
context.math = MATH.PARENS_DIVISION;
}
try {
context.importantScope.push({});
evaldValue = this.value.eval(context);
if (!this.variable && evaldValue.type === 'DetachedRuleset') {
throw { message: 'Rulesets cannot be evaluated on a property.',
index: this.getIndex(), filename: this.fileInfo().filename };
}
var important = this.important;
var importantResult = context.importantScope.pop();
if (!important && importantResult.important) {
important = importantResult.important;
}
return new Declaration(name, evaldValue, important, this.merge, this.getIndex(), this.fileInfo(), this.inline, variable);
}
catch (e) {
if (typeof e.index !== 'number') {
e.index = this.getIndex();
e.filename = this.fileInfo().filename;
}
throw e;
}
finally {
if (mathBypass) {
context.math = prevMath;
}
}
};
Declaration.prototype.makeImportant = function () {
return new Declaration(this.name, this.value, '!important', this.merge, this.getIndex(), this.fileInfo(), this.inline);
};
return Declaration;
}(Node));
function evalName(context, name) {
var value = '';
var i;
var n = name.length;
var output = { add: function (s) { value += s; } };
for (i = 0; i < n; i++) {
name[i].eval(context).genCSS(context, output);
}
return value;
}
Declaration.prototype.type = 'Declaration';
var debugInfo = function (context, ctx, lineSeparator) {
var result = '';
if (context.dumpLineNumbers && !context.compress) {
switch (context.dumpLineNumbers) {
case 'comments':
result = debugInfo.asComment(ctx);
break;
case 'mediaquery':
result = debugInfo.asMediaQuery(ctx);
break;
case 'all':
result = debugInfo.asComment(ctx) + (lineSeparator || '') + debugInfo.asMediaQuery(ctx);
break;
}
}
return result;
};
debugInfo.asComment = function (ctx) { return "/* line " + ctx.debugInfo.lineNumber + ", " + ctx.debugInfo.fileName + " */\n"; };
debugInfo.asMediaQuery = function (ctx) {
var filenameWithProtocol = ctx.debugInfo.fileName;
if (!/^[a-z]+:\/\//i.test(filenameWithProtocol)) {
filenameWithProtocol = "file://" + filenameWithProtocol;
}
return "@media -sass-debug-info{filename{font-family:" + filenameWithProtocol.replace(/([.:\/\\])/g, function (a) {
if (a == '\\') {
a = '\/';
}
return "\\" + a;
}) + "}line{font-family:\\00003" + ctx.debugInfo.lineNumber + "}}\n";
};
var Comment = /** @class */ (function (_super) {
__extends(Comment, _super);
function Comment(value, isLineComment, index, currentFileInfo) {
var _this = _super.call(this) || this;
_this.value = value;
_this.isLineComment = isLineComment;
_this._index = index;
_this._fileInfo = currentFileInfo;
_this.allowRoot = true;
return _this;
}
Comment.prototype.genCSS = function (context, output) {
if (this.debugInfo) {
output.add(debugInfo(context, this), this.fileInfo(), this.getIndex());
}
output.add(this.value);
};
Comment.prototype.isSilent = function (context) {
var isCompressed = context.compress && this.value[2] !== '!';
return this.isLineComment || isCompressed;
};
return Comment;
}(Node));
Comment.prototype.type = 'Comment';
var contexts = {};
var copyFromOriginal = function copyFromOriginal(original, destination, propertiesToCopy) {
if (!original) {
return;
}
for (var i_1 = 0; i_1 < propertiesToCopy.length; i_1++) {
if (original.hasOwnProperty(propertiesToCopy[i_1])) {
destination[propertiesToCopy[i_1]] = original[propertiesToCopy[i_1]];
}
}
};
/*
parse is used whilst parsing
*/
var parseCopyProperties = [
// options
'paths',
'rewriteUrls',
'rootpath',
'strictImports',
'insecure',
'dumpLineNumbers',
'compress',
'syncImport',
'chunkInput',
'mime',
'useFileCache',
// context
'processImports',
// Used by the import manager to stop multiple import visitors being created.
'pluginManager' // Used as the plugin manager for the session
];
contexts.Parse = function (options) {
copyFromOriginal(options, this, parseCopyProperties);
if (typeof this.paths === 'string') {
this.paths = [this.paths];
}
};
var evalCopyProperties = [
'paths',
'compress',
'math',
'strictUnits',
'sourceMap',
'importMultiple',
'urlArgs',
'javascriptEnabled',
'pluginManager',
'importantScope',
'rewriteUrls' // option - whether to adjust URL's to be relative
];
function isPathRelative(path) {
return !/^(?:[a-z-]+:|\/|#)/i.test(path);
}
function isPathLocalRelative(path) {
return path.charAt(0) === '.';
}
contexts.Eval = /** @class */ (function () {
function Eval(options, frames) {
copyFromOriginal(options, this, evalCopyProperties);
if (typeof this.paths === 'string') {
this.paths = [this.paths];
}
this.frames = frames || [];
this.importantScope = this.importantScope || [];
this.inCalc = false;
this.mathOn = true;
}
Eval.prototype.enterCalc = function () {
if (!this.calcStack) {
this.calcStack = [];
}
this.calcStack.push(true);
this.inCalc = true;
};
Eval.prototype.exitCalc = function () {
this.calcStack.pop();
if (!this.calcStack) {
this.inCalc = false;
}
};
Eval.prototype.inParenthesis = function () {
if (!this.parensStack) {
this.parensStack = [];
}
this.parensStack.push(true);
};
Eval.prototype.outOfParenthesis = function () {
this.parensStack.pop();
};
Eval.prototype.isMathOn = function (op) {
if (!this.mathOn) {
return false;
}
if (op === '/' && this.math !== Math$1.ALWAYS && (!this.parensStack || !this.parensStack.length)) {
return false;
}
if (this.math > Math$1.PARENS_DIVISION) {
return this.parensStack && this.parensStack.length;
}
return true;
};
Eval.prototype.pathRequiresRewrite = function (path) {
var isRelative = this.rewriteUrls === RewriteUrls.LOCAL ? isPathLocalRelative : isPathRelative;
return isRelative(path);
};
Eval.prototype.rewritePath = function (path, rootpath) {
var newPath;
rootpath = rootpath || '';
newPath = this.normalizePath(rootpath + path);
// If a path was explicit relative and the rootpath was not an absolute path
// we must ensure that the new path is also explicit relative.
if (isPathLocalRelative(path) &&
isPathRelative(rootpath) &&
isPathLocalRelative(newPath) === false) {
newPath = "./" + newPath;
}
return newPath;
};
Eval.prototype.normalizePath = function (path) {
var segments = path.split('/').reverse();
var segment;
path = [];
while (segments.length !== 0) {
segment = segments.pop();
switch (segment) {
case '.':
break;
case '..':
if ((path.length === 0) || (path[path.length - 1] === '..')) {
path.push(segment);
}
else {
path.pop();
}
break;
default:
path.push(segment);
break;
}
}
return path.join('/');
};
return Eval;
}());
function makeRegistry(base) {
return {
_data: {},
add: function (name, func) {
// precautionary case conversion, as later querying of
// the registry by function-caller uses lower case as well.
name = name.toLowerCase();
if (this._data.hasOwnProperty(name)) ;
this._data[name] = func;
},
addMultiple: function (functions) {
var _this = this;
Object.keys(functions).forEach(function (name) {
_this.add(name, functions[name]);
});
},
get: function (name) {
return this._data[name] || (base && base.get(name));
},
getLocalFunctions: function () {
return this._data;
},
inherit: function () {
return makeRegistry(this);
},
create: function (base) {
return makeRegistry(base);
}
};
}
var functionRegistry = makeRegistry(null);
var defaultFunc = {
eval: function () {
var v = this.value_;
var e = this.error_;
if (e) {
throw e;
}
if (v != null) {
return v ? Keyword.True : Keyword.False;
}
},
value: function (v) {
this.value_ = v;
},
error: function (e) {
this.error_ = e;
},
reset: function () {
this.value_ = this.error_ = null;
}
};
var Ruleset = /** @class */ (function (_super) {
__extends(Ruleset, _super);
function Ruleset(selectors, rules, strictImports, visibilityInfo) {
var _this = _super.call(this) || this;
_this.selectors = selectors;
_this.rules = rules;
_this._lookups = {};
_this._variables = null;
_this._properties = null;
_this.strictImports = strictImports;
_this.copyVisibilityInfo(visibilityInfo);
_this.allowRoot = true;
_this.setParent(_this.selectors, _this);
_this.setParent(_this.rules, _this);
return _this;
}
Ruleset.prototype.isRulesetLike = function () {
return true;
};
Ruleset.prototype.accept = function (visitor) {
if (this.paths) {
this.paths = visitor.visitArray(this.paths, true);
}
else if (this.selectors) {
this.selectors = visitor.visitArray(this.selectors);
}
if (this.rules && this.rules.length) {
this.rules = visitor.visitArray(this.rules);
}
};
Ruleset.prototype.eval = function (context) {
var selectors;
var selCnt;
var selector;
var i;
var hasVariable;
var hasOnePassingSelector = false;
if (this.selectors && (selCnt = this.selectors.length)) {
selectors = new Array(selCnt);
defaultFunc.error({
type: 'Syntax',
message: 'it is currently only allowed in parametric mixin guards,'
});
for (i = 0; i < selCnt; i++) {
selector = this.selectors[i].eval(context);
for (var j = 0; j < selector.elements.length; j++) {
if (selector.elements[j].isVariable) {
hasVariable = true;
break;
}
}
selectors[i] = selector;
if (selector.evaldCondition) {
hasOnePassingSelector = true;
}
}
if (hasVariable) {
var toParseSelectors = new Array(selCnt);
for (i = 0; i < selCnt; i++) {
selector = selectors[i];
toParseSelectors[i] = selector.toCSS(context);
}
this.parse.parseNode(toParseSelectors.join(','), ["selectors"], selectors[0].getIndex(), selectors[0].fileInfo(), function (err, result) {
if (result) {
selectors = flattenArray(result);
}
});
}
defaultFunc.reset();
}
else {
hasOnePassingSelector = true;
}
var rules = this.rules ? copyArray(this.rules) : null;
var ruleset = new Ruleset(selectors, rules, this.strictImports, this.visibilityInfo());
var rule;
var subRule;
ruleset.originalRuleset = this;
ruleset.root = this.root;
ruleset.firstRoot = this.firstRoot;
ruleset.allowImports = this.allowImports;
if (this.debugInfo) {
ruleset.debugInfo = this.debugInfo;
}
if (!hasOnePassingSelector) {
rules.length = 0;
}
// inherit a function registry from the frames stack when possible;
// otherwise from the global registry
ruleset.functionRegistry = (function (frames) {
var i = 0;
var n = frames.length;
var found;
for (; i !== n; ++i) {
found = frames[i].functionRegistry;
if (found) {
return found;
}
}
return functionRegistry;
})(context.frames).inherit();
// push the current ruleset to the frames stack
var ctxFrames = context.frames;
ctxFrames.unshift(ruleset);
// currrent selectors
var ctxSelectors = context.selectors;
if (!ctxSelectors) {
context.selectors = ctxSelectors = [];
}
ctxSelectors.unshift(this.selectors);
// Evaluate imports
if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
ruleset.evalImports(context);
}
// Store the frames around mixin definitions,
// so they can be evaluated like closures when the time comes.
var rsRules = ruleset.rules;
for (i = 0; (rule = rsRules[i]); i++) {
if (rule.evalFirst) {
rsRules[i] = rule.eval(context);
}
}
var mediaBlockCount = (context.mediaBlocks && context.mediaBlocks.length) || 0;
// Evaluate mixin calls.
for (i = 0; (rule = rsRules[i]); i++) {
if (rule.type === 'MixinCall') {
/* jshint loopfunc:true */
rules = rule.eval(context).filter(function (r) {
if ((r instanceof Declaration) && r.variable) {
// do not pollute the scope if the variable is
// already there. consider returning false here
// but we need a way to "return" variable from mixins
return !(ruleset.variable(r.name));
}
return true;
});
rsRules.splice.apply(rsRules, [i, 1].concat(rules));
i += rules.length - 1;
ruleset.resetCache();
}
else if (rule.type === 'VariableCall') {
/* jshint loopfunc:true */
rules = rule.eval(context).rules.filter(function (r) {
if ((r instanceof Declaration) && r.variable) {
// do not pollute the scope at all
return false;
}
return true;
});
rsRules.splice.apply(rsRules, [i, 1].concat(rules));
i += rules.length - 1;
ruleset.resetCache();
}
}
// Evaluate everything else
for (i = 0; (rule = rsRules[i]); i++) {
if (!rule.evalFirst) {
rsRules[i] = rule = rule.eval ? rule.eval(context) : rule;
}
}
// Evaluate everything else
for (i = 0; (rule = rsRules[i]); i++) {
// for rulesets, check if it is a css guard and can be removed
if (rule instanceof Ruleset && rule.selectors && rule.selectors.length === 1) {
// check if it can be folded in (e.g. & where)
if (rule.selectors[0] && rule.selectors[0].isJustParentSelector()) {
rsRules.splice(i--, 1);
for (var j = 0; (subRule = rule.rules[j]); j++) {
if (subRule instanceof Node) {
subRule.copyVisibilityInfo(rule.visibilityInfo());
if (!(subRule instanceof Declaration) || !subRule.variable) {
rsRules.splice(++i, 0, subRule);
}
}
}
}
}
}
// Pop the stack
ctxFrames.shift();
ctxSelectors.shift();
if (context.mediaBlocks) {
for (i = mediaBlockCount; i < context.mediaBlocks.length; i++) {
context.mediaBlocks[i].bubbleSelectors(selectors);
}
}
return ruleset;
};
Ruleset.prototype.evalImports = function (context) {
var rules = this.rules;
var i;
var importRules;
if (!rules) {
return;
}
for (i = 0; i < rules.length; i++) {
if (rules[i].type === 'Import') {
importRules = rules[i].eval(context);
if (importRules && (importRules.length || importRules.length === 0)) {
rules.splice.apply(rules, [i, 1].concat(importRules));
i += importRules.length - 1;
}
else {
rules.splice(i, 1, importRules);
}
this.resetCache();
}
}
};
Ruleset.prototype.makeImportant = function () {
var result = new Ruleset(this.selectors, this.rules.map(function (r) {
if (r.makeImportant) {
return r.makeImportant();
}
else {
return r;
}
}), this.strictImports, this.visibilityInfo());
return result;
};
Ruleset.prototype.matchArgs = function (args) {
return !args || args.length === 0;
};
// lets you call a css selector with a guard
Ruleset.prototype.matchCondition = function (args, context) {
var lastSelector = this.selectors[this.selectors.length - 1];
if (!lastSelector.evaldCondition) {
return false;
}
if (lastSelector.condition &&
!lastSelector.condition.eval(new contexts.Eval(context, context.frames))) {
return false;
}
return true;
};
Ruleset.prototype.resetCache = function () {
this._rulesets = null;
this._variables = null;
this._properties = null;
this._lookups = {};
};
Ruleset.prototype.variables = function () {
if (!this._variables) {
this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) {
if (r instanceof Declaration && r.variable === true) {
hash[r.name] = r;
}
// when evaluating variables in an import statement, imports have not been eval'd
// so we need to go inside import statements.
// guard against root being a string (in the case of inlined less)
if (r.type === 'Import' && r.root && r.root.variables) {
var vars = r.root.variables();
for (var name_1 in vars) {
if (vars.hasOwnProperty(name_1)) {
hash[name_1] = r.root.variable(name_1);
}
}
}
return hash;
}, {});
}
return this._variables;
};
Ruleset.prototype.properties = function () {
if (!this._properties) {
this._properties = !this.rules ? {} : this.rules.reduce(function (hash, r) {
if (r instanceof Declaration && r.variable !== true) {
var name_2 = (r.name.length === 1) && (r.name[0] instanceof Keyword) ?
r.name[0].value : r.name;
// Properties don't overwrite as they can merge
if (!hash["$" + name_2]) {
hash["$" + name_2] = [r];
}
else {
hash["$" + name_2].push(r);
}
}
return hash;
}, {});
}
return this._properties;
};
Ruleset.prototype.variable = function (name) {
var decl = this.variables()[name];
if (decl) {
return this.parseValue(decl);
}
};
Ruleset.prototype.property = function (name) {
var decl = this.properties()[name];
if (decl) {
return this.parseValue(decl);
}
};
Ruleset.prototype.lastDeclaration = function () {
for (var i_1 = this.rules.length; i_1 > 0; i_1--) {
var decl = this.rules[i_1 - 1];
if (decl instanceof Declaration) {
return this.parseValue(decl);
}
}
};
Ruleset.prototype.parseValue = function (toParse) {
var self = this;
function transformDeclaration(decl) {
if (decl.value instanceof Anonymous && !decl.parsed) {
if (typeof decl.value.value === 'string') {
this.parse.parseNode(decl.value.value, ['value', 'important'], decl.value.getIndex(), decl.fileInfo(), function (err, result) {
if (err) {
decl.parsed = true;
}
if (result) {
decl.value = result[0];
decl.important = result[1] || '';
decl.parsed = true;
}
});
}
else {
decl.parsed = true;
}
return decl;
}
else {
return decl;
}
}
if (!Array.isArray(toParse)) {
return transformDeclaration.call(self, toParse);
}
else {
var nodes_1 = [];
toParse.forEach(function (n) {
nodes_1.push(transformDeclaration.call(self, n));
});
return nodes_1;
}
};
Ruleset.prototype.rulesets = function () {
if (!this.rules) {
return [];
}
var filtRules = [];
var rules = this.rules;
var i;
var rule;
for (i = 0; (rule = rules[i]); i++) {
if (rule.isRuleset) {
filtRules.push(rule);
}
}
return filtRules;
};
Ruleset.prototype.prependRule = function (rule) {
var rules = this.rules;
if (rules) {
rules.unshift(rule);
}
else {
this.rules = [rule];
}
this.setParent(rule, this);
};
Ruleset.prototype.find = function (selector, self, filter) {
if (self === void 0) { self = this; }
var rules = [];
var match;
var foundMixins;
var key = selector.toCSS();
if (key in this._lookups) {
return this._lookups[key];
}
this.rulesets().forEach(function (rule) {
if (rule !== self) {
for (var j = 0; j < rule.selectors.length; j++) {
match = selector.match(rule.selectors[j]);
if (match) {
if (selector.elements.length > match) {
if (!filter || filter(rule)) {
foundMixins = rule.find(new Selector(selector.elements.slice(match)), self, filter);
for (var i_2 = 0; i_2 < foundMixins.length; ++i_2) {
foundMixins[i_2].path.push(rule);
}
Array.prototype.push.apply(rules, foundMixins);
}
}
else {
rules.push({ rule: rule, path: [] });
}
break;
}
}
}
});
this._lookups[key] = rules;
return rules;
};
Ruleset.prototype.genCSS = function (context, output) {
var i;
var j;
var charsetRuleNodes = [];
var ruleNodes = [];
var // Line number debugging
debugInfo$1;
var rule;
var path;
context.tabLevel = (context.tabLevel || 0);
if (!this.root) {
context.tabLevel++;
}
var tabRuleStr = context.compress ? '' : Array(context.tabLevel + 1).join(' ');
var tabSetStr = context.compress ? '' : Array(context.tabLevel).join(' ');
var sep;
var charsetNodeIndex = 0;
var importNodeIndex = 0;
for (i = 0; (rule = this.rules[i]); i++) {
if (rule instanceof Comment) {
if (importNodeIndex === i) {
importNodeIndex++;
}
ruleNodes.push(rule);
}
else if (rule.isCharset && rule.isCharset()) {
ruleNodes.splice(charsetNodeIndex, 0, rule);
charsetNodeIndex++;
importNodeIndex++;
}
else if (rule.type === 'Import') {
ruleNodes.splice(importNodeIndex, 0, rule);
importNodeIndex++;
}
else {
ruleNodes.push(rule);
}
}
ruleNodes = charsetRuleNodes.concat(ruleNodes);
// If this is the root node, we don't render
// a selector, or {}.
if (!this.root) {
debugInfo$1 = debugInfo(context, this, tabSetStr);
if (debugInfo$1) {
output.add(debugInfo$1);
output.add(tabSetStr);
}
var paths = this.paths;
var pathCnt = paths.length;
var pathSubCnt = void 0;
sep = context.compress ? ',' : (",\n" + tabSetStr);
for (i = 0; i < pathCnt; i++) {
path = paths[i];
if (!(pathSubCnt = path.length)) {
continue;
}
if (i > 0) {
output.add(sep);
}
context.firstSelector = true;
path[0].genCSS(context, output);
context.firstSelector = false;
for (j = 1; j < pathSubCnt; j++) {
path[j].genCSS(context, output);
}
}
output.add((context.compress ? '{' : ' {\n') + tabRuleStr);
}
// Compile rules and rulesets
for (i = 0; (rule = ruleNodes[i]); i++) {
if (i + 1 === ruleNodes.length) {
context.lastRule = true;
}
var currentLastRule = context.lastRule;
if (rule.isRulesetLike(rule)) {
context.lastRule = false;
}
if (rule.genCSS) {
rule.genCSS(context, output);
}
else if (rule.value) {
output.add(rule.value.toString());
}
context.lastRule = currentLastRule;
if (!context.lastRule && rule.isVisible()) {
output.add(context.compress ? '' : ("\n" + tabRuleStr));
}
else {
context.lastRule = false;
}
}
if (!this.root) {
output.add((context.compress ? '}' : "\n" + tabSetStr + "}"));
context.tabLevel--;
}
if (!output.isEmpty() && !context.compress && this.firstRoot) {
output.add('\n');
}
};
Ruleset.prototype.joinSelectors = function (paths, context, selectors) {
for (var s = 0; s < selectors.length; s++) {
this.joinSelector(paths, context, selectors[s]);
}
};
Ruleset.prototype.joinSelector = function (paths, context, selector) {
function createParenthesis(elementsToPak, originalElement) {
var replacementParen;
var j;
if (elementsToPak.length === 0) {
replacementParen = new Paren(elementsToPak[0]);
}
else {
var insideParent = new Array(elementsToPak.length);
for (j = 0; j < elementsToPak.length; j++) {
insideParent[j] = new Element(null, elementsToPak[j], originalElement.isVariable, originalElement._index, originalElement._fileInfo);
}
replacementParen = new Paren(new Selector(insideParent));
}
return replacementParen;
}
function createSelector(containedElement, originalElement) {
var element;
var selector;
element = new Element(null, containedElement, originalElement.isVariable, originalElement._index, originalElement._fileInfo);
selector = new Selector([element]);
return selector;
}
// joins selector path from `beginningPath` with selector path in `addPath`
// `replacedElement` contains element that is being replaced by `addPath`
// returns concatenated path
function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {
var newSelectorPath;
var lastSelector;
var newJoinedSelector;
// our new selector path
newSelectorPath = [];
// construct the joined selector - if & is the first thing this will be empty,
// if not newJoinedSelector will be the last set of elements in the selector
if (beginningPath.length > 0) {
newSelectorPath = copyArray(beginningPath);
lastSelector = newSelectorPath.pop();
newJoinedSelector = originalSelector.createDerived(copyArray(lastSelector.elements));
}
else {
newJoinedSelector = originalSelector.createDerived([]);
}
if (addPath.length > 0) {
// /deep/ is a CSS4 selector - (removed, so should deprecate)
// that is valid without anything in front of it
// so if the & does not have a combinator that is "" or " " then
// and there is a combinator on the parent, then grab that.
// this also allows + a { & .b { .a & { ... though not sure why you would want to do that
var combinator = replacedElement.combinator;
var parentEl = addPath[0].elements[0];
if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {
combinator = parentEl.combinator;
}
// join the elements so far with the first part of the parent
newJoinedSelector.elements.push(new Element(combinator, parentEl.value, replacedElement.isVariable, replacedElement._index, replacedElement._fileInfo));
newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));
}
// now add the joined selector - but only if it is not empty
if (newJoinedSelector.elements.length !== 0) {
newSelectorPath.push(newJoinedSelector);
}
// put together the parent selectors after the join (e.g. the rest of the parent)
if (addPath.length > 1) {
var restOfPath = addPath.slice(1);
restOfPath = restOfPath.map(function (selector) { return selector.createDerived(selector.elements, []); });
newSelectorPath = newSelectorPath.concat(restOfPath);
}
return newSelectorPath;
}
// joins selector path from `beginningPath` with every selector path in `addPaths` array
// `replacedElement` contains element that is being replaced by `addPath`
// returns array with all concatenated paths
function addAllReplacementsIntoPath(beginningPath, addPaths, replacedElement, originalSelector, result) {
var j;
for (j = 0; j < beginningPath.length; j++) {
var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);
result.push(newSelectorPath);
}
return result;
}
function mergeElementsOnToSelectors(elements, selectors) {
var i;
var sel;
if (elements.length === 0) {
return;
}
if (selectors.length === 0) {
selectors.push([new Selector(elements)]);
return;
}
for (i = 0; (sel = selectors[i]); i++) {
// if the previous thing in sel is a parent this needs to join on to it
if (sel.length > 0) {
sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
}
else {
sel.push(new Selector(elements));
}
}
}
// replace all parent selectors inside `inSelector` by content of `context` array
// resulting selectors are returned inside `paths` array
// returns true if `inSelector` contained at least one parent selector
function replaceParentSelector(paths, context, inSelector) {
// The paths are [[Selector]]
// The first list is a list of comma separated selectors
// The inner list is a list of inheritance separated selectors
// e.g.
// .a, .b {
// .c {
// }
// }
// == [[.a] [.c]] [[.b] [.c]]
//
var i;
var j;
var k;
var currentElements;
var newSelectors;
var selectorsMultiplied;
var sel;
var el;
var hadParentSelector = false;
var length;
var lastSelector;
function findNestedSelector(element) {
var maybeSelector;
if (!(element.value instanceof Paren)) {
return null;
}
maybeSelector = element.value.value;
if (!(maybeSelector instanceof Selector)) {
return null;
}
return maybeSelector;
}
// the elements from the current selector so far
currentElements = [];
// the current list of new selectors to add to the path.
// We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
// by the parents
newSelectors = [
[]
];
for (i = 0; (el = inSelector.elements[i]); i++) {
// non parent reference elements just get added
if (el.value !== '&') {
var nestedSelector = findNestedSelector(el);
if (nestedSelector != null) {
// merge the current list of non parent selector elements
// on to the current list of selectors to add
mergeElementsOnToSelectors(currentElements, newSelectors);
var nestedPaths = [];
var replaced = void 0;
var replacedNewSelectors = [];
replaced = replaceParentSelector(nestedPaths, context, nestedSelector);
hadParentSelector = hadParentSelector || replaced;
// the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors
for (k = 0; k < nestedPaths.length; k++) {
var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);
addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);
}
newSelectors = replacedNewSelectors;
currentElements = [];
}
else {
currentElements.push(el);
}
}
else {
hadParentSelector = true;
// the new list of selectors to add
selectorsMultiplied = [];
// merge the current list of non parent selector elements
// on to the current list of selectors to add
mergeElementsOnToSelectors(currentElements, newSelectors);
// loop through our current selectors
for (j = 0; j < newSelectors.length; j++) {
sel = newSelectors[j];
// if we don't have any parent paths, the & might be in a mixin so that it can be used
// whether there are parents or not
if (context.length === 0) {
// the combinator used on el should now be applied to the next element instead so that
// it is not lost
if (sel.length > 0) {
sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo));
}
selectorsMultiplied.push(sel);
}
else {
// and the parent selectors
for (k = 0; k < context.length; k++) {
// We need to put the current selectors
// then join the last selector's elements on to the parents selectors
var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector);
// add that to our new set of selectors
selectorsMultiplied.push(newSelectorPath);
}
}
}
// our new selectors has been multiplied, so reset the state
newSelectors = selectorsMultiplied;
currentElements = [];
}
}
// if we have any elements left over (e.g. .a& .b == .b)
// add them on to all the current selectors
mergeElementsOnToSelectors(currentElements, newSelectors);
for (i = 0; i < newSelectors.length; i++) {
length = newSelectors[i].length;
if (length > 0) {
paths.push(newSelectors[i]);
lastSelector = newSelectors[i][length - 1];
newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);
}
}
return hadParentSelector;
}
function deriveSelector(visibilityInfo, deriveFrom) {
var newSelector = deriveFrom.createDerived(deriveFrom.elements, deriveFrom.extendList, deriveFrom.evaldCondition);
newSelector.copyVisibilityInfo(visibilityInfo);
return newSelector;
}
// joinSelector code follows
var i;
var newPaths;
var hadParentSelector;
newPaths = [];
hadParentSelector = replaceParentSelector(newPaths, context, selector);
if (!hadParentSelector) {
if (context.length > 0) {
newPaths = [];
for (i = 0; i < context.length; i++) {
var concatenated = context[i].map(deriveSelector.bind(this, selector.visibilityInfo()));
concatenated.push(selector);
newPaths.push(concatenated);
}
}
else {
newPaths = [[selector]];
}
}
for (i = 0; i < newPaths.length; i++) {
paths.push(newPaths[i]);
}
};
return Ruleset;
}(Node));
Ruleset.prototype.type = 'Ruleset';
Ruleset.prototype.isRuleset = true;
var AtRule = /** @class */ (function (_super) {
__extends(AtRule, _super);
function AtRule(name, value, rules, index, currentFileInfo, debugInfo, isRooted, visibilityInfo) {
var _this = _super.call(this) || this;
var i;
_this.name = name;
_this.value = (value instanceof Node) ? value : (value ? new Anonymous(value) : value);
if (rules) {
if (Array.isArray(rules)) {
_this.rules = rules;
}
else {
_this.rules = [rules];
_this.rules[0].selectors = (new Selector([], null, null, index, currentFileInfo)).createEmptySelectors();
}
for (i = 0; i < _this.rules.length; i++) {
_this.rules[i].allowImports = true;
}
_this.setParent(_this.rules, _this);
}
_this._index = index;
_this._fileInfo = currentFileInfo;
_this.debugInfo = debugInfo;
_this.isRooted = isRooted || false;
_this.copyVisibilityInfo(visibilityInfo);
_this.allowRoot = true;
return _this;
}
AtRule.prototype.accept = function (visitor) {
var value = this.value;
var rules = this.rules;
if (rules) {
this.rules = visitor.visitArray(rules);
}
if (value) {
this.value = visitor.visit(value);
}
};
AtRule.prototype.isRulesetLike = function () {
return this.rules || !this.isCharset();
};
AtRule.prototype.isCharset = function () {
return '@charset' === this.name;
};
AtRule.prototype.genCSS = function (context, output) {
var value = this.value;
var rules = this.rules;
output.add(this.name, this.fileInfo(), this.getIndex());
if (value) {
output.add(' ');
value.genCSS(context, output);
}
if (rules) {
this.outputRuleset(context, output, rules);
}
else {
output.add(';');
}
};
AtRule.prototype.eval = function (context) {
var mediaPathBackup;
var mediaBlocksBackup;
var value = this.value;
var rules = this.rules;
// media stored inside other atrule should not bubble over it
// backpup media bubbling information
mediaPathBackup = context.mediaPath;
mediaBlocksBackup = context.mediaBlocks;
// deleted media bubbling information
context.mediaPath = [];
context.mediaBlocks = [];
if (value) {
value = value.eval(context);
}
if (rules) {
// assuming that there is only one rule at this point - that is how parser constructs the rule
rules = [rules[0].eval(context)];
rules[0].root = true;
}
// restore media bubbling information
context.mediaPath = mediaPathBackup;
context.mediaBlocks = mediaBlocksBackup;
return new AtRule(this.name, value, rules, this.getIndex(), this.fileInfo(), this.debugInfo, this.isRooted, this.visibilityInfo());
};
AtRule.prototype.variable = function (name) {
if (this.rules) {
// assuming that there is only one rule at this point - that is how parser constructs the rule
return Ruleset.prototype.variable.call(this.rules[0], name);
}
};
AtRule.prototype.find = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (this.rules) {
// assuming that there is only one rule at this point - that is how parser constructs the rule
return Ruleset.prototype.find.apply(this.rules[0], args);
}
};
AtRule.prototype.rulesets = function () {
if (this.rules) {
// assuming that there is only one rule at this point - that is how parser constructs the rule
return Ruleset.prototype.rulesets.apply(this.rules[0]);
}
};
AtRule.prototype.outputRuleset = function (context, output, rules) {
var ruleCnt = rules.length;
var i;
context.tabLevel = (context.tabLevel | 0) + 1;
// Compressed
if (context.compress) {
output.add('{');
for (i = 0; i < ruleCnt; i++) {
rules[i].genCSS(context, output);
}
output.add('}');
context.tabLevel--;
return;
}
// Non-compressed
var tabSetStr = "\n" + Array(context.tabLevel).join(' ');
var tabRuleStr = tabSetStr + " ";
if (!ruleCnt) {
output.add(" {" + tabSetStr + "}");
}
else {
output.add(" {" + tabRuleStr);
rules[0].genCSS(context, output);
for (i = 1; i < ruleCnt; i++) {
output.add(tabRuleStr);
rules[i].genCSS(context, output);
}
output.add(tabSetStr + "}");
}
context.tabLevel--;
};
return AtRule;
}(Node));
AtRule.prototype.type = 'AtRule';
var DetachedRuleset = /** @class */ (function (_super) {
__extends(DetachedRuleset, _super);
function DetachedRuleset(ruleset, frames) {
var _this = _super.call(this) || this;
_this.ruleset = ruleset;
_this.frames = frames;
_this.setParent(_this.ruleset, _this);
return _this;
}
DetachedRuleset.prototype.accept = function (visitor) {
this.ruleset = visitor.visit(this.ruleset);
};
DetachedRuleset.prototype.eval = function (context) {
var frames = this.frames || copyArray(context.frames);
return new DetachedRuleset(this.ruleset, frames);
};
DetachedRuleset.prototype.callEval = function (context) {
return this.ruleset.eval(this.frames ? new contexts.Eval(context, this.frames.concat(context.frames)) : context);
};
return DetachedRuleset;
}(Node));
DetachedRuleset.prototype.type = 'DetachedRuleset';
DetachedRuleset.prototype.evalFirst = true;
var Unit = /** @class */ (function (_super) {
__extends(Unit, _super);
function Unit(numerator, denominator, backupUnit) {
var _this = _super.call(this) || this;
_this.numerator = numerator ? copyArray(numerator).sort() : [];
_this.denominator = denominator ? copyArray(denominator).sort() : [];
if (backupUnit) {
_this.backupUnit = backupUnit;
}
else if (numerator && numerator.length) {
_this.backupUnit = numerator[0];
}
return _this;
}
Unit.prototype.clone = function () {
return new Unit(copyArray(this.numerator), copyArray(this.denominator), this.backupUnit);
};
Unit.prototype.genCSS = function (context, output) {
// Dimension checks the unit is singular and throws an error if in strict math mode.
var strictUnits = context && context.strictUnits;
if (this.numerator.length === 1) {
output.add(this.numerator[0]); // the ideal situation
}
else if (!strictUnits && this.backupUnit) {
output.add(this.backupUnit);
}
else if (!strictUnits && this.denominator.length) {
output.add(this.denominator[0]);
}
};
Unit.prototype.toString = function () {
var i;
var returnStr = this.numerator.join('*');
for (i = 0; i < this.denominator.length; i++) {
returnStr += "/" + this.denominator[i];
}
return returnStr;
};
Unit.prototype.compare = function (other) {
return this.is(other.toString()) ? 0 : undefined;
};
Unit.prototype.is = function (unitString) {
return this.toString().toUpperCase() === unitString.toUpperCase();
};
Unit.prototype.isLength = function () {
return RegExp('^(px|em|ex|ch|rem|in|cm|mm|pc|pt|ex|vw|vh|vmin|vmax)$', 'gi').test(this.toCSS());
};
Unit.prototype.isEmpty = function () {
return this.numerator.length === 0 && this.denominator.length === 0;
};
Unit.prototype.isSingular = function () {
return this.numerator.length <= 1 && this.denominator.length === 0;
};
Unit.prototype.map = function (callback) {
var i;
for (i = 0; i < this.numerator.length; i++) {
this.numerator[i] = callback(this.numerator[i], false);
}
for (i = 0; i < this.denominator.length; i++) {
this.denominator[i] = callback(this.denominator[i], true);
}
};
Unit.prototype.usedUnits = function () {
var group;
var result = {};
var mapUnit;
var groupName;
mapUnit = function (atomicUnit) {
/* jshint loopfunc:true */
if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
result[groupName] = atomicUnit;
}
return atomicUnit;
};
for (groupName in unitConversions) {
if (unitConversions.hasOwnProperty(groupName)) {
group = unitConversions[groupName];
this.map(mapUnit);
}
}
return result;
};
Unit.prototype.cancel = function () {
var counter = {};
var atomicUnit;
var i;
for (i = 0; i < this.numerator.length; i++) {
atomicUnit = this.numerator[i];
counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
}
for (i = 0; i < this.denominator.length; i++) {
atomicUnit = this.denominator[i];
counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
}
this.numerator = [];
this.denominator = [];
for (atomicUnit in counter) {
if (counter.hasOwnProperty(atomicUnit)) {
var count = counter[atomicUnit];
if (count > 0) {
for (i = 0; i < count; i++) {
this.numerator.push(atomicUnit);
}
}
else if (count < 0) {
for (i = 0; i < -count; i++) {
this.denominator.push(atomicUnit);
}
}
}
}
this.numerator.sort();
this.denominator.sort();
};
return Unit;
}(Node));
Unit.prototype.type = 'Unit';
//
// A number with a unit
//
var Dimension = /** @class */ (function (_super) {
__extends(Dimension, _super);
function Dimension(value, unit) {
var _this = _super.call(this) || this;
_this.value = parseFloat(value);
if (isNaN(_this.value)) {
throw new Error('Dimension is not a number.');
}
_this.unit = (unit && unit instanceof Unit) ? unit :
new Unit(unit ? [unit] : undefined);
_this.setParent(_this.unit, _this);
return _this;
}
Dimension.prototype.accept = function (visitor) {
this.unit = visitor.visit(this.unit);
};
Dimension.prototype.eval = function (context) {
return this;
};
Dimension.prototype.toColor = function () {
return new Color([this.value, this.value, this.value]);
};
Dimension.prototype.genCSS = function (context, output) {
if ((context && context.strictUnits) && !this.unit.isSingular()) {
throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: " + this.unit.toString());
}
var value = this.fround(context, this.value);
var strValue = String(value);
if (value !== 0 && value < 0.000001 && value > -0.000001) {
// would be output 1e-6 etc.
strValue = value.toFixed(20).replace(/0+$/, '');
}
if (context && context.compress) {
// Zero values doesn't need a unit
if (value === 0 && this.unit.isLength()) {
output.add(strValue);
return;
}
// Float values doesn't need a leading zero
if (value > 0 && value < 1) {
strValue = (strValue).substr(1);
}
}
output.add(strValue);
this.unit.genCSS(context, output);
};
// In an operation between two Dimensions,
// we default to the first Dimension's unit,
// so `1px + 2` will yield `3px`.
Dimension.prototype.operate = function (context, op, other) {
/* jshint noempty:false */
var value = this._operate(context, op, this.value, other.value);
var unit = this.unit.clone();
if (op === '+' || op === '-') {
if (unit.numerator.length === 0 && unit.denominator.length === 0) {
unit = other.unit.clone();
if (this.unit.backupUnit) {
unit.backupUnit = this.unit.backupUnit;
}
}
else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) ;
else {
other = other.convertTo(this.unit.usedUnits());
if (context.strictUnits && other.unit.toString() !== unit.toString()) {
throw new Error("Incompatible units. Change the units or use the unit function. " +
("Bad units: '" + unit.toString() + "' and '" + other.unit.toString() + "'."));
}
value = this._operate(context, op, this.value, other.value);
}
}
else if (op === '*') {
unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
unit.cancel();
}
else if (op === '/') {
unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
unit.cancel();
}
return new Dimension(value, unit);
};
Dimension.prototype.compare = function (other) {
var a;
var b;
if (!(other instanceof Dimension)) {
return undefined;
}
if (this.unit.isEmpty() || other.unit.isEmpty()) {
a = this;
b = other;
}
else {
a = this.unify();
b = other.unify();
if (a.unit.compare(b.unit) !== 0) {
return undefined;
}
}
return Node.numericCompare(a.value, b.value);
};
Dimension.prototype.unify = function () {
return this.convertTo({ length: 'px', duration: 's', angle: 'rad' });
};
Dimension.prototype.convertTo = function (conversions) {
var value = this.value;
var unit = this.unit.clone();
var i;
var groupName;
var group;
var targetUnit;
var derivedConversions = {};
var applyUnit;
if (typeof conversions === 'string') {
for (i in unitConversions) {
if (unitConversions[i].hasOwnProperty(conversions)) {
derivedConversions = {};
derivedConversions[i] = conversions;
}
}
conversions = derivedConversions;
}
applyUnit = function (atomicUnit, denominator) {
/* jshint loopfunc:true */
if (group.hasOwnProperty(atomicUnit)) {
if (denominator) {
value = value / (group[atomicUnit] / group[targetUnit]);
}
else {
value = value * (group[atomicUnit] / group[targetUnit]);
}
return targetUnit;
}
return atomicUnit;
};
for (groupName in conversions) {
if (conversions.hasOwnProperty(groupName)) {
targetUnit = conversions[groupName];
group = unitConversions[groupName];
unit.map(applyUnit);
}
}
unit.cancel();
return new Dimension(value, unit);
};
return Dimension;
}(Node));
Dimension.prototype.type = 'Dimension';
var MATH$1 = Math$1;
var Operation = /** @class */ (function (_super) {
__extends(Operation, _super);
function Operation(op, operands, isSpaced) {
var _this = _super.call(this) || this;
_this.op = op.trim();
_this.operands = operands;
_this.isSpaced = isSpaced;
return _this;
}
Operation.prototype.accept = function (visitor) {
this.operands = visitor.visitArray(this.operands);
};
Operation.prototype.eval = function (context) {
var a = this.operands[0].eval(context);
var b = this.operands[1].eval(context);
var op;
if (context.isMathOn(this.op)) {
op = this.op === './' ? '/' : this.op;
if (a instanceof Dimension && b instanceof Color) {
a = a.toColor();
}
if (b instanceof Dimension && a instanceof Color) {
b = b.toColor();
}
if (!a.operate) {
if (a instanceof Operation && a.op === '/' && context.math === MATH$1.PARENS_DIVISION) {
return new Operation(this.op, [a, b], this.isSpaced);
}
throw { type: 'Operation',
message: 'Operation on an invalid type' };
}
return a.operate(context, op, b);
}
else {
return new Operation(this.op, [a, b], this.isSpaced);
}
};
Operation.prototype.genCSS = function (context, output) {
this.operands[0].genCSS(context, output);
if (this.isSpaced) {
output.add(' ');
}
output.add(this.op);
if (this.isSpaced) {
output.add(' ');
}
this.operands[1].genCSS(context, output);
};
return Operation;
}(Node));
Operation.prototype.type = 'Operation';
var MATH$2 = Math$1;
var Expression = /** @class */ (function (_super) {
__extends(Expression, _super);
function Expression(value, noSpacing) {
var _this = _super.call(this) || this;
_this.value = value;
_this.noSpacing = noSpacing;
if (!value) {
throw new Error('Expression requires an array parameter');
}
return _this;
}
Expression.prototype.accept = function (visitor) {
this.value = visitor.visitArray(this.value);
};
Expression.prototype.eval = function (context) {
var returnValue;
var mathOn = context.isMathOn();
var inParenthesis = this.parens &&
(context.math !== MATH$2.STRICT_LEGACY || !this.parensInOp);
var doubleParen = false;
if (inParenthesis) {
context.inParenthesis();
}
if (this.value.length > 1) {
returnValue = new Expression(this.value.map(function (e) {
if (!e.eval) {
return e;
}
return e.eval(context);
}), this.noSpacing);
}
else if (this.value.length === 1) {
if (this.value[0].parens && !this.value[0].parensInOp && !context.inCalc) {
doubleParen = true;
}
returnValue = this.value[0].eval(context);
}
else {
returnValue = this;
}
if (inParenthesis) {
context.outOfParenthesis();
}
if (this.parens && this.parensInOp && !mathOn && !doubleParen
&& (!(returnValue instanceof Dimension))) {
returnValue = new Paren(returnValue);
}
return returnValue;
};
Expression.prototype.genCSS = function (context, output) {
for (var i_1 = 0; i_1 < this.value.length; i_1++) {
this.value[i_1].genCSS(context, output);
if (!this.noSpacing && i_1 + 1 < this.value.length) {
output.add(' ');
}
}
};
Expression.prototype.throwAwayComments = function () {
this.value = this.value.filter(function (v) { return !(v instanceof Comment); });
};
return Expression;
}(Node));
Expression.prototype.type = 'Expression';
var functionCaller = /** @class */ (function () {
function functionCaller(name, context, index, currentFileInfo) {
this.name = name.toLowerCase();
this.index = index;
this.context = context;
this.currentFileInfo = currentFileInfo;
this.func = context.frames[0].functionRegistry.get(this.name);
}
functionCaller.prototype.isValid = function () {
return Boolean(this.func);
};
functionCaller.prototype.call = function (args) {
// This code is terrible and should be replaced as per this issue...
// https://github.com/less/less.js/issues/2477
if (Array.isArray(args)) {
args = args.filter(function (item) {
if (item.type === 'Comment') {
return false;
}
return true;
})
.map(function (item) {
if (item.type === 'Expression') {
var subNodes = item.value.filter(function (item) {
if (item.type === 'Comment') {
return false;
}
return true;
});
if (subNodes.length === 1) {
return subNodes[0];
}
else {
return new Expression(subNodes);
}
}
return item;
});
}
return this.func.apply(this, args);
};
return functionCaller;
}());
//
// A function call node.
//
var Call = /** @class */ (function (_super) {
__extends(Call, _super);
function Call(name, args, index, currentFileInfo) {
var _this = _super.call(this) || this;
_this.name = name;
_this.args = args;
_this.calc = name === 'calc';
_this._index = index;
_this._fileInfo = currentFileInfo;
return _this;
}
Call.prototype.accept = function (visitor) {
if (this.args) {
this.args = visitor.visitArray(this.args);
}
};
//
// When evaluating a function call,
// we either find the function in the functionRegistry,
// in which case we call it, passing the evaluated arguments,
// if this returns null or we cannot find the function, we
// simply print it out as it appeared originally [2].
//
// The reason why we evaluate the arguments, is in the case where
// we try to pass a variable to a function, like: `saturate(@color)`.
// The function should receive the value, not the variable.
//
Call.prototype.eval = function (context) {
/**
* Turn off math for calc(), and switch back on for evaluating nested functions
*/
var currentMathContext = context.mathOn;
context.mathOn = !this.calc;
if (this.calc || context.inCalc) {
context.enterCalc();
}
var args = this.args.map(function (a) { return a.eval(context); });
if (this.calc || context.inCalc) {
context.exitCalc();
}
context.mathOn = currentMathContext;
var result;
var funcCaller = new functionCaller(this.name, context, this.getIndex(), this.fileInfo());
if (funcCaller.isValid()) {
try {
result = funcCaller.call(args);
}
catch (e) {
throw {
type: e.type || 'Runtime',
message: "error evaluating function `" + this.name + "`" + (e.message ? ": " + e.message : ''),
index: this.getIndex(),
filename: this.fileInfo().filename,
line: e.lineNumber,
column: e.columnNumber
};
}
if (result !== null && result !== undefined) {
// Results that that are not nodes are cast as Anonymous nodes
// Falsy values or booleans are returned as empty nodes
if (!(result instanceof Node)) {
if (!result || result === true) {
result = new Anonymous(null);
}
else {
result = new Anonymous(result.toString());
}
}
result._index = this._index;
result._fileInfo = this._fileInfo;
return result;
}
}
return new Call(this.name, args, this.getIndex(), this.fileInfo());
};
Call.prototype.genCSS = function (context, output) {
output.add(this.name + "(", this.fileInfo(), this.getIndex());
for (var i_1 = 0; i_1 < this.args.length; i_1++) {
this.args[i_1].genCSS(context, output);
if (i_1 + 1 < this.args.length) {
output.add(', ');
}
}
output.add(')');
};
return Call;
}(Node));
Call.prototype.type = 'Call';
var Variable = /** @class */ (function (_super) {
__extends(Variable, _super);
function Variable(name, index, currentFileInfo) {
var _this = _super.call(this) || this;
_this.name = name;
_this._index = index;
_this._fileInfo = currentFileInfo;
return _this;
}
Variable.prototype.eval = function (context) {
var variable;
var name = this.name;
if (name.indexOf('@@') === 0) {
name = "@" + new Variable(name.slice(1), this.getIndex(), this.fileInfo()).eval(context).value;
}
if (this.evaluating) {
throw { type: 'Name',
message: "Recursive variable definition for " + name,
filename: this.fileInfo().filename,
index: this.getIndex() };
}
this.evaluating = true;
variable = this.find(context.frames, function (frame) {
var v = frame.variable(name);
if (v) {
if (v.important) {
var importantScope = context.importantScope[context.importantScope.length - 1];
importantScope.important = v.important;
}
// If in calc, wrap vars in a function call to cascade evaluate args first
if (context.inCalc) {
return (new Call('_SELF', [v.value])).eval(context);
}
else {
return v.value.eval(context);
}
}
});
if (variable) {
this.evaluating = false;
return variable;
}
else {
throw { type: 'Name',
message: "variable " + name + " is undefined",
filename: this.fileInfo().filename,
index: this.getIndex() };
}
};
Variable.prototype.find = function (obj, fun) {
for (var i_1 = 0, r = void 0; i_1 < obj.length; i_1++) {
r = fun.call(obj, obj[i_1]);
if (r) {
return r;
}
}
return null;
};
return Variable;
}(Node));
Variable.prototype.type = 'Variable';
var Property = /** @class */ (function (_super) {
__extends(Property, _super);
function Property(name, index, currentFileInfo) {
var _this = _super.call(this) || this;
_this.name = name;
_this._index = index;
_this._fileInfo = currentFileInfo;
return _this;
}
Property.prototype.eval = function (context) {
var property;
var name = this.name;
// TODO: shorten this reference
var mergeRules = context.pluginManager.less.visitors.ToCSSVisitor.prototype._mergeRules;
if (this.evaluating) {
throw { type: 'Name',
message: "Recursive property reference for " + name,
filename: this.fileInfo().filename,
index: this.getIndex() };
}
this.evaluating = true;
property = this.find(context.frames, function (frame) {
var v;
var vArr = frame.property(name);
if (vArr) {
for (var i_1 = 0; i_1 < vArr.length; i_1++) {
v = vArr[i_1];
vArr[i_1] = new Declaration(v.name, v.value, v.important, v.merge, v.index, v.currentFileInfo, v.inline, v.variable);
}
mergeRules(vArr);
v = vArr[vArr.length - 1];
if (v.important) {
var importantScope = context.importantScope[context.importantScope.length - 1];
importantScope.important = v.important;
}
v = v.value.eval(context);
return v;
}
});
if (property) {
this.evaluating = false;
return property;
}
else {
throw { type: 'Name',
message: "Property '" + name + "' is undefined",
filename: this.currentFileInfo.filename,
index: this.index };
}
};
Property.prototype.find = function (obj, fun) {
for (var i_2 = 0, r = void 0; i_2 < obj.length; i_2++) {
r = fun.call(obj, obj[i_2]);
if (r) {
return r;
}
}
return null;
};
return Property;
}(Node));
Property.prototype.type = 'Property';
var Attribute = /** @class */ (function (_super) {
__extends(Attribute, _super);
function Attribute(key, op, value) {
var _this = _super.call(this) || this;
_this.key = key;
_this.op = op;
_this.value = value;
return _this;
}
Attribute.prototype.eval = function (context) {
return new Attribute(this.key.eval ? this.key.eval(context) : this.key, this.op, (this.value && this.value.eval) ? this.value.eval(context) : this.value);
};
Attribute.prototype.genCSS = function (context, output) {
output.add(this.toCSS(context));
};
Attribute.prototype.toCSS = function (context) {
var value = this.key.toCSS ? this.key.toCSS(context) : this.key;
if (this.op) {
value += this.op;
value += (this.value.toCSS ? this.value.toCSS(context) : this.value);
}
return "[" + value + "]";
};
return Attribute;
}(Node));
Attribute.prototype.type = 'Attribute';
var Quoted = /** @class */ (function (_super) {
__extends(Quoted, _super);
function Quoted(str, content, escaped, index, currentFileInfo) {
var _this = _super.call(this) || this;
_this.escaped = (escaped == null) ? true : escaped;
_this.value = content || '';
_this.quote = str.charAt(0);
_this._index = index;
_this._fileInfo = currentFileInfo;
_this.variableRegex = /@\{([\w-]+)\}/g;
_this.propRegex = /\$\{([\w-]+)\}/g;
_this.allowRoot = escaped;
return _this;
}
Quoted.prototype.genCSS = function (context, output) {
if (!this.escaped) {
output.add(this.quote, this.fileInfo(), this.getIndex());
}
output.add(this.value);
if (!this.escaped) {
output.add(this.quote);
}
};
Quoted.prototype.containsVariables = function () {
return this.value.match(this.variableRegex);
};
Quoted.prototype.eval = function (context) {
var that = this;
var value = this.value;
var variableReplacement = function (_, name) {
var v = new Variable("@" + name, that.getIndex(), that.fileInfo()).eval(context, true);
return (v instanceof Quoted) ? v.value : v.toCSS();
};
var propertyReplacement = function (_, name) {
var v = new Property("$" + name, that.getIndex(), that.fileInfo()).eval(context, true);
return (v instanceof Quoted) ? v.value : v.toCSS();
};
function iterativeReplace(value, regexp, replacementFnc) {
var evaluatedValue = value;
do {
value = evaluatedValue.toString();
evaluatedValue = value.replace(regexp, replacementFnc);
} while (value !== evaluatedValue);
return evaluatedValue;
}
value = iterativeReplace(value, this.variableRegex, variableReplacement);
value = iterativeReplace(value, this.propRegex, propertyReplacement);
return new Quoted(this.quote + value + this.quote, value, this.escaped, this.getIndex(), this.fileInfo());
};
Quoted.prototype.compare = function (other) {
// when comparing quoted strings allow the quote to differ
if (other.type === 'Quoted' && !this.escaped && !other.escaped) {
return Node.numericCompare(this.value, other.value);
}
else {
return other.toCSS && this.toCSS() === other.toCSS() ? 0 : undefined;
}
};
return Quoted;
}(Node));
Quoted.prototype.type = 'Quoted';
var URL = /** @class */ (function (_super) {
__extends(URL, _super);
function URL(val, index, currentFileInfo, isEvald) {
var _this = _super.call(this) || this;
_this.value = val;
_this._index = index;
_this._fileInfo = currentFileInfo;
_this.isEvald = isEvald;
return _this;
}
URL.prototype.accept = function (visitor) {
this.value = visitor.visit(this.value);
};
URL.prototype.genCSS = function (context, output) {
output.add('url(');
this.value.genCSS(context, output);
output.add(')');
};
URL.prototype.eval = function (context) {
var val = this.value.eval(context);
var rootpath;
if (!this.isEvald) {
// Add the rootpath if the URL requires a rewrite
rootpath = this.fileInfo() && this.fileInfo().rootpath;
if (typeof rootpath === 'string' &&
typeof val.value === 'string' &&
context.pathRequiresRewrite(val.value)) {
if (!val.quote) {
rootpath = escapePath(rootpath);
}
val.value = context.rewritePath(val.value, rootpath);
}
else {
val.value = context.normalizePath(val.value);
}
// Add url args if enabled
if (context.urlArgs) {
if (!val.value.match(/^\s*data:/)) {
var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
var urlArgs = delimiter + context.urlArgs;
if (val.value.indexOf('#') !== -1) {
val.value = val.value.replace('#', urlArgs + "#");
}
else {
val.value += urlArgs;
}
}
}
}
return new URL(val, this.getIndex(), this.fileInfo(), true);
};
return URL;
}(Node));
URL.prototype.type = 'Url';
function escapePath(path) {
return path.replace(/[\(\)'"\s]/g, function (match) { return "\\" + match; });
}
var Media = /** @class */ (function (_super) {
__extends(Media, _super);
function Media(value, features, index, currentFileInfo, visibilityInfo) {
var _this = _super.call(this) || this;
_this._index = index;
_this._fileInfo = currentFileInfo;
var selectors = (new Selector([], null, null, _this._index, _this._fileInfo)).createEmptySelectors();
_this.features = new Value(features);
_this.rules = [new Ruleset(selectors, value)];
_this.rules[0].allowImports = true;
_this.copyVisibilityInfo(visibilityInfo);
_this.allowRoot = true;
_this.setParent(selectors, _this);
_this.setParent(_this.features, _this);
_this.setParent(_this.rules, _this);
return _this;
}
Media.prototype.isRulesetLike = function () {
return true;
};
Media.prototype.accept = function (visitor) {
if (this.features) {
this.features = visitor.visit(this.features);
}
if (this.rules) {
this.rules = visitor.visitArray(this.rules);
}
};
Media.prototype.genCSS = function (context, output) {
output.add('@media ', this._fileInfo, this._index);
this.features.genCSS(context, output);
this.outputRuleset(context, output, this.rules);
};
Media.prototype.eval = function (context) {
if (!context.mediaBlocks) {
context.mediaBlocks = [];
context.mediaPath = [];
}
var media = new Media(null, [], this._index, this._fileInfo, this.visibilityInfo());
if (this.debugInfo) {
this.rules[0].debugInfo = this.debugInfo;
media.debugInfo = this.debugInfo;
}
media.features = this.features.eval(context);
context.mediaPath.push(media);
context.mediaBlocks.push(media);
this.rules[0].functionRegistry = context.frames[0].functionRegistry.inherit();
context.frames.unshift(this.rules[0]);
media.rules = [this.rules[0].eval(context)];
context.frames.shift();
context.mediaPath.pop();
return context.mediaPath.length === 0 ? media.evalTop(context) :
media.evalNested(context);
};
Media.prototype.evalTop = function (context) {
var result = this;
// Render all dependent Media blocks.
if (context.mediaBlocks.length > 1) {
var selectors = (new Selector([], null, null, this.getIndex(), this.fileInfo())).createEmptySelectors();
result = new Ruleset(selectors, context.mediaBlocks);
result.multiMedia = true;
result.copyVisibilityInfo(this.visibilityInfo());
this.setParent(result, this);
}
delete context.mediaBlocks;
delete context.mediaPath;
return result;
};
Media.prototype.evalNested = function (context) {
var i;
var value;
var path = context.mediaPath.concat([this]);
// Extract the media-query conditions separated with `,` (OR).
for (i = 0; i < path.length; i++) {
value = path[i].features instanceof Value ?
path[i].features.value : path[i].features;
path[i] = Array.isArray(value) ? value : [value];
}
// Trace all permutations to generate the resulting media-query.
//
// (a, b and c) with nested (d, e) ->
// a and d
// a and e
// b and c and d
// b and c and e
this.features = new Value(this.permute(path).map(function (path) {
path = path.map(function (fragment) { return fragment.toCSS ? fragment : new Anonymous(fragment); });
for (i = path.length - 1; i > 0; i--) {
path.splice(i, 0, new Anonymous('and'));
}
return new Expression(path);
}));
this.setParent(this.features, this);
// Fake a tree-node that doesn't output anything.
return new Ruleset([], []);
};
Media.prototype.permute = function (arr) {
if (arr.length === 0) {
return [];
}
else if (arr.length === 1) {
return arr[0];
}
else {
var result = [];
var rest = this.permute(arr.slice(1));
for (var i_1 = 0; i_1 < rest.length; i_1++) {
for (var j = 0; j < arr[0].length; j++) {
result.push([arr[0][j]].concat(rest[i_1]));
}
}
return result;
}
};
Media.prototype.bubbleSelectors = function (selectors) {
if (!selectors) {
return;
}
this.rules = [new Ruleset(copyArray(selectors), [this.rules[0]])];
this.setParent(this.rules, this);
};
return Media;
}(AtRule));
Media.prototype.type = 'Media';
//
// CSS @import node
//
// The general strategy here is that we don't want to wait
// for the parsing to be completed, before we start importing
// the file. That's because in the context of a browser,
// most of the time will be spent waiting for the server to respond.
//
// On creation, we push the import path to our import queue, though
// `import,push`, we also pass it a callback, which it'll call once
// the file has been fetched, and parsed.
//
var Import = /** @class */ (function (_super) {
__extends(Import, _super);
function Import(path, features, options, index, currentFileInfo, visibilityInfo) {
var _this = _super.call(this) || this;
_this.options = options;
_this._index = index;
_this._fileInfo = currentFileInfo;
_this.path = path;
_this.features = features;
_this.allowRoot = true;
if (_this.options.less !== undefined || _this.options.inline) {
_this.css = !_this.options.less || _this.options.inline;
}
else {
var pathValue = _this.getPath();
if (pathValue && /[#\.\&\?]css([\?;].*)?$/.test(pathValue)) {
_this.css = true;
}
}
_this.copyVisibilityInfo(visibilityInfo);
_this.setParent(_this.features, _this);
_this.setParent(_this.path, _this);
return _this;
}
Import.prototype.accept = function (visitor) {
if (this.features) {
this.features = visitor.visit(this.features);
}
this.path = visitor.visit(this.path);
if (!this.options.isPlugin && !this.options.inline && this.root) {
this.root = visitor.visit(this.root);
}
};
Import.prototype.genCSS = function (context, output) {
if (this.css && this.path._fileInfo.reference === undefined) {
output.add('@import ', this._fileInfo, this._index);
this.path.genCSS(context, output);
if (this.features) {
output.add(' ');
this.features.genCSS(context, output);
}
output.add(';');
}
};
Import.prototype.getPath = function () {
return (this.path instanceof URL) ?
this.path.value.value : this.path.value;
};
Import.prototype.isVariableImport = function () {
var path = this.path;
if (path instanceof URL) {
path = path.value;
}
if (path instanceof Quoted) {
return path.containsVariables();
}
return true;
};
Import.prototype.evalForImport = function (context) {
var path = this.path;
if (path instanceof URL) {
path = path.value;
}
return new Import(path.eval(context), this.features, this.options, this._index, this._fileInfo, this.visibilityInfo());
};
Import.prototype.evalPath = function (context) {
var path = this.path.eval(context);
var fileInfo = this._fileInfo;
if (!(path instanceof URL)) {
// Add the rootpath if the URL requires a rewrite
var pathValue = path.value;
if (fileInfo &&
pathValue &&
context.pathRequiresRewrite(pathValue)) {
path.value = context.rewritePath(pathValue, fileInfo.rootpath);
}
else {
path.value = context.normalizePath(path.value);
}
}
return path;
};
Import.prototype.eval = function (context) {
var result = this.doEval(context);
if (this.options.reference || this.blocksVisibility()) {
if (result.length || result.length === 0) {
result.forEach(function (node) {
node.addVisibilityBlock();
});
}
else {
result.addVisibilityBlock();
}
}
return result;
};
Import.prototype.doEval = function (context) {
var ruleset;
var registry;
var features = this.features && this.features.eval(context);
if (this.options.isPlugin) {
if (this.root && this.root.eval) {
try {
this.root.eval(context);
}
catch (e) {
e.message = 'Plugin error during evaluation';
throw new LessError(e, this.root.imports, this.root.filename);
}
}
registry = context.frames[0] && context.frames[0].functionRegistry;
if (registry && this.root && this.root.functions) {
registry.addMultiple(this.root.functions);
}
return [];
}
if (this.skip) {
if (typeof this.skip === 'function') {
this.skip = this.skip();
}
if (this.skip) {
return [];
}
}
if (this.options.inline) {
var contents = new Anonymous(this.root, 0, {
filename: this.importedFilename,
reference: this.path._fileInfo && this.path._fileInfo.reference
}, true, true);
return this.features ? new Media([contents], this.features.value) : [contents];
}
else if (this.css) {
var newImport = new Import(this.evalPath(context), features, this.options, this._index);
if (!newImport.css && this.error) {
throw this.error;
}
return newImport;
}
else {
ruleset = new Ruleset(null, copyArray(this.root.rules));
ruleset.evalImports(context);
return this.features ? new Media(ruleset.rules, this.features.value) : ruleset.rules;
}
};
return Import;
}(Node));
Import.prototype.type = 'Import';
var JsEvalNode = /** @class */ (function (_super) {
__extends(JsEvalNode, _super);
function JsEvalNode() {
return _super !== null && _super.apply(this, arguments) || this;
}
JsEvalNode.prototype.evaluateJavaScript = function (expression, context) {
var result;
var that = this;
var evalContext = {};
if (!context.javascriptEnabled) {
throw { message: 'Inline JavaScript is not enabled. Is it set in your options?',
filename: this.fileInfo().filename,
index: this.getIndex() };
}
expression = expression.replace(/@\{([\w-]+)\}/g, function (_, name) { return that.jsify(new Variable("@" + name, that.getIndex(), that.fileInfo()).eval(context)); });
try {
expression = new Function("return (" + expression + ")");
}
catch (e) {
throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`",
filename: this.fileInfo().filename,
index: this.getIndex() };
}
var variables = context.frames[0].variables();
for (var k in variables) {
if (variables.hasOwnProperty(k)) {
/* jshint loopfunc:true */
evalContext[k.slice(1)] = {
value: variables[k].value,
toJS: function () {
return this.value.eval(context).toCSS();
}
};
}
}
try {
result = expression.call(evalContext);
}
catch (e) {
throw { message: "JavaScript evaluation error: '" + e.name + ": " + e.message.replace(/["]/g, '\'') + "'",
filename: this.fileInfo().filename,
index: this.getIndex() };
}
return result;
};
JsEvalNode.prototype.jsify = function (obj) {
if (Array.isArray(obj.value) && (obj.value.length > 1)) {
return "[" + obj.value.map(function (v) { return v.toCSS(); }).join(', ') + "]";
}
else {
return obj.toCSS();
}
};
return JsEvalNode;
}(Node));
var JavaScript = /** @class */ (function (_super) {
__extends(JavaScript, _super);
function JavaScript(string, escaped, index, currentFileInfo) {
var _this = _super.call(this) || this;
_this.escaped = escaped;
_this.expression = string;
_this._index = index;
_this._fileInfo = currentFileInfo;
return _this;
}
JavaScript.prototype.eval = function (context) {
var result = this.evaluateJavaScript(this.expression, context);
var type = typeof result;
if (type === 'number' && !isNaN(result)) {
return new Dimension(result);
}
else if (type === 'string') {
return new Quoted("\"" + result + "\"", result, this.escaped, this._index);
}
else if (Array.isArray(result)) {
return new Anonymous(result.join(', '));
}
else {
return new Anonymous(result);
}
};
return JavaScript;
}(JsEvalNode));
JavaScript.prototype.type = 'JavaScript';
var Assignment = /** @class */ (function (_super) {
__extends(Assignment, _super);
function Assignment(key, val) {
var _this = _super.call(this) || this;
_this.key = key;
_this.value = val;
return _this;
}
Assignment.prototype.accept = function (visitor) {
this.value = visitor.visit(this.value);
};
Assignment.prototype.eval = function (context) {
if (this.value.eval) {
return new Assignment(this.key, this.value.eval(context));
}
return this;
};
Assignment.prototype.genCSS = function (context, output) {
output.add(this.key + "=");
if (this.value.genCSS) {
this.value.genCSS(context, output);
}
else {
output.add(this.value);
}
};
return Assignment;
}(Node));
Assignment.prototype.type = 'Assignment';
var Condition = /** @class */ (function (_super) {
__extends(Condition, _super);
function Condition(op, l, r, i, negate) {
var _this = _super.call(this) || this;
_this.op = op.trim();
_this.lvalue = l;
_this.rvalue = r;
_this._index = i;
_this.negate = negate;
return _this;
}
Condition.prototype.accept = function (visitor) {
this.lvalue = visitor.visit(this.lvalue);
this.rvalue = visitor.visit(this.rvalue);
};
Condition.prototype.eval = function (context) {
var result = (function (op, a, b) {
switch (op) {
case 'and': return a && b;
case 'or': return a || b;
default:
switch (Node.compare(a, b)) {
case -1:
return op === '<' || op === '=<' || op === '<=';
case 0:
return op === '=' || op === '>=' || op === '=<' || op === '<=';
case 1:
return op === '>' || op === '>=';
default:
return false;
}
}
})(this.op, this.lvalue.eval(context), this.rvalue.eval(context));
return this.negate ? !result : result;
};
return Condition;
}(Node));
Condition.prototype.type = 'Condition';
var UnicodeDescriptor = /** @class */ (function (_super) {
__extends(UnicodeDescriptor, _super);
function UnicodeDescriptor(value) {
var _this = _super.call(this) || this;
_this.value = value;
return _this;
}
return UnicodeDescriptor;
}(Node));
UnicodeDescriptor.prototype.type = 'UnicodeDescriptor';
var Negative = /** @class */ (function (_super) {
__extends(Negative, _super);
function Negative(node) {
var _this = _super.call(this) || this;
_this.value = node;
return _this;
}
Negative.prototype.genCSS = function (context, output) {
output.add('-');
this.value.genCSS(context, output);
};
Negative.prototype.eval = function (context) {
if (context.isMathOn()) {
return (new Operation('*', [new Dimension(-1), this.value])).eval(context);
}
return new Negative(this.value.eval(context));
};
return Negative;
}(Node));
Negative.prototype.type = 'Negative';
var Extend = /** @class */ (function (_super) {
__extends(Extend, _super);
function Extend(selector, option, index, currentFileInfo, visibilityInfo) {
var _this = _super.call(this) || this;
_this.selector = selector;
_this.option = option;
_this.object_id = Extend.next_id++;
_this.parent_ids = [_this.object_id];
_this._index = index;
_this._fileInfo = currentFileInfo;
_this.copyVisibilityInfo(visibilityInfo);
_this.allowRoot = true;
switch (option) {
case 'all':
_this.allowBefore = true;
_this.allowAfter = true;
break;
default:
_this.allowBefore = false;
_this.allowAfter = false;
break;
}
_this.setParent(_this.selector, _this);
return _this;
}
Extend.prototype.accept = function (visitor) {
this.selector = visitor.visit(this.selector);
};
Extend.prototype.eval = function (context) {
return new Extend(this.selector.eval(context), this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
};
Extend.prototype.clone = function (context) {
return new Extend(this.selector, this.option, this.getIndex(), this.fileInfo(), this.visibilityInfo());
};
// it concatenates (joins) all selectors in selector array
Extend.prototype.findSelfSelectors = function (selectors) {
var selfElements = [];
var i;
var selectorElements;
for (i = 0; i < selectors.length; i++) {
selectorElements = selectors[i].elements;
// duplicate the logic in genCSS function inside the selector node.
// future TODO - move both logics into the selector joiner visitor
if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === '') {
selectorElements[0].combinator.value = ' ';
}
selfElements = selfElements.concat(selectors[i].elements);
}
this.selfSelectors = [new Selector(selfElements)];
this.selfSelectors[0].copyVisibilityInfo(this.visibilityInfo());
};
return Extend;
}(Node));
Extend.next_id = 0;
Extend.prototype.type = 'Extend';
var VariableCall = /** @class */ (function (_super) {
__extends(VariableCall, _super);
function VariableCall(variable, index, currentFileInfo) {
var _this = _super.call(this) || this;
_this.variable = variable;
_this._index = index;
_this._fileInfo = currentFileInfo;
_this.allowRoot = true;
return _this;
}
VariableCall.prototype.eval = function (context) {
var rules;
var detachedRuleset = new Variable(this.variable, this.getIndex(), this.fileInfo()).eval(context);
var error = new LessError({ message: "Could not evaluate variable call " + this.variable });
if (!detachedRuleset.ruleset) {
if (detachedRuleset.rules) {
rules = detachedRuleset;
}
else if (Array.isArray(detachedRuleset)) {
rules = new Ruleset('', detachedRuleset);
}
else if (Array.isArray(detachedRuleset.value)) {
rules = new Ruleset('', detachedRuleset.value);
}
else {
throw error;
}
detachedRuleset = new DetachedRuleset(rules);
}
if (detachedRuleset.ruleset) {
return detachedRuleset.callEval(context);
}
throw error;
};
return VariableCall;
}(Node));
VariableCall.prototype.type = 'VariableCall';
var NamespaceValue = /** @class */ (function (_super) {
__extends(NamespaceValue, _super);
function NamespaceValue(ruleCall, lookups, index, fileInfo) {
var _this = _super.call(this) || this;
_this.value = ruleCall;
_this.lookups = lookups;
_this._index = index;
_this._fileInfo = fileInfo;
return _this;
}
NamespaceValue.prototype.eval = function (context) {
var i;
var name;
var rules = this.value.eval(context);
for (i = 0; i < this.lookups.length; i++) {
name = this.lookups[i];
/**
* Eval'd DRs return rulesets.
* Eval'd mixins return rules, so let's make a ruleset if we need it.
* We need to do this because of late parsing of values
*/
if (Array.isArray(rules)) {
rules = new Ruleset([new Selector()], rules);
}
if (name === '') {
rules = rules.lastDeclaration();
}
else if (name.charAt(0) === '@') {
if (name.charAt(1) === '@') {
name = "@" + new Variable(name.substr(1)).eval(context).value;
}
if (rules.variables) {
rules = rules.variable(name);
}
if (!rules) {
throw { type: 'Name',
message: "variable " + name + " not found",
filename: this.fileInfo().filename,
index: this.getIndex() };
}
}
else {
if (name.substring(0, 2) === '$@') {
name = "$" + new Variable(name.substr(1)).eval(context).value;
}
else {
name = name.charAt(0) === '$' ? name : "$" + name;
}
if (rules.properties) {
rules = rules.property(name);
}
if (!rules) {
throw { type: 'Name',
message: "property \"" + name.substr(1) + "\" not found",
filename: this.fileInfo().filename,
index: this.getIndex() };
}
// Properties are an array of values, since a ruleset can have multiple props.
// We pick the last one (the "cascaded" value)
rules = rules[rules.length - 1];
}
if (rules.value) {
rules = rules.eval(context).value;
}
if (rules.ruleset) {
rules = rules.ruleset.eval(context);
}
}
return rules;
};
return NamespaceValue;
}(Node));
NamespaceValue.prototype.type = 'NamespaceValue';
var Definition = /** @class */ (function (_super) {
__extends(Definition, _super);
function Definition(name, params, rules, condition, variadic, frames, visibilityInfo) {
var _this = _super.call(this) || this;
_this.name = name || 'anonymous mixin';
_this.selectors = [new Selector([new Element(null, name, false, _this._index, _this._fileInfo)])];
_this.params = params;
_this.condition = condition;
_this.variadic = variadic;
_this.arity = params.length;
_this.rules = rules;
_this._lookups = {};
var optionalParameters = [];
_this.required = params.reduce(function (count, p) {
if (!p.name || (p.name && !p.value)) {
return count + 1;
}
else {
optionalParameters.push(p.name);
return count;
}
}, 0);
_this.optionalParameters = optionalParameters;
_this.frames = frames;
_this.copyVisibilityInfo(visibilityInfo);
_this.allowRoot = true;
return _this;
}
Definition.prototype.accept = function (visitor) {
if (this.params && this.params.length) {
this.params = visitor.visitArray(this.params);
}
this.rules = visitor.visitArray(this.rules);
if (this.condition) {
this.condition = visitor.visit(this.condition);
}
};
Definition.prototype.evalParams = function (context, mixinEnv, args, evaldArguments) {
/* jshint boss:true */
var frame = new Ruleset(null, null);
var varargs;
var arg;
var params = copyArray(this.params);
var i;
var j;
var val;
var name;
var isNamedFound;
var argIndex;
var argsLength = 0;
if (mixinEnv.frames && mixinEnv.frames[0] && mixinEnv.frames[0].functionRegistry) {
frame.functionRegistry = mixinEnv.frames[0].functionRegistry.inherit();
}
mixinEnv = new contexts.Eval(mixinEnv, [frame].concat(mixinEnv.frames));
if (args) {
args = copyArray(args);
argsLength = args.length;
for (i = 0; i < argsLength; i++) {
arg = args[i];
if (name = (arg && arg.name)) {
isNamedFound = false;
for (j = 0; j < params.length; j++) {
if (!evaldArguments[j] && name === params[j].name) {
evaldArguments[j] = arg.value.eval(context);
frame.prependRule(new Declaration(name, arg.value.eval(context)));
isNamedFound = true;
break;
}
}
if (isNamedFound) {
args.splice(i, 1);
i--;
continue;
}
else {
throw { type: 'Runtime', message: "Named argument for " + this.name + " " + args[i].name + " not found" };
}
}
}
}
argIndex = 0;
for (i = 0; i < params.length; i++) {
if (evaldArguments[i]) {
continue;
}
arg = args && args[argIndex];
if (name = params[i].name) {
if (params[i].variadic) {
varargs = [];
for (j = argIndex; j < argsLength; j++) {
varargs.push(args[j].value.eval(context));
}
frame.prependRule(new Declaration(name, new Expression(varargs).eval(context)));
}
else {
val = arg && arg.value;
if (val) {
// This was a mixin call, pass in a detached ruleset of it's eval'd rules
if (Array.isArray(val)) {
val = new DetachedRuleset(new Ruleset('', val));
}
else {
val = val.eval(context);
}
}
else if (params[i].value) {
val = params[i].value.eval(mixinEnv);
frame.resetCache();
}
else {
throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + " (" + argsLength + " for " + this.arity + ")" };
}
frame.prependRule(new Declaration(name, val));
evaldArguments[i] = val;
}
}
if (params[i].variadic && args) {
for (j = argIndex; j < argsLength; j++) {
evaldArguments[j] = args[j].value.eval(context);
}
}
argIndex++;
}
return frame;
};
Definition.prototype.makeImportant = function () {
var rules = !this.rules ? this.rules : this.rules.map(function (r) {
if (r.makeImportant) {
return r.makeImportant(true);
}
else {
return r;
}
});
var result = new Definition(this.name, this.params, rules, this.condition, this.variadic, this.frames);
return result;
};
Definition.prototype.eval = function (context) {
return new Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || copyArray(context.frames));
};
Definition.prototype.evalCall = function (context, args, important) {
var _arguments = [];
var mixinFrames = this.frames ? this.frames.concat(context.frames) : context.frames;
var frame = this.evalParams(context, new contexts.Eval(context, mixinFrames), args, _arguments);
var rules;
var ruleset;
frame.prependRule(new Declaration('@arguments', new Expression(_arguments).eval(context)));
rules = copyArray(this.rules);
ruleset = new Ruleset(null, rules);
ruleset.originalRuleset = this;
ruleset = ruleset.eval(new contexts.Eval(context, [this, frame].concat(mixinFrames)));
if (important) {
ruleset = ruleset.makeImportant();
}
return ruleset;
};
Definition.prototype.matchCondition = function (args, context) {
if (this.condition && !this.condition.eval(new contexts.Eval(context, [this.evalParams(context, /* the parameter variables */ new contexts.Eval(context, this.frames ? this.frames.concat(context.frames) : context.frames), args, [])]
.concat(this.frames || []) // the parent namespace/mixin frames
.concat(context.frames)))) { // the current environment frames
return false;
}
return true;
};
Definition.prototype.matchArgs = function (args, context) {
var allArgsCnt = (args && args.length) || 0;
var len;
var optionalParameters = this.optionalParameters;
var requiredArgsCnt = !args ? 0 : args.reduce(function (count, p) {
if (optionalParameters.indexOf(p.name) < 0) {
return count + 1;
}
else {
return count;
}
}, 0);
if (!this.variadic) {
if (requiredArgsCnt < this.required) {
return false;
}
if (allArgsCnt > this.params.length) {
return false;
}
}
else {
if (requiredArgsCnt < (this.required - 1)) {
return false;
}
}
// check patterns
len = Math.min(requiredArgsCnt, this.arity);
for (var i_1 = 0; i_1 < len; i_1++) {
if (!this.params[i_1].name && !this.params[i_1].variadic) {
if (args[i_1].value.eval(context).toCSS() != this.params[i_1].value.eval(context).toCSS()) {
return false;
}
}
}
return true;
};
return Definition;
}(Ruleset));
Definition.prototype.type = 'MixinDefinition';
Definition.prototype.evalFirst = true;
var MixinCall = /** @class */ (function (_super) {
__extends(MixinCall, _super);
function MixinCall(elements, args, index, currentFileInfo, important) {
var _this = _super.call(this) || this;
_this.selector = new Selector(elements);
_this.arguments = args || [];
_this._index = index;
_this._fileInfo = currentFileInfo;
_this.important = important;
_this.allowRoot = true;
_this.setParent(_this.selector, _this);
return _this;
}
MixinCall.prototype.accept = function (visitor) {
if (this.selector) {
this.selector = visitor.visit(this.selector);
}
if (this.arguments.length) {
this.arguments = visitor.visitArray(this.arguments);
}
};
MixinCall.prototype.eval = function (context) {
var mixins;
var mixin;
var mixinPath;
var args = [];
var arg;
var argValue;
var rules = [];
var match = false;
var i;
var m;
var f;
var isRecursive;
var isOneFound;
var candidates = [];
var candidate;
var conditionResult = [];
var defaultResult;
var defFalseEitherCase = -1;
var defNone = 0;
var defTrue = 1;
var defFalse = 2;
var count;
var originalRuleset;
var noArgumentsFilter;
this.selector = this.selector.eval(context);
function calcDefGroup(mixin, mixinPath) {
var f;
var p;
var namespace;
for (f = 0; f < 2; f++) {
conditionResult[f] = true;
defaultFunc.value(f);
for (p = 0; p < mixinPath.length && conditionResult[f]; p++) {
namespace = mixinPath[p];
if (namespace.matchCondition) {
conditionResult[f] = conditionResult[f] && namespace.matchCondition(null, context);
}
}
if (mixin.matchCondition) {
conditionResult[f] = conditionResult[f] && mixin.matchCondition(args, context);
}
}
if (conditionResult[0] || conditionResult[1]) {
if (conditionResult[0] != conditionResult[1]) {
return conditionResult[1] ?
defTrue : defFalse;
}
return defNone;
}
return defFalseEitherCase;
}
for (i = 0; i < this.arguments.length; i++) {
arg = this.arguments[i];
argValue = arg.value.eval(context);
if (arg.expand && Array.isArray(argValue.value)) {
argValue = argValue.value;
for (m = 0; m < argValue.length; m++) {
args.push({ value: argValue[m] });
}
}
else {
args.push({ name: arg.name, value: argValue });
}
}
noArgumentsFilter = function (rule) { return rule.matchArgs(null, context); };
for (i = 0; i < context.frames.length; i++) {
if ((mixins = context.frames[i].find(this.selector, null, noArgumentsFilter)).length > 0) {
isOneFound = true;
// To make `default()` function independent of definition order we have two "subpasses" here.
// At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
// and build candidate list with corresponding flags. Then, when we know all possible matches,
// we make a final decision.
for (m = 0; m < mixins.length; m++) {
mixin = mixins[m].rule;
mixinPath = mixins[m].path;
isRecursive = false;
for (f = 0; f < context.frames.length; f++) {
if ((!(mixin instanceof Definition)) && mixin === (context.frames[f].originalRuleset || context.frames[f])) {
isRecursive = true;
break;
}
}
if (isRecursive) {
continue;
}
if (mixin.matchArgs(args, context)) {
candidate = { mixin: mixin, group: calcDefGroup(mixin, mixinPath) };
if (candidate.group !== defFalseEitherCase) {
candidates.push(candidate);
}
match = true;
}
}
defaultFunc.reset();
count = [0, 0, 0];
for (m = 0; m < candidates.length; m++) {
count[candidates[m].group]++;
}
if (count[defNone] > 0) {
defaultResult = defFalse;
}
else {
defaultResult = defTrue;
if ((count[defTrue] + count[defFalse]) > 1) {
throw { type: 'Runtime',
message: "Ambiguous use of `default()` found when matching for `" + this.format(args) + "`",
index: this.getIndex(), filename: this.fileInfo().filename };
}
}
for (m = 0; m < candidates.length; m++) {
candidate = candidates[m].group;
if ((candidate === defNone) || (candidate === defaultResult)) {
try {
mixin = candidates[m].mixin;
if (!(mixin instanceof Definition)) {
originalRuleset = mixin.originalRuleset || mixin;
mixin = new Definition('', [], mixin.rules, null, false, null, originalRuleset.visibilityInfo());
mixin.originalRuleset = originalRuleset;
}
var newRules = mixin.evalCall(context, args, this.important).rules;
this._setVisibilityToReplacement(newRules);
Array.prototype.push.apply(rules, newRules);
}
catch (e) {
throw { message: e.message, index: this.getIndex(), filename: this.fileInfo().filename, stack: e.stack };
}
}
}
if (match) {
return rules;
}
}
}
if (isOneFound) {
throw { type: 'Runtime',
message: "No matching definition was found for `" + this.format(args) + "`",
index: this.getIndex(), filename: this.fileInfo().filename };
}
else {
throw { type: 'Name',
message: this.selector.toCSS().trim() + " is undefined",
index: this.getIndex(), filename: this.fileInfo().filename };
}
};
MixinCall.prototype._setVisibilityToReplacement = function (replacement) {
var i;
var rule;
if (this.blocksVisibility()) {
for (i = 0; i < replacement.length; i++) {
rule = replacement[i];
rule.addVisibilityBlock();
}
}
};
MixinCall.prototype.format = function (args) {
return this.selector.toCSS().trim() + "(" + (args ? args.map(function (a) {
var argValue = '';
if (a.name) {
argValue += a.name + ":";
}
if (a.value.toCSS) {
argValue += a.value.toCSS();
}
else {
argValue += '???';
}
return argValue;
}).join(', ') : '') + ")";
};
return MixinCall;
}(Node));
MixinCall.prototype.type = 'MixinCall';
var tree = {
Node: Node, Color: Color, AtRule: AtRule, DetachedRuleset: DetachedRuleset, Operation: Operation,
Dimension: Dimension, Unit: Unit, Keyword: Keyword, Variable: Variable, Property: Property,
Ruleset: Ruleset, Element: Element, Attribute: Attribute, Combinator: Combinator, Selector: Selector,
Quoted: Quoted, Expression: Expression, Declaration: Declaration, Call: Call, URL: URL, Import: Import,
Comment: Comment, Anonymous: Anonymous, Value: Value, JavaScript: JavaScript, Assignment: Assignment,
Condition: Condition, Paren: Paren, Media: Media, UnicodeDescriptor: UnicodeDescriptor, Negative: Negative,
Extend: Extend, VariableCall: VariableCall, NamespaceValue: NamespaceValue,
mixin: {
Call: MixinCall,
Definition: Definition
}
};
var logger = {
error: function (msg) {
this._fireEvent('error', msg);
},
warn: function (msg) {
this._fireEvent('warn', msg);
},
info: function (msg) {
this._fireEvent('info', msg);
},
debug: function (msg) {
this._fireEvent('debug', msg);
},
addListener: function (listener) {
this._listeners.push(listener);
},
removeListener: function (listener) {
for (var i_1 = 0; i_1 < this._listeners.length; i_1++) {
if (this._listeners[i_1] === listener) {
this._listeners.splice(i_1, 1);
return;
}
}
},
_fireEvent: function (type, msg) {
for (var i_2 = 0; i_2 < this._listeners.length; i_2++) {
var logFunction = this._listeners[i_2][type];
if (logFunction) {
logFunction(msg);
}
}
},
_listeners: []
};
/**
* @todo Document why this abstraction exists, and the relationship between
* environment, file managers, and plugin manager
*/
var environment = /** @class */ (function () {
function environment(externalEnvironment, fileManagers) {
this.fileManagers = fileManagers || [];
externalEnvironment = externalEnvironment || {};
var optionalFunctions = ['encodeBase64', 'mimeLookup', 'charsetLookup', 'getSourceMapGenerator'];
var requiredFunctions = [];
var functions = requiredFunctions.concat(optionalFunctions);
for (var i_1 = 0; i_1 < functions.length; i_1++) {
var propName = functions[i_1];
var environmentFunc = externalEnvironment[propName];
if (environmentFunc) {
this[propName] = environmentFunc.bind(externalEnvironment);
}
else if (i_1 < requiredFunctions.length) {
this.warn("missing required function in environment - " + propName);
}
}
}
environment.prototype.getFileManager = function (filename, currentDirectory, options, environment, isSync) {
if (!filename) {
logger.warn('getFileManager called with no filename.. Please report this issue. continuing.');
}
if (currentDirectory == null) {
logger.warn('getFileManager called with null directory.. Please report this issue. continuing.');
}
var fileManagers = this.fileManagers;
if (options.pluginManager) {
fileManagers = [].concat(fileManagers).concat(options.pluginManager.getFileManagers());
}
for (var i_2 = fileManagers.length - 1; i_2 >= 0; i_2--) {
var fileManager = fileManagers[i_2];
if (fileManager[isSync ? 'supportsSync' : 'supports'](filename, currentDirectory, options, environment)) {
return fileManager;
}
}
return null;
};
environment.prototype.addFileManager = function (fileManager) {
this.fileManagers.push(fileManager);
};
environment.prototype.clearFileManagers = function () {
this.fileManagers = [];
};
return environment;
}());
var AbstractFileManager = /** @class */ (function () {
function AbstractFileManager() {
}
AbstractFileManager.prototype.getPath = function (filename) {
var j = filename.lastIndexOf('?');
if (j > 0) {
filename = filename.slice(0, j);
}
j = filename.lastIndexOf('/');
if (j < 0) {
j = filename.lastIndexOf('\\');
}
if (j < 0) {
return '';
}
return filename.slice(0, j + 1);
};
AbstractFileManager.prototype.tryAppendExtension = function (path, ext) {
return /(\.[a-z]*$)|([\?;].*)$/.test(path) ? path : path + ext;
};
AbstractFileManager.prototype.tryAppendLessExtension = function (path) {
return this.tryAppendExtension(path, '.less');
};
AbstractFileManager.prototype.supportsSync = function () { return false; };
AbstractFileManager.prototype.alwaysMakePathsAbsolute = function () { return false; };
AbstractFileManager.prototype.isPathAbsolute = function (filename) {
return (/^(?:[a-z-]+:|\/|\\|#)/i).test(filename);
};
// TODO: pull out / replace?
AbstractFileManager.prototype.join = function (basePath, laterPath) {
if (!basePath) {
return laterPath;
}
return basePath + laterPath;
};
AbstractFileManager.prototype.pathDiff = function (url, baseUrl) {
// diff between two paths to create a relative path
var urlParts = this.extractUrlParts(url);
var baseUrlParts = this.extractUrlParts(baseUrl);
var i;
var max;
var urlDirectories;
var baseUrlDirectories;
var diff = '';
if (urlParts.hostPart !== baseUrlParts.hostPart) {
return '';
}
max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
for (i = 0; i < max; i++) {
if (baseUrlParts.directories[i] !== urlParts.directories[i]) {
break;
}
}
baseUrlDirectories = baseUrlParts.directories.slice(i);
urlDirectories = urlParts.directories.slice(i);
for (i = 0; i < baseUrlDirectories.length - 1; i++) {
diff += '../';
}
for (i = 0; i < urlDirectories.length - 1; i++) {
diff += urlDirectories[i] + "/";
}
return diff;
};
// helper function, not part of API
AbstractFileManager.prototype.extractUrlParts = function (url, baseUrl) {
// urlParts[1] = protocol://hostname/ OR /
// urlParts[2] = / if path relative to host base
// urlParts[3] = directories
// urlParts[4] = filename
// urlParts[5] = parameters
var urlPartsRegex = /^((?:[a-z-]+:)?\/{2}(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i;
var urlParts = url.match(urlPartsRegex);
var returner = {};
var rawDirectories = [];
var directories = [];
var i;
var baseUrlParts;
if (!urlParts) {
throw new Error("Could not parse sheet href - '" + url + "'");
}
// Stylesheets in IE don't always return the full path
if (baseUrl && (!urlParts[1] || urlParts[2])) {
baseUrlParts = baseUrl.match(urlPartsRegex);
if (!baseUrlParts) {
throw new Error("Could not parse page url - '" + baseUrl + "'");
}
urlParts[1] = urlParts[1] || baseUrlParts[1] || '';
if (!urlParts[2]) {
urlParts[3] = baseUrlParts[3] + urlParts[3];
}
}
if (urlParts[3]) {
rawDirectories = urlParts[3].replace(/\\/g, '/').split('/');
// collapse '..' and skip '.'
for (i = 0; i < rawDirectories.length; i++) {
if (rawDirectories[i] === '..') {
directories.pop();
}
else if (rawDirectories[i] !== '.') {
directories.push(rawDirectories[i]);
}
}
}
returner.hostPart = urlParts[1];
returner.directories = directories;
returner.rawPath = (urlParts[1] || '') + rawDirectories.join('/');
returner.path = (urlParts[1] || '') + directories.join('/');
returner.filename = urlParts[4];
returner.fileUrl = returner.path + (urlParts[4] || '');
returner.url = returner.fileUrl + (urlParts[5] || '');
return returner;
};
return AbstractFileManager;
}());
var AbstractPluginLoader = /** @class */ (function () {
function AbstractPluginLoader() {
// Implemented by Node.js plugin loader
this.require = function () { return null; };
}
AbstractPluginLoader.prototype.evalPlugin = function (contents, context, imports, pluginOptions, fileInfo) {
var loader;
var registry;
var pluginObj;
var localModule;
var pluginManager;
var filename;
var result;
pluginManager = context.pluginManager;
if (fileInfo) {
if (typeof fileInfo === 'string') {
filename = fileInfo;
}
else {
filename = fileInfo.filename;
}
}
var shortname = (new this.less.FileManager()).extractUrlParts(filename).filename;
if (filename) {
pluginObj = pluginManager.get(filename);
if (pluginObj) {
result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
if (result) {
return result;
}
try {
if (pluginObj.use) {
pluginObj.use.call(this.context, pluginObj);
}
}
catch (e) {
e.message = e.message || 'Error during @plugin call';
return new LessError(e, imports, filename);
}
return pluginObj;
}
}
localModule = {
exports: {},
pluginManager: pluginManager,
fileInfo: fileInfo
};
registry = functionRegistry.create();
var registerPlugin = function (obj) {
pluginObj = obj;
};
try {
loader = new Function('module', 'require', 'registerPlugin', 'functions', 'tree', 'less', 'fileInfo', contents);
loader(localModule, this.require(filename), registerPlugin, registry, this.less.tree, this.less, fileInfo);
}
catch (e) {
return new LessError(e, imports, filename);
}
if (!pluginObj) {
pluginObj = localModule.exports;
}
pluginObj = this.validatePlugin(pluginObj, filename, shortname);
if (pluginObj instanceof LessError) {
return pluginObj;
}
if (pluginObj) {
pluginObj.imports = imports;
pluginObj.filename = filename;
// For < 3.x (or unspecified minVersion) - setOptions() before install()
if (!pluginObj.minVersion || this.compareVersion('3.0.0', pluginObj.minVersion) < 0) {
result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
if (result) {
return result;
}
}
// Run on first load
pluginManager.addPlugin(pluginObj, fileInfo.filename, registry);
pluginObj.functions = registry.getLocalFunctions();
// Need to call setOptions again because the pluginObj might have functions
result = this.trySetOptions(pluginObj, filename, shortname, pluginOptions);
if (result) {
return result;
}
// Run every @plugin call
try {
if (pluginObj.use) {
pluginObj.use.call(this.context, pluginObj);
}
}
catch (e) {
e.message = e.message || 'Error during @plugin call';
return new LessError(e, imports, filename);
}
}
else {
return new LessError({ message: 'Not a valid plugin' }, imports, filename);
}
return pluginObj;
};
AbstractPluginLoader.prototype.trySetOptions = function (plugin, filename, name, options) {
if (options && !plugin.setOptions) {
return new LessError({
message: "Options have been provided but the plugin " + name + " does not support any options."
});
}
try {
plugin.setOptions && plugin.setOptions(options);
}
catch (e) {
return new LessError(e);
}
};
AbstractPluginLoader.prototype.validatePlugin = function (plugin, filename, name) {
if (plugin) {
// support plugins being a function
// so that the plugin can be more usable programmatically
if (typeof plugin === 'function') {
plugin = new plugin();
}
if (plugin.minVersion) {
if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
return new LessError({
message: "Plugin " + name + " requires version " + this.versionToString(plugin.minVersion)
});
}
}
return plugin;
}
return null;
};
AbstractPluginLoader.prototype.compareVersion = function (aVersion, bVersion) {
if (typeof aVersion === 'string') {
aVersion = aVersion.match(/^(\d+)\.?(\d+)?\.?(\d+)?/);
aVersion.shift();
}
for (var i_1 = 0; i_1 < aVersion.length; i_1++) {
if (aVersion[i_1] !== bVersion[i_1]) {
return parseInt(aVersion[i_1]) > parseInt(bVersion[i_1]) ? -1 : 1;
}
}
return 0;
};
AbstractPluginLoader.prototype.versionToString = function (version) {
var versionString = '';
for (var i_2 = 0; i_2 < version.length; i_2++) {
versionString += (versionString ? '.' : '') + version[i_2];
}
return versionString;
};
AbstractPluginLoader.prototype.printUsage = function (plugins) {
for (var i_3 = 0; i_3 < plugins.length; i_3++) {
var plugin = plugins[i_3];
if (plugin.printUsage) {
plugin.printUsage();
}
}
};
return AbstractPluginLoader;
}());
var _visitArgs = { visitDeeper: true };
var _hasIndexed = false;
function _noop(node) {
return node;
}
function indexNodeTypes(parent, ticker) {
// add .typeIndex to tree node types for lookup table
var key;
var child;
for (key in parent) {
/* eslint guard-for-in: 0 */
child = parent[key];
switch (typeof child) {
case 'function':
// ignore bound functions directly on tree which do not have a prototype
// or aren't nodes
if (child.prototype && child.prototype.type) {
child.prototype.typeIndex = ticker++;
}
break;
case 'object':
ticker = indexNodeTypes(child, ticker);
break;
}
}
return ticker;
}
var Visitor = /** @class */ (function () {
function Visitor(implementation) {
this._implementation = implementation;
this._visitInCache = {};
this._visitOutCache = {};
if (!_hasIndexed) {
indexNodeTypes(tree, 1);
_hasIndexed = true;
}
}
Visitor.prototype.visit = function (node) {
if (!node) {
return node;
}
var nodeTypeIndex = node.typeIndex;
if (!nodeTypeIndex) {
// MixinCall args aren't a node type?
if (node.value && node.value.typeIndex) {
this.visit(node.value);
}
return node;
}
var impl = this._implementation;
var func = this._visitInCache[nodeTypeIndex];
var funcOut = this._visitOutCache[nodeTypeIndex];
var visitArgs = _visitArgs;
var fnName;
visitArgs.visitDeeper = true;
if (!func) {
fnName = "visit" + node.type;
func = impl[fnName] || _noop;
funcOut = impl[fnName + "Out"] || _noop;
this._visitInCache[nodeTypeIndex] = func;
this._visitOutCache[nodeTypeIndex] = funcOut;
}
if (func !== _noop) {
var newNode = func.call(impl, node, visitArgs);
if (node && impl.isReplacing) {
node = newNode;
}
}
if (visitArgs.visitDeeper && node) {
if (node.length) {
for (var i = 0, cnt = node.length; i < cnt; i++) {
if (node[i].accept) {
node[i].accept(this);
}
}
}
else if (node.accept) {
node.accept(this);
}
}
if (funcOut != _noop) {
funcOut.call(impl, node);
}
return node;
};
Visitor.prototype.visitArray = function (nodes, nonReplacing) {
if (!nodes) {
return nodes;
}
var cnt = nodes.length;
var i;
// Non-replacing
if (nonReplacing || !this._implementation.isReplacing) {
for (i = 0; i < cnt; i++) {
this.visit(nodes[i]);
}
return nodes;
}
// Replacing
var out = [];
for (i = 0; i < cnt; i++) {
var evald = this.visit(nodes[i]);
if (evald === undefined) {
continue;
}
if (!evald.splice) {
out.push(evald);
}
else if (evald.length) {
this.flatten(evald, out);
}
}
return out;
};
Visitor.prototype.flatten = function (arr, out) {
if (!out) {
out = [];
}
var cnt;
var i;
var item;
var nestedCnt;
var j;
var nestedItem;
for (i = 0, cnt = arr.length; i < cnt; i++) {
item = arr[i];
if (item === undefined) {
continue;
}
if (!item.splice) {
out.push(item);
continue;
}
for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
nestedItem = item[j];
if (nestedItem === undefined) {
continue;
}
if (!nestedItem.splice) {
out.push(nestedItem);
}
else if (nestedItem.length) {
this.flatten(nestedItem, out);
}
}
}
return out;
};
return Visitor;
}());
var ImportSequencer = /** @class */ (function () {
function ImportSequencer(onSequencerEmpty) {
this.imports = [];
this.variableImports = [];
this._onSequencerEmpty = onSequencerEmpty;
this._currentDepth = 0;
}
ImportSequencer.prototype.addImport = function (callback) {
var importSequencer = this;
var importItem = {
callback: callback,
args: null,
isReady: false
};
this.imports.push(importItem);
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
importItem.args = Array.prototype.slice.call(args, 0);
importItem.isReady = true;
importSequencer.tryRun();
};
};
ImportSequencer.prototype.addVariableImport = function (callback) {
this.variableImports.push(callback);
};
ImportSequencer.prototype.tryRun = function () {
this._currentDepth++;
try {
while (true) {
while (this.imports.length > 0) {
var importItem = this.imports[0];
if (!importItem.isReady) {
return;
}
this.imports = this.imports.slice(1);
importItem.callback.apply(null, importItem.args);
}
if (this.variableImports.length === 0) {
break;
}
var variableImport = this.variableImports[0];
this.variableImports = this.variableImports.slice(1);
variableImport();
}
}
finally {
this._currentDepth--;
}
if (this._currentDepth === 0 && this._onSequencerEmpty) {
this._onSequencerEmpty();
}
};
return ImportSequencer;
}());
var ImportVisitor = function (importer, finish) {
this._visitor = new Visitor(this);
this._importer = importer;
this._finish = finish;
this.context = new contexts.Eval();
this.importCount = 0;
this.onceFileDetectionMap = {};
this.recursionDetector = {};
this._sequencer = new ImportSequencer(this._onSequencerEmpty.bind(this));
};
ImportVisitor.prototype = {
isReplacing: false,
run: function (root) {
try {
// process the contents
this._visitor.visit(root);
}
catch (e) {
this.error = e;
}
this.isFinished = true;
this._sequencer.tryRun();
},
_onSequencerEmpty: function () {
if (!this.isFinished) {
return;
}
this._finish(this.error);
},
visitImport: function (importNode, visitArgs) {
var inlineCSS = importNode.options.inline;
if (!importNode.css || inlineCSS) {
var context = new contexts.Eval(this.context, copyArray(this.context.frames));
var importParent = context.frames[0];
this.importCount++;
if (importNode.isVariableImport()) {
this._sequencer.addVariableImport(this.processImportNode.bind(this, importNode, context, importParent));
}
else {
this.processImportNode(importNode, context, importParent);
}
}
visitArgs.visitDeeper = false;
},
processImportNode: function (importNode, context, importParent) {
var evaldImportNode;
var inlineCSS = importNode.options.inline;
try {
evaldImportNode = importNode.evalForImport(context);
}
catch (e) {
if (!e.filename) {
e.index = importNode.getIndex();
e.filename = importNode.fileInfo().filename;
}
// attempt to eval properly and treat as css
importNode.css = true;
// if that fails, this error will be thrown
importNode.error = e;
}
if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
if (evaldImportNode.options.multiple) {
context.importMultiple = true;
}
// try appending if we haven't determined if it is css or not
var tryAppendLessExtension = evaldImportNode.css === undefined;
for (var i_1 = 0; i_1 < importParent.rules.length; i_1++) {
if (importParent.rules[i_1] === importNode) {
importParent.rules[i_1] = evaldImportNode;
break;
}
}
var onImported = this.onImported.bind(this, evaldImportNode, context);
var sequencedOnImported = this._sequencer.addImport(onImported);
this._importer.push(evaldImportNode.getPath(), tryAppendLessExtension, evaldImportNode.fileInfo(), evaldImportNode.options, sequencedOnImported);
}
else {
this.importCount--;
if (this.isFinished) {
this._sequencer.tryRun();
}
}
},
onImported: function (importNode, context, e, root, importedAtRoot, fullPath) {
if (e) {
if (!e.filename) {
e.index = importNode.getIndex();
e.filename = importNode.fileInfo().filename;
}
this.error = e;
}
var importVisitor = this;
var inlineCSS = importNode.options.inline;
var isPlugin = importNode.options.isPlugin;
var isOptional = importNode.options.optional;
var duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector;
if (!context.importMultiple) {
if (duplicateImport) {
importNode.skip = true;
}
else {
importNode.skip = function () {
if (fullPath in importVisitor.onceFileDetectionMap) {
return true;
}
importVisitor.onceFileDetectionMap[fullPath] = true;
return false;
};
}
}
if (!fullPath && isOptional) {
importNode.skip = true;
}
if (root) {
importNode.root = root;
importNode.importedFilename = fullPath;
if (!inlineCSS && !isPlugin && (context.importMultiple || !duplicateImport)) {
importVisitor.recursionDetector[fullPath] = true;
var oldContext = this.context;
this.context = context;
try {
this._visitor.visit(root);
}
catch (e) {
this.error = e;
}
this.context = oldContext;
}
}
importVisitor.importCount--;
if (importVisitor.isFinished) {
importVisitor._sequencer.tryRun();
}
},
visitDeclaration: function (declNode, visitArgs) {
if (declNode.value.type === 'DetachedRuleset') {
this.context.frames.unshift(declNode);
}
else {
visitArgs.visitDeeper = false;
}
},
visitDeclarationOut: function (declNode) {
if (declNode.value.type === 'DetachedRuleset') {
this.context.frames.shift();
}
},
visitAtRule: function (atRuleNode, visitArgs) {
this.context.frames.unshift(atRuleNode);
},
visitAtRuleOut: function (atRuleNode) {
this.context.frames.shift();
},
visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
this.context.frames.unshift(mixinDefinitionNode);
},
visitMixinDefinitionOut: function (mixinDefinitionNode) {
this.context.frames.shift();
},
visitRuleset: function (rulesetNode, visitArgs) {
this.context.frames.unshift(rulesetNode);
},
visitRulesetOut: function (rulesetNode) {
this.context.frames.shift();
},
visitMedia: function (mediaNode, visitArgs) {
this.context.frames.unshift(mediaNode.rules[0]);
},
visitMediaOut: function (mediaNode) {
this.context.frames.shift();
}
};
var SetTreeVisibilityVisitor = /** @class */ (function () {
function SetTreeVisibilityVisitor(visible) {
this.visible = visible;
}
SetTreeVisibilityVisitor.prototype.run = function (root) {
this.visit(root);
};
SetTreeVisibilityVisitor.prototype.visitArray = function (nodes) {
if (!nodes) {
return nodes;
}
var cnt = nodes.length;
var i;
for (i = 0; i < cnt; i++) {
this.visit(nodes[i]);
}
return nodes;
};
SetTreeVisibilityVisitor.prototype.visit = function (node) {
if (!node) {
return node;
}
if (node.constructor === Array) {
return this.visitArray(node);
}
if (!node.blocksVisibility || node.blocksVisibility()) {
return node;
}
if (this.visible) {
node.ensureVisibility();
}
else {
node.ensureInvisibility();
}
node.accept(this);
return node;
};
return SetTreeVisibilityVisitor;
}());
/* jshint loopfunc:true */
var ExtendFinderVisitor = /** @class */ (function () {
function ExtendFinderVisitor() {
this._visitor = new Visitor(this);
this.contexts = [];
this.allExtendsStack = [[]];
}
ExtendFinderVisitor.prototype.run = function (root) {
root = this._visitor.visit(root);
root.allExtends = this.allExtendsStack[0];
return root;
};
ExtendFinderVisitor.prototype.visitDeclaration = function (declNode, visitArgs) {
visitArgs.visitDeeper = false;
};
ExtendFinderVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
visitArgs.visitDeeper = false;
};
ExtendFinderVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
if (rulesetNode.root) {
return;
}
var i;
var j;
var extend;
var allSelectorsExtendList = [];
var extendList;
// get &:extend(.a); rules which apply to all selectors in this ruleset
var rules = rulesetNode.rules;
var ruleCnt = rules ? rules.length : 0;
for (i = 0; i < ruleCnt; i++) {
if (rulesetNode.rules[i] instanceof tree.Extend) {
allSelectorsExtendList.push(rules[i]);
rulesetNode.extendOnEveryPath = true;
}
}
// now find every selector and apply the extends that apply to all extends
// and the ones which apply to an individual extend
var paths = rulesetNode.paths;
for (i = 0; i < paths.length; i++) {
var selectorPath = paths[i];
var selector = selectorPath[selectorPath.length - 1];
var selExtendList = selector.extendList;
extendList = selExtendList ? copyArray(selExtendList).concat(allSelectorsExtendList)
: allSelectorsExtendList;
if (extendList) {
extendList = extendList.map(function (allSelectorsExtend) { return allSelectorsExtend.clone(); });
}
for (j = 0; j < extendList.length; j++) {
this.foundExtends = true;
extend = extendList[j];
extend.findSelfSelectors(selectorPath);
extend.ruleset = rulesetNode;
if (j === 0) {
extend.firstExtendOnThisSelectorPath = true;
}
this.allExtendsStack[this.allExtendsStack.length - 1].push(extend);
}
}
this.contexts.push(rulesetNode.selectors);
};
ExtendFinderVisitor.prototype.visitRulesetOut = function (rulesetNode) {
if (!rulesetNode.root) {
this.contexts.length = this.contexts.length - 1;
}
};
ExtendFinderVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
mediaNode.allExtends = [];
this.allExtendsStack.push(mediaNode.allExtends);
};
ExtendFinderVisitor.prototype.visitMediaOut = function (mediaNode) {
this.allExtendsStack.length = this.allExtendsStack.length - 1;
};
ExtendFinderVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
atRuleNode.allExtends = [];
this.allExtendsStack.push(atRuleNode.allExtends);
};
ExtendFinderVisitor.prototype.visitAtRuleOut = function (atRuleNode) {
this.allExtendsStack.length = this.allExtendsStack.length - 1;
};
return ExtendFinderVisitor;
}());
var ProcessExtendsVisitor = /** @class */ (function () {
function ProcessExtendsVisitor() {
this._visitor = new Visitor(this);
}
ProcessExtendsVisitor.prototype.run = function (root) {
var extendFinder = new ExtendFinderVisitor();
this.extendIndices = {};
extendFinder.run(root);
if (!extendFinder.foundExtends) {
return root;
}
root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
this.allExtendsStack = [root.allExtends];
var newRoot = this._visitor.visit(root);
this.checkExtendsForNonMatched(root.allExtends);
return newRoot;
};
ProcessExtendsVisitor.prototype.checkExtendsForNonMatched = function (extendList) {
var indices = this.extendIndices;
extendList.filter(function (extend) { return !extend.hasFoundMatches && extend.parent_ids.length == 1; }).forEach(function (extend) {
var selector = '_unknown_';
try {
selector = extend.selector.toCSS({});
}
catch (_) { }
if (!indices[extend.index + " " + selector]) {
indices[extend.index + " " + selector] = true;
logger.warn("extend '" + selector + "' has no matches");
}
});
};
ProcessExtendsVisitor.prototype.doExtendChaining = function (extendsList, extendsListTarget, iterationCount) {
//
// chaining is different from normal extension.. if we extend an extend then we are not just copying, altering
// and pasting the selector we would do normally, but we are also adding an extend with the same target selector
// this means this new extend can then go and alter other extends
//
// this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
// this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already
// processed if we look at each selector at a time, as is done in visitRuleset
var extendIndex;
var targetExtendIndex;
var matches;
var extendsToAdd = [];
var newSelector;
var extendVisitor = this;
var selectorPath;
var extend;
var targetExtend;
var newExtend;
iterationCount = iterationCount || 0;
// loop through comparing every extend with every target extend.
// a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
// e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
// and the second is the target.
// the separation into two lists allows us to process a subset of chains with a bigger set, as is the
// case when processing media queries
for (extendIndex = 0; extendIndex < extendsList.length; extendIndex++) {
for (targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++) {
extend = extendsList[extendIndex];
targetExtend = extendsListTarget[targetExtendIndex];
// look for circular references
if (extend.parent_ids.indexOf(targetExtend.object_id) >= 0) {
continue;
}
// find a match in the target extends self selector (the bit before :extend)
selectorPath = [targetExtend.selfSelectors[0]];
matches = extendVisitor.findMatch(extend, selectorPath);
if (matches.length) {
extend.hasFoundMatches = true;
// we found a match, so for each self selector..
extend.selfSelectors.forEach(function (selfSelector) {
var info = targetExtend.visibilityInfo();
// process the extend as usual
newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector, extend.isVisible());
// but now we create a new extend from it
newExtend = new (tree.Extend)(targetExtend.selector, targetExtend.option, 0, targetExtend.fileInfo(), info);
newExtend.selfSelectors = newSelector;
// add the extend onto the list of extends for that selector
newSelector[newSelector.length - 1].extendList = [newExtend];
// record that we need to add it.
extendsToAdd.push(newExtend);
newExtend.ruleset = targetExtend.ruleset;
// remember its parents for circular references
newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids);
// only process the selector once.. if we have :extend(.a,.b) then multiple
// extends will look at the same selector path, so when extending
// we know that any others will be duplicates in terms of what is added to the css
if (targetExtend.firstExtendOnThisSelectorPath) {
newExtend.firstExtendOnThisSelectorPath = true;
targetExtend.ruleset.paths.push(newSelector);
}
});
}
}
}
if (extendsToAdd.length) {
// try to detect circular references to stop a stack overflow.
// may no longer be needed.
this.extendChainCount++;
if (iterationCount > 100) {
var selectorOne = '{unable to calculate}';
var selectorTwo = '{unable to calculate}';
try {
selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
selectorTwo = extendsToAdd[0].selector.toCSS();
}
catch (e) { }
throw { message: "extend circular reference detected. One of the circular extends is currently:" + selectorOne + ":extend(" + selectorTwo + ")" };
}
// now process the new extends on the existing rules so that we can handle a extending b extending c extending
// d extending e...
return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount + 1));
}
else {
return extendsToAdd;
}
};
ProcessExtendsVisitor.prototype.visitDeclaration = function (ruleNode, visitArgs) {
visitArgs.visitDeeper = false;
};
ProcessExtendsVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
visitArgs.visitDeeper = false;
};
ProcessExtendsVisitor.prototype.visitSelector = function (selectorNode, visitArgs) {
visitArgs.visitDeeper = false;
};
ProcessExtendsVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
if (rulesetNode.root) {
return;
}
var matches;
var pathIndex;
var extendIndex;
var allExtends = this.allExtendsStack[this.allExtendsStack.length - 1];
var selectorsToAdd = [];
var extendVisitor = this;
var selectorPath;
// look at each selector path in the ruleset, find any extend matches and then copy, find and replace
for (extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
for (pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
selectorPath = rulesetNode.paths[pathIndex];
// extending extends happens initially, before the main pass
if (rulesetNode.extendOnEveryPath) {
continue;
}
var extendList = selectorPath[selectorPath.length - 1].extendList;
if (extendList && extendList.length) {
continue;
}
matches = this.findMatch(allExtends[extendIndex], selectorPath);
if (matches.length) {
allExtends[extendIndex].hasFoundMatches = true;
allExtends[extendIndex].selfSelectors.forEach(function (selfSelector) {
var extendedSelectors;
extendedSelectors = extendVisitor.extendSelector(matches, selectorPath, selfSelector, allExtends[extendIndex].isVisible());
selectorsToAdd.push(extendedSelectors);
});
}
}
}
rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
};
ProcessExtendsVisitor.prototype.findMatch = function (extend, haystackSelectorPath) {
//
// look through the haystack selector path to try and find the needle - extend.selector
// returns an array of selector matches that can then be replaced
//
var haystackSelectorIndex;
var hackstackSelector;
var hackstackElementIndex;
var haystackElement;
var targetCombinator;
var i;
var extendVisitor = this;
var needleElements = extend.selector.elements;
var potentialMatches = [];
var potentialMatch;
var matches = [];
// loop through the haystack elements
for (haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
for (hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
haystackElement = hackstackSelector.elements[hackstackElementIndex];
// if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) {
potentialMatches.push({ pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0,
initialCombinator: haystackElement.combinator });
}
for (i = 0; i < potentialMatches.length; i++) {
potentialMatch = potentialMatches[i];
// selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
// then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to
// work out what the resulting combinator will be
targetCombinator = haystackElement.combinator.value;
if (targetCombinator === '' && hackstackElementIndex === 0) {
targetCombinator = ' ';
}
// if we don't match, null our match to indicate failure
if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) ||
(potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) {
potentialMatch = null;
}
else {
potentialMatch.matched++;
}
// if we are still valid and have finished, test whether we have elements after and whether these are allowed
if (potentialMatch) {
potentialMatch.finished = potentialMatch.matched === needleElements.length;
if (potentialMatch.finished &&
(!extend.allowAfter &&
(hackstackElementIndex + 1 < hackstackSelector.elements.length || haystackSelectorIndex + 1 < haystackSelectorPath.length))) {
potentialMatch = null;
}
}
// if null we remove, if not, we are still valid, so either push as a valid match or continue
if (potentialMatch) {
if (potentialMatch.finished) {
potentialMatch.length = needleElements.length;
potentialMatch.endPathIndex = haystackSelectorIndex;
potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
matches.push(potentialMatch);
}
}
else {
potentialMatches.splice(i, 1);
i--;
}
}
}
}
return matches;
};
ProcessExtendsVisitor.prototype.isElementValuesEqual = function (elementValue1, elementValue2) {
if (typeof elementValue1 === 'string' || typeof elementValue2 === 'string') {
return elementValue1 === elementValue2;
}
if (elementValue1 instanceof tree.Attribute) {
if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
return false;
}
if (!elementValue1.value || !elementValue2.value) {
if (elementValue1.value || elementValue2.value) {
return false;
}
return true;
}
elementValue1 = elementValue1.value.value || elementValue1.value;
elementValue2 = elementValue2.value.value || elementValue2.value;
return elementValue1 === elementValue2;
}
elementValue1 = elementValue1.value;
elementValue2 = elementValue2.value;
if (elementValue1 instanceof tree.Selector) {
if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
return false;
}
for (var i_1 = 0; i_1 < elementValue1.elements.length; i_1++) {
if (elementValue1.elements[i_1].combinator.value !== elementValue2.elements[i_1].combinator.value) {
if (i_1 !== 0 || (elementValue1.elements[i_1].combinator.value || ' ') !== (elementValue2.elements[i_1].combinator.value || ' ')) {
return false;
}
}
if (!this.isElementValuesEqual(elementValue1.elements[i_1].value, elementValue2.elements[i_1].value)) {
return false;
}
}
return true;
}
return false;
};
ProcessExtendsVisitor.prototype.extendSelector = function (matches, selectorPath, replacementSelector, isVisible) {
// for a set of matches, replace each match with the replacement selector
var currentSelectorPathIndex = 0;
var currentSelectorPathElementIndex = 0;
var path = [];
var matchIndex;
var selector;
var firstElement;
var match;
var newElements;
for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
match = matches[matchIndex];
selector = selectorPath[match.pathIndex];
firstElement = new tree.Element(match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].isVariable, replacementSelector.elements[0].getIndex(), replacementSelector.elements[0].fileInfo());
if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
path[path.length - 1].elements = path[path.length - 1]
.elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
currentSelectorPathElementIndex = 0;
currentSelectorPathIndex++;
}
newElements = selector.elements
.slice(currentSelectorPathElementIndex, match.index)
.concat([firstElement])
.concat(replacementSelector.elements.slice(1));
if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
path[path.length - 1].elements =
path[path.length - 1].elements.concat(newElements);
}
else {
path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
path.push(new tree.Selector(newElements));
}
currentSelectorPathIndex = match.endPathIndex;
currentSelectorPathElementIndex = match.endPathElementIndex;
if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
currentSelectorPathElementIndex = 0;
currentSelectorPathIndex++;
}
}
if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
path[path.length - 1].elements = path[path.length - 1]
.elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
currentSelectorPathIndex++;
}
path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
path = path.map(function (currentValue) {
// we can re-use elements here, because the visibility property matters only for selectors
var derived = currentValue.createDerived(currentValue.elements);
if (isVisible) {
derived.ensureVisibility();
}
else {
derived.ensureInvisibility();
}
return derived;
});
return path;
};
ProcessExtendsVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
this.allExtendsStack.push(newAllExtends);
};
ProcessExtendsVisitor.prototype.visitMediaOut = function (mediaNode) {
var lastIndex = this.allExtendsStack.length - 1;
this.allExtendsStack.length = lastIndex;
};
ProcessExtendsVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
var newAllExtends = atRuleNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length - 1]);
newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, atRuleNode.allExtends));
this.allExtendsStack.push(newAllExtends);
};
ProcessExtendsVisitor.prototype.visitAtRuleOut = function (atRuleNode) {
var lastIndex = this.allExtendsStack.length - 1;
this.allExtendsStack.length = lastIndex;
};
return ProcessExtendsVisitor;
}());
var JoinSelectorVisitor = /** @class */ (function () {
function JoinSelectorVisitor() {
this.contexts = [[]];
this._visitor = new Visitor(this);
}
JoinSelectorVisitor.prototype.run = function (root) {
return this._visitor.visit(root);
};
JoinSelectorVisitor.prototype.visitDeclaration = function (declNode, visitArgs) {
visitArgs.visitDeeper = false;
};
JoinSelectorVisitor.prototype.visitMixinDefinition = function (mixinDefinitionNode, visitArgs) {
visitArgs.visitDeeper = false;
};
JoinSelectorVisitor.prototype.visitRuleset = function (rulesetNode, visitArgs) {
var context = this.contexts[this.contexts.length - 1];
var paths = [];
var selectors;
this.contexts.push(paths);
if (!rulesetNode.root) {
selectors = rulesetNode.selectors;
if (selectors) {
selectors = selectors.filter(function (selector) { return selector.getIsOutput(); });
rulesetNode.selectors = selectors.length ? selectors : (selectors = null);
if (selectors) {
rulesetNode.joinSelectors(paths, context, selectors);
}
}
if (!selectors) {
rulesetNode.rules = null;
}
rulesetNode.paths = paths;
}
};
JoinSelectorVisitor.prototype.visitRulesetOut = function (rulesetNode) {
this.contexts.length = this.contexts.length - 1;
};
JoinSelectorVisitor.prototype.visitMedia = function (mediaNode, visitArgs) {
var context = this.contexts[this.contexts.length - 1];
mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia);
};
JoinSelectorVisitor.prototype.visitAtRule = function (atRuleNode, visitArgs) {
var context = this.contexts[this.contexts.length - 1];
if (atRuleNode.rules && atRuleNode.rules.length) {
atRuleNode.rules[0].root = (atRuleNode.isRooted || context.length === 0 || null);
}
};
return JoinSelectorVisitor;
}());
var CSSVisitorUtils = /** @class */ (function () {
function CSSVisitorUtils(context) {
this._visitor = new Visitor(this);
this._context = context;
}
CSSVisitorUtils.prototype.containsSilentNonBlockedChild = function (bodyRules) {
var rule;
if (!bodyRules) {
return false;
}
for (var r = 0; r < bodyRules.length; r++) {
rule = bodyRules[r];
if (rule.isSilent && rule.isSilent(this._context) && !rule.blocksVisibility()) {
// the atrule contains something that was referenced (likely by extend)
// therefore it needs to be shown in output too
return true;
}
}
return false;
};
CSSVisitorUtils.prototype.keepOnlyVisibleChilds = function (owner) {
if (owner && owner.rules) {
owner.rules = owner.rules.filter(function (thing) { return thing.isVisible(); });
}
};
CSSVisitorUtils.prototype.isEmpty = function (owner) {
return (owner && owner.rules)
? (owner.rules.length === 0) : true;
};
CSSVisitorUtils.prototype.hasVisibleSelector = function (rulesetNode) {
return (rulesetNode && rulesetNode.paths)
? (rulesetNode.paths.length > 0) : false;
};
CSSVisitorUtils.prototype.resolveVisibility = function (node, originalRules) {
if (!node.blocksVisibility()) {
if (this.isEmpty(node) && !this.containsSilentNonBlockedChild(originalRules)) {
return;
}
return node;
}
var compiledRulesBody = node.rules[0];
this.keepOnlyVisibleChilds(compiledRulesBody);
if (this.isEmpty(compiledRulesBody)) {
return;
}
node.ensureVisibility();
node.removeVisibilityBlock();
return node;
};
CSSVisitorUtils.prototype.isVisibleRuleset = function (rulesetNode) {
if (rulesetNode.firstRoot) {
return true;
}
if (this.isEmpty(rulesetNode)) {
return false;
}
if (!rulesetNode.root && !this.hasVisibleSelector(rulesetNode)) {
return false;
}
return true;
};
return CSSVisitorUtils;
}());
var ToCSSVisitor = function (context) {
this._visitor = new Visitor(this);
this._context = context;
this.utils = new CSSVisitorUtils(context);
};
ToCSSVisitor.prototype = {
isReplacing: true,
run: function (root) {
return this._visitor.visit(root);
},
visitDeclaration: function (declNode, visitArgs) {
if (declNode.blocksVisibility() || declNode.variable) {
return;
}
return declNode;
},
visitMixinDefinition: function (mixinNode, visitArgs) {
// mixin definitions do not get eval'd - this means they keep state
// so we have to clear that state here so it isn't used if toCSS is called twice
mixinNode.frames = [];
},
visitExtend: function (extendNode, visitArgs) {
},
visitComment: function (commentNode, visitArgs) {
if (commentNode.blocksVisibility() || commentNode.isSilent(this._context)) {
return;
}
return commentNode;
},
visitMedia: function (mediaNode, visitArgs) {
var originalRules = mediaNode.rules[0].rules;
mediaNode.accept(this._visitor);
visitArgs.visitDeeper = false;
return this.utils.resolveVisibility(mediaNode, originalRules);
},
visitImport: function (importNode, visitArgs) {
if (importNode.blocksVisibility()) {
return;
}
return importNode;
},
visitAtRule: function (atRuleNode, visitArgs) {
if (atRuleNode.rules && atRuleNode.rules.length) {
return this.visitAtRuleWithBody(atRuleNode, visitArgs);
}
else {
return this.visitAtRuleWithoutBody(atRuleNode, visitArgs);
}
},
visitAnonymous: function (anonymousNode, visitArgs) {
if (!anonymousNode.blocksVisibility()) {
anonymousNode.accept(this._visitor);
return anonymousNode;
}
},
visitAtRuleWithBody: function (atRuleNode, visitArgs) {
// if there is only one nested ruleset and that one has no path, then it is
// just fake ruleset
function hasFakeRuleset(atRuleNode) {
var bodyRules = atRuleNode.rules;
return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0);
}
function getBodyRules(atRuleNode) {
var nodeRules = atRuleNode.rules;
if (hasFakeRuleset(atRuleNode)) {
return nodeRules[0].rules;
}
return nodeRules;
}
// it is still true that it is only one ruleset in array
// this is last such moment
// process childs
var originalRules = getBodyRules(atRuleNode);
atRuleNode.accept(this._visitor);
visitArgs.visitDeeper = false;
if (!this.utils.isEmpty(atRuleNode)) {
this._mergeRules(atRuleNode.rules[0].rules);
}
return this.utils.resolveVisibility(atRuleNode, originalRules);
},
visitAtRuleWithoutBody: function (atRuleNode, visitArgs) {
if (atRuleNode.blocksVisibility()) {
return;
}
if (atRuleNode.name === '@charset') {
// Only output the debug info together with subsequent @charset definitions
// a comment (or @media statement) before the actual @charset atrule would
// be considered illegal css as it has to be on the first line
if (this.charset) {
if (atRuleNode.debugInfo) {
var comment = new tree.Comment("/* " + atRuleNode.toCSS(this._context).replace(/\n/g, '') + " */\n");
comment.debugInfo = atRuleNode.debugInfo;
return this._visitor.visit(comment);
}
return;
}
this.charset = true;
}
return atRuleNode;
},
checkValidNodes: function (rules, isRoot) {
if (!rules) {
return;
}
for (var i_1 = 0; i_1 < rules.length; i_1++) {
var ruleNode = rules[i_1];
if (isRoot && ruleNode instanceof tree.Declaration && !ruleNode.variable) {
throw { message: 'Properties must be inside selector blocks. They cannot be in the root',
index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
}
if (ruleNode instanceof tree.Call) {
throw { message: "Function '" + ruleNode.name + "' is undefined",
index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
}
if (ruleNode.type && !ruleNode.allowRoot) {
throw { message: ruleNode.type + " node returned by a function is not valid here",
index: ruleNode.getIndex(), filename: ruleNode.fileInfo() && ruleNode.fileInfo().filename };
}
}
},
visitRuleset: function (rulesetNode, visitArgs) {
// at this point rulesets are nested into each other
var rule;
var rulesets = [];
this.checkValidNodes(rulesetNode.rules, rulesetNode.firstRoot);
if (!rulesetNode.root) {
// remove invisible paths
this._compileRulesetPaths(rulesetNode);
// remove rulesets from this ruleset body and compile them separately
var nodeRules = rulesetNode.rules;
var nodeRuleCnt = nodeRules ? nodeRules.length : 0;
for (var i_2 = 0; i_2 < nodeRuleCnt;) {
rule = nodeRules[i_2];
if (rule && rule.rules) {
// visit because we are moving them out from being a child
rulesets.push(this._visitor.visit(rule));
nodeRules.splice(i_2, 1);
nodeRuleCnt--;
continue;
}
i_2++;
}
// accept the visitor to remove rules and refactor itself
// then we can decide nogw whether we want it or not
// compile body
if (nodeRuleCnt > 0) {
rulesetNode.accept(this._visitor);
}
else {
rulesetNode.rules = null;
}
visitArgs.visitDeeper = false;
}
else { // if (! rulesetNode.root) {
rulesetNode.accept(this._visitor);
visitArgs.visitDeeper = false;
}
if (rulesetNode.rules) {
this._mergeRules(rulesetNode.rules);
this._removeDuplicateRules(rulesetNode.rules);
}
// now decide whether we keep the ruleset
if (this.utils.isVisibleRuleset(rulesetNode)) {
rulesetNode.ensureVisibility();
rulesets.splice(0, 0, rulesetNode);
}
if (rulesets.length === 1) {
return rulesets[0];
}
return rulesets;
},
_compileRulesetPaths: function (rulesetNode) {
if (rulesetNode.paths) {
rulesetNode.paths = rulesetNode.paths
.filter(function (p) {
var i;
if (p[0].elements[0].combinator.value === ' ') {
p[0].elements[0].combinator = new (tree.Combinator)('');
}
for (i = 0; i < p.length; i++) {
if (p[i].isVisible() && p[i].getIsOutput()) {
return true;
}
}
return false;
});
}
},
_removeDuplicateRules: function (rules) {
if (!rules) {
return;
}
// remove duplicates
var ruleCache = {};
var ruleList;
var rule;
var i;
for (i = rules.length - 1; i >= 0; i--) {
rule = rules[i];
if (rule instanceof tree.Declaration) {
if (!ruleCache[rule.name]) {
ruleCache[rule.name] = rule;
}
else {
ruleList = ruleCache[rule.name];
if (ruleList instanceof tree.Declaration) {
ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._context)];
}
var ruleCSS = rule.toCSS(this._context);
if (ruleList.indexOf(ruleCSS) !== -1) {
rules.splice(i, 1);
}
else {
ruleList.push(ruleCSS);
}
}
}
}
},
_mergeRules: function (rules) {
if (!rules) {
return;
}
var groups = {};
var groupsArr = [];
for (var i_3 = 0; i_3 < rules.length; i_3++) {
var rule = rules[i_3];
if (rule.merge) {
var key = rule.name;
groups[key] ? rules.splice(i_3--, 1) :
groupsArr.push(groups[key] = []);
groups[key].push(rule);
}
}
groupsArr.forEach(function (group) {
if (group.length > 0) {
var result_1 = group[0];
var space_1 = [];
var comma_1 = [new tree.Expression(space_1)];
group.forEach(function (rule) {
if ((rule.merge === '+') && (space_1.length > 0)) {
comma_1.push(new tree.Expression(space_1 = []));
}
space_1.push(rule.value);
result_1.important = result_1.important || rule.important;
});
result_1.value = new tree.Value(comma_1);
}
});
}
};
var visitors = {
Visitor: Visitor,
ImportVisitor: ImportVisitor,
MarkVisibleSelectorsVisitor: SetTreeVisibilityVisitor,
ExtendVisitor: ProcessExtendsVisitor,
JoinSelectorVisitor: JoinSelectorVisitor,
ToCSSVisitor: ToCSSVisitor
};
// Split the input into chunks.
var chunker = (function (input, fail) {
var len = input.length;
var level = 0;
var parenLevel = 0;
var lastOpening;
var lastOpeningParen;
var lastMultiComment;
var lastMultiCommentEndBrace;
var chunks = [];
var emitFrom = 0;
var chunkerCurrentIndex;
var currentChunkStartIndex;
var cc;
var cc2;
var matched;
function emitChunk(force) {
var len = chunkerCurrentIndex - emitFrom;
if (((len < 512) && !force) || !len) {
return;
}
chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1));
emitFrom = chunkerCurrentIndex + 1;
}
for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
cc = input.charCodeAt(chunkerCurrentIndex);
if (((cc >= 97) && (cc <= 122)) || (cc < 34)) {
// a-z or whitespace
continue;
}
switch (cc) {
case 40: // (
parenLevel++;
lastOpeningParen = chunkerCurrentIndex;
continue;
case 41: // )
if (--parenLevel < 0) {
return fail('missing opening `(`', chunkerCurrentIndex);
}
continue;
case 59: // ;
if (!parenLevel) {
emitChunk();
}
continue;
case 123: // {
level++;
lastOpening = chunkerCurrentIndex;
continue;
case 125: // }
if (--level < 0) {
return fail('missing opening `{`', chunkerCurrentIndex);
}
if (!level && !parenLevel) {
emitChunk();
}
continue;
case 92: // \
if (chunkerCurrentIndex < len - 1) {
chunkerCurrentIndex++;
continue;
}
return fail('unescaped `\\`', chunkerCurrentIndex);
case 34:
case 39:
case 96: // ", ' and `
matched = 0;
currentChunkStartIndex = chunkerCurrentIndex;
for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
cc2 = input.charCodeAt(chunkerCurrentIndex);
if (cc2 > 96) {
continue;
}
if (cc2 == cc) {
matched = 1;
break;
}
if (cc2 == 92) { // \
if (chunkerCurrentIndex == len - 1) {
return fail('unescaped `\\`', chunkerCurrentIndex);
}
chunkerCurrentIndex++;
}
}
if (matched) {
continue;
}
return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex);
case 47: // /, check for comment
if (parenLevel || (chunkerCurrentIndex == len - 1)) {
continue;
}
cc2 = input.charCodeAt(chunkerCurrentIndex + 1);
if (cc2 == 47) {
// //, find lnfeed
for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) {
cc2 = input.charCodeAt(chunkerCurrentIndex);
if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) {
break;
}
}
}
else if (cc2 == 42) {
// /*, find */
lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex;
for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) {
cc2 = input.charCodeAt(chunkerCurrentIndex);
if (cc2 == 125) {
lastMultiCommentEndBrace = chunkerCurrentIndex;
}
if (cc2 != 42) {
continue;
}
if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) {
break;
}
}
if (chunkerCurrentIndex == len - 1) {
return fail('missing closing `*/`', currentChunkStartIndex);
}
chunkerCurrentIndex++;
}
continue;
case 42: // *, check for unmatched */
if ((chunkerCurrentIndex < len - 1) && (input.charCodeAt(chunkerCurrentIndex + 1) == 47)) {
return fail('unmatched `/*`', chunkerCurrentIndex);
}
continue;
}
}
if (level !== 0) {
if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) {
return fail('missing closing `}` or `*/`', lastOpening);
}
else {
return fail('missing closing `}`', lastOpening);
}
}
else if (parenLevel !== 0) {
return fail('missing closing `)`', lastOpeningParen);
}
emitChunk(true);
return chunks;
});
var getParserInput = (function () {
var // Less input string
input;
var // current chunk
j;
var // holds state for backtracking
saveStack = [];
var // furthest index the parser has gone to
furthest;
var // if this is furthest we got to, this is the probably cause
furthestPossibleErrorMessage;
var // chunkified input
chunks;
var // current chunk
current;
var // index of current chunk, in `input`
currentPos;
var parserInput = {};
var CHARCODE_SPACE = 32;
var CHARCODE_TAB = 9;
var CHARCODE_LF = 10;
var CHARCODE_CR = 13;
var CHARCODE_PLUS = 43;
var CHARCODE_COMMA = 44;
var CHARCODE_FORWARD_SLASH = 47;
var CHARCODE_9 = 57;
function skipWhitespace(length) {
var oldi = parserInput.i;
var oldj = j;
var curr = parserInput.i - currentPos;
var endIndex = parserInput.i + current.length - curr;
var mem = (parserInput.i += length);
var inp = input;
var c;
var nextChar;
var comment;
for (; parserInput.i < endIndex; parserInput.i++) {
c = inp.charCodeAt(parserInput.i);
if (parserInput.autoCommentAbsorb && c === CHARCODE_FORWARD_SLASH) {
nextChar = inp.charAt(parserInput.i + 1);
if (nextChar === '/') {
comment = { index: parserInput.i, isLineComment: true };
var nextNewLine = inp.indexOf('\n', parserInput.i + 2);
if (nextNewLine < 0) {
nextNewLine = endIndex;
}
parserInput.i = nextNewLine;
comment.text = inp.substr(comment.index, parserInput.i - comment.index);
parserInput.commentStore.push(comment);
continue;
}
else if (nextChar === '*') {
var nextStarSlash = inp.indexOf('*/', parserInput.i + 2);
if (nextStarSlash >= 0) {
comment = {
index: parserInput.i,
text: inp.substr(parserInput.i, nextStarSlash + 2 - parserInput.i),
isLineComment: false
};
parserInput.i += comment.text.length - 1;
parserInput.commentStore.push(comment);
continue;
}
}
break;
}
if ((c !== CHARCODE_SPACE) && (c !== CHARCODE_LF) && (c !== CHARCODE_TAB) && (c !== CHARCODE_CR)) {
break;
}
}
current = current.slice(length + parserInput.i - mem + curr);
currentPos = parserInput.i;
if (!current.length) {
if (j < chunks.length - 1) {
current = chunks[++j];
skipWhitespace(0); // skip space at the beginning of a chunk
return true; // things changed
}
parserInput.finished = true;
}
return oldi !== parserInput.i || oldj !== j;
}
parserInput.save = function () {
currentPos = parserInput.i;
saveStack.push({ current: current, i: parserInput.i, j: j });
};
parserInput.restore = function (possibleErrorMessage) {
if (parserInput.i > furthest || (parserInput.i === furthest && possibleErrorMessage && !furthestPossibleErrorMessage)) {
furthest = parserInput.i;
furthestPossibleErrorMessage = possibleErrorMessage;
}
var state = saveStack.pop();
current = state.current;
currentPos = parserInput.i = state.i;
j = state.j;
};
parserInput.forget = function () {
saveStack.pop();
};
parserInput.isWhitespace = function (offset) {
var pos = parserInput.i + (offset || 0);
var code = input.charCodeAt(pos);
return (code === CHARCODE_SPACE || code === CHARCODE_CR || code === CHARCODE_TAB || code === CHARCODE_LF);
};
// Specialization of $(tok)
parserInput.$re = function (tok) {
if (parserInput.i > currentPos) {
current = current.slice(parserInput.i - currentPos);
currentPos = parserInput.i;
}
var m = tok.exec(current);
if (!m) {
return null;
}
skipWhitespace(m[0].length);
if (typeof m === 'string') {
return m;
}
return m.length === 1 ? m[0] : m;
};
parserInput.$char = function (tok) {
if (input.charAt(parserInput.i) !== tok) {
return null;
}
skipWhitespace(1);
return tok;
};
parserInput.$str = function (tok) {
var tokLength = tok.length;
// https://jsperf.com/string-startswith/21
for (var i_1 = 0; i_1 < tokLength; i_1++) {
if (input.charAt(parserInput.i + i_1) !== tok.charAt(i_1)) {
return null;
}
}
skipWhitespace(tokLength);
return tok;
};
parserInput.$quoted = function (loc) {
var pos = loc || parserInput.i;
var startChar = input.charAt(pos);
if (startChar !== '\'' && startChar !== '"') {
return;
}
var length = input.length;
var currentPosition = pos;
for (var i_2 = 1; i_2 + currentPosition < length; i_2++) {
var nextChar = input.charAt(i_2 + currentPosition);
switch (nextChar) {
case '\\':
i_2++;
continue;
case '\r':
case '\n':
break;
case startChar:
var str = input.substr(currentPosition, i_2 + 1);
if (!loc && loc !== 0) {
skipWhitespace(i_2 + 1);
return str;
}
return [startChar, str];
}
}
return null;
};
/**
* Permissive parsing. Ignores everything except matching {} [] () and quotes
* until matching token (outside of blocks)
*/
parserInput.$parseUntil = function (tok) {
var quote = '';
var returnVal = null;
var inComment = false;
var blockDepth = 0;
var blockStack = [];
var parseGroups = [];
var length = input.length;
var startPos = parserInput.i;
var lastPos = parserInput.i;
var i = parserInput.i;
var loop = true;
var testChar;
if (typeof tok === 'string') {
testChar = function (char) { return char === tok; };
}
else {
testChar = function (char) { return tok.test(char); };
}
do {
var nextChar = input.charAt(i);
if (blockDepth === 0 && testChar(nextChar)) {
returnVal = input.substr(lastPos, i - lastPos);
if (returnVal) {
parseGroups.push(returnVal);
}
else {
parseGroups.push(' ');
}
returnVal = parseGroups;
skipWhitespace(i - startPos);
loop = false;
}
else {
if (inComment) {
if (nextChar === '*' &&
input.charAt(i + 1) === '/') {
i++;
blockDepth--;
inComment = false;
}
i++;
continue;
}
switch (nextChar) {
case '\\':
i++;
nextChar = input.charAt(i);
parseGroups.push(input.substr(lastPos, i - lastPos + 1));
lastPos = i + 1;
break;
case '/':
if (input.charAt(i + 1) === '*') {
i++;
inComment = true;
blockDepth++;
}
break;
case '\'':
case '"':
quote = parserInput.$quoted(i);
if (quote) {
parseGroups.push(input.substr(lastPos, i - lastPos), quote);
i += quote[1].length - 1;
lastPos = i + 1;
}
else {
skipWhitespace(i - startPos);
returnVal = nextChar;
loop = false;
}
break;
case '{':
blockStack.push('}');
blockDepth++;
break;
case '(':
blockStack.push(')');
blockDepth++;
break;
case '[':
blockStack.push(']');
blockDepth++;
break;
case '}':
case ')':
case ']':
var expected = blockStack.pop();
if (nextChar === expected) {
blockDepth--;
}
else {
// move the parser to the error and return expected
skipWhitespace(i - startPos);
returnVal = expected;
loop = false;
}
}
i++;
if (i > length) {
loop = false;
}
}
} while (loop);
return returnVal ? returnVal : null;
};
parserInput.autoCommentAbsorb = true;
parserInput.commentStore = [];
parserInput.finished = false;
// Same as $(), but don't change the state of the parser,
// just return the match.
parserInput.peek = function (tok) {
if (typeof tok === 'string') {
// https://jsperf.com/string-startswith/21
for (var i_3 = 0; i_3 < tok.length; i_3++) {
if (input.charAt(parserInput.i + i_3) !== tok.charAt(i_3)) {
return false;
}
}
return true;
}
else {
return tok.test(current);
}
};
// Specialization of peek()
// TODO remove or change some currentChar calls to peekChar
parserInput.peekChar = function (tok) { return input.charAt(parserInput.i) === tok; };
parserInput.currentChar = function () { return input.charAt(parserInput.i); };
parserInput.prevChar = function () { return input.charAt(parserInput.i - 1); };
parserInput.getInput = function () { return input; };
parserInput.peekNotNumeric = function () {
var c = input.charCodeAt(parserInput.i);
// Is the first char of the dimension 0-9, '.', '+' or '-'
return (c > CHARCODE_9 || c < CHARCODE_PLUS) || c === CHARCODE_FORWARD_SLASH || c === CHARCODE_COMMA;
};
parserInput.start = function (str, chunkInput, failFunction) {
input = str;
parserInput.i = j = currentPos = furthest = 0;
// chunking apparently makes things quicker (but my tests indicate
// it might actually make things slower in node at least)
// and it is a non-perfect parse - it can't recognise
// unquoted urls, meaning it can't distinguish comments
// meaning comments with quotes or {}() in them get 'counted'
// and then lead to parse errors.
// In addition if the chunking chunks in the wrong place we might
// not be able to parse a parser statement in one go
// this is officially deprecated but can be switched on via an option
// in the case it causes too much performance issues.
if (chunkInput) {
chunks = chunker(str, failFunction);
}
else {
chunks = [str];
}
current = chunks[0];
skipWhitespace(0);
};
parserInput.end = function () {
var message;
var isFinished = parserInput.i >= input.length;
if (parserInput.i < furthest) {
message = furthestPossibleErrorMessage;
parserInput.i = furthest;
}
return {
isFinished: isFinished,
furthest: parserInput.i,
furthestPossibleErrorMessage: message,
furthestReachedEnd: parserInput.i >= input.length - 1,
furthestChar: input[parserInput.i]
};
};
return parserInput;
});
//
// less.js - parser
//
// A relatively straight-forward predictive parser.
// There is no tokenization/lexing stage, the input is parsed
// in one sweep.
//
// To make the parser fast enough to run in the browser, several
// optimization had to be made:
//
// - Matching and slicing on a huge input is often cause of slowdowns.
// The solution is to chunkify the input into smaller strings.
// The chunks are stored in the `chunks` var,
// `j` holds the current chunk index, and `currentPos` holds
// the index of the current chunk in relation to `input`.
// This gives us an almost 4x speed-up.
//
// - In many cases, we don't need to match individual tokens;
// for example, if a value doesn't hold any variables, operations
// or dynamic references, the parser can effectively 'skip' it,
// treating it as a literal.
// An example would be '1px solid #000' - which evaluates to itself,
// we don't need to know what the individual components are.
// The drawback, of course is that you don't get the benefits of
// syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
// and a smaller speed-up in the code-gen.
//
//
// Token matching is done with the `$` function, which either takes
// a terminal string or regexp, or a non-terminal function to call.
// It also takes care of moving all the indices forwards.
//
var Parser = function Parser(context, imports, fileInfo) {
var parsers;
var parserInput = getParserInput();
function error(msg, type) {
throw new LessError({
index: parserInput.i,
filename: fileInfo.filename,
type: type || 'Syntax',
message: msg
}, imports);
}
function expect(arg, msg) {
// some older browsers return typeof 'function' for RegExp
var result = (arg instanceof Function) ? arg.call(parsers) : parserInput.$re(arg);
if (result) {
return result;
}
error(msg || (typeof arg === 'string'
? "expected '" + arg + "' got '" + parserInput.currentChar() + "'"
: 'unexpected token'));
}
// Specialization of expect()
function expectChar(arg, msg) {
if (parserInput.$char(arg)) {
return arg;
}
error(msg || "expected '" + arg + "' got '" + parserInput.currentChar() + "'");
}
function getDebugInfo(index) {
var filename = fileInfo.filename;
return {
lineNumber: getLocation(index, parserInput.getInput()).line + 1,
fileName: filename
};
}
/**
* Used after initial parsing to create nodes on the fly
*
* @param {String} str - string to parse
* @param {Array} parseList - array of parsers to run input through e.g. ["value", "important"]
* @param {Number} currentIndex - start number to begin indexing
* @param {Object} fileInfo - fileInfo to attach to created nodes
*/
function parseNode(str, parseList, currentIndex, fileInfo, callback) {
var result;
var returnNodes = [];
var parser = parserInput;
try {
parser.start(str, false, function fail(msg, index) {
callback({
message: msg,
index: index + currentIndex
});
});
for (var x = 0, p = void 0, i_1; (p = parseList[x]); x++) {
i_1 = parser.i;
result = parsers[p]();
if (result) {
try {
result._index = i_1 + currentIndex;
result._fileInfo = fileInfo;
}
catch (e) { }
returnNodes.push(result);
}
else {
returnNodes.push(null);
}
}
var endInfo = parser.end();
if (endInfo.isFinished) {
callback(null, returnNodes);
}
else {
callback(true, null);
}
}
catch (e) {
throw new LessError({
index: e.index + currentIndex,
message: e.message
}, imports, fileInfo.filename);
}
}
//
// The Parser
//
return {
parserInput: parserInput,
imports: imports,
fileInfo: fileInfo,
parseNode: parseNode,
//
// Parse an input string into an abstract syntax tree,
// @param str A string containing 'less' markup
// @param callback call `callback` when done.
// @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply
//
parse: function (str, callback, additionalData) {
var root;
var error = null;
var globalVars;
var modifyVars;
var ignored;
var preText = '';
globalVars = (additionalData && additionalData.globalVars) ? Parser.serializeVars(additionalData.globalVars) + "\n" : '';
modifyVars = (additionalData && additionalData.modifyVars) ? "\n" + Parser.serializeVars(additionalData.modifyVars) : '';
if (context.pluginManager) {
var preProcessors = context.pluginManager.getPreProcessors();
for (var i_2 = 0; i_2 < preProcessors.length; i_2++) {
str = preProcessors[i_2].process(str, { context: context, imports: imports, fileInfo: fileInfo });
}
}
if (globalVars || (additionalData && additionalData.banner)) {
preText = ((additionalData && additionalData.banner) ? additionalData.banner : '') + globalVars;
ignored = imports.contentsIgnoredChars;
ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0;
ignored[fileInfo.filename] += preText.length;
}
str = str.replace(/\r\n?/g, '\n');
// Remove potential UTF Byte Order Mark
str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
imports.contents[fileInfo.filename] = str;
// Start with the primary rule.
// The whole syntax tree is held under a Ruleset node,
// with the `root` property set to true, so no `{}` are
// output. The callback is called when the input is parsed.
try {
parserInput.start(str, context.chunkInput, function fail(msg, index) {
throw new LessError({
index: index,
type: 'Parse',
message: msg,
filename: fileInfo.filename
}, imports);
});
tree.Node.prototype.parse = this;
root = new tree.Ruleset(null, this.parsers.primary());
tree.Node.prototype.rootNode = root;
root.root = true;
root.firstRoot = true;
root.functionRegistry = functionRegistry.inherit();
}
catch (e) {
return callback(new LessError(e, imports, fileInfo.filename));
}
// If `i` is smaller than the `input.length - 1`,
// it means the parser wasn't able to parse the whole
// string, so we've got a parsing error.
//
// We try to extract a \n delimited string,
// showing the line where the parse error occurred.
// We split it up into two parts (the part which parsed,
// and the part which didn't), so we can color them differently.
var endInfo = parserInput.end();
if (!endInfo.isFinished) {
var message = endInfo.furthestPossibleErrorMessage;
if (!message) {
message = 'Unrecognised input';
if (endInfo.furthestChar === '}') {
message += '. Possibly missing opening \'{\'';
}
else if (endInfo.furthestChar === ')') {
message += '. Possibly missing opening \'(\'';
}
else if (endInfo.furthestReachedEnd) {
message += '. Possibly missing something';
}
}
error = new LessError({
type: 'Parse',
message: message,
index: endInfo.furthest,
filename: fileInfo.filename
}, imports);
}
var finish = function (e) {
e = error || e || imports.error;
if (e) {
if (!(e instanceof LessError)) {
e = new LessError(e, imports, fileInfo.filename);
}
return callback(e);
}
else {
return callback(null, root);
}
};
if (context.processImports !== false) {
new visitors.ImportVisitor(imports, finish)
.run(root);
}
else {
return finish();
}
},
//
// Here in, the parsing rules/functions
//
// The basic structure of the syntax tree generated is as follows:
//
// Ruleset -> Declaration -> Value -> Expression -> Entity
//
// Here's some Less code:
//
// .class {
// color: #fff;
// border: 1px solid #000;
// width: @w + 4px;
// > .child {...}
// }
//
// And here's what the parse tree might look like:
//
// Ruleset (Selector '.class', [
// Declaration ("color", Value ([Expression [Color #fff]]))
// Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
// Declaration ("width", Value ([Expression [Operation " + " [Variable "@w"][Dimension 4px]]]))
// Ruleset (Selector [Element '>', '.child'], [...])
// ])
//
// In general, most rules will try to parse a token with the `$re()` function, and if the return
// value is truly, will return a new node, of the relevant type. Sometimes, we need to check
// first, before parsing, that's when we use `peek()`.
//
parsers: parsers = {
//
// The `primary` rule is the *entry* and *exit* point of the parser.
// The rules here can appear at any level of the parse tree.
//
// The recursive nature of the grammar is an interplay between the `block`
// rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
// as represented by this simplified grammar:
//
// primary → (ruleset | declaration)+
// ruleset → selector+ block
// block → '{' primary '}'
//
// Only at one point is the primary rule not called from the
// block rule: at the root level.
//
primary: function () {
var mixin = this.mixin;
var root = [];
var node;
while (true) {
while (true) {
node = this.comment();
if (!node) {
break;
}
root.push(node);
}
// always process comments before deciding if finished
if (parserInput.finished) {
break;
}
if (parserInput.peek('}')) {
break;
}
node = this.extendRule();
if (node) {
root = root.concat(node);
continue;
}
node = mixin.definition() || this.declaration() || mixin.call(false, false) ||
this.ruleset() || this.variableCall() || this.entities.call() || this.atrule();
if (node) {
root.push(node);
}
else {
var foundSemiColon = false;
while (parserInput.$char(';')) {
foundSemiColon = true;
}
if (!foundSemiColon) {
break;
}
}
}
return root;
},
// comments are collected by the main parsing mechanism and then assigned to nodes
// where the current structure allows it
comment: function () {
if (parserInput.commentStore.length) {
var comment = parserInput.commentStore.shift();
return new (tree.Comment)(comment.text, comment.isLineComment, comment.index, fileInfo);
}
},
//
// Entities are tokens which can be found inside an Expression
//
entities: {
mixinLookup: function () {
return parsers.mixin.call(true, true);
},
//
// A string, which supports escaping " and '
//
// "milky way" 'he\'s the one!'
//
quoted: function (forceEscaped) {
var str;
var index = parserInput.i;
var isEscaped = false;
parserInput.save();
if (parserInput.$char('~')) {
isEscaped = true;
}
else if (forceEscaped) {
parserInput.restore();
return;
}
str = parserInput.$quoted();
if (!str) {
parserInput.restore();
return;
}
parserInput.forget();
return new (tree.Quoted)(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index, fileInfo);
},
//
// A catch-all word, such as:
//
// black border-collapse
//
keyword: function () {
var k = parserInput.$char('%') || parserInput.$re(/^\[?(?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\]?/);
if (k) {
return tree.Color.fromKeyword(k) || new (tree.Keyword)(k);
}
},
//
// A function call
//
// rgb(255, 0, 255)
//
// The arguments are parsed with the `entities.arguments` parser.
//
call: function () {
var name;
var args;
var func;
var index = parserInput.i;
// http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
if (parserInput.peek(/^url\(/i)) {
return;
}
parserInput.save();
name = parserInput.$re(/^([\w-]+|%|progid:[\w\.]+)\(/);
if (!name) {
parserInput.forget();
return;
}
name = name[1];
func = this.customFuncCall(name);
if (func) {
args = func.parse();
if (args && func.stop) {
parserInput.forget();
return args;
}
}
args = this.arguments(args);
if (!parserInput.$char(')')) {
parserInput.restore('Could not parse call arguments or missing \')\'');
return;
}
parserInput.forget();
return new (tree.Call)(name, args, index, fileInfo);
},
//
// Parsing rules for functions with non-standard args, e.g.:
//
// boolean(not(2 > 1))
//
// This is a quick prototype, to be modified/improved when
// more custom-parsed funcs come (e.g. `selector(...)`)
//
customFuncCall: function (name) {
/* Ideally the table is to be moved out of here for faster perf.,
but it's quite tricky since it relies on all these `parsers`
and `expect` available only here */
return {
alpha: f(parsers.ieAlpha, true),
boolean: f(condition),
'if': f(condition)
}[name.toLowerCase()];
function f(parse, stop) {
return {
parse: parse,
stop: stop // when true - stop after parse() and return its result,
// otherwise continue for plain args
};
}
function condition() {
return [expect(parsers.condition, 'expected condition')];
}
},
arguments: function (prevArgs) {
var argsComma = prevArgs || [];
var argsSemiColon = [];
var isSemiColonSeparated;
var value;
parserInput.save();
while (true) {
if (prevArgs) {
prevArgs = false;
}
else {
value = parsers.detachedRuleset() || this.assignment() || parsers.expression();
if (!value) {
break;
}
if (value.value && value.value.length == 1) {
value = value.value[0];
}
argsComma.push(value);
}
if (parserInput.$char(',')) {
continue;
}
if (parserInput.$char(';') || isSemiColonSeparated) {
isSemiColonSeparated = true;
value = (argsComma.length < 1) ? argsComma[0]
: new tree.Value(argsComma);
argsSemiColon.push(value);
argsComma = [];
}
}
parserInput.forget();
return isSemiColonSeparated ? argsSemiColon : argsComma;
},
literal: function () {
return this.dimension() ||
this.color() ||
this.quoted() ||
this.unicodeDescriptor();
},
// Assignments are argument entities for calls.
// They are present in ie filter properties as shown below.
//
// filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
//
assignment: function () {
var key;
var value;
parserInput.save();
key = parserInput.$re(/^\w+(?=\s?=)/i);
if (!key) {
parserInput.restore();
return;
}
if (!parserInput.$char('=')) {
parserInput.restore();
return;
}
value = parsers.entity();
if (value) {
parserInput.forget();
return new (tree.Assignment)(key, value);
}
else {
parserInput.restore();
}
},
//
// Parse url() tokens
//
// We use a specific rule for urls, because they don't really behave like
// standard function calls. The difference is that the argument doesn't have
// to be enclosed within a string, so it can't be parsed as an Expression.
//
url: function () {
var value;
var index = parserInput.i;
parserInput.autoCommentAbsorb = false;
if (!parserInput.$str('url(')) {
parserInput.autoCommentAbsorb = true;
return;
}
value = this.quoted() || this.variable() || this.property() ||
parserInput.$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || '';
parserInput.autoCommentAbsorb = true;
expectChar(')');
return new (tree.URL)((value.value != null ||
value instanceof tree.Variable ||
value instanceof tree.Property) ?
value : new (tree.Anonymous)(value, index), index, fileInfo);
},
//
// A Variable entity, such as `@fink`, in
//
// width: @fink + 2px
//
// We use a different parser for variable definitions,
// see `parsers.variable`.
//
variable: function () {
var ch;
var name;
var index = parserInput.i;
parserInput.save();
if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) {
ch = parserInput.currentChar();
if (ch === '(' || ch === '[' && !parserInput.prevChar().match(/^\s/)) {
// this may be a VariableCall lookup
var result = parsers.variableCall(name);
if (result) {
parserInput.forget();
return result;
}
}
parserInput.forget();
return new (tree.Variable)(name, index, fileInfo);
}
parserInput.restore();
},
// A variable entity using the protective {} e.g. @{var}
variableCurly: function () {
var curly;
var index = parserInput.i;
if (parserInput.currentChar() === '@' && (curly = parserInput.$re(/^@\{([\w-]+)\}/))) {
return new (tree.Variable)("@" + curly[1], index, fileInfo);
}
},
//
// A Property accessor, such as `$color`, in
//
// background-color: $color
//
property: function () {
var name;
var index = parserInput.i;
if (parserInput.currentChar() === '$' && (name = parserInput.$re(/^\$[\w-]+/))) {
return new (tree.Property)(name, index, fileInfo);
}
},
// A property entity useing the protective {} e.g. ${prop}
propertyCurly: function () {
var curly;
var index = parserInput.i;
if (parserInput.currentChar() === '$' && (curly = parserInput.$re(/^\$\{([\w-]+)\}/))) {
return new (tree.Property)("$" + curly[1], index, fileInfo);
}
},
//
// A Hexadecimal color
//
// #4F3C2F
//
// `rgb` and `hsl` colors are parsed through the `entities.call` parser.
//
color: function () {
var rgb;
parserInput.save();
if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\w.#\[])?/))) {
if (!rgb[2]) {
parserInput.forget();
return new (tree.Color)(rgb[1], undefined, rgb[0]);
}
}
parserInput.restore();
},
colorKeyword: function () {
parserInput.save();
var autoCommentAbsorb = parserInput.autoCommentAbsorb;
parserInput.autoCommentAbsorb = false;
var k = parserInput.$re(/^[_A-Za-z-][_A-Za-z0-9-]+/);
parserInput.autoCommentAbsorb = autoCommentAbsorb;
if (!k) {
parserInput.forget();
return;
}
parserInput.restore();
var color = tree.Color.fromKeyword(k);
if (color) {
parserInput.$str(k);
return color;
}
},
//
// A Dimension, that is, a number and a unit
//
// 0.5em 95%
//
dimension: function () {
if (parserInput.peekNotNumeric()) {
return;
}
var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i);
if (value) {
return new (tree.Dimension)(value[1], value[2]);
}
},
//
// A unicode descriptor, as is used in unicode-range
//
// U+0?? or U+00A1-00A9
//
unicodeDescriptor: function () {
var ud;
ud = parserInput.$re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/);
if (ud) {
return new (tree.UnicodeDescriptor)(ud[0]);
}
},
//
// JavaScript code to be evaluated
//
// `window.location.href`
//
javascript: function () {
var js;
var index = parserInput.i;
parserInput.save();
var escape = parserInput.$char('~');
var jsQuote = parserInput.$char('`');
if (!jsQuote) {
parserInput.restore();
return;
}
js = parserInput.$re(/^[^`]*`/);
if (js) {
parserInput.forget();
return new (tree.JavaScript)(js.substr(0, js.length - 1), Boolean(escape), index, fileInfo);
}
parserInput.restore('invalid javascript definition');
}
},
//
// The variable part of a variable definition. Used in the `rule` parser
//
// @fink:
//
variable: function () {
var name;
if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)\s*:/))) {
return name[1];
}
},
//
// Call a variable value to retrieve a detached ruleset
// or a value from a detached ruleset's rules.
//
// @fink();
// @fink;
// color: @fink[@color];
//
variableCall: function (parsedName) {
var lookups;
var i = parserInput.i;
var inValue = !!parsedName;
var name = parsedName;
parserInput.save();
if (name || (parserInput.currentChar() === '@'
&& (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/)))) {
lookups = this.mixin.ruleLookups();
if (!lookups && ((inValue && parserInput.$str('()') !== '()') || (name[2] !== '()'))) {
parserInput.restore('Missing \'[...]\' lookup in variable call');
return;
}
if (!inValue) {
name = name[1];
}
var call = new tree.VariableCall(name, i, fileInfo);
if (!inValue && parsers.end()) {
parserInput.forget();
return call;
}
else {
parserInput.forget();
return new tree.NamespaceValue(call, lookups, i, fileInfo);
}
}
parserInput.restore();
},
//
// extend syntax - used to extend selectors
//
extend: function (isRule) {
var elements;
var e;
var index = parserInput.i;
var option;
var extendList;
var extend;
if (!parserInput.$str(isRule ? '&:extend(' : ':extend(')) {
return;
}
do {
option = null;
elements = null;
while (!(option = parserInput.$re(/^(all)(?=\s*(\)|,))/))) {
e = this.element();
if (!e) {
break;
}
if (elements) {
elements.push(e);
}
else {
elements = [e];
}
}
option = option && option[1];
if (!elements) {
error('Missing target selector for :extend().');
}
extend = new (tree.Extend)(new (tree.Selector)(elements), option, index, fileInfo);
if (extendList) {
extendList.push(extend);
}
else {
extendList = [extend];
}
} while (parserInput.$char(','));
expect(/^\)/);
if (isRule) {
expect(/^;/);
}
return extendList;
},
//
// extendRule - used in a rule to extend all the parent selectors
//
extendRule: function () {
return this.extend(true);
},
//
// Mixins
//
mixin: {
//
// A Mixin call, with an optional argument list
//
// #mixins > .square(#fff);
// #mixins.square(#fff);
// .rounded(4px, black);
// .button;
//
// We can lookup / return a value using the lookup syntax:
//
// color: #mixin.square(#fff)[@color];
//
// The `while` loop is there because mixins can be
// namespaced, but we only support the child and descendant
// selector for now.
//
call: function (inValue, getLookup) {
var s = parserInput.currentChar();
var important = false;
var lookups;
var index = parserInput.i;
var elements;
var args;
var hasParens;
if (s !== '.' && s !== '#') {
return;
}
parserInput.save(); // stop us absorbing part of an invalid selector
elements = this.elements();
if (elements) {
if (parserInput.$char('(')) {
args = this.args(true).args;
expectChar(')');
hasParens = true;
}
if (getLookup !== false) {
lookups = this.ruleLookups();
}
if (getLookup === true && !lookups) {
parserInput.restore();
return;
}
if (inValue && !lookups && !hasParens) {
// This isn't a valid in-value mixin call
parserInput.restore();
return;
}
if (!inValue && parsers.important()) {
important = true;
}
if (inValue || parsers.end()) {
parserInput.forget();
var mixin = new (tree.mixin.Call)(elements, args, index, fileInfo, !lookups && important);
if (lookups) {
return new tree.NamespaceValue(mixin, lookups);
}
else {
return mixin;
}
}
}
parserInput.restore();
},
/**
* Matching elements for mixins
* (Start with . or # and can have > )
*/
elements: function () {
var elements;
var e;
var c;
var elem;
var elemIndex;
var re = /^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/;
while (true) {
elemIndex = parserInput.i;
e = parserInput.$re(re);
if (!e) {
break;
}
elem = new (tree.Element)(c, e, false, elemIndex, fileInfo);
if (elements) {
elements.push(elem);
}
else {
elements = [elem];
}
c = parserInput.$char('>');
}
return elements;
},
args: function (isCall) {
var entities = parsers.entities;
var returner = { args: null, variadic: false };
var expressions = [];
var argsSemiColon = [];
var argsComma = [];
var isSemiColonSeparated;
var expressionContainsNamed;
var name;
var nameLoop;
var value;
var arg;
var expand;
var hasSep = true;
parserInput.save();
while (true) {
if (isCall) {
arg = parsers.detachedRuleset() || parsers.expression();
}
else {
parserInput.commentStore.length = 0;
if (parserInput.$str('...')) {
returner.variadic = true;
if (parserInput.$char(';') && !isSemiColonSeparated) {
isSemiColonSeparated = true;
}
(isSemiColonSeparated ? argsSemiColon : argsComma)
.push({ variadic: true });
break;
}
arg = entities.variable() || entities.property() || entities.literal() || entities.keyword() || this.call(true);
}
if (!arg || !hasSep) {
break;
}
nameLoop = null;
if (arg.throwAwayComments) {
arg.throwAwayComments();
}
value = arg;
var val = null;
if (isCall) {
// Variable
if (arg.value && arg.value.length == 1) {
val = arg.value[0];
}
}
else {
val = arg;
}
if (val && (val instanceof tree.Variable || val instanceof tree.Property)) {
if (parserInput.$char(':')) {
if (expressions.length > 0) {
if (isSemiColonSeparated) {
error('Cannot mix ; and , as delimiter types');
}
expressionContainsNamed = true;
}
value = parsers.detachedRuleset() || parsers.expression();
if (!value) {
if (isCall) {
error('could not understand value for named argument');
}
else {
parserInput.restore();
returner.args = [];
return returner;
}
}
nameLoop = (name = val.name);
}
else if (parserInput.$str('...')) {
if (!isCall) {
returner.variadic = true;
if (parserInput.$char(';') && !isSemiColonSeparated) {
isSemiColonSeparated = true;
}
(isSemiColonSeparated ? argsSemiColon : argsComma)
.push({ name: arg.name, variadic: true });
break;
}
else {
expand = true;
}
}
else if (!isCall) {
name = nameLoop = val.name;
value = null;
}
}
if (value) {
expressions.push(value);
}
argsComma.push({ name: nameLoop, value: value, expand: expand });
if (parserInput.$char(',')) {
hasSep = true;
continue;
}
hasSep = parserInput.$char(';') === ';';
if (hasSep || isSemiColonSeparated) {
if (expressionContainsNamed) {
error('Cannot mix ; and , as delimiter types');
}
isSemiColonSeparated = true;
if (expressions.length > 1) {
value = new (tree.Value)(expressions);
}
argsSemiColon.push({ name: name, value: value, expand: expand });
name = null;
expressions = [];
expressionContainsNamed = false;
}
}
parserInput.forget();
returner.args = isSemiColonSeparated ? argsSemiColon : argsComma;
return returner;
},
//
// A Mixin definition, with a list of parameters
//
// .rounded (@radius: 2px, @color) {
// ...
// }
//
// Until we have a finer grained state-machine, we have to
// do a look-ahead, to make sure we don't have a mixin call.
// See the `rule` function for more information.
//
// We start by matching `.rounded (`, and then proceed on to
// the argument list, which has optional default values.
// We store the parameters in `params`, with a `value` key,
// if there is a value, such as in the case of `@radius`.
//
// Once we've got our params list, and a closing `)`, we parse
// the `{...}` block.
//
definition: function () {
var name;
var params = [];
var match;
var ruleset;
var cond;
var variadic = false;
if ((parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#') ||
parserInput.peek(/^[^{]*\}/)) {
return;
}
parserInput.save();
match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/);
if (match) {
name = match[1];
var argInfo = this.args(false);
params = argInfo.args;
variadic = argInfo.variadic;
// .mixincall("@{a}");
// looks a bit like a mixin definition..
// also
// .mixincall(@a: {rule: set;});
// so we have to be nice and restore
if (!parserInput.$char(')')) {
parserInput.restore('Missing closing \')\'');
return;
}
parserInput.commentStore.length = 0;
if (parserInput.$str('when')) { // Guard
cond = expect(parsers.conditions, 'expected condition');
}
ruleset = parsers.block();
if (ruleset) {
parserInput.forget();
return new (tree.mixin.Definition)(name, params, ruleset, cond, variadic);
}
else {
parserInput.restore();
}
}
else {
parserInput.restore();
}
},
ruleLookups: function () {
var rule;
var lookups = [];
if (parserInput.currentChar() !== '[') {
return;
}
while (true) {
parserInput.save();
rule = this.lookupValue();
if (!rule && rule !== '') {
parserInput.restore();
break;
}
lookups.push(rule);
parserInput.forget();
}
if (lookups.length > 0) {
return lookups;
}
},
lookupValue: function () {
parserInput.save();
if (!parserInput.$char('[')) {
parserInput.restore();
return;
}
var name = parserInput.$re(/^(?:[@$]{0,2})[_a-zA-Z0-9-]*/);
if (!parserInput.$char(']')) {
parserInput.restore();
return;
}
if (name || name === '') {
parserInput.forget();
return name;
}
parserInput.restore();
}
},
//
// Entities are the smallest recognized token,
// and can be found inside a rule's value.
//
entity: function () {
var entities = this.entities;
return this.comment() || entities.literal() || entities.variable() || entities.url() ||
entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) ||
entities.javascript();
},
//
// A Declaration terminator. Note that we use `peek()` to check for '}',
// because the `block` rule will be expecting it, but we still need to make sure
// it's there, if ';' was omitted.
//
end: function () {
return parserInput.$char(';') || parserInput.peek('}');
},
//
// IE's alpha function
//
// alpha(opacity=88)
//
ieAlpha: function () {
var value;
// http://jsperf.com/case-insensitive-regex-vs-strtolower-then-regex/18
if (!parserInput.$re(/^opacity=/i)) {
return;
}
value = parserInput.$re(/^\d+/);
if (!value) {
value = expect(parsers.entities.variable, 'Could not parse alpha');
value = "@{" + value.name.slice(1) + "}";
}
expectChar(')');
return new tree.Quoted('', "alpha(opacity=" + value + ")");
},
//
// A Selector Element
//
// div
// + h1
// #socks
// input[type="text"]
//
// Elements are the building blocks for Selectors,
// they are made out of a `Combinator` (see combinator rule),
// and an element name, such as a tag a class, or `*`.
//
element: function () {
var e;
var c;
var v;
var index = parserInput.i;
c = this.combinator();
e = parserInput.$re(/^(?:\d+\.\d+|\d+)%/) ||
parserInput.$re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) ||
parserInput.$char('*') || parserInput.$char('&') || this.attribute() ||
parserInput.$re(/^\([^&()@]+\)/) || parserInput.$re(/^[\.#:](?=@)/) ||
this.entities.variableCurly();
if (!e) {
parserInput.save();
if (parserInput.$char('(')) {
if ((v = this.selector(false)) && parserInput.$char(')')) {
e = new (tree.Paren)(v);
parserInput.forget();
}
else {
parserInput.restore('Missing closing \')\'');
}
}
else {
parserInput.forget();
}
}
if (e) {
return new (tree.Element)(c, e, e instanceof tree.Variable, index, fileInfo);
}
},
//
// Combinators combine elements together, in a Selector.
//
// Because our parser isn't white-space sensitive, special care
// has to be taken, when parsing the descendant combinator, ` `,
// as it's an empty space. We have to check the previous character
// in the input, to see if it's a ` ` character. More info on how
// we deal with this in *combinator.js*.
//
combinator: function () {
var c = parserInput.currentChar();
if (c === '/') {
parserInput.save();
var slashedCombinator = parserInput.$re(/^\/[a-z]+\//i);
if (slashedCombinator) {
parserInput.forget();
return new (tree.Combinator)(slashedCombinator);
}
parserInput.restore();
}
if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') {
parserInput.i++;
if (c === '^' && parserInput.currentChar() === '^') {
c = '^^';
parserInput.i++;
}
while (parserInput.isWhitespace()) {
parserInput.i++;
}
return new (tree.Combinator)(c);
}
else if (parserInput.isWhitespace(-1)) {
return new (tree.Combinator)(' ');
}
else {
return new (tree.Combinator)(null);
}
},
//
// A CSS Selector
// with less extensions e.g. the ability to extend and guard
//
// .class > div + h1
// li a:hover
//
// Selectors are made out of one or more Elements, see above.
//
selector: function (isLess) {
var index = parserInput.i;
var elements;
var extendList;
var c;
var e;
var allExtends;
var when;
var condition;
isLess = isLess !== false;
while ((isLess && (extendList = this.extend())) || (isLess && (when = parserInput.$str('when'))) || (e = this.element())) {
if (when) {
condition = expect(this.conditions, 'expected condition');
}
else if (condition) {
error('CSS guard can only be used at the end of selector');
}
else if (extendList) {
if (allExtends) {
allExtends = allExtends.concat(extendList);
}
else {
allExtends = extendList;
}
}
else {
if (allExtends) {
error('Extend can only be used at the end of selector');
}
c = parserInput.currentChar();
if (elements) {
elements.push(e);
}
else {
elements = [e];
}
e = null;
}
if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
break;
}
}
if (elements) {
return new (tree.Selector)(elements, allExtends, condition, index, fileInfo);
}
if (allExtends) {
error('Extend must be used to extend a selector, it cannot be used on its own');
}
},
selectors: function () {
var s;
var selectors;
while (true) {
s = this.selector();
if (!s) {
break;
}
if (selectors) {
selectors.push(s);
}
else {
selectors = [s];
}
parserInput.commentStore.length = 0;
if (s.condition && selectors.length > 1) {
error("Guards are only currently allowed on a single selector.");
}
if (!parserInput.$char(',')) {
break;
}
if (s.condition) {
error("Guards are only currently allowed on a single selector.");
}
parserInput.commentStore.length = 0;
}
return selectors;
},
attribute: function () {
if (!parserInput.$char('[')) {
return;
}
var entities = this.entities;
var key;
var val;
var op;
if (!(key = entities.variableCurly())) {
key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
}
op = parserInput.$re(/^[|~*$^]?=/);
if (op) {
val = entities.quoted() || parserInput.$re(/^[0-9]+%/) || parserInput.$re(/^[\w-]+/) || entities.variableCurly();
}
expectChar(']');
return new (tree.Attribute)(key, op, val);
},
//
// The `block` rule is used by `ruleset` and `mixin.definition`.
// It's a wrapper around the `primary` rule, with added `{}`.
//
block: function () {
var content;
if (parserInput.$char('{') && (content = this.primary()) && parserInput.$char('}')) {
return content;
}
},
blockRuleset: function () {
var block = this.block();
if (block) {
block = new tree.Ruleset(null, block);
}
return block;
},
detachedRuleset: function () {
var argInfo;
var params;
var variadic;
parserInput.save();
if (parserInput.$re(/^[.#]\(/)) {
/**
* DR args currently only implemented for each() function, and not
* yet settable as `@dr: #(@arg) {}`
* This should be done when DRs are merged with mixins.
* See: https://github.com/less/less-meta/issues/16
*/
argInfo = this.mixin.args(false);
params = argInfo.args;
variadic = argInfo.variadic;
if (!parserInput.$char(')')) {
parserInput.restore();
return;
}
}
var blockRuleset = this.blockRuleset();
if (blockRuleset) {
parserInput.forget();
if (params) {
return new tree.mixin.Definition(null, params, blockRuleset, null, variadic);
}
return new tree.DetachedRuleset(blockRuleset);
}
parserInput.restore();
},
//
// div, .class, body > p {...}
//
ruleset: function () {
var selectors;
var rules;
var debugInfo;
parserInput.save();
if (context.dumpLineNumbers) {
debugInfo = getDebugInfo(parserInput.i);
}
selectors = this.selectors();
if (selectors && (rules = this.block())) {
parserInput.forget();
var ruleset = new (tree.Ruleset)(selectors, rules, context.strictImports);
if (context.dumpLineNumbers) {
ruleset.debugInfo = debugInfo;
}
return ruleset;
}
else {
parserInput.restore();
}
},
declaration: function () {
var name;
var value;
var index = parserInput.i;
var hasDR;
var c = parserInput.currentChar();
var important;
var merge;
var isVariable;
if (c === '.' || c === '#' || c === '&' || c === ':') {
return;
}
parserInput.save();
name = this.variable() || this.ruleProperty();
if (name) {
isVariable = typeof name === 'string';
if (isVariable) {
value = this.detachedRuleset();
if (value) {
hasDR = true;
}
}
parserInput.commentStore.length = 0;
if (!value) {
// a name returned by this.ruleProperty() is always an array of the form:
// [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
// where each item is a tree.Keyword or tree.Variable
merge = !isVariable && name.length > 1 && name.pop().value;
// Custom property values get permissive parsing
if (name[0].value && name[0].value.slice(0, 2) === '--') {
value = this.permissiveValue();
}
// Try to store values as anonymous
// If we need the value later we'll re-parse it in ruleset.parseValue
else {
value = this.anonymousValue();
}
if (value) {
parserInput.forget();
// anonymous values absorb the end ';' which is required for them to work
return new (tree.Declaration)(name, value, false, merge, index, fileInfo);
}
if (!value) {
value = this.value();
}
if (value) {
important = this.important();
}
else if (isVariable) {
// As a last resort, try permissiveValue
value = this.permissiveValue();
}
}
if (value && (this.end() || hasDR)) {
parserInput.forget();
return new (tree.Declaration)(name, value, important, merge, index, fileInfo);
}
else {
parserInput.restore();
}
}
else {
parserInput.restore();
}
},
anonymousValue: function () {
var index = parserInput.i;
var match = parserInput.$re(/^([^.#@\$+\/'"*`(;{}-]*);/);
if (match) {
return new (tree.Anonymous)(match[1], index);
}
},
/**
* Used for custom properties, at-rules, and variables (as fallback)
* Parses almost anything inside of {} [] () "" blocks
* until it reaches outer-most tokens.
*
* First, it will try to parse comments and entities to reach
* the end. This is mostly like the Expression parser except no
* math is allowed.
*/
permissiveValue: function (untilTokens) {
var i;
var e;
var done;
var value;
var tok = untilTokens || ';';
var index = parserInput.i;
var result = [];
function testCurrentChar() {
var char = parserInput.currentChar();
if (typeof tok === 'string') {
return char === tok;
}
else {
return tok.test(char);
}
}
if (testCurrentChar()) {
return;
}
value = [];
do {
e = this.comment();
if (e) {
value.push(e);
continue;
}
e = this.entity();
if (e) {
value.push(e);
}
} while (e);
done = testCurrentChar();
if (value.length > 0) {
value = new (tree.Expression)(value);
if (done) {
return value;
}
else {
result.push(value);
}
// Preserve space before $parseUntil as it will not
if (parserInput.prevChar() === ' ') {
result.push(new tree.Anonymous(' ', index));
}
}
parserInput.save();
value = parserInput.$parseUntil(tok);
if (value) {
if (typeof value === 'string') {
error("Expected '" + value + "'", 'Parse');
}
if (value.length === 1 && value[0] === ' ') {
parserInput.forget();
return new tree.Anonymous('', index);
}
var item = void 0;
for (i = 0; i < value.length; i++) {
item = value[i];
if (Array.isArray(item)) {
// Treat actual quotes as normal quoted values
result.push(new tree.Quoted(item[0], item[1], true, index, fileInfo));
}
else {
if (i === value.length - 1) {
item = item.trim();
}
// Treat like quoted values, but replace vars like unquoted expressions
var quote = new tree.Quoted('\'', item, true, index, fileInfo);
quote.variableRegex = /@([\w-]+)/g;
quote.propRegex = /\$([\w-]+)/g;
result.push(quote);
}
}
parserInput.forget();
return new tree.Expression(result, true);
}
parserInput.restore();
},
//
// An @import atrule
//
// @import "lib";
//
// Depending on our environment, importing is done differently:
// In the browser, it's an XHR request, in Node, it would be a
// file-system operation. The function used for importing is
// stored in `import`, which we pass to the Import constructor.
//
'import': function () {
var path;
var features;
var index = parserInput.i;
var dir = parserInput.$re(/^@import?\s+/);
if (dir) {
var options_1 = (dir ? this.importOptions() : null) || {};
if ((path = this.entities.quoted() || this.entities.url())) {
features = this.mediaFeatures();
if (!parserInput.$char(';')) {
parserInput.i = index;
error('missing semi-colon or unrecognised media features on import');
}
features = features && new (tree.Value)(features);
return new (tree.Import)(path, features, options_1, index, fileInfo);
}
else {
parserInput.i = index;
error('malformed import statement');
}
}
},
importOptions: function () {
var o;
var options = {};
var optionName;
var value;
// list of options, surrounded by parens
if (!parserInput.$char('(')) {
return null;
}
do {
o = this.importOption();
if (o) {
optionName = o;
value = true;
switch (optionName) {
case 'css':
optionName = 'less';
value = false;
break;
case 'once':
optionName = 'multiple';
value = false;
break;
}
options[optionName] = value;
if (!parserInput.$char(',')) {
break;
}
}
} while (o);
expectChar(')');
return options;
},
importOption: function () {
var opt = parserInput.$re(/^(less|css|multiple|once|inline|reference|optional)/);
if (opt) {
return opt[1];
}
},
mediaFeature: function () {
var entities = this.entities;
var nodes = [];
var e;
var p;
parserInput.save();
do {
e = entities.keyword() || entities.variable() || entities.mixinLookup();
if (e) {
nodes.push(e);
}
else if (parserInput.$char('(')) {
p = this.property();
e = this.value();
if (parserInput.$char(')')) {
if (p && e) {
nodes.push(new (tree.Paren)(new (tree.Declaration)(p, e, null, null, parserInput.i, fileInfo, true)));
}
else if (e) {
nodes.push(new (tree.Paren)(e));
}
else {
error('badly formed media feature definition');
}
}
else {
error('Missing closing \')\'', 'Parse');
}
}
} while (e);
parserInput.forget();
if (nodes.length > 0) {
return new (tree.Expression)(nodes);
}
},
mediaFeatures: function () {
var entities = this.entities;
var features = [];
var e;
do {
e = this.mediaFeature();
if (e) {
features.push(e);
if (!parserInput.$char(',')) {
break;
}
}
else {
e = entities.variable() || entities.mixinLookup();
if (e) {
features.push(e);
if (!parserInput.$char(',')) {
break;
}
}
}
} while (e);
return features.length > 0 ? features : null;
},
media: function () {
var features;
var rules;
var media;
var debugInfo;
var index = parserInput.i;
if (context.dumpLineNumbers) {
debugInfo = getDebugInfo(index);
}
parserInput.save();
if (parserInput.$str('@media')) {
features = this.mediaFeatures();
rules = this.block();
if (!rules) {
error('media definitions require block statements after any features');
}
parserInput.forget();
media = new (tree.Media)(rules, features, index, fileInfo);
if (context.dumpLineNumbers) {
media.debugInfo = debugInfo;
}
return media;
}
parserInput.restore();
},
//
// A @plugin directive, used to import plugins dynamically.
//
// @plugin (args) "lib";
//
plugin: function () {
var path;
var args;
var options;
var index = parserInput.i;
var dir = parserInput.$re(/^@plugin?\s+/);
if (dir) {
args = this.pluginArgs();
if (args) {
options = {
pluginArgs: args,
isPlugin: true
};
}
else {
options = { isPlugin: true };
}
if ((path = this.entities.quoted() || this.entities.url())) {
if (!parserInput.$char(';')) {
parserInput.i = index;
error('missing semi-colon on @plugin');
}
return new (tree.Import)(path, null, options, index, fileInfo);
}
else {
parserInput.i = index;
error('malformed @plugin statement');
}
}
},
pluginArgs: function () {
// list of options, surrounded by parens
parserInput.save();
if (!parserInput.$char('(')) {
parserInput.restore();
return null;
}
var args = parserInput.$re(/^\s*([^\);]+)\)\s*/);
if (args[1]) {
parserInput.forget();
return args[1].trim();
}
else {
parserInput.restore();
return null;
}
},
//
// A CSS AtRule
//
// @charset "utf-8";
//
atrule: function () {
var index = parserInput.i;
var name;
var value;
var rules;
var nonVendorSpecificName;
var hasIdentifier;
var hasExpression;
var hasUnknown;
var hasBlock = true;
var isRooted = true;
if (parserInput.currentChar() !== '@') {
return;
}
value = this['import']() || this.plugin() || this.media();
if (value) {
return value;
}
parserInput.save();
name = parserInput.$re(/^@[a-z-]+/);
if (!name) {
return;
}
nonVendorSpecificName = name;
if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1);
}
switch (nonVendorSpecificName) {
case '@charset':
hasIdentifier = true;
hasBlock = false;
break;
case '@namespace':
hasExpression = true;
hasBlock = false;
break;
case '@keyframes':
case '@counter-style':
hasIdentifier = true;
break;
case '@document':
case '@supports':
hasUnknown = true;
isRooted = false;
break;
default:
hasUnknown = true;
break;
}
parserInput.commentStore.length = 0;
if (hasIdentifier) {
value = this.entity();
if (!value) {
error("expected " + name + " identifier");
}
}
else if (hasExpression) {
value = this.expression();
if (!value) {
error("expected " + name + " expression");
}
}
else if (hasUnknown) {
value = this.permissiveValue(/^[{;]/);
hasBlock = (parserInput.currentChar() === '{');
if (!value) {
if (!hasBlock && parserInput.currentChar() !== ';') {
error(name + " rule is missing block or ending semi-colon");
}
}
else if (!value.value) {
value = null;
}
}
if (hasBlock) {
rules = this.blockRuleset();
}
if (rules || (!hasBlock && value && parserInput.$char(';'))) {
parserInput.forget();
return new (tree.AtRule)(name, value, rules, index, fileInfo, context.dumpLineNumbers ? getDebugInfo(index) : null, isRooted);
}
parserInput.restore('at-rule options not recognised');
},
//
// A Value is a comma-delimited list of Expressions
//
// font-family: Baskerville, Georgia, serif;
//
// In a Rule, a Value represents everything after the `:`,
// and before the `;`.
//
value: function () {
var e;
var expressions = [];
var index = parserInput.i;
do {
e = this.expression();
if (e) {
expressions.push(e);
if (!parserInput.$char(',')) {
break;
}
}
} while (e);
if (expressions.length > 0) {
return new (tree.Value)(expressions, index);
}
},
important: function () {
if (parserInput.currentChar() === '!') {
return parserInput.$re(/^! *important/);
}
},
sub: function () {
var a;
var e;
parserInput.save();
if (parserInput.$char('(')) {
a = this.addition();
if (a && parserInput.$char(')')) {
parserInput.forget();
e = new (tree.Expression)([a]);
e.parens = true;
return e;
}
parserInput.restore('Expected \')\'');
return;
}
parserInput.restore();
},
multiplication: function () {
var m;
var a;
var op;
var operation;
var isSpaced;
m = this.operand();
if (m) {
isSpaced = parserInput.isWhitespace(-1);
while (true) {
if (parserInput.peek(/^\/[*\/]/)) {
break;
}
parserInput.save();
op = parserInput.$char('/') || parserInput.$char('*') || parserInput.$str('./');
if (!op) {
parserInput.forget();
break;
}
a = this.operand();
if (!a) {
parserInput.restore();
break;
}
parserInput.forget();
m.parensInOp = true;
a.parensInOp = true;
operation = new (tree.Operation)(op, [operation || m, a], isSpaced);
isSpaced = parserInput.isWhitespace(-1);
}
return operation || m;
}
},
addition: function () {
var m;
var a;
var op;
var operation;
var isSpaced;
m = this.multiplication();
if (m) {
isSpaced = parserInput.isWhitespace(-1);
while (true) {
op = parserInput.$re(/^[-+]\s+/) || (!isSpaced && (parserInput.$char('+') || parserInput.$char('-')));
if (!op) {
break;
}
a = this.multiplication();
if (!a) {
break;
}
m.parensInOp = true;
a.parensInOp = true;
operation = new (tree.Operation)(op, [operation || m, a], isSpaced);
isSpaced = parserInput.isWhitespace(-1);
}
return operation || m;
}
},
conditions: function () {
var a;
var b;
var index = parserInput.i;
var condition;
a = this.condition(true);
if (a) {
while (true) {
if (!parserInput.peek(/^,\s*(not\s*)?\(/) || !parserInput.$char(',')) {
break;
}
b = this.condition(true);
if (!b) {
break;
}
condition = new (tree.Condition)('or', condition || a, b, index);
}
return condition || a;
}
},
condition: function (needsParens) {
var result;
var logical;
var next;
function or() {
return parserInput.$str('or');
}
result = this.conditionAnd(needsParens);
if (!result) {
return;
}
logical = or();
if (logical) {
next = this.condition(needsParens);
if (next) {
result = new (tree.Condition)(logical, result, next);
}
else {
return;
}
}
return result;
},
conditionAnd: function (needsParens) {
var result;
var logical;
var next;
var self = this;
function insideCondition() {
var cond = self.negatedCondition(needsParens) || self.parenthesisCondition(needsParens);
if (!cond && !needsParens) {
return self.atomicCondition(needsParens);
}
return cond;
}
function and() {
return parserInput.$str('and');
}
result = insideCondition();
if (!result) {
return;
}
logical = and();
if (logical) {
next = this.conditionAnd(needsParens);
if (next) {
result = new (tree.Condition)(logical, result, next);
}
else {
return;
}
}
return result;
},
negatedCondition: function (needsParens) {
if (parserInput.$str('not')) {
var result = this.parenthesisCondition(needsParens);
if (result) {
result.negate = !result.negate;
}
return result;
}
},
parenthesisCondition: function (needsParens) {
function tryConditionFollowedByParenthesis(me) {
var body;
parserInput.save();
body = me.condition(needsParens);
if (!body) {
parserInput.restore();
return;
}
if (!parserInput.$char(')')) {
parserInput.restore();
return;
}
parserInput.forget();
return body;
}
var body;
parserInput.save();
if (!parserInput.$str('(')) {
parserInput.restore();
return;
}
body = tryConditionFollowedByParenthesis(this);
if (body) {
parserInput.forget();
return body;
}
body = this.atomicCondition(needsParens);
if (!body) {
parserInput.restore();
return;
}
if (!parserInput.$char(')')) {
parserInput.restore("expected ')' got '" + parserInput.currentChar() + "'");
return;
}
parserInput.forget();
return body;
},
atomicCondition: function (needsParens) {
var entities = this.entities;
var index = parserInput.i;
var a;
var b;
var c;
var op;
function cond() {
return this.addition() || entities.keyword() || entities.quoted() || entities.mixinLookup();
}
cond = cond.bind(this);
a = cond();
if (a) {
if (parserInput.$char('>')) {
if (parserInput.$char('=')) {
op = '>=';
}
else {
op = '>';
}
}
else if (parserInput.$char('<')) {
if (parserInput.$char('=')) {
op = '<=';
}
else {
op = '<';
}
}
else if (parserInput.$char('=')) {
if (parserInput.$char('>')) {
op = '=>';
}
else if (parserInput.$char('<')) {
op = '=<';
}
else {
op = '=';
}
}
if (op) {
b = cond();
if (b) {
c = new (tree.Condition)(op, a, b, index, false);
}
else {
error('expected expression');
}
}
else {
c = new (tree.Condition)('=', a, new (tree.Keyword)('true'), index, false);
}
return c;
}
},
//
// An operand is anything that can be part of an operation,
// such as a Color, or a Variable
//
operand: function () {
var entities = this.entities;
var negate;
if (parserInput.peek(/^-[@\$\(]/)) {
negate = parserInput.$char('-');
}
var o = this.sub() || entities.dimension() ||
entities.color() || entities.variable() ||
entities.property() || entities.call() ||
entities.quoted(true) || entities.colorKeyword() ||
entities.mixinLookup();
if (negate) {
o.parensInOp = true;
o = new (tree.Negative)(o);
}
return o;
},
//
// Expressions either represent mathematical operations,
// or white-space delimited Entities.
//
// 1px solid black
// @var * 2
//
expression: function () {
var entities = [];
var e;
var delim;
var index = parserInput.i;
do {
e = this.comment();
if (e) {
entities.push(e);
continue;
}
e = this.addition() || this.entity();
if (e) {
entities.push(e);
// operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
if (!parserInput.peek(/^\/[\/*]/)) {
delim = parserInput.$char('/');
if (delim) {
entities.push(new (tree.Anonymous)(delim, index));
}
}
}
} while (e);
if (entities.length > 0) {
return new (tree.Expression)(entities);
}
},
property: function () {
var name = parserInput.$re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);
if (name) {
return name[1];
}
},
ruleProperty: function () {
var name = [];
var index = [];
var s;
var k;
parserInput.save();
var simpleProperty = parserInput.$re(/^([_a-zA-Z0-9-]+)\s*:/);
if (simpleProperty) {
name = [new (tree.Keyword)(simpleProperty[1])];
parserInput.forget();
return name;
}
function match(re) {
var i = parserInput.i;
var chunk = parserInput.$re(re);
if (chunk) {
index.push(i);
return name.push(chunk[1]);
}
}
match(/^(\*?)/);
while (true) {
if (!match(/^((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/)) {
break;
}
}
if ((name.length > 1) && match(/^((?:\+_|\+)?)\s*:/)) {
parserInput.forget();
// at last, we have the complete match now. move forward,
// convert name particles to tree objects and return:
if (name[0] === '') {
name.shift();
index.shift();
}
for (k = 0; k < name.length; k++) {
s = name[k];
name[k] = (s.charAt(0) !== '@' && s.charAt(0) !== '$') ?
new (tree.Keyword)(s) :
(s.charAt(0) === '@' ?
new (tree.Variable)("@" + s.slice(2, -1), index[k], fileInfo) :
new (tree.Property)("$" + s.slice(2, -1), index[k], fileInfo));
}
return name;
}
parserInput.restore();
}
}
};
};
Parser.serializeVars = function (vars) {
var s = '';
for (var name_1 in vars) {
if (Object.hasOwnProperty.call(vars, name_1)) {
var value = vars[name_1];
s += ((name_1[0] === '@') ? '' : '@') + name_1 + ": " + value + ((String(value).slice(-1) === ';') ? '' : ';');
}
}
return s;
};
function boolean(condition) {
return condition ? Keyword.True : Keyword.False;
}
function If(condition, trueValue, falseValue) {
return condition ? trueValue
: (falseValue || new Anonymous);
}
var boolean$1 = { boolean: boolean, 'if': If };
var colorFunctions;
function clamp$1(val) {
return Math.min(1, Math.max(0, val));
}
function hsla(origColor, hsl) {
var color = colorFunctions.hsla(hsl.h, hsl.s, hsl.l, hsl.a);
if (color) {
if (origColor.value &&
/^(rgb|hsl)/.test(origColor.value)) {
color.value = origColor.value;
}
else {
color.value = 'rgb';
}
return color;
}
}
function toHSL(color) {
if (color.toHSL) {
return color.toHSL();
}
else {
throw new Error('Argument cannot be evaluated to a color');
}
}
function toHSV(color) {
if (color.toHSV) {
return color.toHSV();
}
else {
throw new Error('Argument cannot be evaluated to a color');
}
}
function number(n) {
if (n instanceof Dimension) {
return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
}
else if (typeof n === 'number') {
return n;
}
else {
throw {
type: 'Argument',
message: 'color functions take numbers as parameters'
};
}
}
function scaled(n, size) {
if (n instanceof Dimension && n.unit.is('%')) {
return parseFloat(n.value * size / 100);
}
else {
return number(n);
}
}
colorFunctions = {
rgb: function (r, g, b) {
var color = colorFunctions.rgba(r, g, b, 1.0);
if (color) {
color.value = 'rgb';
return color;
}
},
rgba: function (r, g, b, a) {
try {
if (r instanceof Color) {
if (g) {
a = number(g);
}
else {
a = r.alpha;
}
return new Color(r.rgb, a, 'rgba');
}
var rgb = [r, g, b].map(function (c) { return scaled(c, 255); });
a = number(a);
return new Color(rgb, a, 'rgba');
}
catch (e) { }
},
hsl: function (h, s, l) {
var color = colorFunctions.hsla(h, s, l, 1.0);
if (color) {
color.value = 'hsl';
return color;
}
},
hsla: function (h, s, l, a) {
try {
if (h instanceof Color) {
if (s) {
a = number(s);
}
else {
a = h.alpha;
}
return new Color(h.rgb, a, 'hsla');
}
var m1_1;
var m2_1;
function hue(h) {
h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
if (h * 6 < 1) {
return m1_1 + (m2_1 - m1_1) * h * 6;
}
else if (h * 2 < 1) {
return m2_1;
}
else if (h * 3 < 2) {
return m1_1 + (m2_1 - m1_1) * (2 / 3 - h) * 6;
}
else {
return m1_1;
}
}
h = (number(h) % 360) / 360;
s = clamp$1(number(s));
l = clamp$1(number(l));
a = clamp$1(number(a));
m2_1 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
m1_1 = l * 2 - m2_1;
var rgb = [
hue(h + 1 / 3) * 255,
hue(h) * 255,
hue(h - 1 / 3) * 255
];
a = number(a);
return new Color(rgb, a, 'hsla');
}
catch (e) { }
},
hsv: function (h, s, v) {
return colorFunctions.hsva(h, s, v, 1.0);
},
hsva: function (h, s, v, a) {
h = ((number(h) % 360) / 360) * 360;
s = number(s);
v = number(v);
a = number(a);
var i;
var f;
i = Math.floor((h / 60) % 6);
f = (h / 60) - i;
var vs = [v,
v * (1 - s),
v * (1 - f * s),
v * (1 - (1 - f) * s)];
var perm = [[0, 3, 1],
[2, 0, 1],
[1, 0, 3],
[1, 2, 0],
[3, 1, 0],
[0, 1, 2]];
return colorFunctions.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a);
},
hue: function (color) {
return new Dimension(toHSL(color).h);
},
saturation: function (color) {
return new Dimension(toHSL(color).s * 100, '%');
},
lightness: function (color) {
return new Dimension(toHSL(color).l * 100, '%');
},
hsvhue: function (color) {
return new Dimension(toHSV(color).h);
},
hsvsaturation: function (color) {
return new Dimension(toHSV(color).s * 100, '%');
},
hsvvalue: function (color) {
return new Dimension(toHSV(color).v * 100, '%');
},
red: function (color) {
return new Dimension(color.rgb[0]);
},
green: function (color) {
return new Dimension(color.rgb[1]);
},
blue: function (color) {
return new Dimension(color.rgb[2]);
},
alpha: function (color) {
return new Dimension(toHSL(color).a);
},
luma: function (color) {
return new Dimension(color.luma() * color.alpha * 100, '%');
},
luminance: function (color) {
var luminance = (0.2126 * color.rgb[0] / 255) +
(0.7152 * color.rgb[1] / 255) +
(0.0722 * color.rgb[2] / 255);
return new Dimension(luminance * color.alpha * 100, '%');
},
saturate: function (color, amount, method) {
// filter: saturate(3.2);
// should be kept as is, so check for color
if (!color.rgb) {
return null;
}
var hsl = toHSL(color);
if (typeof method !== 'undefined' && method.value === 'relative') {
hsl.s += hsl.s * amount.value / 100;
}
else {
hsl.s += amount.value / 100;
}
hsl.s = clamp$1(hsl.s);
return hsla(color, hsl);
},
desaturate: function (color, amount, method) {
var hsl = toHSL(color);
if (typeof method !== 'undefined' && method.value === 'relative') {
hsl.s -= hsl.s * amount.value / 100;
}
else {
hsl.s -= amount.value / 100;
}
hsl.s = clamp$1(hsl.s);
return hsla(color, hsl);
},
lighten: function (color, amount, method) {
var hsl = toHSL(color);
if (typeof method !== 'undefined' && method.value === 'relative') {
hsl.l += hsl.l * amount.value / 100;
}
else {
hsl.l += amount.value / 100;
}
hsl.l = clamp$1(hsl.l);
return hsla(color, hsl);
},
darken: function (color, amount, method) {
var hsl = toHSL(color);
if (typeof method !== 'undefined' && method.value === 'relative') {
hsl.l -= hsl.l * amount.value / 100;
}
else {
hsl.l -= amount.value / 100;
}
hsl.l = clamp$1(hsl.l);
return hsla(color, hsl);
},
fadein: function (color, amount, method) {
var hsl = toHSL(color);
if (typeof method !== 'undefined' && method.value === 'relative') {
hsl.a += hsl.a * amount.value / 100;
}
else {
hsl.a += amount.value / 100;
}
hsl.a = clamp$1(hsl.a);
return hsla(color, hsl);
},
fadeout: function (color, amount, method) {
var hsl = toHSL(color);
if (typeof method !== 'undefined' && method.value === 'relative') {
hsl.a -= hsl.a * amount.value / 100;
}
else {
hsl.a -= amount.value / 100;
}
hsl.a = clamp$1(hsl.a);
return hsla(color, hsl);
},
fade: function (color, amount) {
var hsl = toHSL(color);
hsl.a = amount.value / 100;
hsl.a = clamp$1(hsl.a);
return hsla(color, hsl);
},
spin: function (color, amount) {
var hsl = toHSL(color);
var hue = (hsl.h + amount.value) % 360;
hsl.h = hue < 0 ? 360 + hue : hue;
return hsla(color, hsl);
},
//
// Copyright (c) 2006-2009 Hampton Catlin, Natalie Weizenbaum, and Chris Eppstein
// http://sass-lang.com
//
mix: function (color1, color2, weight) {
if (!weight) {
weight = new Dimension(50);
}
var p = weight.value / 100.0;
var w = p * 2 - 1;
var a = toHSL(color1).a - toHSL(color2).a;
var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
var w2 = 1 - w1;
var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2,
color1.rgb[1] * w1 + color2.rgb[1] * w2,
color1.rgb[2] * w1 + color2.rgb[2] * w2];
var alpha = color1.alpha * p + color2.alpha * (1 - p);
return new Color(rgb, alpha);
},
greyscale: function (color) {
return colorFunctions.desaturate(color, new Dimension(100));
},
contrast: function (color, dark, light, threshold) {
// filter: contrast(3.2);
// should be kept as is, so check for color
if (!color.rgb) {
return null;
}
if (typeof light === 'undefined') {
light = colorFunctions.rgba(255, 255, 255, 1.0);
}
if (typeof dark === 'undefined') {
dark = colorFunctions.rgba(0, 0, 0, 1.0);
}
// Figure out which is actually light and dark:
if (dark.luma() > light.luma()) {
var t = light;
light = dark;
dark = t;
}
if (typeof threshold === 'undefined') {
threshold = 0.43;
}
else {
threshold = number(threshold);
}
if (color.luma() < threshold) {
return light;
}
else {
return dark;
}
},
// Changes made in 2.7.0 - Reverted in 3.0.0
// contrast: function (color, color1, color2, threshold) {
// // Return which of `color1` and `color2` has the greatest contrast with `color`
// // according to the standard WCAG contrast ratio calculation.
// // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
// // The threshold param is no longer used, in line with SASS.
// // filter: contrast(3.2);
// // should be kept as is, so check for color
// if (!color.rgb) {
// return null;
// }
// if (typeof color1 === 'undefined') {
// color1 = colorFunctions.rgba(0, 0, 0, 1.0);
// }
// if (typeof color2 === 'undefined') {
// color2 = colorFunctions.rgba(255, 255, 255, 1.0);
// }
// var contrast1, contrast2;
// var luma = color.luma();
// var luma1 = color1.luma();
// var luma2 = color2.luma();
// // Calculate contrast ratios for each color
// if (luma > luma1) {
// contrast1 = (luma + 0.05) / (luma1 + 0.05);
// } else {
// contrast1 = (luma1 + 0.05) / (luma + 0.05);
// }
// if (luma > luma2) {
// contrast2 = (luma + 0.05) / (luma2 + 0.05);
// } else {
// contrast2 = (luma2 + 0.05) / (luma + 0.05);
// }
// if (contrast1 > contrast2) {
// return color1;
// } else {
// return color2;
// }
// },
argb: function (color) {
return new Anonymous(color.toARGB());
},
color: function (c) {
if ((c instanceof Quoted) &&
(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/i.test(c.value))) {
var val = c.value.slice(1);
return new Color(val, undefined, "#" + val);
}
if ((c instanceof Color) || (c = Color.fromKeyword(c.value))) {
c.value = undefined;
return c;
}
throw {
type: 'Argument',
message: 'argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF'
};
},
tint: function (color, amount) {
return colorFunctions.mix(colorFunctions.rgb(255, 255, 255), color, amount);
},
shade: function (color, amount) {
return colorFunctions.mix(colorFunctions.rgb(0, 0, 0), color, amount);
}
};
var color = colorFunctions;
// Color Blending
// ref: http://www.w3.org/TR/compositing-1
function colorBlend(mode, color1, color2) {
var ab = color1.alpha; // result
var // backdrop
cb;
var as = color2.alpha;
var // source
cs;
var ar;
var cr;
var r = [];
ar = as + ab * (1 - as);
for (var i_1 = 0; i_1 < 3; i_1++) {
cb = color1.rgb[i_1] / 255;
cs = color2.rgb[i_1] / 255;
cr = mode(cb, cs);
if (ar) {
cr = (as * cs + ab * (cb -
as * (cb + cs - cr))) / ar;
}
r[i_1] = cr * 255;
}
return new Color(r, ar);
}
var colorBlendModeFunctions = {
multiply: function (cb, cs) {
return cb * cs;
},
screen: function (cb, cs) {
return cb + cs - cb * cs;
},
overlay: function (cb, cs) {
cb *= 2;
return (cb <= 1) ?
colorBlendModeFunctions.multiply(cb, cs) :
colorBlendModeFunctions.screen(cb - 1, cs);
},
softlight: function (cb, cs) {
var d = 1;
var e = cb;
if (cs > 0.5) {
e = 1;
d = (cb > 0.25) ? Math.sqrt(cb)
: ((16 * cb - 12) * cb + 4) * cb;
}
return cb - (1 - 2 * cs) * e * (d - cb);
},
hardlight: function (cb, cs) {
return colorBlendModeFunctions.overlay(cs, cb);
},
difference: function (cb, cs) {
return Math.abs(cb - cs);
},
exclusion: function (cb, cs) {
return cb + cs - 2 * cb * cs;
},
// non-w3c functions:
average: function (cb, cs) {
return (cb + cs) / 2;
},
negation: function (cb, cs) {
return 1 - Math.abs(cb + cs - 1);
}
};
for (var f in colorBlendModeFunctions) {
if (colorBlendModeFunctions.hasOwnProperty(f)) {
colorBlend[f] = colorBlend.bind(null, colorBlendModeFunctions[f]);
}
}
var dataUri = (function (environment) {
var fallback = function (functionThis, node) { return new URL(node, functionThis.index, functionThis.currentFileInfo).eval(functionThis.context); };
return { 'data-uri': function (mimetypeNode, filePathNode) {
if (!filePathNode) {
filePathNode = mimetypeNode;
mimetypeNode = null;
}
var mimetype = mimetypeNode && mimetypeNode.value;
var filePath = filePathNode.value;
var currentFileInfo = this.currentFileInfo;
var currentDirectory = currentFileInfo.rewriteUrls ?
currentFileInfo.currentDirectory : currentFileInfo.entryPath;
var fragmentStart = filePath.indexOf('#');
var fragment = '';
if (fragmentStart !== -1) {
fragment = filePath.slice(fragmentStart);
filePath = filePath.slice(0, fragmentStart);
}
var context = clone(this.context);
context.rawBuffer = true;
var fileManager = environment.getFileManager(filePath, currentDirectory, context, environment, true);
if (!fileManager) {
return fallback(this, filePathNode);
}
var useBase64 = false;
// detect the mimetype if not given
if (!mimetypeNode) {
mimetype = environment.mimeLookup(filePath);
if (mimetype === 'image/svg+xml') {
useBase64 = false;
}
else {
// use base 64 unless it's an ASCII or UTF-8 format
var charset = environment.charsetLookup(mimetype);
useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
}
if (useBase64) {
mimetype += ';base64';
}
}
else {
useBase64 = /;base64$/.test(mimetype);
}
var fileSync = fileManager.loadFileSync(filePath, currentDirectory, context, environment);
if (!fileSync.contents) {
logger.warn("Skipped data-uri embedding of " + filePath + " because file not found");
return fallback(this, filePathNode || mimetypeNode);
}
var buf = fileSync.contents;
if (useBase64 && !environment.encodeBase64) {
return fallback(this, filePathNode);
}
buf = useBase64 ? environment.encodeBase64(buf) : encodeURIComponent(buf);
var uri = "data:" + mimetype + "," + buf + fragment;
return new URL(new Quoted("\"" + uri + "\"", uri, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
} };
});
var getItemsFromNode = function (node) {
// handle non-array values as an array of length 1
// return 'undefined' if index is invalid
var items = Array.isArray(node.value) ?
node.value : Array(node);
return items;
};
var list = {
_SELF: function (n) {
return n;
},
extract: function (values, index) {
// (1-based index)
index = index.value - 1;
return getItemsFromNode(values)[index];
},
length: function (values) {
return new Dimension(getItemsFromNode(values).length);
},
/**
* Creates a Less list of incremental values.
* Modeled after Lodash's range function, also exists natively in PHP
*
* @param {Dimension} [start=1]
* @param {Dimension} end - e.g. 10 or 10px - unit is added to output
* @param {Dimension} [step=1]
*/
range: function (start, end, step) {
var from;
var to;
var stepValue = 1;
var list = [];
if (end) {
to = end;
from = start.value;
if (step) {
stepValue = step.value;
}
}
else {
from = 1;
to = start;
}
for (var i_1 = from; i_1 <= to.value; i_1 += stepValue) {
list.push(new Dimension(i_1, to.unit));
}
return new Expression(list);
},
each: function (list, rs) {
var rules = [];
var newRules;
var iterator;
if (list.value && !(list instanceof Quoted)) {
if (Array.isArray(list.value)) {
iterator = list.value;
}
else {
iterator = [list.value];
}
}
else if (list.ruleset) {
iterator = list.ruleset.rules;
}
else if (list.rules) {
iterator = list.rules;
}
else if (Array.isArray(list)) {
iterator = list;
}
else {
iterator = [list];
}
var valueName = '@value';
var keyName = '@key';
var indexName = '@index';
if (rs.params) {
valueName = rs.params[0] && rs.params[0].name;
keyName = rs.params[1] && rs.params[1].name;
indexName = rs.params[2] && rs.params[2].name;
rs = rs.rules;
}
else {
rs = rs.ruleset;
}
for (var i_2 = 0; i_2 < iterator.length; i_2++) {
var key = void 0;
var value = void 0;
var item = iterator[i_2];
if (item instanceof Declaration) {
key = typeof item.name === 'string' ? item.name : item.name[0].value;
value = item.value;
}
else {
key = new Dimension(i_2 + 1);
value = item;
}
if (item instanceof Comment) {
continue;
}
newRules = rs.rules.slice(0);
if (valueName) {
newRules.push(new Declaration(valueName, value, false, false, this.index, this.currentFileInfo));
}
if (indexName) {
newRules.push(new Declaration(indexName, new Dimension(i_2 + 1), false, false, this.index, this.currentFileInfo));
}
if (keyName) {
newRules.push(new Declaration(keyName, key, false, false, this.index, this.currentFileInfo));
}
rules.push(new Ruleset([new (Selector)([new Element("", '&')])], newRules, rs.strictImports, rs.visibilityInfo()));
}
return new Ruleset([new (Selector)([new Element("", '&')])], rules, rs.strictImports, rs.visibilityInfo()).eval(this.context);
}
};
var MathHelper = function (fn, unit, n) {
if (!(n instanceof Dimension)) {
throw { type: 'Argument', message: 'argument must be a number' };
}
if (unit == null) {
unit = n.unit;
}
else {
n = n.unify();
}
return new Dimension(fn(parseFloat(n.value)), unit);
};
var mathFunctions = {
// name, unit
ceil: null,
floor: null,
sqrt: null,
abs: null,
tan: '',
sin: '',
cos: '',
atan: 'rad',
asin: 'rad',
acos: 'rad'
};
for (var f$1 in mathFunctions) {
if (mathFunctions.hasOwnProperty(f$1)) {
mathFunctions[f$1] = MathHelper.bind(null, Math[f$1], mathFunctions[f$1]);
}
}
mathFunctions.round = function (n, f) {
var fraction = typeof f === 'undefined' ? 0 : f.value;
return MathHelper(function (num) { return num.toFixed(fraction); }, null, n);
};
var minMax = function (isMin, args) {
args = Array.prototype.slice.call(args);
switch (args.length) {
case 0: throw { type: 'Argument', message: 'one or more arguments required' };
}
var i; // key is the unit.toString() for unified Dimension values,
var j;
var current;
var currentUnified;
var referenceUnified;
var unit;
var unitStatic;
var unitClone;
var // elems only contains original argument values.
order = [];
var values = {};
// value is the index into the order array.
for (i = 0; i < args.length; i++) {
current = args[i];
if (!(current instanceof Dimension)) {
if (Array.isArray(args[i].value)) {
Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
}
continue;
}
currentUnified = current.unit.toString() === '' && unitClone !== undefined ? new Dimension(current.value, unitClone).unify() : current.unify();
unit = currentUnified.unit.toString() === '' && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
unitStatic = unit !== '' && unitStatic === undefined || unit !== '' && order[0].unify().unit.toString() === '' ? unit : unitStatic;
unitClone = unit !== '' && unitClone === undefined ? current.unit.toString() : unitClone;
j = values[''] !== undefined && unit !== '' && unit === unitStatic ? values[''] : values[unit];
if (j === undefined) {
if (unitStatic !== undefined && unit !== unitStatic) {
throw { type: 'Argument', message: 'incompatible types' };
}
values[unit] = order.length;
order.push(current);
continue;
}
referenceUnified = order[j].unit.toString() === '' && unitClone !== undefined ? new Dimension(order[j].value, unitClone).unify() : order[j].unify();
if (isMin && currentUnified.value < referenceUnified.value ||
!isMin && currentUnified.value > referenceUnified.value) {
order[j] = current;
}
}
if (order.length == 1) {
return order[0];
}
args = order.map(function (a) { return a.toCSS(this.context); }).join(this.context.compress ? ',' : ', ');
return new Anonymous((isMin ? 'min' : 'max') + "(" + args + ")");
};
var number$1 = {
min: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return minMax(true, args);
},
max: function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return minMax(false, args);
},
convert: function (val, unit) {
return val.convertTo(unit.value);
},
pi: function () {
return new Dimension(Math.PI);
},
mod: function (a, b) {
return new Dimension(a.value % b.value, a.unit);
},
pow: function (x, y) {
if (typeof x === 'number' && typeof y === 'number') {
x = new Dimension(x);
y = new Dimension(y);
}
else if (!(x instanceof Dimension) || !(y instanceof Dimension)) {
throw { type: 'Argument', message: 'arguments must be numbers' };
}
return new Dimension(Math.pow(x.value, y.value), x.unit);
},
percentage: function (n) {
var result = MathHelper(function (num) { return num * 100; }, '%', n);
return result;
}
};
var string = {
e: function (str) {
return new Quoted('"', str instanceof JavaScript ? str.evaluated : str.value, true);
},
escape: function (str) {
return new Anonymous(encodeURI(str.value).replace(/=/g, '%3D').replace(/:/g, '%3A').replace(/#/g, '%23').replace(/;/g, '%3B')
.replace(/\(/g, '%28').replace(/\)/g, '%29'));
},
replace: function (string, pattern, replacement, flags) {
var result = string.value;
replacement = (replacement.type === 'Quoted') ?
replacement.value : replacement.toCSS();
result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement);
return new Quoted(string.quote || '', result, string.escaped);
},
'%': function (string /* arg, arg, ... */) {
var args = Array.prototype.slice.call(arguments, 1);
var result = string.value;
var _loop_1 = function (i_1) {
/* jshint loopfunc:true */
result = result.replace(/%[sda]/i, function (token) {
var value = ((args[i_1].type === 'Quoted') &&
token.match(/s/i)) ? args[i_1].value : args[i_1].toCSS();
return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
});
};
for (var i_1 = 0; i_1 < args.length; i_1++) {
_loop_1(i_1);
}
result = result.replace(/%%/g, '%');
return new Quoted(string.quote || '', result, string.escaped);
}
};
var svg = (function (environment) {
return { 'svg-gradient': function (direction) {
var stops;
var gradientDirectionSvg;
var gradientType = 'linear';
var rectangleDimension = 'x="0" y="0" width="1" height="1"';
var renderEnv = { compress: false };
var returner;
var directionValue = direction.toCSS(renderEnv);
var i;
var color;
var position;
var positionValue;
var alpha;
function throwArgumentDescriptor() {
throw { type: 'Argument',
message: 'svg-gradient expects direction, start_color [start_position], [color position,]...,' +
' end_color [end_position] or direction, color list' };
}
if (arguments.length == 2) {
if (arguments[1].value.length < 2) {
throwArgumentDescriptor();
}
stops = arguments[1].value;
}
else if (arguments.length < 3) {
throwArgumentDescriptor();
}
else {
stops = Array.prototype.slice.call(arguments, 1);
}
switch (directionValue) {
case 'to bottom':
gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
break;
case 'to right':
gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
break;
case 'to bottom right':
gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
break;
case 'to top right':
gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
break;
case 'ellipse':
case 'ellipse at center':
gradientType = 'radial';
gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
break;
default:
throw { type: 'Argument', message: 'svg-gradient direction must be \'to bottom\', \'to right\',' +
' \'to bottom right\', \'to top right\' or \'ellipse at center\'' };
}
returner = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1 1\"><" + gradientType + "Gradient id=\"g\" " + gradientDirectionSvg + ">";
for (i = 0; i < stops.length; i += 1) {
if (stops[i] instanceof Expression) {
color = stops[i].value[0];
position = stops[i].value[1];
}
else {
color = stops[i];
position = undefined;
}
if (!(color instanceof Color) || (!((i === 0 || i + 1 === stops.length) && position === undefined) && !(position instanceof Dimension))) {
throwArgumentDescriptor();
}
positionValue = position ? position.toCSS(renderEnv) : i === 0 ? '0%' : '100%';
alpha = color.alpha;
returner += "<stop offset=\"" + positionValue + "\" stop-color=\"" + color.toRGB() + "\"" + (alpha < 1 ? " stop-opacity=\"" + alpha + "\"" : '') + "/>";
}
returner += "</" + gradientType + "Gradient><rect " + rectangleDimension + " fill=\"url(#g)\" /></svg>";
returner = encodeURIComponent(returner);
returner = "data:image/svg+xml," + returner;
return new URL(new Quoted("'" + returner + "'", returner, false, this.index, this.currentFileInfo), this.index, this.currentFileInfo);
} };
});
var isa = function (n, Type) { return (n instanceof Type) ? Keyword.True : Keyword.False; };
var isunit = function (n, unit) {
if (unit === undefined) {
throw { type: 'Argument', message: 'missing the required second argument to isunit.' };
}
unit = typeof unit.value === 'string' ? unit.value : unit;
if (typeof unit !== 'string') {
throw { type: 'Argument', message: 'Second argument to isunit should be a unit or a string.' };
}
return (n instanceof Dimension) && n.unit.is(unit) ? Keyword.True : Keyword.False;
};
var types = {
isruleset: function (n) {
return isa(n, DetachedRuleset);
},
iscolor: function (n) {
return isa(n, Color);
},
isnumber: function (n) {
return isa(n, Dimension);
},
isstring: function (n) {
return isa(n, Quoted);
},
iskeyword: function (n) {
return isa(n, Keyword);
},
isurl: function (n) {
return isa(n, URL);
},
ispixel: function (n) {
return isunit(n, 'px');
},
ispercentage: function (n) {
return isunit(n, '%');
},
isem: function (n) {
return isunit(n, 'em');
},
isunit: isunit,
unit: function (val, unit) {
if (!(val instanceof Dimension)) {
throw { type: 'Argument',
message: "the first argument to unit must be a number" + (val instanceof Operation ? '. Have you forgotten parenthesis?' : '') };
}
if (unit) {
if (unit instanceof Keyword) {
unit = unit.value;
}
else {
unit = unit.toCSS();
}
}
else {
unit = '';
}
return new Dimension(val.value, unit);
},
'get-unit': function (n) {
return new Anonymous(n.unit);
}
};
var Functions = (function (environment) {
var functions = { functionRegistry: functionRegistry, functionCaller: functionCaller };
// register functions
functionRegistry.addMultiple(boolean$1);
functionRegistry.add('default', defaultFunc.eval.bind(defaultFunc));
functionRegistry.addMultiple(color);
functionRegistry.addMultiple(colorBlend);
functionRegistry.addMultiple(dataUri(environment));
functionRegistry.addMultiple(list);
functionRegistry.addMultiple(mathFunctions);
functionRegistry.addMultiple(number$1);
functionRegistry.addMultiple(string);
functionRegistry.addMultiple(svg());
functionRegistry.addMultiple(types);
return functions;
});
var sourceMapOutput = (function (environment) {
var SourceMapOutput = /** @class */ (function () {
function SourceMapOutput(options) {
this._css = [];
this._rootNode = options.rootNode;
this._contentsMap = options.contentsMap;
this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
if (options.sourceMapFilename) {
this._sourceMapFilename = options.sourceMapFilename.replace(/\\/g, '/');
}
this._outputFilename = options.outputFilename;
this.sourceMapURL = options.sourceMapURL;
if (options.sourceMapBasepath) {
this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
}
if (options.sourceMapRootpath) {
this._sourceMapRootpath = options.sourceMapRootpath.replace(/\\/g, '/');
if (this._sourceMapRootpath.charAt(this._sourceMapRootpath.length - 1) !== '/') {
this._sourceMapRootpath += '/';
}
}
else {
this._sourceMapRootpath = '';
}
this._outputSourceFiles = options.outputSourceFiles;
this._sourceMapGeneratorConstructor = environment.getSourceMapGenerator();
this._lineNumber = 0;
this._column = 0;
}
SourceMapOutput.prototype.removeBasepath = function (path) {
if (this._sourceMapBasepath && path.indexOf(this._sourceMapBasepath) === 0) {
path = path.substring(this._sourceMapBasepath.length);
if (path.charAt(0) === '\\' || path.charAt(0) === '/') {
path = path.substring(1);
}
}
return path;
};
SourceMapOutput.prototype.normalizeFilename = function (filename) {
filename = filename.replace(/\\/g, '/');
filename = this.removeBasepath(filename);
return (this._sourceMapRootpath || '') + filename;
};
SourceMapOutput.prototype.add = function (chunk, fileInfo, index, mapLines) {
// ignore adding empty strings
if (!chunk) {
return;
}
var lines;
var sourceLines;
var columns;
var sourceColumns;
var i;
if (fileInfo && fileInfo.filename) {
var inputSource = this._contentsMap[fileInfo.filename];
// remove vars/banner added to the top of the file
if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
// adjust the index
index -= this._contentsIgnoredCharsMap[fileInfo.filename];
if (index < 0) {
index = 0;
}
// adjust the source
inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
}
// ignore empty content
if (inputSource === undefined) {
return;
}
inputSource = inputSource.substring(0, index);
sourceLines = inputSource.split('\n');
sourceColumns = sourceLines[sourceLines.length - 1];
}
lines = chunk.split('\n');
columns = lines[lines.length - 1];
if (fileInfo && fileInfo.filename) {
if (!mapLines) {
this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column },
original: { line: sourceLines.length, column: sourceColumns.length },
source: this.normalizeFilename(fileInfo.filename) });
}
else {
for (i = 0; i < lines.length; i++) {
this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0 },
original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0 },
source: this.normalizeFilename(fileInfo.filename) });
}
}
}
if (lines.length === 1) {
this._column += columns.length;
}
else {
this._lineNumber += lines.length - 1;
this._column = columns.length;
}
this._css.push(chunk);
};
SourceMapOutput.prototype.isEmpty = function () {
return this._css.length === 0;
};
SourceMapOutput.prototype.toCSS = function (context) {
this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null });
if (this._outputSourceFiles) {
for (var filename in this._contentsMap) {
if (this._contentsMap.hasOwnProperty(filename)) {
var source = this._contentsMap[filename];
if (this._contentsIgnoredCharsMap[filename]) {
source = source.slice(this._contentsIgnoredCharsMap[filename]);
}
this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
}
}
}
this._rootNode.genCSS(context, this);
if (this._css.length > 0) {
var sourceMapURL = void 0;
var sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
if (this.sourceMapURL) {
sourceMapURL = this.sourceMapURL;
}
else if (this._sourceMapFilename) {
sourceMapURL = this._sourceMapFilename;
}
this.sourceMapURL = sourceMapURL;
this.sourceMap = sourceMapContent;
}
return this._css.join('');
};
return SourceMapOutput;
}());
return SourceMapOutput;
});
var sourceMapBuilder = (function (SourceMapOutput, environment) {
var SourceMapBuilder = /** @class */ (function () {
function SourceMapBuilder(options) {
this.options = options;
}
SourceMapBuilder.prototype.toCSS = function (rootNode, options, imports) {
var sourceMapOutput = new SourceMapOutput({
contentsIgnoredCharsMap: imports.contentsIgnoredChars,
rootNode: rootNode,
contentsMap: imports.contents,
sourceMapFilename: this.options.sourceMapFilename,
sourceMapURL: this.options.sourceMapURL,
outputFilename: this.options.sourceMapOutputFilename,
sourceMapBasepath: this.options.sourceMapBasepath,
sourceMapRootpath: this.options.sourceMapRootpath,
outputSourceFiles: this.options.outputSourceFiles,
sourceMapGenerator: this.options.sourceMapGenerator,
sourceMapFileInline: this.options.sourceMapFileInline
});
var css = sourceMapOutput.toCSS(options);
this.sourceMap = sourceMapOutput.sourceMap;
this.sourceMapURL = sourceMapOutput.sourceMapURL;
if (this.options.sourceMapInputFilename) {
this.sourceMapInputFilename = sourceMapOutput.normalizeFilename(this.options.sourceMapInputFilename);
}
if (this.options.sourceMapBasepath !== undefined && this.sourceMapURL !== undefined) {
this.sourceMapURL = sourceMapOutput.removeBasepath(this.sourceMapURL);
}
return css + this.getCSSAppendage();
};
SourceMapBuilder.prototype.getCSSAppendage = function () {
var sourceMapURL = this.sourceMapURL;
if (this.options.sourceMapFileInline) {
if (this.sourceMap === undefined) {
return '';
}
sourceMapURL = "data:application/json;base64," + environment.encodeBase64(this.sourceMap);
}
if (sourceMapURL) {
return "/*# sourceMappingURL=" + sourceMapURL + " */";
}
return '';
};
SourceMapBuilder.prototype.getExternalSourceMap = function () {
return this.sourceMap;
};
SourceMapBuilder.prototype.setExternalSourceMap = function (sourceMap) {
this.sourceMap = sourceMap;
};
SourceMapBuilder.prototype.isInline = function () {
return this.options.sourceMapFileInline;
};
SourceMapBuilder.prototype.getSourceMapURL = function () {
return this.sourceMapURL;
};
SourceMapBuilder.prototype.getOutputFilename = function () {
return this.options.sourceMapOutputFilename;
};
SourceMapBuilder.prototype.getInputFilename = function () {
return this.sourceMapInputFilename;
};
return SourceMapBuilder;
}());
return SourceMapBuilder;
});
var transformTree = (function (root, options) {
if (options === void 0) { options = {}; }
var evaldRoot;
var variables = options.variables;
var evalEnv = new contexts.Eval(options);
//
// Allows setting variables with a hash, so:
//
// `{ color: new tree.Color('#f01') }` will become:
//
// new tree.Declaration('@color',
// new tree.Value([
// new tree.Expression([
// new tree.Color('#f01')
// ])
// ])
// )
//
if (typeof variables === 'object' && !Array.isArray(variables)) {
variables = Object.keys(variables).map(function (k) {
var value = variables[k];
if (!(value instanceof tree.Value)) {
if (!(value instanceof tree.Expression)) {
value = new tree.Expression([value]);
}
value = new tree.Value([value]);
}
return new tree.Declaration("@" + k, value, false, null, 0);
});
evalEnv.frames = [new tree.Ruleset(null, variables)];
}
var visitors$1 = [
new visitors.JoinSelectorVisitor(),
new visitors.MarkVisibleSelectorsVisitor(true),
new visitors.ExtendVisitor(),
new visitors.ToCSSVisitor({ compress: Boolean(options.compress) })
];
var preEvalVisitors = [];
var v;
var visitorIterator;
/**
* first() / get() allows visitors to be added while visiting
*
* @todo Add scoping for visitors just like functions for @plugin; right now they're global
*/
if (options.pluginManager) {
visitorIterator = options.pluginManager.visitor();
for (var i = 0; i < 2; i++) {
visitorIterator.first();
while ((v = visitorIterator.get())) {
if (v.isPreEvalVisitor) {
if (i === 0 || preEvalVisitors.indexOf(v) === -1) {
preEvalVisitors.push(v);
v.run(root);
}
}
else {
if (i === 0 || visitors$1.indexOf(v) === -1) {
if (v.isPreVisitor) {
visitors$1.unshift(v);
}
else {
visitors$1.push(v);
}
}
}
}
}
}
evaldRoot = root.eval(evalEnv);
for (var i = 0; i < visitors$1.length; i++) {
visitors$1[i].run(evaldRoot);
}
// Run any remaining visitors added after eval pass
if (options.pluginManager) {
visitorIterator.first();
while ((v = visitorIterator.get())) {
if (visitors$1.indexOf(v) === -1 && preEvalVisitors.indexOf(v) === -1) {
v.run(evaldRoot);
}
}
}
return evaldRoot;
});
var parseTree = (function (SourceMapBuilder) {
var ParseTree = /** @class */ (function () {
function ParseTree(root, imports) {
this.root = root;
this.imports = imports;
}
ParseTree.prototype.toCSS = function (options) {
var evaldRoot;
var result = {};
var sourceMapBuilder;
try {
evaldRoot = transformTree(this.root, options);
}
catch (e) {
throw new LessError(e, this.imports);
}
try {
var compress = Boolean(options.compress);
if (compress) {
logger.warn('The compress option has been deprecated. ' +
'We recommend you use a dedicated css minifier, for instance see less-plugin-clean-css.');
}
var toCSSOptions = {
compress: compress,
dumpLineNumbers: options.dumpLineNumbers,
strictUnits: Boolean(options.strictUnits),
numPrecision: 8
};
if (options.sourceMap) {
sourceMapBuilder = new SourceMapBuilder(options.sourceMap);
result.css = sourceMapBuilder.toCSS(evaldRoot, toCSSOptions, this.imports);
}
else {
result.css = evaldRoot.toCSS(toCSSOptions);
}
}
catch (e) {
throw new LessError(e, this.imports);
}
if (options.pluginManager) {
var postProcessors = options.pluginManager.getPostProcessors();
for (var i_1 = 0; i_1 < postProcessors.length; i_1++) {
result.css = postProcessors[i_1].process(result.css, { sourceMap: sourceMapBuilder, options: options, imports: this.imports });
}
}
if (options.sourceMap) {
result.map = sourceMapBuilder.getExternalSourceMap();
}
result.imports = [];
for (var file_1 in this.imports.files) {
if (this.imports.files.hasOwnProperty(file_1) && file_1 !== this.imports.rootFilename) {
result.imports.push(file_1);
}
}
return result;
};
return ParseTree;
}());
return ParseTree;
});
var importManager = (function (environment) {
// FileInfo = {
// 'rewriteUrls' - option - whether to adjust URL's to be relative
// 'filename' - full resolved filename of current file
// 'rootpath' - path to append to normal URLs for this node
// 'currentDirectory' - path to the current file, absolute
// 'rootFilename' - filename of the base file
// 'entryPath' - absolute path to the entry file
// 'reference' - whether the file should not be output and only output parts that are referenced
var ImportManager = /** @class */ (function () {
function ImportManager(less, context, rootFileInfo) {
this.less = less;
this.rootFilename = rootFileInfo.filename;
this.paths = context.paths || []; // Search paths, when importing
this.contents = {}; // map - filename to contents of all the files
this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore
this.mime = context.mime;
this.error = null;
this.context = context;
// Deprecated? Unused outside of here, could be useful.
this.queue = []; // Files which haven't been imported yet
this.files = {}; // Holds the imported parse trees.
}
/**
* Add an import to be imported
* @param path - the raw path
* @param tryAppendExtension - whether to try appending a file extension (.less or .js if the path has no extension)
* @param currentFileInfo - the current file info (used for instance to work out relative paths)
* @param importOptions - import options
* @param callback - callback for when it is imported
*/
ImportManager.prototype.push = function (path, tryAppendExtension, currentFileInfo, importOptions, callback) {
var importManager = this;
var pluginLoader = this.context.pluginManager.Loader;
this.queue.push(path);
var fileParsedFunc = function (e, root, fullPath) {
importManager.queue.splice(importManager.queue.indexOf(path), 1); // Remove the path from the queue
var importedEqualsRoot = fullPath === importManager.rootFilename;
if (importOptions.optional && e) {
callback(null, { rules: [] }, false, null);
logger.info("The file " + fullPath + " was skipped because it was not found and the import was marked optional.");
}
else {
// Inline imports aren't cached here.
// If we start to cache them, please make sure they won't conflict with non-inline imports of the
// same name as they used to do before this comment and the condition below have been added.
if (!importManager.files[fullPath] && !importOptions.inline) {
importManager.files[fullPath] = { root: root, options: importOptions };
}
if (e && !importManager.error) {
importManager.error = e;
}
callback(e, root, importedEqualsRoot, fullPath);
}
};
var newFileInfo = {
rewriteUrls: this.context.rewriteUrls,
entryPath: currentFileInfo.entryPath,
rootpath: currentFileInfo.rootpath,
rootFilename: currentFileInfo.rootFilename
};
var fileManager = environment.getFileManager(path, currentFileInfo.currentDirectory, this.context, environment);
if (!fileManager) {
fileParsedFunc({ message: "Could not find a file-manager for " + path });
return;
}
var loadFileCallback = function (loadedFile) {
var plugin;
var resolvedFilename = loadedFile.filename;
var contents = loadedFile.contents.replace(/^\uFEFF/, '');
// Pass on an updated rootpath if path of imported file is relative and file
// is in a (sub|sup) directory
//
// Examples:
// - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/',
// then rootpath should become 'less/module/nav/'
// - If path of imported file is '../mixins.less' and rootpath is 'less/',
// then rootpath should become 'less/../'
newFileInfo.currentDirectory = fileManager.getPath(resolvedFilename);
if (newFileInfo.rewriteUrls) {
newFileInfo.rootpath = fileManager.join((importManager.context.rootpath || ''), fileManager.pathDiff(newFileInfo.currentDirectory, newFileInfo.entryPath));
if (!fileManager.isPathAbsolute(newFileInfo.rootpath) && fileManager.alwaysMakePathsAbsolute()) {
newFileInfo.rootpath = fileManager.join(newFileInfo.entryPath, newFileInfo.rootpath);
}
}
newFileInfo.filename = resolvedFilename;
var newEnv = new contexts.Parse(importManager.context);
newEnv.processImports = false;
importManager.contents[resolvedFilename] = contents;
if (currentFileInfo.reference || importOptions.reference) {
newFileInfo.reference = true;
}
if (importOptions.isPlugin) {
plugin = pluginLoader.evalPlugin(contents, newEnv, importManager, importOptions.pluginArgs, newFileInfo);
if (plugin instanceof LessError) {
fileParsedFunc(plugin, null, resolvedFilename);
}
else {
fileParsedFunc(null, plugin, resolvedFilename);
}
}
else if (importOptions.inline) {
fileParsedFunc(null, contents, resolvedFilename);
}
else {
// import (multiple) parse trees apparently get altered and can't be cached.
// TODO: investigate why this is
if (importManager.files[resolvedFilename]
&& !importManager.files[resolvedFilename].options.multiple
&& !importOptions.multiple) {
fileParsedFunc(null, importManager.files[resolvedFilename].root, resolvedFilename);
}
else {
new Parser(newEnv, importManager, newFileInfo).parse(contents, function (e, root) {
fileParsedFunc(e, root, resolvedFilename);
});
}
}
};
var promise;
var context = clone(this.context);
if (tryAppendExtension) {
context.ext = importOptions.isPlugin ? '.js' : '.less';
}
if (importOptions.isPlugin) {
context.mime = 'application/javascript';
promise = pluginLoader.loadPlugin(path, currentFileInfo.currentDirectory, context, environment, fileManager);
}
else {
promise = fileManager.loadFile(path, currentFileInfo.currentDirectory, context, environment, function (err, loadedFile) {
if (err) {
fileParsedFunc(err);
}
else {
loadFileCallback(loadedFile);
}
});
}
if (promise) {
promise.then(loadFileCallback, fileParsedFunc);
}
};
return ImportManager;
}());
return ImportManager;
});
var Render = (function (environment, ParseTree, ImportManager) {
var render = function (input, options, callback) {
if (typeof options === 'function') {
callback = options;
options = copyOptions(this.options, {});
}
else {
options = copyOptions(this.options, options || {});
}
if (!callback) {
var self_1 = this;
return new Promise(function (resolve, reject) {
render.call(self_1, input, options, function (err, output) {
if (err) {
reject(err);
}
else {
resolve(output);
}
});
});
}
else {
this.parse(input, options, function (err, root, imports, options) {
if (err) {
return callback(err);
}
var result;
try {
var parseTree = new ParseTree(root, imports);
result = parseTree.toCSS(options);
}
catch (err) {
return callback(err);
}
callback(null, result);
});
}
};
return render;
});
/**
* Plugin Manager
*/
var PluginManager = /** @class */ (function () {
function PluginManager(less) {
this.less = less;
this.visitors = [];
this.preProcessors = [];
this.postProcessors = [];
this.installedPlugins = [];
this.fileManagers = [];
this.iterator = -1;
this.pluginCache = {};
this.Loader = new less.PluginLoader(less);
}
/**
* Adds all the plugins in the array
* @param {Array} plugins
*/
PluginManager.prototype.addPlugins = function (plugins) {
if (plugins) {
for (var i_1 = 0; i_1 < plugins.length; i_1++) {
this.addPlugin(plugins[i_1]);
}
}
};
/**
*
* @param plugin
* @param {String} filename
*/
PluginManager.prototype.addPlugin = function (plugin, filename, functionRegistry) {
this.installedPlugins.push(plugin);
if (filename) {
this.pluginCache[filename] = plugin;
}
if (plugin.install) {
plugin.install(this.less, this, functionRegistry || this.less.functions.functionRegistry);
}
};
/**
*
* @param filename
*/
PluginManager.prototype.get = function (filename) {
return this.pluginCache[filename];
};
/**
* Adds a visitor. The visitor object has options on itself to determine
* when it should run.
* @param visitor
*/
PluginManager.prototype.addVisitor = function (visitor) {
this.visitors.push(visitor);
};
/**
* Adds a pre processor object
* @param {object} preProcessor
* @param {number} priority - guidelines 1 = before import, 1000 = import, 2000 = after import
*/
PluginManager.prototype.addPreProcessor = function (preProcessor, priority) {
var indexToInsertAt;
for (indexToInsertAt = 0; indexToInsertAt < this.preProcessors.length; indexToInsertAt++) {
if (this.preProcessors[indexToInsertAt].priority >= priority) {
break;
}
}
this.preProcessors.splice(indexToInsertAt, 0, { preProcessor: preProcessor, priority: priority });
};
/**
* Adds a post processor object
* @param {object} postProcessor
* @param {number} priority - guidelines 1 = before compression, 1000 = compression, 2000 = after compression
*/
PluginManager.prototype.addPostProcessor = function (postProcessor, priority) {
var indexToInsertAt;
for (indexToInsertAt = 0; indexToInsertAt < this.postProcessors.length; indexToInsertAt++) {
if (this.postProcessors[indexToInsertAt].priority >= priority) {
break;
}
}
this.postProcessors.splice(indexToInsertAt, 0, { postProcessor: postProcessor, priority: priority });
};
/**
*
* @param manager
*/
PluginManager.prototype.addFileManager = function (manager) {
this.fileManagers.push(manager);
};
/**
*
* @returns {Array}
* @private
*/
PluginManager.prototype.getPreProcessors = function () {
var preProcessors = [];
for (var i_2 = 0; i_2 < this.preProcessors.length; i_2++) {
preProcessors.push(this.preProcessors[i_2].preProcessor);
}
return preProcessors;
};
/**
*
* @returns {Array}
* @private
*/
PluginManager.prototype.getPostProcessors = function () {
var postProcessors = [];
for (var i_3 = 0; i_3 < this.postProcessors.length; i_3++) {
postProcessors.push(this.postProcessors[i_3].postProcessor);
}
return postProcessors;
};
/**
*
* @returns {Array}
* @private
*/
PluginManager.prototype.getVisitors = function () {
return this.visitors;
};
PluginManager.prototype.visitor = function () {
var self = this;
return {
first: function () {
self.iterator = -1;
return self.visitors[self.iterator];
},
get: function () {
self.iterator += 1;
return self.visitors[self.iterator];
}
};
};
/**
*
* @returns {Array}
* @private
*/
PluginManager.prototype.getFileManagers = function () {
return this.fileManagers;
};
return PluginManager;
}());
var pm;
function PluginManagerFactory(less, newFactory) {
if (newFactory || !pm) {
pm = new PluginManager(less);
}
return pm;
}
var Parse = (function (environment, ParseTree, ImportManager) {
var parse = function (input, options, callback) {
if (typeof options === 'function') {
callback = options;
options = copyOptions(this.options, {});
}
else {
options = copyOptions(this.options, options || {});
}
if (!callback) {
var self_1 = this;
return new Promise(function (resolve, reject) {
parse.call(self_1, input, options, function (err, output) {
if (err) {
reject(err);
}
else {
resolve(output);
}
});
});
}
else {
var context_1;
var rootFileInfo = void 0;
var pluginManager_1 = new PluginManagerFactory(this, !options.reUsePluginManager);
options.pluginManager = pluginManager_1;
context_1 = new contexts.Parse(options);
if (options.rootFileInfo) {
rootFileInfo = options.rootFileInfo;
}
else {
var filename = options.filename || 'input';
var entryPath = filename.replace(/[^\/\\]*$/, '');
rootFileInfo = {
filename: filename,
rewriteUrls: context_1.rewriteUrls,
rootpath: context_1.rootpath || '',
currentDirectory: entryPath,
entryPath: entryPath,
rootFilename: filename
};
// add in a missing trailing slash
if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== '/') {
rootFileInfo.rootpath += '/';
}
}
var imports_1 = new ImportManager(this, context_1, rootFileInfo);
this.importManager = imports_1;
// TODO: allow the plugins to be just a list of paths or names
// Do an async plugin queue like lessc
if (options.plugins) {
options.plugins.forEach(function (plugin) {
var evalResult;
var contents;
if (plugin.fileContent) {
contents = plugin.fileContent.replace(/^\uFEFF/, '');
evalResult = pluginManager_1.Loader.evalPlugin(contents, context_1, imports_1, plugin.options, plugin.filename);
if (evalResult instanceof LessError) {
return callback(evalResult);
}
}
else {
pluginManager_1.addPlugin(plugin);
}
});
}
new Parser(context_1, imports_1, rootFileInfo)
.parse(input, function (e, root) {
if (e) {
return callback(e);
}
callback(null, root, imports_1, options);
}, options);
}
};
return parse;
});
var lessRoot = (function (environment$1, fileManagers) {
/**
* @todo
* This original code could be improved quite a bit.
* Many classes / modules currently add side-effects / mutations to passed in objects,
* which makes it hard to refactor and reason about.
*/
environment$1 = new environment(environment$1, fileManagers);
var SourceMapOutput = sourceMapOutput(environment$1);
var SourceMapBuilder = sourceMapBuilder(SourceMapOutput, environment$1);
var ParseTree = parseTree(SourceMapBuilder);
var ImportManager = importManager(environment$1);
var render = Render(environment$1, ParseTree);
var parse = Parse(environment$1, ParseTree, ImportManager);
var functions = Functions(environment$1);
/**
* @todo
* This root properties / methods need to be organized.
* It's not clear what should / must be public and why.
*/
var initial = {
version: [3, 11, 1],
data: data,
tree: tree,
Environment: environment,
AbstractFileManager: AbstractFileManager,
AbstractPluginLoader: AbstractPluginLoader,
environment: environment$1,
visitors: visitors,
Parser: Parser,
functions: functions,
contexts: contexts,
SourceMapOutput: SourceMapOutput,
SourceMapBuilder: SourceMapBuilder,
ParseTree: ParseTree,
ImportManager: ImportManager,
render: render,
parse: parse,
LessError: LessError,
transformTree: transformTree,
utils: utils,
PluginManager: PluginManagerFactory,
logger: logger
};
// Create a public API
var ctor = function (t) { return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new (t.bind.apply(t, __spreadArrays([void 0], args)))();
}; };
var t;
var api = Object.create(initial);
for (var n in initial.tree) {
/* eslint guard-for-in: 0 */
t = initial.tree[n];
if (typeof t === 'function') {
api[n.toLowerCase()] = ctor(t);
}
else {
api[n] = Object.create(null);
for (var o in t) {
/* eslint guard-for-in: 0 */
api[n][o.toLowerCase()] = ctor(t[o]);
}
}
}
return api;
});
/* global window, XMLHttpRequest */
var options;
var logger$1;
var fileCache = {};
// TODOS - move log somewhere. pathDiff and doing something similar in node. use pathDiff in the other browser file for the initial load
var FileManager = /** @class */ (function (_super) {
__extends(FileManager, _super);
function FileManager() {
return _super !== null && _super.apply(this, arguments) || this;
}
FileManager.prototype.alwaysMakePathsAbsolute = function () {
return true;
};
FileManager.prototype.join = function (basePath, laterPath) {
if (!basePath) {
return laterPath;
}
return this.extractUrlParts(laterPath, basePath).path;
};
FileManager.prototype.doXHR = function (url, type, callback, errback) {
var xhr = new XMLHttpRequest();
var async = options.isFileProtocol ? options.fileAsync : true;
if (typeof xhr.overrideMimeType === 'function') {
xhr.overrideMimeType('text/css');
}
logger$1.debug("XHR: Getting '" + url + "'");
xhr.open('GET', url, async);
xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
xhr.send(null);
function handleResponse(xhr, callback, errback) {
if (xhr.status >= 200 && xhr.status < 300) {
callback(xhr.responseText, xhr.getResponseHeader('Last-Modified'));
}
else if (typeof errback === 'function') {
errback(xhr.status, url);
}
}
if (options.isFileProtocol && !options.fileAsync) {
if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
callback(xhr.responseText);
}
else {
errback(xhr.status, url);
}
}
else if (async) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
handleResponse(xhr, callback, errback);
}
};
}
else {
handleResponse(xhr, callback, errback);
}
};
FileManager.prototype.supports = function () {
return true;
};
FileManager.prototype.clearFileCache = function () {
fileCache = {};
};
FileManager.prototype.loadFile = function (filename, currentDirectory, options, environment) {
// TODO: Add prefix support like less-node?
// What about multiple paths?
if (currentDirectory && !this.isPathAbsolute(filename)) {
filename = currentDirectory + filename;
}
filename = options.ext ? this.tryAppendExtension(filename, options.ext) : filename;
options = options || {};
// sheet may be set to the stylesheet for the initial load or a collection of properties including
// some context variables for imports
var hrefParts = this.extractUrlParts(filename, window.location.href);
var href = hrefParts.url;
var self = this;
return new Promise(function (resolve, reject) {
if (options.useFileCache && fileCache[href]) {
try {
var lessText_1 = fileCache[href];
return resolve({ contents: lessText_1, filename: href, webInfo: { lastModified: new Date() } });
}
catch (e) {
return reject({ filename: href, message: "Error loading file " + href + " error was " + e.message });
}
}
self.doXHR(href, options.mime, function doXHRCallback(data, lastModified) {
// per file cache
fileCache[href] = data;
// Use remote copy (re-parse)
resolve({ contents: data, filename: href, webInfo: { lastModified: lastModified } });
}, function doXHRError(status, url) {
reject({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")", href: href });
});
});
};
return FileManager;
}(AbstractFileManager));
var FM = (function (opts, log) {
options = opts;
logger$1 = log;
return FileManager;
});
// TODO: Add tests for browser @plugin
/**
* Browser Plugin Loader
*/
var PluginLoader = /** @class */ (function (_super) {
__extends(PluginLoader, _super);
function PluginLoader(less) {
var _this = _super.call(this) || this;
_this.less = less;
return _this;
// Should we shim this.require for browser? Probably not?
}
PluginLoader.prototype.loadPlugin = function (filename, basePath, context, environment, fileManager) {
return new Promise(function (fulfill, reject) {
fileManager.loadFile(filename, basePath, context, environment)
.then(fulfill).catch(reject);
});
};
return PluginLoader;
}(AbstractPluginLoader));
var LogListener = (function (less, options) {
var logLevel_debug = 4;
var logLevel_info = 3;
var logLevel_warn = 2;
var logLevel_error = 1;
// The amount of logging in the javascript console.
// 3 - Debug, information and errors
// 2 - Information and errors
// 1 - Errors
// 0 - None
// Defaults to 2
options.logLevel = typeof options.logLevel !== 'undefined' ? options.logLevel : (options.env === 'development' ? logLevel_info : logLevel_error);
if (!options.loggers) {
options.loggers = [{
debug: function (msg) {
if (options.logLevel >= logLevel_debug) {
console.log(msg);
}
},
info: function (msg) {
if (options.logLevel >= logLevel_info) {
console.log(msg);
}
},
warn: function (msg) {
if (options.logLevel >= logLevel_warn) {
console.warn(msg);
}
},
error: function (msg) {
if (options.logLevel >= logLevel_error) {
console.error(msg);
}
}
}];
}
for (var i_1 = 0; i_1 < options.loggers.length; i_1++) {
less.logger.addListener(options.loggers[i_1]);
}
});
var ErrorReporting = (function (window, less, options) {
function errorHTML(e, rootHref) {
var id = "less-error-message:" + extractId(rootHref || '');
var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>';
var elem = window.document.createElement('div');
var timer;
var content;
var errors = [];
var filename = e.filename || rootHref;
var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1];
elem.id = id;
elem.className = 'less-error-message';
content = "<h3>" + (e.type || 'Syntax') + "Error: " + (e.message || 'There is an error in your .less file') +
("</h3><p>in <a href=\"" + filename + "\">" + filenameNoPath + "</a> ");
var errorline = function (e, i, classname) {
if (e.extract[i] !== undefined) {
errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
.replace(/\{class\}/, classname)
.replace(/\{content\}/, e.extract[i]));
}
};
if (e.line) {
errorline(e, 0, '');
errorline(e, 1, 'line');
errorline(e, 2, '');
content += "on line " + e.line + ", column " + (e.column + 1) + ":</p><ul>" + errors.join('') + "</ul>";
}
if (e.stack && (e.extract || options.logLevel >= 4)) {
content += "<br/>Stack Trace</br />" + e.stack.split('\n').slice(1).join('<br/>');
}
elem.innerHTML = content;
// CSS for error messages
browser.createCSS(window.document, [
'.less-error-message ul, .less-error-message li {',
'list-style-type: none;',
'margin-right: 15px;',
'padding: 4px 0;',
'margin: 0;',
'}',
'.less-error-message label {',
'font-size: 12px;',
'margin-right: 15px;',
'padding: 4px 0;',
'color: #cc7777;',
'}',
'.less-error-message pre {',
'color: #dd6666;',
'padding: 4px 0;',
'margin: 0;',
'display: inline-block;',
'}',
'.less-error-message pre.line {',
'color: #ff0000;',
'}',
'.less-error-message h3 {',
'font-size: 20px;',
'font-weight: bold;',
'padding: 15px 0 5px 0;',
'margin: 0;',
'}',
'.less-error-message a {',
'color: #10a',
'}',
'.less-error-message .error {',
'color: red;',
'font-weight: bold;',
'padding-bottom: 2px;',
'border-bottom: 1px dashed red;',
'}'
].join('\n'), { title: 'error-message' });
elem.style.cssText = [
'font-family: Arial, sans-serif',
'border: 1px solid #e00',
'background-color: #eee',
'border-radius: 5px',
'-webkit-border-radius: 5px',
'-moz-border-radius: 5px',
'color: #e00',
'padding: 15px',
'margin-bottom: 15px'
].join(';');
if (options.env === 'development') {
timer = setInterval(function () {
var document = window.document;
var body = document.body;
if (body) {
if (document.getElementById(id)) {
body.replaceChild(elem, document.getElementById(id));
}
else {
body.insertBefore(elem, body.firstChild);
}
clearInterval(timer);
}
}, 10);
}
}
function removeErrorHTML(path) {
var node = window.document.getElementById("less-error-message:" + extractId(path));
if (node) {
node.parentNode.removeChild(node);
}
}
function removeError(path) {
if (!options.errorReporting || options.errorReporting === 'html') {
removeErrorHTML(path);
}
else if (options.errorReporting === 'console') ;
else if (typeof options.errorReporting === 'function') {
options.errorReporting('remove', path);
}
}
function errorConsole(e, rootHref) {
var template = '{line} {content}';
var filename = e.filename || rootHref;
var errors = [];
var content = (e.type || 'Syntax') + "Error: " + (e.message || 'There is an error in your .less file') + " in " + filename;
var errorline = function (e, i, classname) {
if (e.extract[i] !== undefined) {
errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
.replace(/\{class\}/, classname)
.replace(/\{content\}/, e.extract[i]));
}
};
if (e.line) {
errorline(e, 0, '');
errorline(e, 1, 'line');
errorline(e, 2, '');
content += " on line " + e.line + ", column " + (e.column + 1) + ":\n" + errors.join('\n');
}
if (e.stack && (e.extract || options.logLevel >= 4)) {
content += "\nStack Trace\n" + e.stack;
}
less.logger.error(content);
}
function error(e, rootHref) {
if (!options.errorReporting || options.errorReporting === 'html') {
errorHTML(e, rootHref);
}
else if (options.errorReporting === 'console') {
errorConsole(e, rootHref);
}
else if (typeof options.errorReporting === 'function') {
options.errorReporting('add', e, rootHref);
}
}
return {
add: error,
remove: removeError
};
});
// Cache system is a bit outdated and could do with work
var Cache = (function (window, options, logger) {
var cache = null;
if (options.env !== 'development') {
try {
cache = (typeof window.localStorage === 'undefined') ? null : window.localStorage;
}
catch (_) { }
}
return {
setCSS: function (path, lastModified, modifyVars, styles) {
if (cache) {
logger.info("saving " + path + " to cache.");
try {
cache.setItem(path, styles);
cache.setItem(path + ":timestamp", lastModified);
if (modifyVars) {
cache.setItem(path + ":vars", JSON.stringify(modifyVars));
}
}
catch (e) {
// TODO - could do with adding more robust error handling
logger.error("failed to save \"" + path + "\" to local storage for caching.");
}
}
},
getCSS: function (path, webInfo, modifyVars) {
var css = cache && cache.getItem(path);
var timestamp = cache && cache.getItem(path + ":timestamp");
var vars = cache && cache.getItem(path + ":vars");
modifyVars = modifyVars || {};
vars = vars || "{}"; // if not set, treat as the JSON representation of an empty object
if (timestamp && webInfo.lastModified &&
(new Date(webInfo.lastModified).valueOf() ===
new Date(timestamp).valueOf()) &&
JSON.stringify(modifyVars) === vars) {
// Use local copy
return css;
}
}
};
});
var ImageSize = (function () {
function imageSize() {
throw {
type: 'Runtime',
message: 'Image size functions are not supported in browser version of less'
};
}
var imageFunctions = {
'image-size': function (filePathNode) {
imageSize();
return -1;
},
'image-width': function (filePathNode) {
imageSize();
return -1;
},
'image-height': function (filePathNode) {
imageSize();
return -1;
}
};
functionRegistry.addMultiple(imageFunctions);
});
//
var root = (function (window, options) {
var document = window.document;
var less = lessRoot();
less.options = options;
var environment = less.environment;
var FileManager = FM(options, less.logger);
var fileManager = new FileManager();
environment.addFileManager(fileManager);
less.FileManager = FileManager;
less.PluginLoader = PluginLoader;
LogListener(less, options);
var errors = ErrorReporting(window, less, options);
var cache = less.cache = options.cache || Cache(window, options, less.logger);
ImageSize(less.environment);
// Setup user functions - Deprecate?
if (options.functions) {
less.functions.functionRegistry.addMultiple(options.functions);
}
var typePattern = /^text\/(x-)?less$/;
function clone(obj) {
var cloned = {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
cloned[prop] = obj[prop];
}
}
return cloned;
}
// only really needed for phantom
function bind(func, thisArg) {
var curryArgs = Array.prototype.slice.call(arguments, 2);
return function () {
var args = curryArgs.concat(Array.prototype.slice.call(arguments, 0));
return func.apply(thisArg, args);
};
}
function loadStyles(modifyVars) {
var styles = document.getElementsByTagName('style');
var style;
for (var i_1 = 0; i_1 < styles.length; i_1++) {
style = styles[i_1];
if (style.type.match(typePattern)) {
var instanceOptions = clone(options);
instanceOptions.modifyVars = modifyVars;
var lessText_1 = style.innerHTML || '';
instanceOptions.filename = document.location.href.replace(/#.*$/, '');
/* jshint loopfunc:true */
// use closure to store current style
less.render(lessText_1, instanceOptions, bind(function (style, e, result) {
if (e) {
errors.add(e, 'inline');
}
else {
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = result.css;
}
else {
style.innerHTML = result.css;
}
}
}, null, style));
}
}
}
function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) {
var instanceOptions = clone(options);
addDataAttr(instanceOptions, sheet);
instanceOptions.mime = sheet.type;
if (modifyVars) {
instanceOptions.modifyVars = modifyVars;
}
function loadInitialFileCallback(loadedFile) {
var data = loadedFile.contents;
var path = loadedFile.filename;
var webInfo = loadedFile.webInfo;
var newFileInfo = {
currentDirectory: fileManager.getPath(path),
filename: path,
rootFilename: path,
rewriteUrls: instanceOptions.rewriteUrls
};
newFileInfo.entryPath = newFileInfo.currentDirectory;
newFileInfo.rootpath = instanceOptions.rootpath || newFileInfo.currentDirectory;
if (webInfo) {
webInfo.remaining = remaining;
var css = cache.getCSS(path, webInfo, instanceOptions.modifyVars);
if (!reload && css) {
webInfo.local = true;
callback(null, css, data, sheet, webInfo, path);
return;
}
}
// TODO add tests around how this behaves when reloading
errors.remove(path);
instanceOptions.rootFileInfo = newFileInfo;
less.render(data, instanceOptions, function (e, result) {
if (e) {
e.href = path;
callback(e);
}
else {
cache.setCSS(sheet.href, webInfo.lastModified, instanceOptions.modifyVars, result.css);
callback(null, result.css, data, sheet, webInfo, path);
}
});
}
fileManager.loadFile(sheet.href, null, instanceOptions, environment)
.then(function (loadedFile) {
loadInitialFileCallback(loadedFile);
}).catch(function (err) {
console.log(err);
callback(err);
});
}
function loadStyleSheets(callback, reload, modifyVars) {
for (var i_2 = 0; i_2 < less.sheets.length; i_2++) {
loadStyleSheet(less.sheets[i_2], callback, reload, less.sheets.length - (i_2 + 1), modifyVars);
}
}
function initRunningMode() {
if (less.env === 'development') {
less.watchTimer = setInterval(function () {
if (less.watchMode) {
fileManager.clearFileCache();
loadStyleSheets(function (e, css, _, sheet, webInfo) {
if (e) {
errors.add(e, e.href || sheet.href);
}
else if (css) {
browser.createCSS(window.document, css, sheet);
}
});
}
}, options.poll);
}
}
//
// Watch mode
//
less.watch = function () {
if (!less.watchMode) {
less.env = 'development';
initRunningMode();
}
this.watchMode = true;
return true;
};
less.unwatch = function () { clearInterval(less.watchTimer); this.watchMode = false; return false; };
//
// Synchronously get all <link> tags with the 'rel' attribute set to
// "stylesheet/less".
//
less.registerStylesheetsImmediately = function () {
var links = document.getElementsByTagName('link');
less.sheets = [];
for (var i_3 = 0; i_3 < links.length; i_3++) {
if (links[i_3].rel === 'stylesheet/less' || (links[i_3].rel.match(/stylesheet/) &&
(links[i_3].type.match(typePattern)))) {
less.sheets.push(links[i_3]);
}
}
};
//
// Asynchronously get all <link> tags with the 'rel' attribute set to
// "stylesheet/less", returning a Promise.
//
less.registerStylesheets = function () { return new Promise(function (resolve, reject) {
less.registerStylesheetsImmediately();
resolve();
}); };
//
// With this function, it's possible to alter variables and re-render
// CSS without reloading less-files
//
less.modifyVars = function (record) { return less.refresh(true, record, false); };
less.refresh = function (reload, modifyVars, clearFileCache) {
if ((reload || clearFileCache) && clearFileCache !== false) {
fileManager.clearFileCache();
}
return new Promise(function (resolve, reject) {
var startTime;
var endTime;
var totalMilliseconds;
var remainingSheets;
startTime = endTime = new Date();
// Set counter for remaining unprocessed sheets
remainingSheets = less.sheets.length;
if (remainingSheets === 0) {
endTime = new Date();
totalMilliseconds = endTime - startTime;
less.logger.info('Less has finished and no sheets were loaded.');
resolve({
startTime: startTime,
endTime: endTime,
totalMilliseconds: totalMilliseconds,
sheets: less.sheets.length
});
}
else {
// Relies on less.sheets array, callback seems to be guaranteed to be called for every element of the array
loadStyleSheets(function (e, css, _, sheet, webInfo) {
if (e) {
errors.add(e, e.href || sheet.href);
reject(e);
return;
}
if (webInfo.local) {
less.logger.info("Loading " + sheet.href + " from cache.");
}
else {
less.logger.info("Rendered " + sheet.href + " successfully.");
}
browser.createCSS(window.document, css, sheet);
less.logger.info("CSS for " + sheet.href + " generated in " + (new Date() - endTime) + "ms");
// Count completed sheet
remainingSheets--;
// Check if the last remaining sheet was processed and then call the promise
if (remainingSheets === 0) {
totalMilliseconds = new Date() - startTime;
less.logger.info("Less has finished. CSS generated in " + totalMilliseconds + "ms");
resolve({
startTime: startTime,
endTime: endTime,
totalMilliseconds: totalMilliseconds,
sheets: less.sheets.length
});
}
endTime = new Date();
}, reload, modifyVars);
}
loadStyles(modifyVars);
});
};
less.refreshStyles = loadStyles;
return less;
});
/**
* Kicks off less and compiles any stylesheets
* used in the browser distributed version of less
* to kick-start less using the browser api
*/
var options$1 = defaultOptions();
if (window.less) {
for (var key in window.less) {
if (window.less.hasOwnProperty(key)) {
options$1[key] = window.less[key];
}
}
}
addDefaultOptions(window, options$1);
options$1.plugins = options$1.plugins || [];
if (window.LESS_PLUGINS) {
options$1.plugins = options$1.plugins.concat(window.LESS_PLUGINS);
}
var less = root(window, options$1);
window.less = less;
var css;
var head;
var style;
// Always restore page visibility
function resolveOrReject(data) {
if (data.filename) {
console.warn(data);
}
if (!options$1.async) {
head.removeChild(style);
}
}
if (options$1.onReady) {
if (/!watch/.test(window.location.hash)) {
less.watch();
}
// Simulate synchronous stylesheet loading by hiding page rendering
if (!options$1.async) {
css = 'body { display: none !important }';
head = document.head || document.getElementsByTagName('head')[0];
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
}
else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
}
less.registerStylesheetsImmediately();
less.pageLoadFinished = less.refresh(less.env === 'development').then(resolveOrReject, resolveOrReject);
}
return less;
})));
| BigBoss424/portfolio | v7/development/node_modules/less/dist/less.js | JavaScript | apache-2.0 | 468,443 |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
angular.module('flowableModeler')
.controller('EditModelPopupCtrl', ['$rootScope', '$scope', '$http', '$translate', '$location',
function ($rootScope, $scope, $http, $translate, $location) {
var model;
var popupType;
if ($scope.model.process) {
model = $scope.model.process;
popupType = 'PROCESS';
} else if ($scope.model.form) {
model = $scope.model.form;
popupType = 'FORM';
} else if ($scope.model.decisionTable) {
model = $scope.model.decisionTable;
popupType = 'DECISION-TABLE';
} else {
model = $scope.model.app;
popupType = 'APP';
}
$scope.popup = {
loading: false,
popupType: popupType,
modelName: model.name,
modelKey: model.key,
modelDescription: model.description,
id: model.id
};
$scope.ok = function () {
if (!$scope.popup.modelName || $scope.popup.modelName.length == 0 ||
!$scope.popup.modelKey || $scope.popup.modelKey.length == 0) {
return;
}
$scope.model.name = $scope.popup.modelName;
$scope.model.key = $scope.popup.modelKey;
$scope.model.description = $scope.popup.modelDescription;
$scope.popup.loading = true;
var updateData = {
name: $scope.model.name,
key: $scope.model.key, description:
$scope.model.description
};
$http({method: 'PUT', url: FLOWABLE.CONFIG.contextRoot + '/app/rest/models/' + $scope.popup.id, data: updateData}).
success(function(data, status, headers, config) {
if ($scope.model.process) {
$scope.model.process = data;
} else if ($scope.model.form) {
$scope.model.form = data;
} else if ($scope.model.decisionTable) {
$scope.model.decisionTable = data;
} else {
$scope.model.app = data;
}
$scope.addAlertPromise($translate('PROCESS.ALERT.EDIT-CONFIRM'), 'info');
$scope.$hide();
$scope.popup.loading = false;
if (popupType === 'FORM') {
$location.path("/forms/" + $scope.popup.id);
} else if (popupType === 'APP') {
$location.path("/apps/" + $scope.popup.id);
} else if (popupType === 'DECISION-TABLE') {
$location.path("/decision-tables/" + $scope.popup.id);
} else {
$location.path("/processes/" + $scope.popup.id);
}
}).
error(function(data, status, headers, config) {
$scope.popup.loading = false;
$scope.popup.errorMessage = data.message;
});
};
$scope.cancel = function () {
if (!$scope.popup.loading) {
$scope.$hide();
}
};
}]);
angular.module('flowableModeler')
.controller('DeleteModelPopupCtrl', ['$rootScope', '$scope', '$http', '$translate', function ($rootScope, $scope, $http, $translate) {
var model;
var popupType;
if ($scope.model.process) {
model = $scope.model.process;
popupType = 'PROCESS';
} else if ($scope.model.form) {
model = $scope.model.form;
popupType = 'FORM';
} else if ($scope.model.decisionTable) {
model = $scope.model.decisionTable;
popupType = 'DECISION-TABLE';
} else {
model = $scope.model.app;
popupType = 'APP';
}
$scope.popup = {
loading: true,
loadingRelations: true,
cascade: 'false',
popupType: popupType,
model: model
};
// Loading relations when opening
$http({method: 'GET', url: FLOWABLE.CONFIG.contextRoot + '/app/rest/models/' + $scope.popup.model.id + '/parent-relations'}).
success(function (data, status, headers, config) {
$scope.popup.loading = false;
$scope.popup.loadingRelations = false;
$scope.popup.relations = data;
}).
error(function (data, status, headers, config) {
$scope.$hide();
$scope.popup.loading = false;
});
$scope.ok = function () {
$scope.popup.loading = true;
var params = {
// Explicit string-check because radio-values cannot be js-booleans
cascade: $scope.popup.cascade === 'true'
};
$http({method: 'DELETE', url: FLOWABLE.CONFIG.contextRoot + '/app/rest/models/' + $scope.popup.model.id, params: params}).
success(function (data, status, headers, config) {
$scope.$hide();
$scope.popup.loading = false;
$scope.addAlertPromise($translate(popupType + '.ALERT.DELETE-CONFIRM'), 'info');
$scope.returnToList();
}).
error(function (data, status, headers, config) {
$scope.$hide();
$scope.popup.loading = false;
});
};
$scope.cancel = function () {
if (!$scope.popup.loading) {
$scope.$hide();
}
};
}]);
angular.module('flowableModeler')
.controller('UseAsNewVersionPopupCtrl', ['$rootScope', '$scope', '$http', '$translate', '$location', function ($rootScope, $scope, $http, $translate, $location) {
var model;
var popupType;
if ($scope.model.process) {
model = $scope.model.process;
popupType = 'PROCESS';
} else if ($scope.model.form) {
model = $scope.model.form;
popupType = 'FORM';
} else if ($scope.model.decisionTable) {
model = $scope.model.decisionTable;
popupType = 'DECISION-TABLE';
} else {
model = $scope.model.app;
popupType = 'APP';
}
$scope.popup = {
loading: false,
model: model,
popupType: popupType,
latestModelId: $scope.model.latestModelId,
comment: ''
};
$scope.ok = function () {
$scope.popup.loading = true;
var actionData = {
action: 'useAsNewVersion',
comment: $scope.popup.comment
};
$http({method: 'POST', url: FLOWABLE.CONFIG.contextRoot + '/app/rest/models/' + $scope.popup.latestModelId + '/history/' + $scope.popup.model.id, data: actionData}).
success(function(data, status, headers, config) {
var backToOverview = function() {
if (popupType === 'FORM') {
$location.path("/forms/" + $scope.popup.latestModelId);
} else if (popupType === 'APP') {
$location.path("/apps/" + $scope.popup.latestModelId);
} else if (popupType === 'DECISION-TABLE') {
$location.path("/decision-tables/" + $scope.popup.latestModelId);
} else {
$location.path("/processes/" + $scope.popup.latestModelId);
}
};
if (data && data.unresolvedModels && data.unresolvedModels.length > 0) {
// There were unresolved models
$scope.popup.loading = false;
$scope.popup.foundUnresolvedModels = true;
$scope.popup.unresolvedModels = data.unresolvedModels;
$scope.close = function() {
$scope.$hide();
backToOverview();
};
} else {
// All models working resolved perfectly
$scope.popup.loading = false;
$scope.$hide();
$scope.addAlertPromise($translate(popupType + '.ALERT.NEW-VERSION-CONFIRM'), 'info');
backToOverview();
}
}).
error(function(data, status, headers, config) {
$scope.$hide();
$scope.popup.loading = false;
});
};
$scope.cancel = function () {
if (!$scope.popup.loading) {
$scope.$hide();
}
};
}]);
| robsoncardosoti/flowable-engine | modules/flowable-ui-modeler/flowable-ui-modeler-app/src/main/webapp/scripts/controllers/model-common-actions.js | JavaScript | apache-2.0 | 8,719 |
'use strict';
define(['angular', 'require'], function(angular, require) {
var app = angular.module('my-app.marketplace.directives', []);
app.directive('marketplacePortlet', function() {
return {
restrict : 'E',
templateUrl : require.toUrl('./partials/marketplace-portlet.html')
}
});
app.directive('ratingModalTemplate', function() {
return {
restrict : 'E',
templateUrl : require.toUrl('./partials/rating-modal-template.html')
}
});
return app;
});
| paulerickson/angularjs-portal | angularjs-portal-home/src/main/webapp/my-app/marketplace/directives.js | JavaScript | apache-2.0 | 560 |
// Create variables for the welcome message
var greeting = 'Howdy ';
var name = 'Molly';
var message = ', please check your order:';
// Concatenate the three variables above to create the welcome message
var welcome = greeting + name + message;
// Create variables to hold details about the sign
var sign = 'Montague House';
var tiles = sign.length;
var subTotal = tiles * 5;
var shipping = 7;
var grandTotal = subTotal + shipping;
// Get the element that has an id of greeting
var el = document.getElementById('greeting');
// Replace the content of that element with the personalized welcome message
el.textContent = welcome;
// Get the element that has an id of userSign then update its contents
var elSign = document.getElementById('userSign');
elSign.textContent = sign;
// Get the element that has an id of tiles then update its contents
var elTiles = document.getElementById('tiles');
elTiles.textContent = tiles;
// Get the element that has an id of subTotal then update its contents
var elSubTotal = document.getElementById('subTotal');
elSubTotal.textContent = '$' + subTotal;
// Get the element that has an id of shipping then update its contents
var elShipping = document.getElementById('shipping');
elShipping.textContent = '$' + shipping;
// Get the element that has an id of grandTotal then update its contents
var elGrandTotal = document.getElementById('grandTotal');
elGrandTotal.textContent = '$' + grandTotal;
/*
NOTE: textContent does not work in IE8 or earlier
You can use innerHTML instead of textContent, but note the security issues on p228-231
In the first print run, line 33-34 repeated elSubTotal (rather than elShipping).
This was fixed in later print runs and in this code sample.
*/ | shammunhossain/ITE220 | web2/javascript-and-jquery-book-code-0915/c02/js/example.js | JavaScript | apache-2.0 | 1,721 |
/*
* Copyright 2016 IBM Corp.
* Copyright 2016 99Cloud.
*
* 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.
*/
(function () {
'use strict';
angular
.module('horizon.framework.widgets.table')
.controller('HzTableFooterController', HzTableFooterController);
HzTableFooterController.$inject = [
'horizon.framework.conf.tableOptions'
];
function HzTableFooterController(tableOptions) {
var ctrl = this;
ctrl.pageSize = horizon.cookies.get('API_RESULT_PAGE_SIZE') || tableOptions.pageSize;
}
})();
| openstack/horizon | horizon/static/framework/widgets/table/hz-table-footer.controller.js | JavaScript | apache-2.0 | 1,037 |
/**
* This task starts a dev server that provides a script loader for OpenLayers
* and Closure Library and runs tests in PhantomJS.
*/
var path = require('path');
var spawn = require('child_process').spawn;
var phantomjs = require('phantomjs-prebuilt');
var serve = require('../build/serve');
/**
* Try listening for incoming connections on a range of ports.
* @param {number} min Minimum port to try.
* @param {number} max Maximum port to try.
* @param {http.Server} server The server.
* @param {function(Error)} callback Callback called with any error.
*/
function listen(min, max, server, callback) {
function _listen(port) {
server.once('error', function(err) {
if (err.code === 'EADDRINUSE') {
++port;
if (port < max) {
_listen(port);
} else {
callback(new Error('Could not find an open port'));
}
} else {
callback(err);
}
});
server.listen(port, '127.0.0.1');
}
server.once('listening', function() {
callback(null);
});
_listen(min);
}
function runTests(conf, callback) {
var coverage = 'coverage' in conf ? conf.coverage : false;
var reporter = 'reporter' in conf ? conf.reporter : 'spec';
/**
* Create the debug server and run tests.
*/
serve.createServer(function(err, server) {
if (err) {
process.stderr.write(err.message + '\n');
process.exit(1);
}
listen(3001, 3005, server, function(err) {
if (err) {
process.stderr.write('Server failed to start: ' + err.message + '\n');
process.exit(1);
}
var address = server.address();
var url = 'http://' + address.address + ':' + address.port;
var args = [
require.resolve('mocha-phantomjs-core'),
url + '/test/index.html',
reporter
];
var config = {
ignoreResourceErrors: true,
useColors: true
};
if (coverage) {
config.hooks = path.join(__dirname, '../test/phantom_hooks.js');
}
args.push(JSON.stringify(config));
var child = spawn(phantomjs.path, args, {stdio: 'inherit'});
child.on('exit', function(code) {
callback(code);
});
});
}, true);
}
if (require.main === module) {
runTests({coverage: false, reporter: 'spec'}, function(code) {
process.exit(code);
});
}
module.exports = {
runTests: runTests,
listen: listen
};
| dsmiley/hhypermap-bop | bop-ui/assets/lib/ol3-google-maps/tasks/test.js | JavaScript | apache-2.0 | 2,414 |
angular.module('gdgXBoomerang')
.controller('OrganizersController', function ($http, Config, NavService) {
var vm = this;
vm.loading = false;
NavService.setNavTab(4);
var url = 'http://hub.gdgx.io/api/v1/chapters/' + Config.id + '?callback=JSON_CALLBACK';
var headers = { 'headers': { 'Accept': 'application/json;' }, 'timeout': 2000 };
$http.jsonp(url, headers).success(function (data) {
if (data.organizers) {
vm.organizers = data.organizers;
}
});
});
| jhoon/boomerang | app/organizers/organizers.js | JavaScript | apache-2.0 | 512 |
/**
* @preserve Copyright 2014 Washington University
* @author [email protected] (Sunil Kumar)
* @author [email protected] (Rick Herrick)
*/
goog.provide('gxnat');
// goog
goog.require('goog.net.XhrIo');
goog.require('goog.object');
goog.require('goog.string');
goog.require('goog.array');
/**
* gxnat is the class that handles communication with the XNAT
* server, leveraging google closure tools.
* It uses RESTful calls to acquire JSON objects that are
* parsed to construct Thumbnails, which contain information regarding
* image sets that can be loaded into a ViewBox. xnat makes use of
* several Google Closure libraries to communicate with the XNAT server,
* especially goog.net.XhrIo.
*
*/
gxnat = function(){}
goog.exportSymbol('gxnat', gxnat);
/**
* @type {!string}
* @const
* @expose
*/
gxnat.JPEG_CONVERT_SUFFIX = '?format=image/jpeg';
/**
* XNAT folder abbreviations.
* @type {!Object.<!string, !string>}
* @const
* @public
*/
gxnat.folderAbbrev = {
'projects': 'proj',
'subjects': 'subj',
'experiments': 'expt',
'scans': 'scans'
};
/**
* @const
*/
gxnat.ZIP_SUFFIX = '?format=zip'
/**
* Queries a server for a JSON formatted object for processing in the
* 'callback' argument. Utilizes the Google closure library 'XhrIo' to
* handle communication with the XNAT server.
* @param {!string} url The XNAT url to run the operation on.
* @param {!function} callback The callback to send the results to.
* @param {string=} opt_suffix The optional suffix to add.
* @public
*/
gxnat.jsonGet = function(url, callback, opt_suffix){
var queryChar = (url.indexOf('?') > -1) ? '&' : '?';
var queryUrl = url + queryChar + "format=json";
if (goog.isDefAndNotNull(opt_suffix)){
if (opt_suffix[0] !== '&') {
opt_suffix = '&' + opt_suffix;
}
queryUrl += opt_suffix;
}
window.console.log('Getting XNAT json: \'' + queryUrl + '\'', url);
gxnat.get(queryUrl, callback, 'json');
}
/**
* Queries a server using a generic 'GET' call. Sends the response object into
* the 'callback' argument.
* @param {!string} url The URL to run GET on.
* @param {!function} callback The callback once GET communication is
* established. Callback should have a parameter for the recieved xhr.
* @param {string=} opt_getType The type of get to apply (i.e. 'json').
* If none, xhr is sent to the callback. If 'json', xhr.getResponseJson()
* is sent into the callback.
* @public
*/
gxnat.get = function(url, callback, opt_getType){
//window.console.log("\n\nxnat - get: ", url);
goog.net.XhrIo.send(url, function(e) {
var xhr = e.target;
switch (opt_getType) {
case undefined:
callback(xhr);
break;
case 'json':
var responseJson = xhr.getResponseJson();
if (responseJson.hasOwnProperty('ResultSet')){
callback(responseJson['ResultSet']['Result']);
} else {
callback(responseJson);
}
break;
case 'text':
callback(xhr.getResponseText());
break;
}
});
}
/**
* source: https://github.com/overset/javascript-natural-sort/blob/master/naturalSort.js
*/
gxnat.naturalSort = function(a, b) {
var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
sre = /(^[ ]*|[ ]*$)/g,
dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
hre = /^0x[0-9a-f]+$/i,
ore = /^0/,
i = function(s) { return gxnat.naturalSort.insensitive && (''+s).toLowerCase() || ''+s },
// convert all to strings strip whitespace
x = i(a).replace(sre, '') || '',
y = i(b).replace(sre, '') || '',
// chunk/tokenize
xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
// numeric, hex or date detection
xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null,
oFxNcL, oFyNcL;
// first try and sort Hex codes or Dates
if (yD)
if ( xD < yD ) return -1;
else if ( xD > yD ) return 1;
// natural sorting through split numeric strings and default strings
for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
// find floats not starting with '0', string or 0 if not defined (Clint Priest)
oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams)
if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; }
// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
else if (typeof oFxNcL !== typeof oFyNcL) {
oFxNcL += '';
oFyNcL += '';
}
if (oFxNcL < oFyNcL) return -1;
if (oFxNcL > oFyNcL) return 1;
}
return 0;
}
/**
* Sorts the viewable collection, which is an array of XNAT derived JSONS
* customized (added to) for the purposes of the Image viewer.
* @param {!Array.<gxnat.vis.AjaxViewableTree>} viewables The array of
* gxnat.vis.AjaxViewableTree to sort.
* @param {!Array.<String>} keyDepthArr The key depth array indicating the
* sorting criteria.
* @public
*/
gxnat.sortXnatPropertiesArray = function (viewables, keyDepthArr){
var sorterKeys = [];
var sorterObj = {};
var sortedViewableCollection = [];
var sorterKey = {};
//
// Update sorting data types.
//
goog.array.forEach(viewables, function(viewable){
sorterKey = viewable;
goog.array.forEach(keyDepthArr, function(key){
sorterKey = sorterKey[key];
})
sorterKey = sorterKey.toLowerCase();
sorterKeys.push(sorterKey);
sorterObj[sorterKey] = viewable;
})
//
// Natural sort sorterKeys.
//
sorterKeys = sorterKeys.sort(gxnat.naturalCompare);
//goog.array.sort(sorterKeys);
//
// Construct and return the sorted collection.
//
goog.array.forEach(sorterKeys, function(sorterKey){
sortedViewableCollection.push(sorterObj[sorterKey]);
})
return sortedViewableCollection;
}
goog.exportSymbol('gxnat.JPEG_CONVERT_SUFFIX', gxnat.JPEG_CONVERT_SUFFIX);
goog.exportSymbol('gxnat.folderAbbrev', gxnat.folderAbbrev);
goog.exportSymbol('gxnat.ZIP_SUFFIX', gxnat.ZIP_SUFFIX);
goog.exportSymbol('gxnat.jsonGet', gxnat.jsonGet);
goog.exportSymbol('gxnat.get', gxnat.get);
goog.exportSymbol('gxnat.naturalSort', gxnat.naturalSort);
goog.exportSymbol('gxnat.sortXnatPropertiesArray',
gxnat.sortXnatPropertiesArray);
| evast/XNATImageViewer | src/main/scripts/viewer/gxnat/gxnat.js | JavaScript | bsd-3-clause | 6,826 |
/*
* Author: Zoltán Lajos Kis <[email protected]>
*/
"use strict";
(function() {
var util = require('util');
var ofp = require('../ofp.js');
var packet = require('../../packet.js');
var offsets = ofp.offsets.ofp_action_header;
module.exports = {
"unpack" : function(buffer, offset) {
var action = {
"header" : {"type" : 'OFPAT_POP_VLAN'}
};
var len = buffer.readUInt16BE(offset + offsets.len, true);
if (len != ofp.sizes.ofp_action_header) {
return {
"error" : {
"desc" : util.format('%s action at offset %d has invalid length (%d).', action.header.type, offset, len),
"type" : 'OFPET_BAD_ACTION', "code" : 'OFPBAC_BAD_LEN'
}
}
}
return {
"action" : action,
"offset" : offset + len
}
},
"pack" : function(action, buffer, offset) {
buffer.writeUInt16BE(ofp.ofp_action_type.OFPAT_POP_VLAN, offset + offsets.type, true);
buffer.writeUInt16BE(ofp.sizes.ofp_action_header, offset + offsets.len, true);
buffer.fill(0, offset + offsets.pad, offset + offsets.pad + 4);
return {
offset : offset + ofp.sizes.ofp_action_header
}
}
}
})();
| John-Lin/oflib-node | lib/ofp-1.1/actions/pop-vlan.js | JavaScript | bsd-3-clause | 1,615 |
var searchData=
[
['comparator_5ffunction_148',['comparator_function',['../namespacepmem_1_1kv.html#a030860872cabda2262ece46fc77785d7',1,'pmem::kv']]]
];
| pbalcer/pbalcer.github.io | content/pmemkv/v1.3/doxygen/search/typedefs_0.js | JavaScript | bsd-3-clause | 156 |
// FORK:
// https://github.com/danielweck/keymaster
// keymaster.js
// (c) 2011-2013 Thomas Fuchs
// keymaster.js may be freely distributed under the MIT license.
;(function(global){
var k,
_handlers = {},
_mods = { 16: false, 18: false, 17: false, 91: false },
_scope = 'all',
// modifier keys
_MODIFIERS = {
'⇧': 16, shift: 16,
'⌥': 18, alt: 18, option: 18,
'⌃': 17, ctrl: 17, control: 17,
'⌘': 91, command: 91
},
// special keys
_MAP = {
backspace: 8, tab: 9, clear: 12,
enter: 13, 'return': 13,
esc: 27, escape: 27, space: 32,
left: 37, up: 38,
right: 39, down: 40,
del: 46, 'delete': 46,
home: 36, end: 35,
pageup: 33, pagedown: 34,
',': 188, '.': 190, '/': 191,
'`': 192, '-': 189, '=': 187,
';': 186, '\'': 222,
'[': 219, ']': 221, '\\': 220
},
code = function(x){
return x.toUpperCase ? (_MAP[x] || x.toUpperCase().charCodeAt(0)) : x;
},
_downKeys = [];
for(k=1;k<20;k++) _MAP['f'+k] = 111+k;
// IE doesn't support Array#indexOf, so have a simple replacement
function index(array, item){
var i = array.length;
while(i--) if(array[i]===item) return i;
return -1;
}
// for comparing mods before unassignment
function compareArray(a1, a2) {
if (a1.length != a2.length) return false;
for (var i = 0; i < a1.length; i++) {
if (a1[i] !== a2[i]) return false;
}
return true;
}
var modifierMap = {
16:'shiftKey',
18:'altKey',
17:'ctrlKey',
91:'metaKey'
};
function updateModifierKey(event) {
for(k in _mods) _mods[k] = event[modifierMap[k]];
};
function getKeyCode(event)
{
return event.keyCode || event.charCode || event.which || event.key || 0;
}
// handle keydown event
function dispatch(event) {
var key, handler, k, i, modifiersMatch, scope;
key = getKeyCode(event);
if (index(_downKeys, key) == -1) {
_downKeys.push(key);
}
// if a modifier key, set the key.<modifierkeyname> property to true and return
if(key == 93 || key == 224) key = 91; // right command on webkit, command on Gecko
if(key in _mods) {
_mods[key] = true;
// 'assignKey' from inside this closure is exported to window.key
for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = true;
return;
}
updateModifierKey(event);
// see if we need to ignore the keypress (filter() can can be overridden)
// by default ignore key presses if a select, textarea, or input is focused
if(!assignKey.filter.call(this, event)) return;
// abort if no potentially matching shortcuts found
if (!(key in _handlers)) return;
scope = getScope();
// for each potential shortcut
for (i = 0; i < _handlers[key].length; i++) {
handler = _handlers[key][i];
// see if it's in the current scope
if(handler.scope == scope || handler.scope == 'all'){
// check if modifiers match if any
modifiersMatch = handler.mods.length > 0;
for(k in _mods)
if((!_mods[k] && index(handler.mods, +k) > -1) ||
(_mods[k] && index(handler.mods, +k) == -1)) modifiersMatch = false;
// call the handler and stop the event if neccessary
if((handler.mods.length == 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch){
if(handler.method(event, handler)===false){
if(event.preventDefault) event.preventDefault();
else event.returnValue = false;
if(event.stopPropagation) event.stopPropagation();
if(event.cancelBubble) event.cancelBubble = true;
}
}
}
}
};
// unset modifier keys on keyup
function clearModifier(event){
var key = getKeyCode(event), k,
i = index(_downKeys, key);
// remove key from _downKeys
if (i >= 0) {
_downKeys.splice(i, 1);
}
if(key == 93 || key == 224) key = 91;
if(key in _mods) {
_mods[key] = false;
for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = false;
}
};
function resetModifiers() {
for(k in _mods) _mods[k] = false;
for(k in _MODIFIERS) assignKey[k] = false;
};
// parse and assign shortcut
function assignKey(key, scope, method){
var keys, mods;
keys = getKeys(key);
if (method === undefined) {
method = scope;
scope = 'all';
}
// for each shortcut
for (var i = 0; i < keys.length; i++) {
// set modifier keys if any
mods = [];
key = keys[i].split('+');
if (key.length > 1){
mods = getMods(key);
key = [key[key.length-1]];
}
// convert to keycode and...
key = key[0]
key = code(key);
// ...store handler
if (!(key in _handlers)) _handlers[key] = [];
_handlers[key].push({ shortcut: keys[i], scope: scope, method: method, key: keys[i], mods: mods });
}
};
// unbind all handlers for given key in current scope
function unbindKey(key, scope) {
var multipleKeys, keys,
mods = [],
i, j, obj;
multipleKeys = getKeys(key);
for (j = 0; j < multipleKeys.length; j++) {
keys = multipleKeys[j].split('+');
if (keys.length > 1) {
mods = getMods(keys);
}
key = keys[keys.length - 1];
key = code(key);
if (scope === undefined) {
scope = getScope();
}
if (!_handlers[key]) {
return;
}
for (i = 0; i < _handlers[key].length; i++) {
obj = _handlers[key][i];
// only clear handlers if correct scope and mods match
if (obj.scope === scope && compareArray(obj.mods, mods)) {
_handlers[key][i] = {};
}
}
}
};
// Returns true if the key with code 'keyCode' is currently down
// Converts strings into key codes.
function isPressed(keyCode) {
if (typeof(keyCode)=='string') {
keyCode = code(keyCode);
}
return index(_downKeys, keyCode) != -1;
}
function getPressedKeyCodes() {
return _downKeys.slice(0);
}
function filter(event){
var tagName = (event.target || event.srcElement).tagName;
// ignore keypressed in any elements that support keyboard data input
return !(tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
}
// initialize key.<modifier> to false
for(k in _MODIFIERS) assignKey[k] = false;
// set current scope (default 'all')
function setScope(scope){ _scope = scope || 'all' };
function getScope(){ return _scope || 'all' };
// delete all handlers for a given scope
function deleteScope(scope){
var key, handlers, i;
for (key in _handlers) {
handlers = _handlers[key];
for (i = 0; i < handlers.length; ) {
if (handlers[i].scope === scope) handlers.splice(i, 1);
else i++;
}
}
};
// abstract key logic for assign and unassign
function getKeys(key) {
var keys;
key = key.replace(/\s/g, '');
keys = key.split(',');
if ((keys[keys.length - 1]) == '') {
keys[keys.length - 2] += ',';
}
return keys;
}
// abstract mods logic for assign and unassign
function getMods(key) {
var mods = key.slice(0, key.length - 1);
for (var mi = 0; mi < mods.length; mi++)
mods[mi] = _MODIFIERS[mods[mi]];
return mods;
}
// cross-browser events
function addEvent(object, event, method) {
if (object.addEventListener)
object.addEventListener(event, method, false);
else if(object.attachEvent)
object.attachEvent('on'+event, function(){ method(window.event) });
};
// set the handlers globally on document
addEvent(document, 'keydown', function(event) { dispatch(event) }); // Passing _scope to a callback to ensure it remains the same by execution. Fixes #48
addEvent(document, 'keyup', clearModifier);
// reset modifiers to false whenever the window is (re)focused.
addEvent(window, 'focus', resetModifiers);
// store previously defined key
var previousKey = global.key;
// restore previously defined key and return reference to our key object
function noConflict() {
var k = global.key;
global.key = previousKey;
return k;
}
// set window.key and window.key.set/get/deleteScope, and the default filter
global.key = assignKey;
global.key.setScope = setScope;
global.key.getScope = getScope;
global.key.deleteScope = deleteScope;
global.key.filter = filter;
global.key.isPressed = isPressed;
global.key.getPressedKeyCodes = getPressedKeyCodes;
global.key.noConflict = noConflict;
global.key.unbind = unbindKey;
if(typeof module !== 'undefined') module.exports = assignKey;
})(this);
| cene-co-za/readium-js-viewer | lib/thirdparty/keymaster.js | JavaScript | bsd-3-clause | 8,780 |
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule isReactComponent
* @typechecks
* @flow
*/
'use strict';
/**
* @internal
*
* Helper for checking if this is a React Component
* created with React.Component or React.createClass().
*/
function isReactComponent(component: mixed): boolean {
return !!(
component &&
component.prototype &&
component.prototype.isReactComponent
);
}
module.exports = isReactComponent;
| mroch/relay | src/container/isReactComponent.js | JavaScript | bsd-3-clause | 716 |
export default function min(values, valueof) {
let min;
if (valueof === undefined) {
for (const value of values) {
if (value != null
&& (min > value || (min === undefined && value >= value))) {
min = value;
}
}
} else {
let index = -1;
for (let value of values) {
if ((value = valueof(value, ++index, values)) != null
&& (min > value || (min === undefined && value >= value))) {
min = value;
}
}
}
return min;
}
| d3/d3-arrays | src/min.js | JavaScript | isc | 502 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.3.4.4_A5_T5;
* @section: 15.3.4.4;
* @assertion: If thisArg is not null(defined) the called function is passed ToObject(thisArg) as the this value;
* @description: thisArg is function variable;
*/
f = function(){this.touched= true;};
obj={};
f.call(obj);
//CHECK#1
if (!(obj.touched)) {
$ERROR('#1: If thisArg is not null(defined) the called function is passed ToObject(thisArg) as the this value');
}
| seraum/nectarjs | tests/ES3/Conformance/15_Native_ECMA_Script_Objects/15.3_Function_Objects/15.3.4_Properties_of_the_Function_Prototype_Object/15.3.4.4_Function.prototype.call/S15.3.4.4_A5_T5.js | JavaScript | mit | 558 |
import createSlicer from './createSlicer.js'
import mergeState from './util/mergeState.js'
/**
* @description
* persistState is a Store Enhancer that syncs (a subset of) store state to localStorage.
*
* @param {String|String[]} [paths] Specify keys to sync with localStorage, if left undefined the whole store is persisted
* @param {Object} [config] Optional config object
* @param {String} [config.key="redux"] String used as localStorage key
* @param {Function} [config.slicer] (paths) => (state) => subset. A function that returns a subset
* of store state that should be persisted to localStorage
* @param {Function} [config.serialize=JSON.stringify] (subset) => serializedData. Called just before persisting to
* localStorage. Should transform the subset into a format that can be stored.
* @param {Function} [config.deserialize=JSON.parse] (persistedData) => subset. Called directly after retrieving
* persistedState from localStorage. Should transform the data into the format expected by your application
*
* @return {Function} An enhanced store
*/
export default function persistState(paths, config) {
const cfg = {
key: 'redux',
merge: mergeState,
slicer: createSlicer,
serialize: JSON.stringify,
deserialize: JSON.parse,
...config
}
const {
key,
merge,
slicer,
serialize,
deserialize
} = cfg
return next => (reducer, initialState) => {
let persistedState
let finalInitialState
try {
persistedState = deserialize(localStorage.getItem(key))
finalInitialState = merge(initialState, persistedState)
} catch (e) {
console.warn('Failed to retrieve initialize state from localStorage:', e)
}
const store = next(reducer, finalInitialState)
const slicerFn = slicer(paths)
store.subscribe(function () {
const state = store.getState()
const subset = slicerFn(state)
try {
localStorage.setItem(key, serialize(subset))
} catch (e) {
console.warn('Unable to persist state to localStorage:', e)
}
})
return store
}
}
| ruprict/redux-localstorage | src/persistState.js | JavaScript | mit | 2,096 |
// This project uses "Yarn" package manager for managing JavaScript dependencies along
// with "Webpack Encore" library that helps working with the CSS and JavaScript files
// that are stored in the "assets/" directory.
//
// Read https://symfony.com/doc/current/frontend.html to learn more about how
// to manage CSS and JavaScript files in Symfony applications.
var Encore = require('@symfony/webpack-encore');
Encore
.setOutputPath('public/build/')
.setPublicPath('/build')
.cleanupOutputBeforeBuild()
.autoProvidejQuery()
.autoProvideVariables({
"window.Bloodhound": require.resolve('bloodhound-js'),
"jQuery.tagsinput": "bootstrap-tagsinput"
})
.enableSassLoader()
// when versioning is enabled, each filename will include a hash that changes
// whenever the contents of that file change. This allows you to use aggressive
// caching strategies. Use Encore.isProduction() to enable it only for production.
.enableVersioning(false)
.addEntry('app', './assets/js/app.js')
.addEntry('login', './assets/js/login.js')
.addEntry('admin', './assets/js/admin.js')
.addEntry('search', './assets/js/search.js')
.splitEntryChunks()
.enableSingleRuntimeChunk()
.enableIntegrityHashes(Encore.isProduction())
.configureBabel(null, {
useBuiltIns: 'usage',
corejs: 3,
})
;
module.exports = Encore.getWebpackConfig();
| voronkovich/symfony-demo | webpack.config.js | JavaScript | mit | 1,420 |
//FIXME: should be part of the jdl, but test are broken there
import React from 'react';
import { assert} from 'chai';
import sd from 'skin-deep';
import Immutable from 'immutable';
import { StatusIndicator, SvgStatus, SvgSpinner }
from '@jenkins-cd/design-language';
const props = {
width: '640px',
height: '640px',
};
const results = {
failure: {
fill: '#d54c53',
stroke: '#cf3a41',
},
};
describe("StatusIndicator should render", () => {
let tree = null;
beforeEach(() => {
tree = sd.shallowRender(<StatusIndicator
result="SUCCESS"
{...props}
/>);
});
it("does render success", () => {
const statusindicator = tree.getRenderOutput();
assert.isNotNull(statusindicator, 'tree.getRenderOutput()');
assert.equal(statusindicator.props.width, props.width, 'width prop');
assert.isOk(tree.subTree('title'), 'contains a <title> element');
assert.isOk(tree.subTree('g'), 'contains a <g> element');
});
});
describe("SvgStatus should render", () => {
let tree = null;
beforeEach(() => {
tree = sd.shallowRender(<SvgStatus
result="FAILURE"
/>);
});
it("does render FAILURE", () => {
const circle = tree.subTree('circle').getRenderOutput();
assert.isNotNull(circle);
});
});
describe("SvgSpinner should render", () => {
let tree = null;
beforeEach(() => {
tree = sd.shallowRender(<SvgSpinner
result="RUNNING"
percentage={40}
/>);
});
it("does render RUNNING", () => {
assert.isOk(tree.subTree('circle'), 'contains a <circle> element');
assert.isOk(tree.subTree('path'), 'contains a <path> element');
});
});
| alvarolobato/blueocean-plugin | blueocean-dashboard/src/test/js/status-spec.js | JavaScript | mit | 1,682 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.3.2.1_A3_T5;
* @section: 15.3.2.1, 13.2;
* @assertion: When the Function constructor is called with arguments p, body the following steps are taken:
* i) Let Result(i) be the first argument
* ii) Let P be ToString(Result(i))
* iii) Call ToString(body)
* iv) If P is not parsable as a FormalParameterList_opt then throw a SyntaxError exception
* v) If body is not parsable as FunctionBody then throw a SyntaxError exception
* vi) Create a new Function object as specified in 13.2 with parameters specified by parsing P as a FormalParameterListopt and body specified by parsing body as a FunctionBody
* Pass in a scope chain consisting of the global object as the Scope parameter
* vii) Return Result(vi);
* @description: Values of the function constructor arguments are "void 0" and "return \"A\";";
*/
body = "return \"A\";";
//CHECK#1
try {
f = new Function(void 0,body);
} catch (e) {
$FAIL('#1: test failed with error '+e);
}
//CHECK#2
if (f.constructor !== Function) {
$ERROR('#2: When the Function constructor is called with one argument then body be that argument and creates a new Function object as specified in 13.2');
}
//CHECK#3
if (f()!=='\u0041') {
$ERROR('#3: When the Function constructor is called with one argument then body be that argument the following steps are taken...');
}
| seraum/nectarjs | tests/ES3/Conformance/15_Native_ECMA_Script_Objects/15.3_Function_Objects/15.3.2_The_Function_Constructor/S15.3.2.1_A3_T5.js | JavaScript | mit | 1,463 |
version https://git-lfs.github.com/spec/v1
oid sha256:28450dc809566b07cabb11d478ddd9745359835b95a9fb707d2d6c5c7f2b2a47
size 26134
| yogeshsaroya/new-cdnjs | ajax/libs/dojo/1.10.4/cldr/nls/japanese.js.uncompressed.js | JavaScript | mit | 130 |
var searchData=
[
['cparbiter',['cpArbiter',['../group__cp_arbiter.html',1,'']]],
['cpbb',['cpBB',['../group__cp_b_b_b.html',1,'']]],
['cpbody',['cpBody',['../group__cp_body.html',1,'']]],
['cpcircleshape',['cpCircleShape',['../group__cp_circle_shape.html',1,'']]],
['cpconstraint',['cpConstraint',['../group__cp_constraint.html',1,'']]],
['cpdampedrotaryspring',['cpDampedRotarySpring',['../group__cp_damped_rotary_spring.html',1,'']]],
['cpdampedspring',['cpDampedSpring',['../group__cp_damped_spring.html',1,'']]],
['cpgearjoint',['cpGearJoint',['../group__cp_gear_joint.html',1,'']]],
['cpgroovejoint',['cpGrooveJoint',['../group__cp_groove_joint.html',1,'']]],
['cpmat2x2',['cpMat2x2',['../group__cp_mat2x2.html',1,'']]],
['cppinjoint',['cpPinJoint',['../group__cp_pin_joint.html',1,'']]],
['cppivotjoint',['cpPivotJoint',['../group__cp_pivot_joint.html',1,'']]],
['cppolyshape',['cpPolyShape',['../group__cp_poly_shape.html',1,'']]],
['cpratchetjoint',['cpRatchetJoint',['../group__cp_ratchet_joint.html',1,'']]],
['cprotarylimitjoint',['cpRotaryLimitJoint',['../group__cp_rotary_limit_joint.html',1,'']]],
['cpsegmentshape',['cpSegmentShape',['../group__cp_segment_shape.html',1,'']]],
['cpshape',['cpShape',['../group__cp_shape.html',1,'']]],
['cpsimplemotor',['cpSimpleMotor',['../group__cp_simple_motor.html',1,'']]],
['cpslidejoint',['cpSlideJoint',['../group__cp_slide_joint.html',1,'']]],
['cpspace',['cpSpace',['../group__cp_space.html',1,'']]],
['cpspatialindex',['cpSpatialIndex',['../group__cp_spatial_index.html',1,'']]],
['cpvect',['cpVect',['../group__cp_vect.html',1,'']]],
['chipmunk_20unsafe_20shape_20operations',['Chipmunk Unsafe Shape Operations',['../group__unsafe.html',1,'']]]
];
| mnewhouse/tselements | dependencies/chipmunk-7.0.2/doc/API-Reference/search/groups_63.js | JavaScript | mit | 1,755 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.4.4.10_A4_T1;
* @section: 15.4.4.10, 8.6.2.1, 15.2.4.5;
* @assertion: [[Get]] from not an inherited property;
* @description: [[Prototype]] of Array instance is Array.prototype;
*/
Array.prototype[1] = 1;
x = [0];
x.length = 2;
var arr = x.slice();
//CHECK#1
if (arr[0] !== 0) {
$ERROR('#1: Array.prototype[1] = 1; x = [0]; x.length = 2; var arr = x.slice(); arr[0] === 0. Actual: ' + (arr[0]));
}
//CHECK#2
if (arr[1] !== 1) {
$ERROR('#2: Array.prototype[1] = 1; x = [0]; x.length = 2; var arr = x.slice(); arr[1] === 1. Actual: ' + (arr[1]));
}
//CHECK#3
if (arr.hasOwnProperty('1') !== true) {
$ERROR('#3: Array.prototype[1] = 1; x = [0]; x.length = 2; var arr = x.slice(); arr.hasOwnProperty(\'1\') === true. Actual: ' + (arr.hasOwnProperty('1')));
}
| seraum/nectarjs | tests/ES3/Conformance/15_Native_ECMA_Script_Objects/15.4_Array_Objects/15.4.4_Properties_of_the_Array_Prototype_Object/15.4.4.10_Array_prototype_slice/S15.4.4.10_A4_T1.js | JavaScript | mit | 939 |
/**
* @fileoverview Rule to flag when deleting variables
* @author Ilya Volodin
*/
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = function(context) {
"use strict";
return {
"UnaryExpression": function(node) {
if (node.operator === "delete" && node.argument.type === "Identifier") {
context.report(node, "Variables should not be deleted.");
}
}
};
};
| okuryu/eslint | lib/rules/no-delete-var.js | JavaScript | mit | 581 |
IntlRelativeFormat.__addLocaleData({"locale":"ks","pluralRuleFunction":function (n,ord){if(ord)return"other";return n==1?"one":"other"},"fields":{"year":{"displayName":"ؤری","relative":{"0":"this year","1":"next year","-1":"last year"},"relativeTime":{"future":{"other":"+{0} y"},"past":{"other":"-{0} y"}}},"month":{"displayName":"رٮ۪تھ","relative":{"0":"this month","1":"next month","-1":"last month"},"relativeTime":{"future":{"other":"+{0} m"},"past":{"other":"-{0} m"}}},"day":{"displayName":"دۄہ","relative":{"0":"اَز","1":"پگاہ","-1":"راتھ"},"relativeTime":{"future":{"other":"+{0} d"},"past":{"other":"-{0} d"}}},"hour":{"displayName":"گٲنٛٹہٕ","relativeTime":{"future":{"other":"+{0} h"},"past":{"other":"-{0} h"}}},"minute":{"displayName":"مِنَٹ","relativeTime":{"future":{"other":"+{0} min"},"past":{"other":"-{0} min"}}},"second":{"displayName":"سٮ۪کَنڑ","relative":{"0":"now"},"relativeTime":{"future":{"other":"+{0} s"},"past":{"other":"-{0} s"}}}}});
IntlRelativeFormat.__addLocaleData({"locale":"ks-Arab","parentLocale":"ks"});
IntlRelativeFormat.__addLocaleData({"locale":"ks-Arab-IN","parentLocale":"ks-Arab"});
| Hive-Team/venus | node_modules/intl-relativeformat/dist/locale-data/ks.js | JavaScript | mit | 1,171 |
/*
This plugin extends lazySizes to lazyLoad:
background images, videos/posters and scripts
Background-Image:
For background images, use data-bg attribute:
<div class="lazyload" data-bg="bg-img.jpg"></div>
Video:
For video/audio use data-poster and preload="none":
<video class="lazyload" preload="none" data-poster="poster.jpg" src="src.mp4">
<!-- sources -->
</video>
For video that plays automatically if in view:
<video
class="lazyload"
preload="none"
muted=""
data-autoplay=""
data-poster="poster.jpg"
src="src.mp4">
</video>
Scripts:
For scripts use data-script:
<div class="lazyload" data-script="module-name.js"></div>
Script modules using require:
For modules using require use data-require:
<div class="lazyload" data-require="module-name"></div>
*/
(function(window, factory) {
var globalInstall = function(){
factory(window.lazySizes);
window.removeEventListener('lazyunveilread', globalInstall, true);
};
factory = factory.bind(null, window, window.document);
if(typeof module == 'object' && module.exports){
factory(require('lazysizes'));
} else if (typeof define == 'function' && define.amd) {
define(['lazysizes'], factory);
} else if(window.lazySizes) {
globalInstall();
} else {
window.addEventListener('lazyunveilread', globalInstall, true);
}
}(window, function(window, document, lazySizes) {
/*jshint eqnull:true */
'use strict';
var bgLoad, regBgUrlEscape;
var uniqueUrls = {};
if(document.addEventListener){
regBgUrlEscape = /\(|\)|\s|'/;
bgLoad = function (url, cb){
var img = document.createElement('img');
img.onload = function(){
img.onload = null;
img.onerror = null;
img = null;
cb();
};
img.onerror = img.onload;
img.src = url;
if(img && img.complete && img.onload){
img.onload();
}
};
addEventListener('lazybeforeunveil', function(e){
if(e.detail.instance != lazySizes){return;}
var tmp, load, bg, poster;
if(!e.defaultPrevented) {
var target = e.target;
if(target.preload == 'none'){
target.preload = target.getAttribute('data-preload') || 'auto';
}
if (target.getAttribute('data-autoplay') != null) {
if (target.getAttribute('data-expand') && !target.autoplay) {
try {
target.play();
} catch (er) {}
} else {
requestAnimationFrame(function () {
target.setAttribute('data-expand', '-10');
lazySizes.aC(target, lazySizes.cfg.lazyClass);
});
}
}
tmp = target.getAttribute('data-link');
if(tmp){
addStyleScript(tmp, true);
}
// handle data-script
tmp = target.getAttribute('data-script');
if(tmp){
e.detail.firesLoad = true;
load = function(){
e.detail.firesLoad = false;
lazySizes.fire(target, '_lazyloaded', {}, true, true);
};
addStyleScript(tmp, null, load);
}
// handle data-require
tmp = target.getAttribute('data-require');
if(tmp){
if(lazySizes.cfg.requireJs){
lazySizes.cfg.requireJs([tmp]);
} else {
addStyleScript(tmp);
}
}
// handle data-bg
bg = target.getAttribute('data-bg');
if (bg) {
e.detail.firesLoad = true;
load = function(){
target.style.backgroundImage = 'url(' + (regBgUrlEscape.test(bg) ? JSON.stringify(bg) : bg ) + ')';
e.detail.firesLoad = false;
lazySizes.fire(target, '_lazyloaded', {}, true, true);
};
bgLoad(bg, load);
}
// handle data-poster
poster = target.getAttribute('data-poster');
if(poster){
e.detail.firesLoad = true;
load = function(){
target.poster = poster;
e.detail.firesLoad = false;
lazySizes.fire(target, '_lazyloaded', {}, true, true);
};
bgLoad(poster, load);
}
}
}, false);
}
function addStyleScript(src, style, cb){
if(uniqueUrls[src]){
return;
}
var elem = document.createElement(style ? 'link' : 'script');
var insertElem = document.getElementsByTagName('script')[0];
if(style){
elem.rel = 'stylesheet';
elem.href = src;
} else {
elem.onload = function(){
elem.onerror = null;
elem.onload = null;
cb();
};
elem.onerror = elem.onload;
elem.src = src;
}
uniqueUrls[src] = true;
uniqueUrls[elem.src || elem.href] = true;
insertElem.parentNode.insertBefore(elem, insertElem);
}
}));
| aFarkas/lazysizes | plugins/unveilhooks/ls.unveilhooks.js | JavaScript | mit | 4,355 |
( function ( $ ) {
'use strict';
var nqoTransliteration = {
id: 'nqo-transliteration',
name: "N'Ko transliteration",
description: "N'Ko transliteration",
date: '2019-04-26',
URL: 'http://github.com/wikimedia/jquery.ime',
author: 'Amir E. Aharoni',
license: 'GPLv3',
version: '1.0',
maxKeyLength: 3,
patterns: [
// Sequences
[ 'ߣn', 'ߠ' ], // nn
[ 'ߢw', 'ߧ' ], // nyw
[ 'ߣy', 'ߢ' ], // ny
[
'ߖ\\/',
'ߨ'
], // j/
[
'ߗ\\/',
'ߩ'
], // c/
[
'ߙ\\/',
'ߪ'
], // r/
[ '\u07F2\u07F2\\.', '߷' ], // ...
[ '\u07EB-', '-' ], // --
[ '\u07EC~', '~' ], // ~~
[ '\\\\\\?', '?' ], // \?
[ '\\?', '؟' ],
// Unshifted
[ '`', 'ߑ' ],
[ '1', '߁' ],
[ '2', '߂' ],
[ '3', '߃' ],
[ '4', '߄' ],
[ '5', '߅' ],
[ '6', '߆' ],
[ '7', '߇' ],
[ '8', '߈' ],
[ '9', '߉' ],
[ '0', '߀' ],
[ 'w', 'ߥ' ],
[ 'e', 'ߍ' ],
[ 'r', 'ߙ' ],
[ 't', 'ߕ' ],
[ 'y', 'ߦ' ],
[ 'u', 'ߎ' ],
[ 'i', 'ߌ' ],
[ 'o', 'ߐ' ],
[ 'p', 'ߔ' ],
[ 'a', 'ߊ' ],
[ 's', 'ߛ' ],
[ 'd', 'ߘ' ],
[ 'f', 'ߝ' ],
[ 'g', 'ߜ' ],
[ 'h', 'ߤ' ],
[ 'j', 'ߖ' ],
[ 'k', 'ߞ' ],
[ 'l', 'ߟ' ],
[ 'c', 'ߗ' ],
[ 'b', 'ߓ' ],
[ 'n', 'ߣ' ],
[ 'm', 'ߡ' ],
// Shifted
[ '~', '\u07EC' ],
[ '!', '߹' ],
[ '#', '\u07F0' ],
[ '%', '\u07F3' ],
[ 'E', 'ߋ' ],
[ 'R', 'ߚ' ],
[ 'O', 'ߏ' ],
[ 'N', 'ߒ' ],
[ '<', '\u07F1' ],
[ '>', '\u07EF' ],
[ '\u07EE\\.', '\u07ED' ], // ^.
[ '\\^', '\u07EE' ], // ^
[ '߸\\/', 'ߺ' ], // ,/
[ '\\.', '\u07F2' ], // Combining nasalization mark ("dot below")
[ ',', '߸' ], // Comma
[ '/', '߶' ],
[ "'", 'ߴ' ], // High tone apostrophe
[ '"', 'ߵ' ], // Low tone apostrophe
[ '-', '\u07EB' ] // Combining short high tone ("macron")
]
};
$.ime.register( nqoTransliteration );
}( jQuery ) );
| cdnjs/cdnjs | ajax/libs/jquery.ime/0.3.0/rules/nqo/nqo-transliteration.js | JavaScript | mit | 1,938 |
/* Source and licensing information for the line(s) below can be found at http://www.hottubstore.com/sites/all/modules/flexslider/assets/js/flexslider.load.js. */
(function($){Drupal.behaviors.flexslider={attach:function(context,settings){var sliders=[];if($.type(settings.flexslider)!=='undefined'&&$.type(settings.flexslider.instances)!=='undefined')for(id in settings.flexslider.instances)if(settings.flexslider.optionsets[settings.flexslider.instances[id]]!==undefined)if(settings.flexslider.optionsets[settings.flexslider.instances[id]].asNavFor!==''){_flexslider_init(id,settings.flexslider.optionsets[settings.flexslider.instances[id]],context)}else sliders[id]=settings.flexslider.optionsets[settings.flexslider.instances[id]];for(id in sliders)_flexslider_init(id,settings.flexslider.optionsets[settings.flexslider.instances[id]],context)}}
function _flexslider_init(id,optionset,context){$('#'+id,context).once('flexslider',function(){$(this).find('ul.slides > li > *').removeAttr('width').removeAttr('height');if(optionset){$(this).flexslider($.extend(optionset,{start:function(slider){slider.trigger('start')},before:function(slider){slider.trigger('before')},after:function(slider){slider.trigger('after')},end:function(slider){slider.trigger('end')},added:function(slider){slider.trigger('added')},removed:function(slider){slider.trigger('removed')}}))}else $(this).flexslider()})}}(jQuery));;
/* Source and licensing information for the above line(s) can be found at http://www.hottubstore.com/sites/all/modules/flexslider/assets/js/flexslider.load.js. */
| mikeusry/thts | hot_tub/advagg_js/js__9VOFA0ojDRe-jzLYqMfhS65SJRxkYxfImCkNhDzFTGY__303WIuiWT3VWvFC6uhfqIZq0KlK2nYVnjfIOpqHEtUU__mI8nZtE_y7QMByurk4XzZQbcUvZv2i4LHlRJhG9hHJQ.js | JavaScript | gpl-2.0 | 1,571 |
module.exports = require('./lib/ClusterPlus'); | cw0100/cwse | nodejs/node_modules/rrestjs/lib/modules/ClusterPlus/index.js | JavaScript | gpl-2.0 | 46 |
// script.aculo.us controls.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
// (c) 2005-2008 Jon Tirsen (http://www.tirsen.com)
// Contributors:
// Richard Livsey
// Rahul Bhargava
// Rob Wills
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
// Autocompleter.Base handles all the autocompletion functionality
// that's independent of the data source for autocompletion. This
// includes drawing the autocompletion menu, observing keyboard
// and mouse events, and similar.
//
// Specific autocompleters need to provide, at the very least,
// a getUpdatedChoices function that will be invoked every time
// the text inside the monitored textbox changes. This method
// should get the text for which to provide autocompletion by
// invoking this.getToken(), NOT by directly accessing
// this.element.value. This is to allow incremental tokenized
// autocompletion. Specific auto-completion logic (AJAX, etc)
// belongs in getUpdatedChoices.
//
// Tokenized incremental autocompletion is enabled automatically
// when an autocompleter is instantiated with the 'tokens' option
// in the options parameter, e.g.:
// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
// will incrementally autocomplete with a comma as the token.
// Additionally, ',' in the above example can be replaced with
// a token array, e.g. { tokens: [',', '\n'] } which
// enables autocompletion on multiple tokens. This is most
// useful when one of the tokens is \n (a newline), as it
// allows smart autocompletion after linebreaks.
if(typeof Effect == 'undefined')
throw("controls.js requires including script.aculo.us' effects.js library");
var Autocompleter = { };
Autocompleter.Base = Class.create({
baseInitialize: function(element, update, options) {
element = $(element);
this.element = element;
this.update = $(update);
this.hasFocus = false;
this.changed = false;
this.active = false;
this.index = 0;
this.entryCount = 0;
this.oldElementValue = this.element.value;
if(this.setOptions)
this.setOptions(options);
else
this.options = options || { };
this.options.paramName = this.options.paramName || this.element.name;
this.options.tokens = this.options.tokens || [];
this.options.frequency = this.options.frequency || 0.4;
this.options.minChars = this.options.minChars || 1;
this.options.onShow = this.options.onShow ||
function(element, update){
if(!update.style.position || update.style.position=='absolute') {
update.style.position = 'absolute';
Position.clone(element, update, {
setHeight: false,
offsetTop: element.offsetHeight
});
}
Effect.Appear(update,{duration:0.15});
};
this.options.onHide = this.options.onHide ||
function(element, update){ new Effect.Fade(update,{duration:0.15}) };
if(typeof(this.options.tokens) == 'string')
this.options.tokens = new Array(this.options.tokens);
// Force carriage returns as token delimiters anyway
if (!this.options.tokens.include('\n'))
this.options.tokens.push('\n');
this.observer = null;
this.element.setAttribute('autocomplete','off');
Element.hide(this.update);
Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
},
show: function() {
if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
if(!this.iefix &&
(Prototype.Browser.IE) &&
(Element.getStyle(this.update, 'position')=='absolute')) {
new Insertion.After(this.update,
'<iframe id="' + this.update.id + '_iefix" '+
'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
this.iefix = $(this.update.id+'_iefix');
}
if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
},
fixIEOverlapping: function() {
Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
this.iefix.style.zIndex = 1;
this.update.style.zIndex = 2;
Element.show(this.iefix);
},
hide: function() {
this.stopIndicator();
if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
if(this.iefix) Element.hide(this.iefix);
},
startIndicator: function() {
if(this.options.indicator) Element.show(this.options.indicator);
},
stopIndicator: function() {
if(this.options.indicator) Element.hide(this.options.indicator);
},
onKeyPress: function(event) {
if(this.active)
switch(event.keyCode) {
case Event.KEY_TAB:
case Event.KEY_RETURN:
this.selectEntry();
Event.stop(event);
case Event.KEY_ESC:
this.hide();
this.active = false;
Event.stop(event);
return;
case Event.KEY_LEFT:
case Event.KEY_RIGHT:
return;
case Event.KEY_UP:
this.markPrevious();
this.render();
Event.stop(event);
return;
case Event.KEY_DOWN:
this.markNext();
this.render();
Event.stop(event);
return;
}
else
if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
(Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
this.changed = true;
this.hasFocus = true;
if(this.observer) clearTimeout(this.observer);
this.observer =
setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
},
activate: function() {
this.changed = false;
this.hasFocus = true;
this.getUpdatedChoices();
},
onHover: function(event) {
var element = Event.findElement(event, 'LI');
if(this.index != element.autocompleteIndex)
{
this.index = element.autocompleteIndex;
this.render();
}
Event.stop(event);
},
onClick: function(event) {
var element = Event.findElement(event, 'LI');
this.index = element.autocompleteIndex;
this.selectEntry();
this.hide();
},
onBlur: function(event) {
// needed to make click events working
setTimeout(this.hide.bind(this), 250);
this.hasFocus = false;
this.active = false;
},
render: function() {
if(this.entryCount > 0) {
for (var i = 0; i < this.entryCount; i++)
this.index==i ?
Element.addClassName(this.getEntry(i),"selected") :
Element.removeClassName(this.getEntry(i),"selected");
if(this.hasFocus) {
this.show();
this.active = true;
}
} else {
this.active = false;
this.hide();
}
},
markPrevious: function() {
if(this.index > 0) this.index--;
else {
this.index = this.entryCount-1;
this.update.scrollTop = this.update.scrollHeight;
}
selection = this.getEntry(this.index);
selection_top = selection.offsetTop;
if(selection_top < this.update.scrollTop){
this.update.scrollTop = this.update.scrollTop-selection.offsetHeight;
}
},
markNext: function() {
if(this.index < this.entryCount-1) this.index++;
else {
this.index = 0;
this.update.scrollTop = 0;
}
selection = this.getEntry(this.index);
selection_bottom = selection.offsetTop+selection.offsetHeight;
if(selection_bottom > this.update.scrollTop+this.update.offsetHeight){
this.update.scrollTop = this.update.scrollTop+selection.offsetHeight;
}
},
getEntry: function(index) {
return this.update.firstChild.childNodes[index];
},
getCurrentEntry: function() {
return this.getEntry(this.index);
},
selectEntry: function() {
this.active = false;
this.updateElement(this.getCurrentEntry());
},
updateElement: function(selectedElement) {
if (this.options.updateElement) {
this.options.updateElement(selectedElement);
return;
}
var value = '';
if (this.options.select) {
var nodes = $(selectedElement).select('.' + this.options.select) || [];
if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
} else
value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
var bounds = this.getTokenBounds();
if (bounds[0] != -1) {
var newValue = this.element.value.substr(0, bounds[0]);
var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
if (whitespace)
newValue += whitespace[0];
this.element.value = newValue + value + this.element.value.substr(bounds[1]);
} else {
this.element.value = value;
}
this.oldElementValue = this.element.value;
this.element.focus();
if (this.options.afterUpdateElement)
this.options.afterUpdateElement(this.element, selectedElement);
},
updateChoices: function(choices) {
if(!this.changed && this.hasFocus) {
this.update.innerHTML = choices;
Element.cleanWhitespace(this.update);
Element.cleanWhitespace(this.update.down());
if(this.update.firstChild && this.update.down().childNodes) {
this.entryCount =
this.update.down().childNodes.length;
for (var i = 0; i < this.entryCount; i++) {
var entry = this.getEntry(i);
entry.autocompleteIndex = i;
this.addObservers(entry);
}
} else {
this.entryCount = 0;
}
this.stopIndicator();
this.update.scrollTop = 0;
this.index = 0;
if(this.entryCount==1 && this.options.autoSelect) {
this.selectEntry();
this.hide();
} else {
this.render();
}
}
},
addObservers: function(element) {
Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
Event.observe(element, "click", this.onClick.bindAsEventListener(this));
},
onObserverEvent: function() {
this.changed = false;
this.tokenBounds = null;
if(this.getToken().length>=this.options.minChars) {
this.getUpdatedChoices();
} else {
this.active = false;
this.hide();
}
this.oldElementValue = this.element.value;
},
getToken: function() {
var bounds = this.getTokenBounds();
return this.element.value.substring(bounds[0], bounds[1]).strip();
},
getTokenBounds: function() {
if (null != this.tokenBounds) return this.tokenBounds;
var value = this.element.value;
if (value.strip().empty()) return [-1, 0];
var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
var offset = (diff == this.oldElementValue.length ? 1 : 0);
var prevTokenPos = -1, nextTokenPos = value.length;
var tp;
for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
if (tp > prevTokenPos) prevTokenPos = tp;
tp = value.indexOf(this.options.tokens[index], diff + offset);
if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
}
return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
}
});
Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
var boundary = Math.min(newS.length, oldS.length);
for (var index = 0; index < boundary; ++index)
if (newS[index] != oldS[index])
return index;
return boundary;
};
Ajax.Autocompleter = Class.create(Autocompleter.Base, {
initialize: function(element, update, url, options) {
this.baseInitialize(element, update, options);
this.options.asynchronous = true;
this.options.onComplete = this.onComplete.bind(this);
this.options.defaultParams = this.options.parameters || null;
this.url = url;
},
getUpdatedChoices: function() {
this.startIndicator();
var entry = encodeURIComponent(this.options.paramName) + '=' +
encodeURIComponent(this.getToken());
this.options.parameters = this.options.callback ?
this.options.callback(this.element, entry) : entry;
if(this.options.defaultParams)
this.options.parameters += '&' + this.options.defaultParams;
new Ajax.Request(this.url, this.options);
},
onComplete: function(request) {
this.updateChoices(request.responseText);
}
});
// The local array autocompleter. Used when you'd prefer to
// inject an array of autocompletion options into the page, rather
// than sending out Ajax queries, which can be quite slow sometimes.
//
// The constructor takes four parameters. The first two are, as usual,
// the id of the monitored textbox, and id of the autocompletion menu.
// The third is the array you want to autocomplete from, and the fourth
// is the options block.
//
// Extra local autocompletion options:
// - choices - How many autocompletion choices to offer
//
// - partialSearch - If false, the autocompleter will match entered
// text only at the beginning of strings in the
// autocomplete array. Defaults to true, which will
// match text at the beginning of any *word* in the
// strings in the autocomplete array. If you want to
// search anywhere in the string, additionally set
// the option fullSearch to true (default: off).
//
// - fullSsearch - Search anywhere in autocomplete array strings.
//
// - partialChars - How many characters to enter before triggering
// a partial match (unlike minChars, which defines
// how many characters are required to do any match
// at all). Defaults to 2.
//
// - ignoreCase - Whether to ignore case when autocompleting.
// Defaults to true.
//
// It's possible to pass in a custom function as the 'selector'
// option, if you prefer to write your own autocompletion logic.
// In that case, the other options above will not apply unless
// you support them.
Autocompleter.Local = Class.create(Autocompleter.Base, {
initialize: function(element, update, array, options) {
this.baseInitialize(element, update, options);
this.options.array = array;
},
getUpdatedChoices: function() {
this.updateChoices(this.options.selector(this));
},
setOptions: function(options) {
this.options = Object.extend({
choices: 10,
partialSearch: true,
partialChars: 2,
ignoreCase: true,
fullSearch: false,
selector: function(instance) {
var ret = []; // Beginning matches
var partial = []; // Inside matches
var entry = instance.getToken();
var count = 0;
for (var i = 0; i < instance.options.array.length &&
ret.length < instance.options.choices ; i++) {
var elem = instance.options.array[i];
var foundPos = instance.options.ignoreCase ?
elem.toLowerCase().indexOf(entry.toLowerCase()) :
elem.indexOf(entry);
while (foundPos != -1) {
if (foundPos == 0 && elem.length != entry.length) {
ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
elem.substr(entry.length) + "</li>");
break;
} else if (entry.length >= instance.options.partialChars &&
instance.options.partialSearch && foundPos != -1) {
if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
foundPos + entry.length) + "</li>");
break;
}
}
foundPos = instance.options.ignoreCase ?
elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
elem.indexOf(entry, foundPos + 1);
}
}
if (partial.length)
ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
return "<ul>" + ret.join('') + "</ul>";
}
}, options || { });
}
});
// AJAX in-place editor and collection editor
// Full rewrite by Christophe Porteneuve <[email protected]> (April 2007).
// Use this if you notice weird scrolling problems on some browsers,
// the DOM might be a bit confused when this gets called so do this
// waits 1 ms (with setTimeout) until it does the activation
Field.scrollFreeActivate = function(field) {
setTimeout(function() {
Field.activate(field);
}, 1);
};
Ajax.InPlaceEditor = Class.create({
initialize: function(element, url, options) {
this.url = url;
this.element = element = $(element);
this.prepareOptions();
this._controls = { };
arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
Object.extend(this.options, options || { });
if (!this.options.formId && this.element.id) {
this.options.formId = this.element.id + '-inplaceeditor';
if ($(this.options.formId))
this.options.formId = '';
}
if (this.options.externalControl)
this.options.externalControl = $(this.options.externalControl);
if (!this.options.externalControl)
this.options.externalControlOnly = false;
this._originalBackground = this.element.getStyle('background-color') || 'transparent';
this.element.title = this.options.clickToEditText;
this._boundCancelHandler = this.handleFormCancellation.bind(this);
this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
this._boundFailureHandler = this.handleAJAXFailure.bind(this);
this._boundSubmitHandler = this.handleFormSubmission.bind(this);
this._boundWrapperHandler = this.wrapUp.bind(this);
this.registerListeners();
},
checkForEscapeOrReturn: function(e) {
if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
if (Event.KEY_ESC == e.keyCode)
this.handleFormCancellation(e);
else if (Event.KEY_RETURN == e.keyCode)
this.handleFormSubmission(e);
},
createControl: function(mode, handler, extraClasses) {
var control = this.options[mode + 'Control'];
var text = this.options[mode + 'Text'];
if ('button' == control) {
var btn = document.createElement('input');
btn.type = 'submit';
btn.value = text;
btn.className = 'editor_' + mode + '_button';
if ('cancel' == mode)
btn.onclick = this._boundCancelHandler;
this._form.appendChild(btn);
this._controls[mode] = btn;
} else if ('link' == control) {
var link = document.createElement('a');
link.href = '#';
link.appendChild(document.createTextNode(text));
link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
link.className = 'editor_' + mode + '_link';
if (extraClasses)
link.className += ' ' + extraClasses;
this._form.appendChild(link);
this._controls[mode] = link;
}
},
createEditField: function() {
var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
var fld;
if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
fld = document.createElement('input');
fld.type = 'text';
var size = this.options.size || this.options.cols || 0;
if (0 < size) fld.size = size;
} else {
fld = document.createElement('textarea');
fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
fld.cols = this.options.cols || 40;
}
fld.name = this.options.paramName;
fld.value = text; // No HTML breaks conversion anymore
fld.className = 'editor_field';
if (this.options.submitOnBlur)
fld.onblur = this._boundSubmitHandler;
this._controls.editor = fld;
if (this.options.loadTextURL)
this.loadExternalText();
this._form.appendChild(this._controls.editor);
},
createForm: function() {
var ipe = this;
function addText(mode, condition) {
var text = ipe.options['text' + mode + 'Controls'];
if (!text || condition === false) return;
ipe._form.appendChild(document.createTextNode(text));
};
this._form = $(document.createElement('form'));
this._form.id = this.options.formId;
this._form.addClassName(this.options.formClassName);
this._form.onsubmit = this._boundSubmitHandler;
this.createEditField();
if ('textarea' == this._controls.editor.tagName.toLowerCase())
this._form.appendChild(document.createElement('br'));
if (this.options.onFormCustomization)
this.options.onFormCustomization(this, this._form);
addText('Before', this.options.okControl || this.options.cancelControl);
this.createControl('ok', this._boundSubmitHandler);
addText('Between', this.options.okControl && this.options.cancelControl);
this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
addText('After', this.options.okControl || this.options.cancelControl);
},
destroy: function() {
if (this._oldInnerHTML)
this.element.innerHTML = this._oldInnerHTML;
this.leaveEditMode();
this.unregisterListeners();
},
enterEditMode: function(e) {
if (this._saving || this._editing) return;
this._editing = true;
this.triggerCallback('onEnterEditMode');
if (this.options.externalControl)
this.options.externalControl.hide();
this.element.hide();
this.createForm();
this.element.parentNode.insertBefore(this._form, this.element);
if (!this.options.loadTextURL)
this.postProcessEditField();
if (e) Event.stop(e);
},
enterHover: function(e) {
if (this.options.hoverClassName)
this.element.addClassName(this.options.hoverClassName);
if (this._saving) return;
this.triggerCallback('onEnterHover');
},
getText: function() {
return this.element.innerHTML.unescapeHTML();
},
handleAJAXFailure: function(transport) {
this.triggerCallback('onFailure', transport);
if (this._oldInnerHTML) {
this.element.innerHTML = this._oldInnerHTML;
this._oldInnerHTML = null;
}
},
handleFormCancellation: function(e) {
this.wrapUp();
if (e) Event.stop(e);
},
handleFormSubmission: function(e) {
var form = this._form;
var value = $F(this._controls.editor);
this.prepareSubmission();
var params = this.options.callback(form, value) || '';
if (Object.isString(params))
params = params.toQueryParams();
params.editorId = this.element.id;
if (this.options.htmlResponse) {
var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
Object.extend(options, {
parameters: params,
onComplete: this._boundWrapperHandler,
onFailure: this._boundFailureHandler
});
new Ajax.Updater({ success: this.element }, this.url, options);
} else {
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: params,
onComplete: this._boundWrapperHandler,
onFailure: this._boundFailureHandler
});
new Ajax.Request(this.url, options);
}
if (e) Event.stop(e);
},
leaveEditMode: function() {
this.element.removeClassName(this.options.savingClassName);
this.removeForm();
this.leaveHover();
this.element.style.backgroundColor = this._originalBackground;
this.element.show();
if (this.options.externalControl)
this.options.externalControl.show();
this._saving = false;
this._editing = false;
this._oldInnerHTML = null;
this.triggerCallback('onLeaveEditMode');
},
leaveHover: function(e) {
if (this.options.hoverClassName)
this.element.removeClassName(this.options.hoverClassName);
if (this._saving) return;
this.triggerCallback('onLeaveHover');
},
loadExternalText: function() {
this._form.addClassName(this.options.loadingClassName);
this._controls.editor.disabled = true;
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
this._form.removeClassName(this.options.loadingClassName);
var text = transport.responseText;
if (this.options.stripLoadedTextTags)
text = text.stripTags();
this._controls.editor.value = text;
this._controls.editor.disabled = false;
this.postProcessEditField();
}.bind(this),
onFailure: this._boundFailureHandler
});
new Ajax.Request(this.options.loadTextURL, options);
},
postProcessEditField: function() {
var fpc = this.options.fieldPostCreation;
if (fpc)
$(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
},
prepareOptions: function() {
this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
[this._extraDefaultOptions].flatten().compact().each(function(defs) {
Object.extend(this.options, defs);
}.bind(this));
},
prepareSubmission: function() {
this._saving = true;
this.removeForm();
this.leaveHover();
this.showSaving();
},
registerListeners: function() {
this._listeners = { };
var listener;
$H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
listener = this[pair.value].bind(this);
this._listeners[pair.key] = listener;
if (!this.options.externalControlOnly)
this.element.observe(pair.key, listener);
if (this.options.externalControl)
this.options.externalControl.observe(pair.key, listener);
}.bind(this));
},
removeForm: function() {
if (!this._form) return;
this._form.remove();
this._form = null;
this._controls = { };
},
showSaving: function() {
this._oldInnerHTML = this.element.innerHTML;
this.element.innerHTML = this.options.savingText;
this.element.addClassName(this.options.savingClassName);
this.element.style.backgroundColor = this._originalBackground;
this.element.show();
},
triggerCallback: function(cbName, arg) {
if ('function' == typeof this.options[cbName]) {
this.options[cbName](this, arg);
}
},
unregisterListeners: function() {
$H(this._listeners).each(function(pair) {
if (!this.options.externalControlOnly)
this.element.stopObserving(pair.key, pair.value);
if (this.options.externalControl)
this.options.externalControl.stopObserving(pair.key, pair.value);
}.bind(this));
},
wrapUp: function(transport) {
this.leaveEditMode();
// Can't use triggerCallback due to backward compatibility: requires
// binding + direct element
this._boundComplete(transport, this.element);
}
});
Object.extend(Ajax.InPlaceEditor.prototype, {
dispose: Ajax.InPlaceEditor.prototype.destroy
});
Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
initialize: function($super, element, url, options) {
this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
$super(element, url, options);
},
createEditField: function() {
var list = document.createElement('select');
list.name = this.options.paramName;
list.size = 1;
this._controls.editor = list;
this._collection = this.options.collection || [];
if (this.options.loadCollectionURL)
this.loadCollection();
else
this.checkForExternalText();
this._form.appendChild(this._controls.editor);
},
loadCollection: function() {
this._form.addClassName(this.options.loadingClassName);
this.showLoadingText(this.options.loadingCollectionText);
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
var js = transport.responseText.strip();
if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
throw('Server returned an invalid collection representation.');
this._collection = eval(js);
this.checkForExternalText();
}.bind(this),
onFailure: this.onFailure
});
new Ajax.Request(this.options.loadCollectionURL, options);
},
showLoadingText: function(text) {
this._controls.editor.disabled = true;
var tempOption = this._controls.editor.firstChild;
if (!tempOption) {
tempOption = document.createElement('option');
tempOption.value = '';
this._controls.editor.appendChild(tempOption);
tempOption.selected = true;
}
tempOption.update((text || '').stripScripts().stripTags());
},
checkForExternalText: function() {
this._text = this.getText();
if (this.options.loadTextURL)
this.loadExternalText();
else
this.buildOptionList();
},
loadExternalText: function() {
this.showLoadingText(this.options.loadingText);
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
this._text = transport.responseText.strip();
this.buildOptionList();
}.bind(this),
onFailure: this.onFailure
});
new Ajax.Request(this.options.loadTextURL, options);
},
buildOptionList: function() {
this._form.removeClassName(this.options.loadingClassName);
this._collection = this._collection.map(function(entry) {
return 2 === entry.length ? entry : [entry, entry].flatten();
});
var marker = ('value' in this.options) ? this.options.value : this._text;
var textFound = this._collection.any(function(entry) {
return entry[0] == marker;
}.bind(this));
this._controls.editor.update('');
var option;
this._collection.each(function(entry, index) {
option = document.createElement('option');
option.value = entry[0];
option.selected = textFound ? entry[0] == marker : 0 == index;
option.appendChild(document.createTextNode(entry[1]));
this._controls.editor.appendChild(option);
}.bind(this));
this._controls.editor.disabled = false;
Field.scrollFreeActivate(this._controls.editor);
}
});
//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
//**** This only exists for a while, in order to let ****
//**** users adapt to the new API. Read up on the new ****
//**** API and convert your code to it ASAP! ****
Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
if (!options) return;
function fallback(name, expr) {
if (name in options || expr === undefined) return;
options[name] = expr;
};
fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
options.cancelLink == options.cancelButton == false ? false : undefined)));
fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
options.okLink == options.okButton == false ? false : undefined)));
fallback('highlightColor', options.highlightcolor);
fallback('highlightEndColor', options.highlightendcolor);
};
Object.extend(Ajax.InPlaceEditor, {
DefaultOptions: {
ajaxOptions: { },
autoRows: 3, // Use when multi-line w/ rows == 1
cancelControl: 'link', // 'link'|'button'|false
cancelText: 'cancel',
clickToEditText: 'Click to edit',
externalControl: null, // id|elt
externalControlOnly: false,
fieldPostCreation: 'activate', // 'activate'|'focus'|false
formClassName: 'inplaceeditor-form',
formId: null, // id|elt
highlightColor: '#ffff99',
highlightEndColor: '#ffffff',
hoverClassName: '',
htmlResponse: true,
loadingClassName: 'inplaceeditor-loading',
loadingText: 'Loading...',
okControl: 'button', // 'link'|'button'|false
okText: 'ok',
paramName: 'value',
rows: 1, // If 1 and multi-line, uses autoRows
savingClassName: 'inplaceeditor-saving',
savingText: 'Saving...',
size: 0,
stripLoadedTextTags: false,
submitOnBlur: false,
textAfterControls: '',
textBeforeControls: '',
textBetweenControls: ''
},
DefaultCallbacks: {
callback: function(form) {
return Form.serialize(form);
},
onComplete: function(transport, element) {
// For backward compatibility, this one is bound to the IPE, and passes
// the element directly. It was too often customized, so we don't break it.
new Effect.Highlight(element, {
startcolor: this.options.highlightColor, keepBackgroundImage: true });
},
onEnterEditMode: null,
onEnterHover: function(ipe) {
ipe.element.style.backgroundColor = ipe.options.highlightColor;
if (ipe._effect)
ipe._effect.cancel();
},
onFailure: function(transport, ipe) {
alert('Error communication with the server: ' + transport.responseText.stripTags());
},
onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
onLeaveEditMode: null,
onLeaveHover: function(ipe) {
ipe._effect = new Effect.Highlight(ipe.element, {
startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
restorecolor: ipe._originalBackground, keepBackgroundImage: true
});
}
},
Listeners: {
click: 'enterEditMode',
keydown: 'checkForEscapeOrReturn',
mouseover: 'enterHover',
mouseout: 'leaveHover'
}
});
Ajax.InPlaceCollectionEditor.DefaultOptions = {
loadingCollectionText: 'Loading options...'
};
// Delayed observer, like Form.Element.Observer,
// but waits for delay after last key input
// Ideal for live-search fields
Form.Element.DelayedObserver = Class.create({
initialize: function(element, delay, callback) {
this.delay = delay || 0.5;
this.element = $(element);
this.callback = callback;
this.timer = null;
this.lastValue = $F(this.element);
Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
},
delayedListener: function(event) {
if(this.lastValue == $F(this.element)) return;
if(this.timer) clearTimeout(this.timer);
this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
this.lastValue = $F(this.element);
},
onTimerEvent: function() {
this.timer = null;
this.callback(this.element, $F(this.element));
}
});
| bczmufrn/riaufrn | static/js/scriptaculous/controls.js | JavaScript | gpl-3.0 | 35,309 |
/* ----------------------------------------------------------------------
* js/ca/ca.utils.js
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2009-2014 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* ----------------------------------------------------------------------
*/
var caUI = caUI || {};
(function ($) {
caUI.initUtils = function(options) {
var that = jQuery.extend({
// Unsaved change warning options
unsavedChangesWarningMessage: 'You have made changes in this form that you have not yet saved. If you navigate away from this form you will lose your unsaved changes.',
disableUnsavedChangesWarning: false
}, options);
that.showUnsavedChangesWarningFlag = false;
caUI.utils = {};
//
// Unsaved change warning methods
//
// Sets whether warning should be shown if user tries to navigate away
caUI.utils.showUnsavedChangesWarning = function(b) {
if (b === undefined) { b = true; }
that.showUnsavedChangesWarningFlag = b ? true : false;
return this;
};
// Returns true if warning will be shown if user user tries to navigate away
caUI.utils.shouldShowUnsavedChangesWarning = function() {
return that.showUnsavedChangesWarningFlag;
};
// returns text of warning message
caUI.utils.getUnsavedChangesWarningMessage = function() {
return that.unsavedChangesWarningMessage;
};
// If set to true, no warning will be triggered
caUI.utils.disableUnsavedChangesWarning = function(b) {
that.disableUnsavedChangesWarning = b ? true : false;
};
caUI.utils.getDisableUnsavedChangesWarning = function(b) {
return that.disableUnsavedChangesWarning;
};
// init event handler
window.addEventListener("beforeunload", function (e) {
if (!caUI.utils.getDisableUnsavedChangesWarning() && caUI.utils.shouldShowUnsavedChangesWarning()) {
e.returnValue = caUI.utils.getUnsavedChangesWarningMessage(); // Gecko, Trident, Chrome 34+
return caUI.utils.getUnsavedChangesWarningMessage(); // Gecko, WebKit, Chrome <34
}
});
// ------------------------------------------------------------------------------------
caUI.utils.sortObj = function(arr, isCaseInsensitive) {
var sortedKeys = new Array();
var sortedObj = {};
// Separate keys and sort them
for (var i in arr){
sortedKeys.push(i);
}
if (isCaseInsensitive) {
sortedKeys.sort(caUI.utils._caseInsensitiveSort);
} else {
sortedKeys.sort();
}
// Reconstruct sorted obj based on keys
for (var i in sortedKeys){
sortedObj[sortedKeys[i]] = arr[sortedKeys[i]];
}
return sortedObj;
};
caUI.utils._caseInsensitiveSort = function(a, b) {
var ret = 0;
a = a.toLowerCase();
b = b.toLowerCase();
if(a > b)
ret = 1;
if(a < b)
ret = -1;
return ret;
}
// ------------------------------------------------------------------------------------
// Update state/province form drop-down based upon country setting
// Used by BaseModel for text fields with DISPLAY_TYPE DT_COUNTRY_LIST and DT_STATEPROV_LIST
//
caUI.utils.updateStateProvinceForCountry = function(e) {
var data = e.data;
var stateProvID = data.stateProvID;
var countryID = data.countryID;
var statesByCountryList = data.statesByCountryList;
var stateValue = data.value;
var mirrorStateProvID = data.mirrorStateProvID;
var mirrorCountryID = data.mirrorCountryID;
var origStateValue = jQuery('#' + stateProvID + '_select').val();
jQuery('#' + stateProvID + '_select').empty();
var countryCode = jQuery('#' + countryID).val();
if (statesByCountryList[countryCode]) {
for(k in statesByCountryList[countryCode]) {
jQuery('#' + stateProvID + '_select').append('<option value="' + statesByCountryList[countryCode][k] + '">' + k + '</option>');
if (!stateValue && (origStateValue == statesByCountryList[countryCode][k])) {
stateValue = origStateValue;
}
}
jQuery('#' + stateProvID + '_text').css('display', 'none').attr('name', stateProvID + '_text');
jQuery('#' + stateProvID + '_select').css('display', 'inline').attr('name', stateProvID).val(stateValue);
if (mirrorCountryID) {
jQuery('#' + stateProvID + '_select').change(function() {
jQuery('#' + mirrorStateProvID + '_select').val(jQuery('#' + stateProvID + '_select').val());
});
jQuery('#' + mirrorCountryID + '_select').val(jQuery('#' + countryID + '_select').val());
caUI.utils.updateStateProvinceForCountry({ data: {stateProvID: mirrorStateProvID, countryID: mirrorCountryID, statesByCountryList: statesByCountryList, value: stateValue}});
}
} else {
jQuery('#' + stateProvID + '_text').css('display', 'inline').attr('name', stateProvID);
jQuery('#' + stateProvID + '_select').css('display', 'none').attr('name', stateProvID + '_select');
if (mirrorCountryID) {
jQuery('#' + stateProvID + '_text').change(function() {
jQuery('#' + mirrorStateProvID + '_text').val(jQuery('#' + stateProvID + '_text').val());
});
jQuery('#' + mirrorCountryID + '_select').attr('selectedIndex', jQuery('#' + countryID + '_select').attr('selectedIndex'));
caUI.utils.updateStateProvinceForCountry({ data: {stateProvID: mirrorStateProvID, countryID: mirrorCountryID, statesByCountryList: statesByCountryList}});
}
}
};
// --------------------------------------------------------------------------------
// Convert file size in bytes to display format
//
// @param string The file size in bytes
//
caUI.utils.formatFilesize = function(filesize) {
if (filesize >= 1073741824) {
filesize = caUI.utils.formatNumber(filesize / 1073741824, 2, '.', '') + ' Gb';
} else {
if (filesize >= 1048576) {
filesize = caUI.utils.formatNumber(filesize / 1048576, 2, '.', '') + ' Mb';
} else {
if (filesize >= 1024) {
filesize = caUI.utils.formatNumber(filesize / 1024, 0) + ' Kb';
} else {
filesize = caUI.utils.formatNumber(filesize, 0) + ' bytes';
};
};
};
return filesize;
};
caUI.utils.formatNumber = function formatNumber( number, decimals, dec_point, thousands_sep ) {
// http://kevin.vanzonneveld.net
// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfix by: Michael White (http://crestidg.com)
// + bugfix by: Benjamin Lupton
// + bugfix by: Allan Jensen (http://www.winternet.no)
// + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// * example 1: number_format(1234.5678, 2, '.', '');
// * returns 1: 1234.57
var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
var d = dec_point == undefined ? "," : dec_point;
var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
//
// http://thecodeabode.blogspot.com
// @author: Ben Kitzelman
// @updated: 03-03-2013
//
caUI.utils.getAcrobatInfo = function() {
var getBrowserName = function() {
return this.name = this.name || function() {
var userAgent = navigator ? navigator.userAgent.toLowerCase() : "other";
if(userAgent.indexOf("chrome") > -1) return "chrome";
else if(userAgent.indexOf("safari") > -1) return "safari";
else if(userAgent.indexOf("msie") > -1) return "ie";
else if(userAgent.indexOf("firefox") > -1) return "firefox";
return userAgent;
}();
};
var getActiveXObject = function(name) {
try { return new ActiveXObject(name); } catch(e) {}
};
var getNavigatorPlugin = function(name) {
for(key in navigator.plugins) {
var plugin = navigator.plugins[key];
if(plugin.name == name) return plugin;
}
};
var getPDFPlugin = function() {
return this.plugin = this.plugin || function() {
if(getBrowserName() == 'ie') {
//
// load the activeX control
// AcroPDF.PDF is used by version 7 and later
// PDF.PdfCtrl is used by version 6 and earlier
return getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl');
} else {
return getNavigatorPlugin('Adobe Acrobat') || getNavigatorPlugin('Chrome PDF Viewer') || getNavigatorPlugin('WebKit built-in PDF');
}
}();
};
var isAcrobatInstalled = function() {
return !!getPDFPlugin();
};
var getAcrobatVersion = function() {
try {
var plugin = getPDFPlugin();
if(getBrowserName() == 'ie') {
var versions = plugin.GetVersions().split(',');
var latest = versions[0].split('=');
return parseFloat(latest[1]);
}
if(plugin.version) return parseInt(plugin.version);
return plugin.name
} catch(e) {
return null;
}
}
//
// The returned object
//
return {
browser: getBrowserName(),
acrobat: isAcrobatInstalled() ? 'installed' : false,
acrobatVersion: getAcrobatVersion()
};
};
// ------------------------------------------------------------------------------------
return that;
};
})(jQuery);
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
}; | rwahs/providence | assets/ca/ca.utils.js | JavaScript | gpl-3.0 | 10,930 |
var locale = {
placeholder: 'Избор на час'
};
export default locale; | ZSMingNB/react-news | node_modules/antd/es/time-picker/locale/bg_BG.js | JavaScript | gpl-3.0 | 82 |
var parseStructureFile = require('./parseStructureFile');
var Summary = require('../models/summary');
var SummaryModifier = require('../modifiers').Summary;
/**
Parse summary in a book, the summary can only be parsed
if the readme as be detected before.
@param {Book} book
@return {Promise<Book>}
*/
function parseSummary(book) {
var readme = book.getReadme();
var logger = book.getLogger();
var readmeFile = readme.getFile();
return parseStructureFile(book, 'summary')
.spread(function(file, result) {
var summary;
if (!file) {
logger.warn.ln('no summary file in this book');
summary = Summary();
} else {
logger.debug.ln('summary file found at', file.getPath());
summary = Summary.createFromParts(file, result.parts);
}
// Insert readme as first entry if not in SUMMARY.md
var readmeArticle = summary.getByPath(readmeFile.getPath());
if (readmeFile.exists() && !readmeArticle) {
summary = SummaryModifier.unshiftArticle(summary, {
title: 'Introduction',
ref: readmeFile.getPath()
});
}
// Set new summary
return book.setSummary(summary);
});
}
module.exports = parseSummary;
| hhkaos/awesome-arcgis | node_modules/gitbook/lib/parse/parseSummary.js | JavaScript | gpl-3.0 | 1,309 |
export default Ember.HTMLBars.template((function() {
return {
meta: {
"fragmentReason": {
"name": "triple-curlies"
},
"revision": "[email protected]",
"loc": {
"source": null,
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 3,
"column": 6
}
},
"moduleName": "modules/ember-basic-dropdown/templates/components/basic-dropdown/content.hbs"
},
isEmpty: false,
arity: 0,
cachedFragment: null,
hasRendered: false,
buildFragment: function buildFragment(dom) {
var el0 = dom.createDocumentFragment();
var el1 = dom.createElement("div");
var el2 = dom.createTextNode("\n ");
dom.appendChild(el1, el2);
var el2 = dom.createComment("");
dom.appendChild(el1, el2);
var el2 = dom.createTextNode("\n");
dom.appendChild(el1, el2);
dom.appendChild(el0, el1);
return el0;
},
buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) {
var element0 = dom.childAt(fragment, [0]);
var morphs = new Array(4);
morphs[0] = dom.createAttrMorph(element0, 'id');
morphs[1] = dom.createAttrMorph(element0, 'class');
morphs[2] = dom.createAttrMorph(element0, 'dir');
morphs[3] = dom.createMorphAt(element0,1,1);
return morphs;
},
statements: [
["attribute","id",["get","dropdownId",["loc",[null,[1,10],[1,20]]]]],
["attribute","class",["concat",["ember-basic-dropdown-content ",["get","transitionClass",["loc",[null,[1,61],[1,76]]]]," ",["get","dropdownClass",["loc",[null,[1,81],[1,94]]]]," ",["get","verticalPositionClass",["loc",[null,[1,99],[1,120]]]]," ",["get","horizontalPositionClass",["loc",[null,[1,125],[1,148]]]]]]],
["attribute","dir",["get","dir",["loc",[null,[1,158],[1,161]]]]],
["content","yield",["loc",[null,[2,2],[2,11]]]]
],
locals: [],
templates: []
};
}())); | Elektro1776/latestEarthables | core/client/tmp/broccoli_persistent_filtertemplate_compiler-output_path-WWntW3wm.tmp/modules/ember-basic-dropdown/templates/components/basic-dropdown/content.js | JavaScript | gpl-3.0 | 1,984 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var SECTION = "exception-011";
var VERSION = "ECMA_2";
startTest();
var TITLE = "Don't Crash throwing undefined";
writeHeaderToLog( SECTION + " "+ TITLE);
print("Undefined throw test.");
DESCRIPTION = "throw undefined";
EXPECTED = "error";
new TestCase( SECTION, "throw undefined", "error", eval("throw (void 0)") );
test();
print("FAILED!: Should have exited with uncaught exception.");
| SlateScience/MozillaJS | js/src/tests/ecma_2/Exceptions/exception-011-n.js | JavaScript | mpl-2.0 | 685 |
$(document).ready(function() {
$("#wrap_filter_system input").click(function() {
$(this).parents("form").submit();
});
$("#filter_field").change(function() {
$(this).parents("form").submit();
});
var redirectLoginClick = function() {
if($("#redirectLogin_-1:checked").size() > 0) $("#wrap_redirectLoginURL").slideDown();
else $("#wrap_redirectLoginURL").hide();
}
var adjustAccessFields = function() {
var items = [ '#wrap_redirectLogin', '#wrap_guestSearchable' ];
if($("#roles_37").is(":checked")) {
$("#wrap_redirectLoginURL").hide();
$(items).each(function(key, value) {
var $item = $(value);
if($item.is(".InputfieldStateCollapsed")) {
$item.hide();
} else {
$item.slideUp();
}
});
$("input.viewRoles").attr('checked', 'checked');
} else {
$(items).each(function(key, value) {
var $item = $(value);
if($item.is(":visible")) return;
$item.slideDown("fast", function() {
if(!$item.is(".InputfieldStateCollapsed")) return;
$item.find(".InputfieldStateToggle").click();
});
});
redirectLoginClick();
}
};
$("#wrap_useRoles input").click(function() {
if($("#useRoles_1:checked").size() > 0) {
$("#wrap_redirectLogin").hide();
$("#wrap_guestSearchable").hide();
$("#useRolesYes").slideDown();
$("#wrap_useRoles > label").click();
$("input.viewRoles").attr('checked', 'checked');
} else {
$("#useRolesYes").slideUp();
}
});
if($("#useRoles_0:checked").size() > 0) $("#useRolesYes").hide();
$("#roles_37").click(adjustAccessFields);
$("input.viewRoles:not(#roles_37)").click(function() {
// prevent unchecking 'view' for other roles when 'guest' role is checked
var $t = $(this);
if($("#roles_37").is(":checked")) return false;
return true;
});
// when edit checked or unchecked, update the createRoles to match since they are dependent
var editRolesClick = function() {
var $editRoles = $("#roles_editor input.editRoles");
$editRoles.each(function() {
var $t = $(this);
if($t.is(":disabled")) return false;
var $createRoles = $("input.createRoles[value=" + $t.attr('value') + "]");
if($t.is(":checked")) {
$createRoles.removeAttr('disabled');
} else {
$createRoles.removeAttr('checked').attr('disabled', 'disabled');
}
});
return true;
};
$("#roles_editor input.editRoles").click(editRolesClick);
editRolesClick();
$("#wrap_redirectLogin input").click(redirectLoginClick);
/*
// ----------------
// family
$("#wrap_noChildren input").click(function() {
if($("#noChildren_0:checked").size() > 0) {
$("#wrap_childTemplates").slideDown();
$("#sortfield_fieldset").slideDown();
} else {
$("#wrap_childTemplates").slideUp();
$("#sortfield_fieldset").slideUp();
}
});
if($("#noChildren_1:checked").size() > 0) {
$("#wrap_childTemplates").hide();
$("#sortfield_fieldset").hide();
}
$("#wrap_Inputfield_noParents input").click(function() {
if($("#Inputfield_noParents_0:checked").size() > 0) {
$("#wrap_Inputfield_parentTemplates").slideDown();
} else {
$("#wrap_Inputfield_parentTemplates").slideUp();
}
});
if($("#Inputfield_noParents_1:checked").size() > 0) $("#wrap_Inputfield_parentTemplates").hide();
*/
// ----------------
var adjustCacheExpireFields = function() {
var $t = $("#wrap_cacheExpire input:checked");
var $f = $("#wrap_cacheExpirePages");
var val = parseInt($t.attr('value'));
if(val == 3) {
if(!$f.is(":visible")) {
$f.slideDown();
}
} else if($f.is(":visible")) {
$f.hide();
}
};
var adjustCacheFields = function() {
var val = parseInt($(this).attr('value'));
if(val > 0) {
if(!$("#wrap_noCacheGetVars").is(":visible")) {
$("#wrap_useCacheForUsers").slideDown();
$("#wrap_noCacheGetVars").slideDown();
$("#wrap_noCachePostVars").slideDown();
$("#wrap_cacheExpire").slideDown();
$("#wrap_cacheExpire input:checked").change();
}
} else {
if($("#wrap_noCacheGetVars").is(":visible")) {
$("#wrap_useCacheForUsers").hide();
$("#wrap_noCacheGetVars").hide();
$("#wrap_noCachePostVars").hide();
$("#wrap_cacheExpire").hide();
$("#wrap_cacheExpirePages").hide();
}
}
};
$("#wrap_cacheExpire input").change(adjustCacheExpireFields).change();
$("#cache_time").change(adjustCacheFields).change();
// -----------------
// asmSelect fieldgroup indentation
var fieldgroupFieldsChange = function() {
$ol = $('#fieldgroup_fields').prev('ol.asmList');
$ol.find('span.asmFieldsetIndent').remove();
$ol.children('li').children('span.asmListItemLabel').children("a:contains('_END')").each(function() {
var label = $(this).text();
if(label.substring(label.length-4) != '_END') return;
label = label.substring(0, label.length-4);
var $li = $(this).parents('li.asmListItem');
$li.addClass('asmFieldset asmFieldsetEnd');
while(1) {
$li = $li.prev('li.asmListItem');
if($li.size() < 1) break;
var $span = $li.children('span.asmListItemLabel'); // .children('a');
var label2 = $span.text();
if(label2 == label) {
$li.addClass('asmFieldset asmFieldsetStart');
break;
}
$span.prepend($('<span class="asmFieldsetIndent"></span>'));
}
});
};
$("#fieldgroup_fields").change(fieldgroupFieldsChange).bind('init', fieldgroupFieldsChange);
adjustAccessFields();
redirectLoginClick();
// instantiate the WireTabs
var $templateEdit = $("#ProcessTemplateEdit");
if($templateEdit.size() > 0) {
$templateEdit.find('script').remove();
$templateEdit.WireTabs({
items: $(".Inputfields li.WireTab"),
id: 'TemplateEditTabs',
skipRememberTabIDs: ['WireTabDelete']
});
}
// export and import functions
$("#export_data").click(function() { $(this).select(); });
$(".import_toggle input[type=radio]").change(function() {
var $table = $(this).parents('p.import_toggle').next('table');
var $fieldset = $(this).closest('.InputfieldFieldset');
if($(this).is(":checked") && $(this).val() == 0) {
$table.hide();
$fieldset.addClass('ui-priority-secondary');
} else {
$table.show();
$fieldset.removeClass('ui-priority-secondary');
}
}).change();
$("#import_form table td:not(:first-child)").each(function() {
var html = $(this).html();
var refresh = false;
if(html.substring(0,1) == '{') {
html = '<pre>' + html + '</pre>';
html = html.replace(/<br>/g, "");
refresh = true;
}
if(refresh) $(this).html(html);
});
});
| e-gob/modernizacion | wire/modules/Process/ProcessTemplate/ProcessTemplate.js | JavaScript | mpl-2.0 | 6,544 |
cms_learning = {
};
| EcoAlternative/noosfero-ecosol | plugins/cms_learning/public/javascripts/cms_learning.js | JavaScript | agpl-3.0 | 23 |
// Generated by CoffeeScript 1.11.1
var OVHFetcher, async, cozydb, fetcher, moment,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
cozydb = require('cozydb');
moment = require('moment');
async = require('async');
fetcher = require('../lib/fetcher');
OVHFetcher = (function() {
function OVHFetcher(ovhApi, slug, logger) {
this.needToConnectFirst = bind(this.needToConnectFirst, this);
this.saveUrlAndToken = bind(this.saveUrlAndToken, this);
this.fetchBills = bind(this.fetchBills, this);
this.ovh = require('ovh')(ovhApi);
this.slug = slug;
this.logger = logger;
}
OVHFetcher.prototype.fetchBills = function(requiredFields, bills, data, next) {
this.ovh.consumerKey = requiredFields.token || null;
if (!this.ovh.consumerKey) {
return this.needToConnectFirst(requiredFields, next);
}
return this.ovh.request('GET', '/me/bill', (function(_this) {
return function(err, ovhBills) {
if (err === 401 || err === 403) {
return _this.needToConnectFirst(requiredFields, next);
} else if (err) {
_this.logger.info(err);
return next('bad credentials');
}
return async.map(ovhBills, function(ovhBill, cb) {
return _this.ovh.request('GET', '/me/bill/' + ovhBill, cb);
}, function(err, ovhBills) {
if (err) {
_this.logger.info(err);
return next('request error');
}
bills.fetched = [];
ovhBills.forEach(function(ovhBill) {
var bill;
bill = {
date: moment(ovhBill.date),
amount: ovhBill.priceWithTax.value,
pdfurl: ovhBill.pdfUrl,
vendor: 'OVH',
type: 'hosting'
};
return bills.fetched.push(bill);
});
_this.logger.info('Bill data parsed.');
return next();
});
};
})(this));
};
OVHFetcher.prototype.getLoginUrl = function(callback) {
var accessRules;
accessRules = {
'accessRules': [
{
method: 'GET',
path: '/me/*'
}
]
};
this.logger.info('Request the login url...');
return this.ovh.request('POST', '/auth/credential', accessRules, (function(_this) {
return function(err, credential) {
if (err) {
_this.logger.info(err);
return callback('token not found');
}
return callback(null, credential.validationUrl, credential.consumerKey);
};
})(this));
};
OVHFetcher.prototype.saveUrlAndToken = function(url, token, callback) {
var Konnector;
Konnector = require('../models/konnector');
return Konnector.all((function(_this) {
return function(err, konnectors) {
var accounts, ovhKonnector;
if (err) {
return callback(err);
}
ovhKonnector = (konnectors.filter(function(konnector) {
return konnector.slug === _this.slug;
}))[0];
accounts = [
{
loginUrl: url,
token: token
}
];
return ovhKonnector.updateAttributes({
accounts: accounts
}, callback);
};
})(this));
};
OVHFetcher.prototype.needToConnectFirst = function(requiredFields, callback) {
this.ovh.consumerKey = null;
return this.getLoginUrl((function(_this) {
return function(err, url, token) {
if (err) {
_this.logger.info(err);
return callback('request error');
}
requiredFields.loginUrl = url;
requiredFields.token = token;
return _this.saveUrlAndToken(url, token, function() {
_this.logger.info('You need to login to your OVH account first.');
return callback('konnector ovh connect first');
});
};
})(this));
};
return OVHFetcher;
})();
module.exports = {
"new": function(ovhApi, slug, logger) {
return new OVHFetcher(ovhApi, slug, logger);
}
};
| nono/konnectors | build/server/lib/ovh_fetcher.js | JavaScript | agpl-3.0 | 4,038 |
/**
* Kendo UI v2018.1.221 (http://www.telerik.com/kendo-ui)
* Copyright 2018 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f){
if (typeof define === 'function' && define.amd) {
define(["kendo.core"], f);
} else {
f();
}
}(function(){
(function( window, undefined ) {
kendo.cultures["rm-CH"] = {
name: "rm-CH",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": "’",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": "’",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
name: "Swiss Franc",
abbr: "CHF",
pattern: ["-n $","n $"],
decimals: 2,
",": "’",
".": ".",
groupSize: [3],
symbol: "CHF"
}
},
calendars: {
standard: {
days: {
names: ["dumengia","glindesdi","mardi","mesemna","gievgia","venderdi","sonda"],
namesAbbr: ["du","gli","ma","me","gie","ve","so"],
namesShort: ["du","gli","ma","me","gie","ve","so"]
},
months: {
names: ["schaner","favrer","mars","avrigl","matg","zercladur","fanadur","avust","settember","october","november","december"],
namesAbbr: ["schan.","favr.","mars","avr.","matg","zercl.","fan.","avust","sett.","oct.","nov.","dec."]
},
AM: ["AM","am","AM"],
PM: ["PM","pm","PM"],
patterns: {
d: "dd-MM-yyyy",
D: "dddd, 'ils' d 'da' MMMM yyyy",
F: "dddd, 'ils' d 'da' MMMM yyyy HH:mm:ss",
g: "dd-MM-yyyy HH:mm",
G: "dd-MM-yyyy HH:mm:ss",
m: "d. MMMM",
M: "d. MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "-",
":": ":",
firstDay: 1
}
}
}
})(this);
})); | Memba/Memba-Widgets | src/js/vendor/kendo/cultures/kendo.culture.rm-CH.js | JavaScript | agpl-3.0 | 6,584 |
module("tinymce.EditorManager", {
setupModule: function() {
QUnit.stop();
tinymce.init({
selector: "textarea",
add_unload_trigger: false,
disable_nodechange: true,
skin: false
}).then(function(editors) {
window.editor = editors[0];
QUnit.start();
});
}
});
test('get', function() {
strictEqual(tinymce.get().length, 1);
strictEqual(tinymce.get(0), tinymce.activeEditor);
strictEqual(tinymce.get(1), null);
strictEqual(tinymce.get("noid"), null);
strictEqual(tinymce.get(undefined), null);
strictEqual(tinymce.get()[0], tinymce.activeEditor);
strictEqual(tinymce.get(tinymce.activeEditor.id), tinymce.activeEditor);
});
test('addI18n/translate', function() {
tinymce.addI18n('en', {
'from': 'to'
});
equal(tinymce.translate('from'), 'to');
});
test('triggerSave', function() {
var saveCount = 0;
window.editor.on('SaveContent', function() {
saveCount++;
});
tinymce.triggerSave();
equal(saveCount, 1);
});
test('Re-init on same id', function() {
tinymce.init({selector: "#" + tinymce.activeEditor.id});
strictEqual(tinymce.get().length, 1);
});
asyncTest('Externally destroyed editor', function() {
tinymce.remove();
tinymce.init({
selector: "textarea",
init_instance_callback: function(editor1) {
tinymce.util.Delay.setTimeout(function() {
// Destroy the editor by setting innerHTML common ajax pattern
document.getElementById('view').innerHTML = '<textarea id="' + editor1.id + '"></textarea>';
// Re-init the editor will have the same id
tinymce.init({
selector: "textarea",
init_instance_callback: function(editor2) {
QUnit.start();
strictEqual(tinymce.get().length, 1);
strictEqual(editor1.id, editor2.id);
ok(editor1.destroyed, "First editor instance should be destroyed");
}
});
}, 0);
}
});
});
asyncTest('Init/remove on same id', function() {
var textArea = document.createElement('textarea');
document.getElementById('view').appendChild(textArea);
tinymce.init({
selector: "#view textarea",
init_instance_callback: function() {
tinymce.util.Delay.setTimeout(function() {
QUnit.start();
strictEqual(tinymce.get().length, 2);
strictEqual(tinymce.get(1), tinymce.activeEditor);
tinymce.remove('#' + tinymce.get(1).id);
strictEqual(tinymce.get().length, 1);
strictEqual(tinymce.get(0), tinymce.activeEditor);
textArea.parentNode.removeChild(textArea);
}, 0);
}
});
strictEqual(tinymce.get().length, 2);
});
asyncTest('Init editor async with proper editors state', function() {
var unloadUrl = function (url) {
tinymce.dom.ScriptLoader.ScriptLoader.remove(url);
tinymce.ThemeManager.remove(name);
};
var unloadTheme = function(name) {
unloadUrl(tinymce.baseURI.toAbsolute('themes/' + name + '/theme.min.js'));
unloadUrl(tinymce.baseURI.toAbsolute('themes/' + name + '/theme.js'));
};
tinymce.remove();
var init = function() {
tinymce.init({
selector: "textarea",
init_instance_callback: function() {
tinymce.util.Delay.setTimeout(function() {
QUnit.start();
}, 0);
}
});
};
unloadTheme("modern");
strictEqual(tinymce.get().length, 0);
init();
strictEqual(tinymce.get().length, 1);
init();
strictEqual(tinymce.get().length, 1);
});
test('overrideDefaults', function() {
var oldBaseURI, oldBaseUrl, oldSuffix;
oldBaseURI = tinymce.baseURI;
oldBaseUrl = tinymce.baseURL;
oldSuffix = tinymce.suffix;
tinymce.overrideDefaults({
test: 42,
base_url: "http://www.tinymce.com/base/",
suffix: "x",
external_plugins: {
"plugina": "//domain/plugina.js",
"pluginb": "//domain/pluginb.js"
},
plugin_base_urls: {
testplugin: 'http://custom.ephox.com/dir/testplugin'
}
});
strictEqual(tinymce.baseURI.path, "/base");
strictEqual(tinymce.baseURL, "http://www.tinymce.com/base");
strictEqual(tinymce.suffix, "x");
strictEqual(new tinymce.Editor('ed1', {}, tinymce).settings.test, 42);
strictEqual(tinymce.PluginManager.urls.testplugin, 'http://custom.ephox.com/dir/testplugin');
deepEqual(new tinymce.Editor('ed2', {
external_plugins: {
"plugina": "//domain/plugina2.js",
"pluginc": "//domain/pluginc.js"
},
plugin_base_urls: {
testplugin: 'http://custom.ephox.com/dir/testplugin'
}
}, tinymce).settings.external_plugins, {
"plugina": "//domain/plugina2.js",
"pluginb": "//domain/pluginb.js",
"pluginc": "//domain/pluginc.js"
});
deepEqual(new tinymce.Editor('ed3', {}, tinymce).settings.external_plugins, {
"plugina": "//domain/plugina.js",
"pluginb": "//domain/pluginb.js"
});
tinymce.baseURI = oldBaseURI;
tinymce.baseURL = oldBaseUrl;
tinymce.suffix = oldSuffix;
tinymce.overrideDefaults({});
});
test('Init inline editor on invalid targets', function() {
var invalidNames;
invalidNames = (
'area base basefont br col frame hr img input isindex link meta param embed source wbr track ' +
'colgroup option tbody tfoot thead tr script noscript style textarea video audio iframe object menu'
);
tinymce.remove();
tinymce.each(invalidNames.split(' '), function (invalidName) {
var elm = tinymce.DOM.add(document.body, invalidName, {'class': 'targetEditor'}, null);
tinymce.init({
selector: invalidName + '.targetEditor',
inline: true
});
strictEqual(tinymce.get().length, 0, 'Should not have created an editor');
tinymce.DOM.remove(elm);
});
});
| jtark/tinymce | tests/tinymce/EditorManager.js | JavaScript | lgpl-2.1 | 5,380 |
(function() {
var DD = YAHOO.util.DragDropMgr, Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, lang = YAHOO.lang;
/**
* DDProxy for DDList items (used by DDList)
* @class inputEx.widget.DDListItem
* @extends YAHOO.util.DDProxy
* @constructor
* @param {String} id
*/
inputEx.widget.DDListItem = function(id) {
inputEx.widget.DDListItem.superclass.constructor.call(this, id);
// Prevent lateral draggability
this.setXConstraint(0,0);
this.goingUp = false;
this.lastY = 0;
};
YAHOO.extend(inputEx.widget.DDListItem, YAHOO.util.DDProxy, {
/**
* Create the proxy element
*/
startDrag: function(x, y) {
// make the proxy look like the source element
var dragEl = this.getDragEl();
var clickEl = this.getEl();
Dom.setStyle(clickEl, "visibility", "hidden");
this._originalIndex = inputEx.indexOf(clickEl ,clickEl.parentNode.childNodes);
dragEl.className = clickEl.className;
dragEl.innerHTML = clickEl.innerHTML;
},
/**
* Handle the endDrag and eventually fire the listReordered event
*/
endDrag: function(e) {
Dom.setStyle(this.id, "visibility", "");
// Fire the reordered event if position in list has changed
var clickEl = this.getEl();
var newIndex = inputEx.indexOf(clickEl ,clickEl.parentNode.childNodes);
if(this._originalIndex != newIndex) {
this._list.onReordered(this._originalIndex, newIndex);
}
},
/**
* @method onDragDrop
*/
onDragDrop: function(e, id) {
// If there is one drop interaction, the li was dropped either on the list,
// or it was dropped on the current location of the source element.
if (DD.interactionInfo.drop.length === 1) {
// The position of the cursor at the time of the drop (YAHOO.util.Point)
var pt = DD.interactionInfo.point;
// The region occupied by the source element at the time of the drop
var region = DD.interactionInfo.sourceRegion;
// Check to see if we are over the source element's location. We will
// append to the bottom of the list once we are sure it was a drop in
// the negative space (the area of the list without any list items)
if (!region.intersect(pt)) {
var destEl = Dom.get(id);
if (destEl.nodeName.toLowerCase() != "li") {
var destDD = DD.getDDById(id);
destEl.appendChild(this.getEl());
destDD.isEmpty = false;
DD.refreshCache();
}
}
}
},
/**
* Keep track of the direction of the drag for use during onDragOver
*/
onDrag: function(e) {
var y = Event.getPageY(e);
if (y < this.lastY) {
this.goingUp = true;
} else if (y > this.lastY) {
this.goingUp = false;
}
this.lastY = y;
},
/**
* @method onDragOver
*/
onDragOver: function(e, id) {
var srcEl = this.getEl();
var destEl = Dom.get(id);
// We are only concerned with list items, we ignore the dragover
// notifications for the list.
if (destEl.nodeName.toLowerCase() == "li") {
var orig_p = srcEl.parentNode;
var p = destEl.parentNode;
if (this.goingUp) {
p.insertBefore(srcEl, destEl); // insert above
} else {
p.insertBefore(srcEl, destEl.nextSibling); // insert below
}
DD.refreshCache();
}
}
});
/**
* Create a sortable list
* @class inputEx.widget.DDList
* @constructor
* @param {Object} options Options:
* <ul>
* <li>id: id of the ul element</li>
* <li>value: initial value of the list</li>
* </ul>
*/
inputEx.widget.DDList = function(options) {
this.ul = inputEx.cn('ul');
this.items = [];
this.setOptions(options);
/**
* @event YAHOO custom event fired when an item is removed
* @param {Any} itemValue value of the removed item
*/
this.itemRemovedEvt = new YAHOO.util.CustomEvent('itemRemoved', this);
/**
* @event YAHOO custom event fired when the list is reordered
*/
this.listReorderedEvt = new YAHOO.util.CustomEvent('listReordered', this);
// append it immediatly to the parent DOM element
if(options.parentEl) {
if( lang.isString(options.parentEl) ) {
Dom.get(options.parentEl).appendChild(this.ul);
}
else {
options.parentEl.appendChild(this.ul);
}
}
};
inputEx.widget.DDList.prototype = {
/**
* Set the options
*/
setOptions: function(options) {
this.options = {};
this.options.allowDelete = lang.isUndefined(options.allowDelete) ? true : options.allowDelete;
if(options.id) {
this.ul.id = options.id;
}
if(options.value) {
this.setValue(options.value);
}
},
/**
* Add an item to the list
* @param {String|Object} item Either a string with the given value or an object with "label" and "value" attributes
*/
addItem: function(item) {
var li = inputEx.cn('li', {className: 'inputEx-DDList-item'});
li.appendChild( inputEx.cn('span', null, null, (typeof item == "object") ? item.label : item) );
// Option for the "remove" link (default: true)
if(!!this.options.allowDelete){
var removeLink = inputEx.cn('a', null, null, "remove");
li.appendChild( removeLink );
Event.addListener(removeLink, 'click', function(e) {
var a = Event.getTarget(e);
var li = a.parentNode;
this.removeItem( inputEx.indexOf(li,this.ul.childNodes) );
}, this, true);
}
var dditem = new inputEx.widget.DDListItem(li);
dditem._list = this;
this.items.push( (typeof item == "object") ? item.value : item );
this.ul.appendChild(li);
},
/**
* private method to remove an item
* @param {Integer} index index of item to be removed
* @private
*/
_removeItem: function(i) {
var itemValue = this.items[i];
this.ul.removeChild(this.ul.childNodes[i]);
this.items[i] = null;
this.items = inputEx.compactArray(this.items);
return itemValue;
},
/**
* Method to remove an item (_removeItem function + event firing)
* @param {Integer} index Item index
*/
removeItem: function(index) {
var itemValue = this._removeItem(index);
// Fire the itemRemoved Event
this.itemRemovedEvt.fire(itemValue);
},
/**
* Called by the DDListItem when an item as been moved
*/
onReordered: function(originalIndex, newIndex) {
if(originalIndex < newIndex) {
this.items.splice(newIndex+1,0, this.items[originalIndex]);
this.items[originalIndex] = null;
}
else {
this.items.splice(newIndex,0, this.items[originalIndex]);
this.items[originalIndex+1] = null;
}
this.items = inputEx.compactArray(this.items);
this.listReorderedEvt.fire();
},
/**
* Return the current value of the field
* @return {Array} array of values
*/
getValue: function() {
return this.items;
},
/**
* Update the value of a given item
* @param {Integer} index Item index
* @param {Any} value New value
*/
updateItem: function(index,value) {
this.items[index] = value;
this.ul.childNodes[index].childNodes[0].innerHTML = value;
},
/**
* Set the value of the list
* @param {Array} value list of values
*/
setValue: function(value) {
// if trying to set wrong value (or ""), reset
if (!lang.isArray(value)) {
value = [];
}
var oldNb = this.ul.childNodes.length;
var newNb = value.length;
for(var i = 0 ; i < newNb ; i++) {
if(i < oldNb) {
this.updateItem(i, value[i]);
}
else {
this.addItem(value[i]);
}
}
// remove extra li items if any
for(var j = newNb; j < oldNb; j++) {
this._removeItem(newNb); // newNb is always the index of first li to remove (not j !)
}
}
};
})(); | whummer/WS-Aggregation | web/wireit/lib/inputex/js/widgets/ddlist.js | JavaScript | apache-2.0 | 8,389 |
// Generated by CoffeeScript 1.9.0
var BulkLoad, Connection, ConnectionError, DEFAULT_CANCEL_TIMEOUT, DEFAULT_CLIENT_REQUEST_TIMEOUT, DEFAULT_CONNECT_TIMEOUT, DEFAULT_PACKET_SIZE, DEFAULT_PORT, DEFAULT_TDS_VERSION, DEFAULT_TEXTSIZE, Debug, EventEmitter, ISOLATION_LEVEL, KEEP_ALIVE_INITIAL_DELAY, Login7Payload, MessageIO, NTLMResponsePayload, PreloginPayload, Request, RequestError, RpcRequestPayload, Socket, SqlBatchPayload, TYPE, TokenStreamParser, Transaction, crypto, instanceLookup, tls, _ref,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__hasProp = {}.hasOwnProperty,
__slice = [].slice;
require('./buffertools');
BulkLoad = require('./bulk-load');
Debug = require('./debug');
EventEmitter = require('events').EventEmitter;
instanceLookup = require('./instance-lookup').instanceLookup;
TYPE = require('./packet').TYPE;
PreloginPayload = require('./prelogin-payload');
Login7Payload = require('./login7-payload');
NTLMResponsePayload = require('./ntlm-payload');
Request = require('./request');
RpcRequestPayload = require('./rpcrequest-payload');
SqlBatchPayload = require('./sqlbatch-payload');
MessageIO = require('./message-io');
Socket = require('net').Socket;
TokenStreamParser = require('./token/token-stream-parser').Parser;
Transaction = require('./transaction').Transaction;
ISOLATION_LEVEL = require('./transaction').ISOLATION_LEVEL;
crypto = require('crypto');
tls = require('tls');
_ref = require('./errors'), ConnectionError = _ref.ConnectionError, RequestError = _ref.RequestError;
KEEP_ALIVE_INITIAL_DELAY = 30 * 1000;
DEFAULT_CONNECT_TIMEOUT = 15 * 1000;
DEFAULT_CLIENT_REQUEST_TIMEOUT = 15 * 1000;
DEFAULT_CANCEL_TIMEOUT = 5 * 1000;
DEFAULT_PACKET_SIZE = 4 * 1024;
DEFAULT_TEXTSIZE = '2147483647';
DEFAULT_PORT = 1433;
DEFAULT_TDS_VERSION = '7_4';
Connection = (function(_super) {
__extends(Connection, _super);
Connection.prototype.STATE = {
CONNECTING: {
name: 'Connecting',
enter: function() {
return this.initialiseConnection();
},
events: {
socketError: function(error) {
return this.transitionTo(this.STATE.FINAL);
},
connectTimeout: function() {
return this.transitionTo(this.STATE.FINAL);
},
socketConnect: function() {
this.sendPreLogin();
return this.transitionTo(this.STATE.SENT_PRELOGIN);
}
}
},
SENT_PRELOGIN: {
name: 'SentPrelogin',
enter: function() {
return this.emptyMessageBuffer();
},
events: {
socketError: function(error) {
return this.transitionTo(this.STATE.FINAL);
},
connectTimeout: function() {
return this.transitionTo(this.STATE.FINAL);
},
data: function(data) {
return this.addToMessageBuffer(data);
},
message: function() {
return this.processPreLoginResponse();
},
noTls: function() {
this.sendLogin7Packet();
if (this.config.domain) {
return this.transitionTo(this.STATE.SENT_LOGIN7_WITH_NTLM);
} else {
return this.transitionTo(this.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN);
}
},
tls: function() {
this.initiateTlsSslHandshake();
this.sendLogin7Packet();
return this.transitionTo(this.STATE.SENT_TLSSSLNEGOTIATION);
}
}
},
REROUTING: {
name: 'ReRouting',
enter: function() {
return this.cleanupConnection(true);
},
events: {
message: function() {},
socketError: function(error) {
return this.transitionTo(this.STATE.FINAL);
},
connectTimeout: function() {
return this.transitionTo(this.STATE.FINAL);
},
reconnect: function() {
this.config.server = this.routingData.server;
this.config.options.port = this.routingData.port;
return this.transitionTo(this.STATE.CONNECTING);
}
}
},
SENT_TLSSSLNEGOTIATION: {
name: 'SentTLSSSLNegotiation',
enter: function() {
return this.tlsNegotiationComplete = false;
},
events: {
socketError: function(error) {
return this.transitionTo(this.STATE.FINAL);
},
connectTimeout: function() {
return this.transitionTo(this.STATE.FINAL);
},
data: function(data) {
return this.securePair.encrypted.write(data);
},
tlsNegotiated: function() {
return this.tlsNegotiationComplete = true;
},
message: function() {
if (this.tlsNegotiationComplete) {
return this.transitionTo(this.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN);
} else {
}
}
}
},
SENT_LOGIN7_WITH_STANDARD_LOGIN: {
name: 'SentLogin7WithStandardLogin',
events: {
socketError: function(error) {
return this.transitionTo(this.STATE.FINAL);
},
connectTimeout: function() {
return this.transitionTo(this.STATE.FINAL);
},
data: function(data) {
return this.sendDataToTokenStreamParser(data);
},
loggedIn: function() {
return this.transitionTo(this.STATE.LOGGED_IN_SENDING_INITIAL_SQL);
},
routingChange: function() {
return this.transitionTo(this.STATE.REROUTING);
},
loginFailed: function() {
return this.transitionTo(this.STATE.FINAL);
},
message: function() {
return this.processLogin7Response();
}
}
},
SENT_LOGIN7_WITH_NTLM: {
name: 'SentLogin7WithNTLMLogin',
events: {
socketError: function(error) {
return this.transitionTo(this.STATE.FINAL);
},
connectTimeout: function() {
return this.transitionTo(this.STATE.FINAL);
},
data: function(data) {
return this.sendDataToTokenStreamParser(data);
},
receivedChallenge: function() {
this.sendNTLMResponsePacket();
return this.transitionTo(this.STATE.SENT_NTLM_RESPONSE);
},
loginFailed: function() {
return this.transitionTo(this.STATE.FINAL);
},
message: function() {
return this.processLogin7NTLMResponse();
}
}
},
SENT_NTLM_RESPONSE: {
name: 'SentNTLMResponse',
events: {
socketError: function(error) {
return this.transitionTo(this.STATE.FINAL);
},
connectTimeout: function() {
return this.transitionTo(this.STATE.FINAL);
},
data: function(data) {
return this.sendDataToTokenStreamParser(data);
},
loggedIn: function() {
return this.transitionTo(this.STATE.LOGGED_IN_SENDING_INITIAL_SQL);
},
loginFailed: function() {
return this.transitionTo(this.STATE.FINAL);
},
routingChange: function() {
return this.transitionTo(this.STATE.REROUTING);
},
message: function() {
return this.processLogin7NTLMAck();
}
}
},
LOGGED_IN_SENDING_INITIAL_SQL: {
name: 'LoggedInSendingInitialSql',
enter: function() {
return this.sendInitialSql();
},
events: {
connectTimeout: function() {
return this.transitionTo(this.STATE.FINAL);
},
data: function(data) {
return this.sendDataToTokenStreamParser(data);
},
message: function(error) {
this.transitionTo(this.STATE.LOGGED_IN);
return this.processedInitialSql();
}
}
},
LOGGED_IN: {
name: 'LoggedIn',
events: {
socketError: function(error) {
return this.transitionTo(this.STATE.FINAL);
}
}
},
SENT_CLIENT_REQUEST: {
name: 'SentClientRequest',
events: {
socketError: function(error) {
return this.transitionTo(this.STATE.FINAL);
},
data: function(data) {
return this.sendDataToTokenStreamParser(data);
},
message: function() {
var sqlRequest;
this.clearRequestTimer();
this.transitionTo(this.STATE.LOGGED_IN);
sqlRequest = this.request;
this.request = void 0;
return sqlRequest.callback(sqlRequest.error, sqlRequest.rowCount, sqlRequest.rows);
}
}
},
SENT_ATTENTION: {
name: 'SentAttention',
enter: function() {
return this.attentionReceived = false;
},
events: {
socketError: function(error) {
return this.transitionTo(this.STATE.FINAL);
},
data: function(data) {
return this.sendDataToTokenStreamParser(data);
},
attention: function() {
return this.attentionReceived = true;
},
message: function() {
var message, sqlRequest;
if (this.attentionReceived) {
sqlRequest = this.request;
this.request = void 0;
this.transitionTo(this.STATE.LOGGED_IN);
if (sqlRequest.canceled) {
return sqlRequest.callback(RequestError("Canceled.", 'ECANCEL'));
} else {
message = "Timeout: Request failed to complete in " + this.config.options.requestTimeout + "ms";
return sqlRequest.callback(RequestError(message, 'ETIMEOUT'));
}
}
}
}
},
FINAL: {
name: 'Final',
enter: function() {
return this.cleanupConnection();
},
events: {
loginFailed: function() {},
connectTimeout: function() {},
message: function() {},
socketError: function() {}
}
}
};
function Connection(_at_config) {
this.config = _at_config;
this.reset = __bind(this.reset, this);
this.socketClose = __bind(this.socketClose, this);
this.socketEnd = __bind(this.socketEnd, this);
this.socketConnect = __bind(this.socketConnect, this);
this.socketError = __bind(this.socketError, this);
this.requestTimeout = __bind(this.requestTimeout, this);
this.connectTimeout = __bind(this.connectTimeout, this);
this.defaultConfig();
this.createDebug();
this.createTokenStreamParser();
this.inTransaction = false;
this.transactionDescriptors = [new Buffer([0, 0, 0, 0, 0, 0, 0, 0])];
this.transitionTo(this.STATE.CONNECTING);
}
Connection.prototype.close = function() {
return this.transitionTo(this.STATE.FINAL);
};
Connection.prototype.initialiseConnection = function() {
this.connect();
return this.createConnectTimer();
};
Connection.prototype.cleanupConnection = function(_at_redirect) {
this.redirect = _at_redirect;
if (!this.closed) {
this.clearConnectTimer();
this.clearRequestTimer();
this.closeConnection();
if (!this.redirect) {
this.emit('end');
} else {
this.emit('rerouting');
}
this.closed = true;
this.loggedIn = false;
return this.loginError = null;
}
};
Connection.prototype.defaultConfig = function() {
var _base, _base1, _base10, _base11, _base12, _base13, _base14, _base2, _base3, _base4, _base5, _base6, _base7, _base8, _base9;
(_base = this.config).options || (_base.options = {});
(_base1 = this.config.options).textsize || (_base1.textsize = DEFAULT_TEXTSIZE);
(_base2 = this.config.options).connectTimeout || (_base2.connectTimeout = DEFAULT_CONNECT_TIMEOUT);
if ((_base3 = this.config.options).requestTimeout == null) {
_base3.requestTimeout = DEFAULT_CLIENT_REQUEST_TIMEOUT;
}
if ((_base4 = this.config.options).cancelTimeout == null) {
_base4.cancelTimeout = DEFAULT_CANCEL_TIMEOUT;
}
(_base5 = this.config.options).packetSize || (_base5.packetSize = DEFAULT_PACKET_SIZE);
(_base6 = this.config.options).tdsVersion || (_base6.tdsVersion = DEFAULT_TDS_VERSION);
(_base7 = this.config.options).isolationLevel || (_base7.isolationLevel = ISOLATION_LEVEL.READ_COMMITTED);
(_base8 = this.config.options).encrypt || (_base8.encrypt = false);
(_base9 = this.config.options).cryptoCredentialsDetails || (_base9.cryptoCredentialsDetails = {});
if ((_base10 = this.config.options).useUTC == null) {
_base10.useUTC = true;
}
if ((_base11 = this.config.options).useColumnNames == null) {
_base11.useColumnNames = false;
}
(_base12 = this.config.options).connectionIsolationLevel || (_base12.connectionIsolationLevel = ISOLATION_LEVEL.READ_COMMITTED);
if ((_base13 = this.config.options).readOnlyIntent == null) {
_base13.readOnlyIntent = false;
}
if ((_base14 = this.config.options).enableAnsiNullDefault == null) {
_base14.enableAnsiNullDefault = true;
}
if (!this.config.options.port && !this.config.options.instanceName) {
this.config.options.port = DEFAULT_PORT;
} else if (this.config.options.port && this.config.options.instanceName) {
throw new Error("Port and instanceName are mutually exclusive, but " + this.config.options.port + " and " + this.config.options.instanceName + " provided");
} else if (this.config.options.port) {
if (this.config.options.port < 0 || this.config.options.port > 65536) {
throw new RangeError("Port should be > 0 and < 65536");
}
}
if (this.config.options.columnNameReplacer && typeof this.config.options.columnNameReplacer !== 'function') {
throw new TypeError('options.columnNameReplacer must be a function or null.');
}
};
Connection.prototype.createDebug = function() {
this.debug = new Debug(this.config.options.debug);
return this.debug.on('debug', (function(_this) {
return function(message) {
return _this.emit('debug', message);
};
})(this));
};
Connection.prototype.createTokenStreamParser = function() {
this.tokenStreamParser = new TokenStreamParser(this.debug, void 0, this.config.options);
this.tokenStreamParser.on('infoMessage', (function(_this) {
return function(token) {
return _this.emit('infoMessage', token);
};
})(this));
this.tokenStreamParser.on('sspichallenge', (function(_this) {
return function(token) {
if (token.ntlmpacket) {
_this.ntlmpacket = token.ntlmpacket;
}
return _this.emit('sspichallenge', token);
};
})(this));
this.tokenStreamParser.on('errorMessage', (function(_this) {
return function(token) {
_this.emit('errorMessage', token);
if (_this.loggedIn) {
if (_this.request) {
_this.request.error = RequestError(token.message, 'EREQUEST');
_this.request.error.number = token.number;
_this.request.error.state = token.state;
_this.request.error["class"] = token["class"];
_this.request.error.serverName = token.serverName;
_this.request.error.procName = token.procName;
return _this.request.error.lineNumber = token.lineNumber;
}
} else {
return _this.loginError = ConnectionError(token.message, 'ELOGIN');
}
};
})(this));
this.tokenStreamParser.on('databaseChange', (function(_this) {
return function(token) {
return _this.emit('databaseChange', token.newValue);
};
})(this));
this.tokenStreamParser.on('languageChange', (function(_this) {
return function(token) {
return _this.emit('languageChange', token.newValue);
};
})(this));
this.tokenStreamParser.on('charsetChange', (function(_this) {
return function(token) {
return _this.emit('charsetChange', token.newValue);
};
})(this));
this.tokenStreamParser.on('loginack', (function(_this) {
return function(token) {
if (!token.tdsVersion) {
_this.loginError = ConnectionError("Server responded with unknown TDS version.", 'ETDS');
_this.loggedIn = false;
return;
}
if (!token["interface"]) {
_this.loginError = ConnectionError("Server responded with unsupported interface.", 'EINTERFACENOTSUPP');
_this.loggedIn = false;
return;
}
_this.config.options.tdsVersion = token.tdsVersion;
return _this.loggedIn = true;
};
})(this));
this.tokenStreamParser.on('routingChange', (function(_this) {
return function(token) {
_this.routingData = token.newValue;
return _this.dispatchEvent('routingChange');
};
})(this));
this.tokenStreamParser.on('packetSizeChange', (function(_this) {
return function(token) {
return _this.messageIo.packetSize(token.newValue);
};
})(this));
this.tokenStreamParser.on('beginTransaction', (function(_this) {
return function(token) {
_this.transactionDescriptors.push(token.newValue);
return _this.inTransaction = true;
};
})(this));
this.tokenStreamParser.on('commitTransaction', (function(_this) {
return function(token) {
_this.transactionDescriptors.length = 1;
return _this.inTransaction = false;
};
})(this));
this.tokenStreamParser.on('rollbackTransaction', (function(_this) {
return function(token) {
_this.transactionDescriptors.length = 1;
_this.inTransaction = false;
return _this.emit('rollbackTransaction');
};
})(this));
this.tokenStreamParser.on('columnMetadata', (function(_this) {
return function(token) {
var col, columns, _i, _len, _ref1;
if (_this.request) {
if (_this.config.options.useColumnNames) {
columns = {};
_ref1 = token.columns;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
col = _ref1[_i];
if (columns[col.colName] == null) {
columns[col.colName] = col;
}
}
} else {
columns = token.columns;
}
return _this.request.emit('columnMetadata', columns);
} else {
_this.emit('error', new Error("Received 'columnMetadata' when no sqlRequest is in progress"));
return _this.close();
}
};
})(this));
this.tokenStreamParser.on('order', (function(_this) {
return function(token) {
if (_this.request) {
return _this.request.emit('order', token.orderColumns);
} else {
_this.emit('error', new Error("Received 'order' when no sqlRequest is in progress"));
return _this.close();
}
};
})(this));
this.tokenStreamParser.on('row', (function(_this) {
return function(token) {
if (_this.request) {
if (_this.config.options.rowCollectionOnRequestCompletion) {
_this.request.rows.push(token.columns);
}
if (_this.config.options.rowCollectionOnDone) {
_this.request.rst.push(token.columns);
}
return _this.request.emit('row', token.columns);
} else {
_this.emit('error', new Error("Received 'row' when no sqlRequest is in progress"));
return _this.close();
}
};
})(this));
this.tokenStreamParser.on('returnStatus', (function(_this) {
return function(token) {
if (_this.request) {
return _this.procReturnStatusValue = token.value;
}
};
})(this));
this.tokenStreamParser.on('returnValue', (function(_this) {
return function(token) {
if (_this.request) {
return _this.request.emit('returnValue', token.paramName, token.value, token.metadata);
}
};
})(this));
this.tokenStreamParser.on('doneProc', (function(_this) {
return function(token) {
if (_this.request) {
_this.request.emit('doneProc', token.rowCount, token.more, _this.procReturnStatusValue, _this.request.rst);
_this.procReturnStatusValue = void 0;
if (token.rowCount !== void 0) {
_this.request.rowCount += token.rowCount;
}
if (_this.config.options.rowCollectionOnDone) {
return _this.request.rst = [];
}
}
};
})(this));
this.tokenStreamParser.on('doneInProc', (function(_this) {
return function(token) {
if (_this.request) {
_this.request.emit('doneInProc', token.rowCount, token.more, _this.request.rst);
if (token.rowCount !== void 0) {
_this.request.rowCount += token.rowCount;
}
if (_this.config.options.rowCollectionOnDone) {
return _this.request.rst = [];
}
}
};
})(this));
this.tokenStreamParser.on('done', (function(_this) {
return function(token) {
if (_this.request) {
if (token.attention) {
_this.dispatchEvent("attention");
}
if (token.sqlError && !_this.request.error) {
_this.request.error = RequestError('An unknown error has occurred.', 'UNKNOWN');
}
_this.request.emit('done', token.rowCount, token.more, _this.request.rst);
if (token.rowCount !== void 0) {
_this.request.rowCount += token.rowCount;
}
if (_this.config.options.rowCollectionOnDone) {
return _this.request.rst = [];
}
}
};
})(this));
this.tokenStreamParser.on('resetConnection', (function(_this) {
return function(token) {
return _this.emit('resetConnection');
};
})(this));
return this.tokenStreamParser.on('tokenStreamError', (function(_this) {
return function(error) {
_this.emit('error', error);
return _this.close();
};
})(this));
};
Connection.prototype.connect = function() {
if (this.config.options.port) {
return this.connectOnPort(this.config.options.port);
} else {
return instanceLookup(this.config.server, this.config.options.instanceName, (function(_this) {
return function(message, port) {
if (_this.state === _this.STATE.FINAL) {
return;
}
if (message) {
return _this.emit('connect', ConnectionError(message, 'EINSTLOOKUP'));
} else {
return _this.connectOnPort(port);
}
};
})(this), this.config.options.connectTimeout);
}
};
Connection.prototype.connectOnPort = function(port) {
var connectOpts;
this.socket = new Socket({});
connectOpts = {
host: this.config.server,
port: port
};
if (this.config.options.localAddress) {
connectOpts.localAddress = this.config.options.localAddress;
}
this.socket.connect(connectOpts);
this.socket.on('error', this.socketError);
this.socket.on('connect', this.socketConnect);
this.socket.on('close', this.socketClose);
this.socket.on('end', this.socketEnd);
this.messageIo = new MessageIO(this.socket, this.config.options.packetSize, this.debug);
this.messageIo.on('data', (function(_this) {
return function(data) {
return _this.dispatchEvent('data', data);
};
})(this));
return this.messageIo.on('message', (function(_this) {
return function() {
return _this.dispatchEvent('message');
};
})(this));
};
Connection.prototype.closeConnection = function() {
var _ref1;
return (_ref1 = this.socket) != null ? _ref1.destroy() : void 0;
};
Connection.prototype.createConnectTimer = function() {
return this.connectTimer = setTimeout(this.connectTimeout, this.config.options.connectTimeout);
};
Connection.prototype.createRequestTimer = function() {
if (this.config.options.requestTimeout) {
return this.requestTimer = setTimeout(this.requestTimeout, this.config.options.requestTimeout);
}
};
Connection.prototype.connectTimeout = function() {
var message;
message = "Failed to connect to " + this.config.server + ":" + this.config.options.port + " in " + this.config.options.connectTimeout + "ms";
this.debug.log(message);
this.emit('connect', ConnectionError(message, 'ETIMEOUT'));
this.connectTimer = void 0;
return this.dispatchEvent('connectTimeout');
};
Connection.prototype.requestTimeout = function() {
this.requestTimer = void 0;
this.messageIo.sendMessage(TYPE.ATTENTION);
return this.transitionTo(this.STATE.SENT_ATTENTION);
};
Connection.prototype.clearConnectTimer = function() {
if (this.connectTimer) {
return clearTimeout(this.connectTimer);
}
};
Connection.prototype.clearRequestTimer = function() {
if (this.requestTimer) {
return clearTimeout(this.requestTimer);
}
};
Connection.prototype.transitionTo = function(newState) {
var _ref1, _ref2;
if (this.state === newState) {
this.debug.log("State is already " + newState.name);
return;
}
if ((_ref1 = this.state) != null ? _ref1.exit : void 0) {
this.state.exit.apply(this);
}
this.debug.log("State change: " + ((_ref2 = this.state) != null ? _ref2.name : void 0) + " -> " + newState.name);
this.state = newState;
if (this.state.enter) {
return this.state.enter.apply(this);
}
};
Connection.prototype.dispatchEvent = function() {
var args, eventFunction, eventName, _ref1;
eventName = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if ((_ref1 = this.state) != null ? _ref1.events[eventName] : void 0) {
return eventFunction = this.state.events[eventName].apply(this, args);
} else {
this.emit('error', new Error("No event '" + eventName + "' in state '" + this.state.name + "'"));
return this.close();
}
};
Connection.prototype.socketError = function(error) {
var message;
if (this.state === this.STATE.CONNECTING) {
message = "Failed to connect to " + this.config.server + ":" + this.config.options.port + " - " + error.message;
this.debug.log(message);
this.emit('connect', ConnectionError(message, 'ESOCKET'));
} else {
message = "Connection lost - " + error.message;
this.debug.log(message);
this.emit('error', ConnectionError(message, 'ESOCKET'));
}
return this.dispatchEvent('socketError', error);
};
Connection.prototype.socketConnect = function() {
this.socket.setKeepAlive(true, KEEP_ALIVE_INITIAL_DELAY);
this.closed = false;
this.debug.log("connected to " + this.config.server + ":" + this.config.options.port);
return this.dispatchEvent('socketConnect');
};
Connection.prototype.socketEnd = function() {
this.debug.log("socket ended");
return this.transitionTo(this.STATE.FINAL);
};
Connection.prototype.socketClose = function() {
this.debug.log("connection to " + this.config.server + ":" + this.config.options.port + " closed");
if (this.state === this.STATE.REROUTING) {
this.debug.log("Rerouting to " + this.routingData.server + ":" + this.routingData.port);
return this.dispatchEvent('reconnect');
} else {
return this.transitionTo(this.STATE.FINAL);
}
};
Connection.prototype.sendPreLogin = function() {
var payload;
payload = new PreloginPayload({
encrypt: this.config.options.encrypt
});
this.messageIo.sendMessage(TYPE.PRELOGIN, payload.data);
return this.debug.payload(function() {
return payload.toString(' ');
});
};
Connection.prototype.emptyMessageBuffer = function() {
return this.messageBuffer = new Buffer(0);
};
Connection.prototype.addToMessageBuffer = function(data) {
return this.messageBuffer = Buffer.concat([this.messageBuffer, data]);
};
Connection.prototype.processPreLoginResponse = function() {
var preloginPayload, _ref1;
preloginPayload = new PreloginPayload(this.messageBuffer);
this.debug.payload(function() {
return preloginPayload.toString(' ');
});
if ((_ref1 = preloginPayload.encryptionString) === 'ON' || _ref1 === 'REQ') {
return this.dispatchEvent('tls');
} else {
return this.dispatchEvent('noTls');
}
};
Connection.prototype.sendLogin7Packet = function() {
var loginData, payload;
loginData = {
domain: this.config.domain,
userName: this.config.userName,
password: this.config.password,
database: this.config.options.database,
serverName: this.config.server,
appName: this.config.options.appName,
packetSize: this.config.options.packetSize,
tdsVersion: this.config.options.tdsVersion,
initDbFatal: !this.config.options.fallbackToDefaultDb,
readOnlyIntent: this.config.options.readOnlyIntent
};
payload = new Login7Payload(loginData);
this.messageIo.sendMessage(TYPE.LOGIN7, payload.data);
return this.debug.payload(function() {
return payload.toString(' ');
});
};
Connection.prototype.sendNTLMResponsePacket = function() {
var payload, responseData;
responseData = {
domain: this.config.domain,
userName: this.config.userName,
password: this.config.password,
database: this.config.options.database,
appName: this.config.options.appName,
packetSize: this.config.options.packetSize,
tdsVersion: this.config.options.tdsVersion,
ntlmpacket: this.ntlmpacket,
additional: this.additional
};
payload = new NTLMResponsePayload(responseData);
this.messageIo.sendMessage(TYPE.NTLMAUTH_PKT, payload.data);
return this.debug.payload(function() {
return payload.toString(' ');
});
};
Connection.prototype.initiateTlsSslHandshake = function() {
var credentials;
credentials = tls.createSecureContext ? tls.createSecureContext(this.config.options.cryptoCredentialsDetails) : crypto.createCredentials(this.config.options.cryptoCredentialsDetails);
this.securePair = tls.createSecurePair(credentials);
this.securePair.on('secure', (function(_this) {
return function() {
var cipher;
cipher = _this.securePair.cleartext.getCipher();
_this.debug.log("TLS negotiated (" + cipher.name + ", " + cipher.version + ")");
_this.emit('secure', _this.securePair.cleartext);
_this.messageIo.encryptAllFutureTraffic();
return _this.dispatchEvent('tlsNegotiated');
};
})(this));
this.securePair.encrypted.on('data', (function(_this) {
return function(data) {
return _this.messageIo.sendMessage(TYPE.PRELOGIN, data);
};
})(this));
return this.messageIo.tlsNegotiationStarting(this.securePair);
};
Connection.prototype.sendDataToTokenStreamParser = function(data) {
return this.tokenStreamParser.addBuffer(data);
};
Connection.prototype.sendInitialSql = function() {
var payload;
payload = new SqlBatchPayload(this.getInitialSql(), this.currentTransactionDescriptor(), this.config.options);
return this.messageIo.sendMessage(TYPE.SQL_BATCH, payload.data);
};
Connection.prototype.getInitialSql = function() {
var enableAnsiNullDefault, xact_abort;
xact_abort = this.config.options.abortTransactionOnError ? 'on' : 'off';
enableAnsiNullDefault = this.config.options.enableAnsiNullDefault ? 'on' : 'off';
return "set textsize " + this.config.options.textsize + "\nset quoted_identifier on\nset arithabort off\nset numeric_roundabort off\nset ansi_warnings on\nset ansi_padding on\nset ansi_nulls on\nset ansi_null_dflt_on " + enableAnsiNullDefault + "\nset concat_null_yields_null on\nset cursor_close_on_commit off\nset implicit_transactions off\nset language us_english\nset dateformat mdy\nset datefirst 7\nset transaction isolation level " + (this.getIsolationLevelText(this.config.options.connectionIsolationLevel)) + "\nset xact_abort " + xact_abort;
};
Connection.prototype.processedInitialSql = function() {
this.clearConnectTimer();
return this.emit('connect');
};
Connection.prototype.processLogin7Response = function() {
if (this.loggedIn) {
return this.dispatchEvent('loggedIn');
} else {
if (this.loginError) {
this.emit('connect', this.loginError);
} else {
this.emit('connect', ConnectionError('Login failed.', 'ELOGIN'));
}
return this.dispatchEvent('loginFailed');
}
};
Connection.prototype.processLogin7NTLMResponse = function() {
if (this.ntlmpacket) {
return this.dispatchEvent('receivedChallenge');
} else {
if (this.loginError) {
this.emit('connect', this.loginError);
} else {
this.emit('connect', ConnectionError('Login failed.', 'ELOGIN'));
}
return this.dispatchEvent('loginFailed');
}
};
Connection.prototype.processLogin7NTLMAck = function() {
if (this.loggedIn) {
return this.dispatchEvent('loggedIn');
} else {
if (this.loginError) {
this.emit('connect', this.loginError);
} else {
this.emit('connect', ConnectionError('Login failed.', 'ELOGIN'));
}
return this.dispatchEvent('loginFailed');
}
};
Connection.prototype.execSqlBatch = function(request) {
return this.makeRequest(request, TYPE.SQL_BATCH, new SqlBatchPayload(request.sqlTextOrProcedure, this.currentTransactionDescriptor(), this.config.options));
};
Connection.prototype.execSql = function(request) {
request.transformIntoExecuteSqlRpc();
if (request.error != null) {
return process.nextTick((function(_this) {
return function() {
_this.debug.log(request.error.message);
return request.callback(request.error);
};
})(this));
}
return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
};
Connection.prototype.newBulkLoad = function(table, callback) {
return new BulkLoad(table, this.config.options, callback);
};
Connection.prototype.execBulkLoad = function(bulkLoad) {
var request;
request = new Request(bulkLoad.getBulkInsertSql(), (function(_this) {
return function(error) {
if (error) {
if (error.code === 'UNKNOWN') {
error.message += ' This is likely because the schema of the BulkLoad does not match the schema of the table you are attempting to insert into.';
}
bulkLoad.error = error;
return bulkLoad.callback(error);
} else {
return _this.makeRequest(bulkLoad, TYPE.BULK_LOAD, bulkLoad.getPayload());
}
};
})(this));
return this.execSqlBatch(request);
};
Connection.prototype.prepare = function(request) {
request.transformIntoPrepareRpc();
return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
};
Connection.prototype.unprepare = function(request) {
request.transformIntoUnprepareRpc();
return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
};
Connection.prototype.execute = function(request, parameters) {
request.transformIntoExecuteRpc(parameters);
if (request.error != null) {
return process.nextTick((function(_this) {
return function() {
_this.debug.log(request.error.message);
return request.callback(request.error);
};
})(this));
}
return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
};
Connection.prototype.callProcedure = function(request) {
request.validateParameters();
if (request.error != null) {
return process.nextTick((function(_this) {
return function() {
_this.debug.log(request.error.message);
return request.callback(request.error);
};
})(this));
}
return this.makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, this.currentTransactionDescriptor(), this.config.options));
};
Connection.prototype.beginTransaction = function(callback, name, isolationLevel) {
var request, transaction;
isolationLevel || (isolationLevel = this.config.options.isolationLevel);
transaction = new Transaction(name || '', isolationLevel);
if (this.config.options.tdsVersion < "7_2") {
return this.execSqlBatch(new Request("SET TRANSACTION ISOLATION LEVEL " + (transaction.isolationLevelToTSQL()) + ";BEGIN TRAN " + transaction.name, callback));
}
request = new Request(void 0, (function(_this) {
return function(err) {
return callback(err, _this.currentTransactionDescriptor());
};
})(this));
return this.makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.beginPayload(this.currentTransactionDescriptor()));
};
Connection.prototype.commitTransaction = function(callback, name) {
var request, transaction;
transaction = new Transaction(name || '');
if (this.config.options.tdsVersion < "7_2") {
return this.execSqlBatch(new Request("COMMIT TRAN " + transaction.name, callback));
}
request = new Request(void 0, callback);
return this.makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.commitPayload(this.currentTransactionDescriptor()));
};
Connection.prototype.rollbackTransaction = function(callback, name) {
var request, transaction;
transaction = new Transaction(name || '');
if (this.config.options.tdsVersion < "7_2") {
return this.execSqlBatch(new Request("ROLLBACK TRAN " + transaction.name, callback));
}
request = new Request(void 0, callback);
return this.makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.rollbackPayload(this.currentTransactionDescriptor()));
};
Connection.prototype.saveTransaction = function(callback, name) {
var request, transaction;
transaction = new Transaction(name);
if (this.config.options.tdsVersion < "7_2") {
return this.execSqlBatch(new Request("SAVE TRAN " + transaction.name, callback));
}
request = new Request(void 0, callback);
return this.makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.savePayload(this.currentTransactionDescriptor()));
};
Connection.prototype.transaction = function(cb, isolationLevel) {
var name, txDone, useSavepoint;
if (typeof cb !== 'function') {
throw new TypeError('`cb` must be a function');
}
useSavepoint = this.inTransaction;
name = "_tedious_" + (crypto.randomBytes(10).toString('hex'));
txDone = (function(_this) {
return function(err, done) {
var args, i, _i, _ref1;
args = [];
for (i = _i = 2, _ref1 = arguments.length; 2 <= _ref1 ? _i <= _ref1 : _i >= _ref1; i = 2 <= _ref1 ? ++_i : --_i) {
args.push(arguments[i]);
}
if (err) {
if (_this.inTransaction) {
return _this.rollbackTransaction(function(txErr) {
args.unshift(txErr || err);
return done.apply(null, args);
}, name);
} else {
return process.nextTick(function() {
args.unshift(err);
return done.apply(null, args);
});
}
} else {
if (useSavepoint) {
return process.nextTick(function() {
args.unshift(null);
return done.apply(null, args);
});
} else {
return _this.commitTransaction(function(txErr) {
args.unshift(txErr);
return done.apply(null, args);
}, name);
}
}
};
})(this);
if (useSavepoint) {
return this.saveTransaction((function(_this) {
return function(err) {
if (err) {
return cb(err);
}
if (isolationLevel) {
return _this.execSqlBatch(new Request("SET transaction isolation level " + (_this.getIsolationLevelText(isolationLevel)), function(err) {
return cb(err, txDone);
}));
} else {
return cb(null, txDone);
}
};
})(this), name);
} else {
return this.beginTransaction(function(err) {
if (err) {
return cb(err);
}
return cb(null, txDone);
}, name, isolationLevel);
}
};
Connection.prototype.makeRequest = function(request, packetType, payload) {
var message;
if (this.state !== this.STATE.LOGGED_IN) {
message = "Requests can only be made in the " + this.STATE.LOGGED_IN.name + " state, not the " + this.state.name + " state";
this.debug.log(message);
return request.callback(RequestError(message, 'EINVALIDSTATE'));
} else {
this.request = request;
this.request.rowCount = 0;
this.request.rows = [];
this.request.rst = [];
this.createRequestTimer();
this.messageIo.sendMessage(packetType, payload.data, this.resetConnectionOnNextRequest);
this.resetConnectionOnNextRequest = false;
this.debug.payload(function() {
return payload.toString(' ');
});
return this.transitionTo(this.STATE.SENT_CLIENT_REQUEST);
}
};
Connection.prototype.cancel = function() {
var message;
if (this.state !== this.STATE.SENT_CLIENT_REQUEST) {
message = "Requests can only be canceled in the " + this.STATE.SENT_CLIENT_REQUEST.name + " state, not the " + this.state.name + " state";
this.debug.log(message);
return false;
} else {
this.request.canceled = true;
this.messageIo.sendMessage(TYPE.ATTENTION);
this.transitionTo(this.STATE.SENT_ATTENTION);
return true;
}
};
Connection.prototype.reset = function(callback) {
var request;
request = new Request(this.getInitialSql(), function(err, rowCount, rows) {
return callback(err);
});
this.resetConnectionOnNextRequest = true;
return this.execSqlBatch(request);
};
Connection.prototype.currentTransactionDescriptor = function() {
return this.transactionDescriptors[this.transactionDescriptors.length - 1];
};
Connection.prototype.getIsolationLevelText = function(isolationLevel) {
switch (isolationLevel) {
case ISOLATION_LEVEL.READ_UNCOMMITTED:
return 'read uncommitted';
case ISOLATION_LEVEL.REPEATABLE_READ:
return 'repeatable read';
case ISOLATION_LEVEL.SERIALIZABLE:
return 'serializable';
case ISOLATION_LEVEL.SNAPSHOT:
return 'snapshot';
default:
return 'read committed';
}
};
return Connection;
})(EventEmitter);
module.exports = Connection;
| erkankoc1221647/MyGrade | node_modules/tedious/lib/connection.js | JavaScript | apache-2.0 | 43,286 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
(function () {
var module = angular.module('pnc.milestone');
module.directive('versionUnique',['$q','versionFactory',
function ($q, versionFactory) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$asyncValidators.unique = function (modelValue, viewValue) {
var deferred = $q.defer(),
milestoneVersion = modelValue || viewValue,
productVersionId = attrs.productVersionId,
productVersion = attrs.productVersion;
if (milestoneVersion && productVersionId && productVersion) {
versionFactory.checkUniqueValue(productVersionId, milestoneVersion, productVersion)
.then(function (unique) {
if (unique) {
deferred.resolve();
}
else {
deferred.reject();
}
});
}
else {
deferred.resolve();
}
return deferred.promise;
};
}
};
}
]);
}());
| ruhan1/pnc | ui/app/milestone/directives/unqiue-version.js | JavaScript | apache-2.0 | 2,086 |
import objstr from 'obj-str';
import * as Preact from '#preact';
import {useCallback} from '#preact';
import {propName} from '#preact/utils';
import {useStyles} from './component.jss';
/**
* @param {!BentoBaseCarouselDef.ArrowProps} props
* @return {PreactDef.Renderable}
*/
export function Arrow({
advance,
as: Comp = DefaultArrow,
by,
disabled,
outsetArrows,
rtl,
}) {
const classes = useStyles();
const onClick = useCallback(() => {
if (!disabled) {
advance();
}
}, [advance, disabled]);
return (
<Comp
aria-disabled={String(!!disabled)}
by={by}
class={objstr({
[classes.arrow]: true,
[classes.arrowDisabled]: disabled,
[classes.arrowPrev]: by < 0,
[classes.arrowNext]: by > 0,
[classes.outsetArrow]: outsetArrows,
[classes.insetArrow]: !outsetArrows,
[classes.rtl]: rtl,
[classes.ltr]: !rtl,
})}
disabled={disabled}
onClick={onClick}
outsetArrows={outsetArrows}
rtl={rtl.toString()}
/>
);
}
/**
* @param {!BentoBaseCarouselDef.ArrowProps} props
* @return {PreactDef.Renderable}
*/
function DefaultArrow({
'aria-disabled': ariaDisabled,
by,
disabled,
onClick,
[propName('class')]: className,
}) {
const classes = useStyles();
return (
<div class={className}>
<button
aria-disabled={ariaDisabled}
aria-label={
by < 0 ? 'Previous item in carousel' : 'Next item in carousel'
}
class={classes.defaultArrowButton}
disabled={disabled}
onClick={onClick}
>
<div class={`${classes.arrowBaseStyle} ${classes.arrowFrosting}`}></div>
<div class={`${classes.arrowBaseStyle} ${classes.arrowBackdrop}`}></div>
<div
class={`${classes.arrowBaseStyle} ${classes.arrowBackground}`}
></div>
<svg class={classes.arrowIcon} viewBox="0 0 24 24">
<path
d={
by < 0 ? 'M14,7.4 L9.4,12 L14,16.6' : 'M10,7.4 L14.6,12 L10,16.6'
}
fill="none"
stroke-width="2px"
stroke-linejoin="round"
stroke-linecap="round"
/>
</svg>
</button>
</div>
);
}
| ampproject/amphtml | src/bento/components/bento-base-carousel/1.0/arrow.js | JavaScript | apache-2.0 | 2,244 |
//// [newTargetNarrowing.ts]
function foo(x: true) { }
function f() {
if (new.target.marked === true) {
foo(new.target.marked);
}
}
f.marked = true;
//// [newTargetNarrowing.js]
"use strict";
function foo(x) { }
function f() {
if (new.target.marked === true) {
foo(new.target.marked);
}
}
f.marked = true;
| Microsoft/TypeScript | tests/baselines/reference/newTargetNarrowing.js | JavaScript | apache-2.0 | 346 |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
'use strict';
exports.ManagementLockClient = require('./lock/managementLockClient');
exports.FeatureClient = require('./feature/featureClient');
exports.SubscriptionClient = require('./subscription/subscriptionClient');
exports.ResourceManagementClient = require('./resource/resourceManagementClient');
exports.PolicyClient = require('./policy/policyClient');
exports.ManagementLinkClient = require('./link/managementLinkClient');
exports.ManagementGroupsClient = require('./management/managementGroupsClient');
exports = module.exports; | xingwu1/azure-sdk-for-node | lib/services/resourceManagement/lib/resource.js | JavaScript | apache-2.0 | 1,167 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.