code
stringlengths 2
1.05M
|
---|
version https://git-lfs.github.com/spec/v1
oid sha256:ced03d673daaf62a712c8b067fe1a211aa8febe60802a13eb96d76d81b82eed7
size 779
|
define([
'backbone',
'underscore',
'find/app/util/model-any-changed-attribute-listener',
'find/app/util/topic-map-view',
'i18n!find/nls/bundle',
'find/app/configuration',
'text!find/templates/app/page/search/results/entity-topic-map-view.html',
'text!find/templates/app/page/loading-spinner.html',
'iCheck',
'slider/bootstrap-slider'
], function(Backbone, _, addChangeListener, TopicMapView, i18n, configuration, template, loadingTemplate) {
'use strict';
var loadingHtml = _.template(loadingTemplate)({i18n: i18n, large: true});
/**
* @readonly
* @enum {String}
*/
var ViewState = {
LOADING: 'LOADING',
ERROR: 'ERROR',
EMPTY: 'EMPTY',
MAP: 'MAP'
};
var Type = {
QUERY: 'QUERY',
COMPARISON: 'COMPARISON'
};
var CLUSTER_MODE = 'docsWithPhrase';
return Backbone.View.extend({
template: _.template(template),
events: {
'slideStop .speed-slider': function(event) {
var maxResults = event.value;
this.model.set('maxResults', maxResults);
}
},
initialize: function(options) {
this.entityCollection = options.entityCollection;
this.queryModel = options.queryModel;
this.type = options.type;
this.topicMap = new TopicMapView({
clickHandler: options.clickHandler
});
var viewState;
if (this.entityCollection.currentRequest) {
viewState = ViewState.LOADING;
} else {
viewState = this.entityCollection.isEmpty() ? ViewState.EMPTY : ViewState.MAP;
}
this.viewModel = new Backbone.Model({
state: viewState
});
this.model = new Backbone.Model({
maxCount: 10
});
this.listenTo(this.model, 'change:maxResults', this.fetchRelatedConcepts);
this.listenTo(this.entityCollection, 'sync', function() {
this.viewModel.set('state', this.entityCollection.isEmpty() ? ViewState.EMPTY : ViewState.MAP);
this.updateTopicMapData();
this.update();
});
this.listenTo(this.entityCollection, 'request', function() {
this.viewModel.set('state', ViewState.LOADING);
});
this.listenTo(this.entityCollection, 'error', function(collection, xhr) {
// Status of zero means the request has been aborted
this.viewModel.set('state', xhr.status === 0 ? ViewState.LOADING : ViewState.ERROR);
});
this.listenTo(this.viewModel, 'change', this.updateViewState);
this.updateTopicMapData();
},
update: function() {
// If the view is not visible, update will be called again if the user switches to this tab
if (this.$el.is(':visible')) {
this.topicMap.draw();
}
},
updateTopicMapData: function() {
var data = _.chain(this.entityCollection.groupBy('cluster'))
// Order the concepts in each cluster
.map(function (cluster) {
return _.sortBy(cluster, function (model) {
return -model.get(CLUSTER_MODE);
});
})
// For each related concept give the name and size
.map(function(cluster) {
return cluster.map(function (model) {
return {name: model.get('text'), size: model.get(CLUSTER_MODE)};
})
})
// Give each cluster a name (first concept in list), total size and add all concepts to the children attribute to create the topic map double level
.map(function(cluster) {
var size = _.chain(cluster)
.pluck('size')
.reduce(function(a,b) {return a + b;})
.value();
return {
name: cluster[0].name,
size: size,
children: cluster
};
})
.sortBy(function(clusterNode) {
return -clusterNode.size;
})
.value();
this.topicMap.setData(data);
},
updateViewState: function() {
var state = this.viewModel.get('state');
this.topicMap.$el.toggleClass('hide', state !== ViewState.MAP);
this.$('.entity-topic-map-error').toggleClass('hide', state !== ViewState.ERROR);
this.$('.entity-topic-map-empty').toggleClass('hide', state !== ViewState.EMPTY);
this.$('.entity-topic-map-loading').toggleClass('hide', state !== ViewState.LOADING);
},
fetchRelatedConcepts: function() {
var data;
if (this.type === Type.COMPARISON) {
data = {
queryText: '*',
maxResults: this.model.get('maxResults'),
databases: this.queryModel.get('indexes'),
stateTokens: this.queryModel.get('stateMatchIds')
};
} else if (this.queryModel.get('queryText') && this.queryModel.get('indexes').length !== 0) {
data = {
databases: this.queryModel.get('indexes'),
queryText: this.queryModel.get('queryText'),
fieldText: this.queryModel.get('fieldText'),
minDate: this.queryModel.getIsoDate('minDate'),
maxDate: this.queryModel.getIsoDate('maxDate'),
minScore: this.queryModel.get('minScore'),
stateTokens: this.queryModel.get('stateMatchIds'),
maxResults: this.model.get('maxResults')
};
}
if (data) {
this.entityCollection.fetch({data: data});
}
},
render: function() {
this.$el.html(this.template({
i18n: i18n,
loadingHtml: loadingHtml,
cid: this.cid
}));
this.$('.speed-slider')
.slider({
id: this.cid + '-speed-slider',
min: 50,
max: configuration().topicMapMaxResults,
value: 300
});
this.topicMap.setElement(this.$('.entity-topic-map')).render();
this.update();
this.updateViewState();
}
});
});
|
var searchData=
[
['esp_2dnow_20apis',['ESP-NOW APIs',['../group__ESPNow__APIs.html',1,'']]]
];
|
import Component from '@ember/component';
import { setProperties, getProperties, get } from '@ember/object';
/**
* `donation-goal-edit` used to edit new and existing donation goals
*
* ## default usage
*
* ```handlebars
* {{donation-goal-edit
* canCancel=externalCancellableFlag
* cancel=(action externalCancelHandler donationGoal)
* donationGoal = donationGoal
* save=(action externalSaveHandler donationGoal)}}
*
* Used as above, the `externalSaveHandler` function will receive a call with the actual
* `donationGoal` model as the first argument, and the properties set via the
* component as the second argument.
*
* Similarly, the `externalCancelHandler` function will recieve a call with the
* `donationGoal` as the first and only argument.
*
* @class donation-goal-edit
* @module Component
* @extends Ember.Component
*/
export default Component.extend({
classNames: ['donation-goal-edit'],
/**
* Indicates if "cancel" button should render.
*
* Cancel button should only render if one of two cases
* - the record is already persisted and we are simply editing it
* - the record is new, but there are other persisted records, so cancelling this one
* does not mean there will be no persisted records at all
*
* @property canCancel
* @type {Boolean}
*/
canCancel: false,
init() {
this._super(...arguments);
let donationGoal = get(this, 'donationGoal');
let { amount, description } = getProperties(donationGoal, 'amount', 'description');
setProperties(this, { amount, description });
}
});
|
'use strict';
var _ = require('underscore'),
expect = require('expect.js'),
sinon = require('sinon'),
proxyquire = require('proxyquire').noCallThru();
describe('Projcts collection `_archiveUnarchive` method', function() {
var getMocks = function(params) {
return {
projects: {
get: sinon.stub().returns(params.getResult),
_getProjectPath: sinon.stub().returns(
params.getProjectPathResult
),
unload: sinon.stub().callsArgWithAsync(1, null),
load: sinon.stub().callsArgWithAsync(1, null)
},
fs: {
rename: sinon.stub().callsArgWithAsync(
2, params.renameError
)
}
};
};
var getProjectsCollection = function(mocks) {
var ProjectsCollection = proxyquire(
'../../../lib/project', _(mocks).pick('fs')
).ProjectsCollection;
projects = new ProjectsCollection({});
_(projects).extend(mocks.projects);
return projects;
};
var projects, mocks;
var checkProjectsGetCall = function(expected) {
expected.called = _(expected).has('called') ? expected.called : true;
if (expected.called) {
it('should call `get` with project name', function() {
expect(mocks.projects.get.calledOnce).equal(true);
var args = mocks.projects.get.getCall(0).args;
expect(args[0]).eql(expected.projectName);
});
} else {
it('should not call `get`', function() {
expect(mocks.projects.get.called).equal(false);
});
}
};
var checkProjectsUnloadCall = function(expected) {
expected.called = _(expected).has('called') ? expected.called : true;
if (expected.called) {
it('should call `unload` with project name', function() {
expect(mocks.projects.unload.calledOnce).equal(true);
var args = mocks.projects.unload.getCall(0).args;
expect(args[0]).eql({name: expected.projectName});
});
} else {
it('should not call `unload`', function() {
expect(mocks.projects.unload.called).equal(false);
});
}
};
var checkProjectsGetPathCall = function(expected) {
expected.called = _(expected).has('called') ? expected.called : true;
if (expected.called) {
it(
'should call `_getProjectPath` with project name ' +
'and archived ' + String(expected.archived),
function() {
expect(mocks.projects._getProjectPath.calledOnce).equal(true);
var args = mocks.projects._getProjectPath.getCall(0).args;
expect(args[0]).eql({
name: expected.projectName,
archived: expected.archived
});
}
);
} else {
it('should not call `_getProjectPath`', function() {
expect(mocks.projects._getProjectPath.called).equal(false);
});
}
};
var checkFsRenameCall = function(expected) {
expected.called = _(expected).has('called') ? expected.called : true;
if (expected.called) {
it('should call `fs.rename` with current and new path', function() {
expect(mocks.fs.rename.calledOnce).equal(true);
var args = mocks.fs.rename.getCall(0).args;
expect(args[0]).eql(expected.projectPath);
expect(args[1]).eql(expected.newProjectPath);
});
} else {
it('should not call `fs.rename`', function() {
expect(mocks.fs.rename.called).equal(false);
});
}
};
var checkProjectsLoadCall = function(expected) {
expected.called = _(expected).has('called') ? expected.called : true;
if (expected.called) {
it(
'should call `load` with project name and archived ' +
String(expected.archived),
function() {
expect(mocks.projects.load.calledOnce).equal(true);
var args = mocks.projects.load.getCall(0).args;
expect(args[0]).eql({
name: expected.projectName,
archived: expected.archived
});
}
);
} else {
it('should not call `load`', function() {
expect(mocks.projects.load.called).equal(false);
});
}
};
describe('with archive action and suitable params', function() {
var projectName = 'test_project',
projectPath = '/some/path',
project = {name: projectName, dir: projectPath},
newProjectPath = '/archived/project/path';
before(function() {
mocks = getMocks({
getResult: project,
getProjectPathResult: newProjectPath
});
projects = getProjectsCollection(mocks);
});
it('should be called without errors', function(done) {
projects._archiveUnarchive({
name: projectName,
action: 'archive'
}, done);
});
checkProjectsGetCall({projectName: projectName});
checkProjectsUnloadCall({projectName: projectName});
checkProjectsGetPathCall({projectName: projectName, archived: true});
checkFsRenameCall({
projectPath: projectPath,
newProjectPath: newProjectPath
});
checkProjectsLoadCall({projectName: projectName, archived: true});
});
describe('with unarchive action and suitable params', function() {
var projectName = 'test_project',
projectPath = '/archived/project/path',
project = {name: projectName, dir: projectPath, archived: true},
newProjectPath = '/some/path';
before(function() {
mocks = getMocks({
getResult: project,
getProjectPathResult: newProjectPath
});
projects = getProjectsCollection(mocks);
});
it('should be called without errors', function(done) {
projects._archiveUnarchive({
name: projectName,
action: 'unarchive'
}, done);
});
checkProjectsGetCall({projectName: projectName});
checkProjectsUnloadCall({projectName: projectName});
checkProjectsGetPathCall({projectName: projectName, archived: false});
checkFsRenameCall({
projectPath: projectPath,
newProjectPath: newProjectPath
});
checkProjectsLoadCall({projectName: projectName, archived: false});
});
describe('with unknown action', function() {
var projectName = 'test_project',
projectPath = '/some/path',
project = {name: projectName, dir: projectPath},
newProjectPath = '/archived/project/path',
action = 'doIt';
before(function() {
mocks = getMocks({
getResult: project,
getProjectPathResult: newProjectPath
});
projects = getProjectsCollection(mocks);
});
it('should be called with error', function(done) {
projects._archiveUnarchive({
name: projectName,
action: action
}, function(err) {
expect(err).an(Error);
expect(err.message).eql('Unknown action: ' + action);
done();
});
});
checkProjectsGetCall({projectName: projectName});
checkProjectsUnloadCall({called: false});
checkProjectsGetPathCall({called: false});
checkFsRenameCall({called: false});
checkProjectsLoadCall({called: false});
});
describe('when project name is not set', function() {
var projectName = null,
projectPath = '/some/path',
project = {name: projectName, dir: projectPath},
newProjectPath = '/archived/project/path';
before(function() {
mocks = getMocks({
getResult: project,
getProjectPathResult: newProjectPath
});
projects = getProjectsCollection(mocks);
});
it('should be called with error', function(done) {
projects._archiveUnarchive({
name: projectName,
action: 'archive'
}, function(err) {
expect(err).an(Error);
expect(err.message).eql('Project name is required');
done();
});
});
checkProjectsGetCall({called: false});
checkProjectsUnloadCall({called: false});
checkProjectsGetPathCall({called: false});
checkFsRenameCall({called: false});
checkProjectsLoadCall({called: false});
});
describe('when project is not loaded', function() {
var projectName = 'test_project',
projectPath = '/some/path',
project = null,
newProjectPath = '/archived/project/path',
action = 'archive';
before(function() {
mocks = getMocks({
getResult: project,
getProjectPathResult: newProjectPath
});
projects = getProjectsCollection(mocks);
});
it('should be called with error', function(done) {
projects._archiveUnarchive({
name: projectName,
action: action
}, function(err) {
expect(err).an(Error);
expect(err.message).eql(
'Can`t find project "' + projectName + '" for ' + action
);
done();
});
});
checkProjectsGetCall({projectName: projectName});
checkProjectsUnloadCall({called: false});
checkProjectsGetPathCall({called: false});
checkFsRenameCall({called: false});
checkProjectsLoadCall({called: false});
});
describe('when archive already archived project', function() {
var projectName = 'test_project',
projectPath = '/some/path',
project = {name: projectName, dir: projectPath, archived: true},
newProjectPath = '/archived/project/path',
action = 'archive';
before(function() {
mocks = getMocks({
getResult: project,
getProjectPathResult: newProjectPath
});
projects = getProjectsCollection(mocks);
});
it('should be called with error', function(done) {
projects._archiveUnarchive({
name: projectName,
action: action
}, function(err) {
expect(err).an(Error);
expect(err.message).eql(
'Project "' + projectName + '" already archived'
);
done();
});
});
checkProjectsGetCall({projectName: projectName});
checkProjectsUnloadCall({called: false});
checkProjectsGetPathCall({called: false});
checkFsRenameCall({called: false});
checkProjectsLoadCall({called: false});
});
describe('when unarchive not archived project', function() {
var projectName = 'test_project',
projectPath = '/some/path',
project = {name: projectName, dir: projectPath},
newProjectPath = '/archived/project/path',
action = 'unarchive';
before(function() {
mocks = getMocks({
getResult: project,
getProjectPathResult: newProjectPath
});
projects = getProjectsCollection(mocks);
});
it('should be called with error', function(done) {
projects._archiveUnarchive({
name: projectName,
action: action
}, function(err) {
expect(err).an(Error);
expect(err.message).eql(
'Project "' + projectName + '" is not archived'
);
done();
});
});
checkProjectsGetCall({projectName: projectName});
checkProjectsUnloadCall({called: false});
checkProjectsGetPathCall({called: false});
checkFsRenameCall({called: false});
checkProjectsLoadCall({called: false});
});
});
|
import init from "./init";
class TestPluginClass {
constructor(element, options, name) {
this.name = name;
this.element = element;
this.options = options;
}
}
describe("`init` helper", () => {
let TestPlugin = {};
beforeEach(() => {
document.body.innerHTML = `<div class="test test_1">test</div>
<div class="test test_2">test</div>
<div class="test test_3">test</div>`;
const name = "test-plugin";
TestPlugin = init(TestPluginClass, name);
});
test("should return new plugin instance", () => {
const plugin = TestPlugin();
expect(plugin).toHaveLength(1);
expect(plugin[0]).toBeInstanceOf(TestPluginClass);
});
test("when selector not set", () => {
const plugin = TestPlugin();
expect(plugin).toHaveLength(1);
expect(plugin[0].element).toEqual(document.body);
});
describe("when selector type", () => {
test("string", () => {
const selector = ".test";
const plugin = TestPlugin(selector);
expect(plugin).toHaveLength(3);
expect(plugin[0].element.className).toEqual("test test_1");
expect(plugin[1].element.className).toEqual("test test_2");
expect(plugin[2].element.className).toEqual("test test_3");
});
test("array of string", () => {
const plugin = TestPlugin(["", ".test_1", ".test_2"]);
expect(plugin).toHaveLength(2);
expect(plugin[0].element.className).toEqual("test test_1");
expect(plugin[1].element.className).toEqual("test test_2");
});
test("array of HTMLElements", () => {
const test1 = document.querySelector(".test_1");
const test2 = document.querySelector(".test_2");
const plugin = TestPlugin([test1, test2]);
expect(plugin).toHaveLength(2);
expect(plugin[0].element).toEqual(test1);
expect(plugin[1].element).toEqual(test2);
// expect(plugin[2].element).toEqual(document.body);
});
test("HTMLElement", () => {
const pluginElement = document.querySelector(".test");
const plugin = TestPlugin(pluginElement);
expect(plugin[0].element).toEqual(pluginElement);
});
});
describe("when selector is", () => {
test("empty string", () => {
const plugin = TestPlugin("");
expect(plugin).toEqual([]);
});
test("empty array", () => {
const plugin = TestPlugin([]);
expect(plugin).toEqual([]);
});
test("array of empty strings", () => {
const plugin = TestPlugin(["", ""]);
expect(plugin).toEqual([]);
});
test("undefined", () => {
const plugin = TestPlugin(undefined);
expect(plugin[0].element).toEqual(document.body);
});
test("null", () => {
const plugin = TestPlugin(null);
expect(plugin[0].element).toEqual(document.body);
});
});
});
|
// For a test author to enable code covergage instrumentation,
// they make a single call
var ass = require('ass').enable();
var cp = require('child_process'),
should = require('should'),
fs = require('fs'),
request = require('request');
describe('a test', function() {
var kid, url;
it('server should start up', function(done) {
kid = cp.fork("./stub.js", [], { stdio: 'inherit' });
kid.on('message', function(msg) {
(msg).should.be.type('object');
(msg).should.have.property('url');
url = msg.url;
done && done(null);
done = null;
});
kid.on('exit', function() {
done && done("unexpected exit");
done = null;
});
});
it('server should respond to hello', function(done) {
request(url + '/hello', function(error, response, body) {
should.not.exist(error);
(response.statusCode).should.equal(200);
(body).should.equal('Hello World');
done();
});
});
it('server should shut down', function(done) {
kid.kill();
kid.on('exit', function(code, signal) {
var err = (code !== 0) ? "non-zero exit code: " + code : null;
done(err);
});
});
it('code coverage should exceed 90%', function(done) {
ass.report('json', function(err, r) {
(r.percent).should.be.above(90.0);
done(err);
});
});
it('coverage.html should be written', function(done) {
ass.report('html', function(err, r) {
try {
fs.writeFileSync('coverage.html', r);
} catch (e) {
if (!err) err = e;
}
done(err);
});
});
it('coverage.svg should be written', function(done) {
ass.report('svg', function(err, r) {
try {
fs.writeFileSync('coverage.svg', r);
} catch (e) {
if (!err) err = e;
}
done(err);
});
});
});
|
// This is the RequireJS configuration that is used by all examples.
//
// Curran Kelleher November 2014
require.config({
paths: {
// Use "modelContrib/someModule" as the module name to load
// reusable modules provided by modelContrib.
modelContrib: "../../modules",
d3: "../../bower_components/d3/d3.min",
// Required for choropleth maps.
topojson: "../../bower_components/topojson/topojson",
model: "../../bower_components/model/dist/model",
lodash: "../../bower_components/lodash/dist/lodash",
crossfilter: "../../bower_components/crossfilter/crossfilter",
sql: "../../bower_components/sql.js/js/sql"
},
shim: {
crossfilter: { exports: "crossfilter" },
sql: { exports: "SQL" }
}
});
|
const Boom = require('@hapi/boom')
const Hoek = require('@hapi/hoek')
exports.register = function HapiRateLimit (plugin, _options) {
// Apply default options
const options = Hoek.applyToDefaults(defaults, _options)
// Create limiter instance
// const limiter = new RedisRateLimit(options)
let Driver = options.driver
if (typeof Driver === 'string') {
Driver = require('./providers/' + Driver)
}
const limiter = new Driver(options)
const handleLimits = async (request, h) => {
const route = request.route
// Get route-specific limits
let routeLimit = route.settings.plugins && route.settings.plugins.ratelimit
// Try to apply global if no options
if (options.global) {
routeLimit = Object.assign({}, options.global, routeLimit)
}
// If no limits on route
if (!routeLimit) {
return h.continue
}
// Check limits on route
const rateLimit = await limiter.check(
options.namespace + ':' + realIP(request) + ':' + (request.route.id || request.route.path),
routeLimit.limit,
routeLimit.duration
)
request.plugins.ratelimit = {
limit: rateLimit.limit,
remaining: rateLimit.remaining - 1,
reset: rateLimit.reset
}
if (rateLimit.remaining > 0) {
return h.continue
}
const error = Boom.tooManyRequests('RATE_LIMIT_EXCEEDED')
setHeaders(error.output.headers, request.plugins.ratelimit, options.XHeaders)
error.reformat()
return error
}
const responseLimits = (request, h) => {
if (request.plugins.ratelimit) {
const response = request.response
if (!response.isBoom) {
setHeaders(response.headers, request.plugins.ratelimit, options.XHeaders)
}
}
return h.continue
}
// Ext
plugin.ext('onPreAuth', handleLimits)
plugin.ext('onPostHandler', responseLimits)
}
// Set rate-limit headers
function setHeaders (headers, ratelimit, XHeaders = false) {
if (XHeaders) {
headers['X-Rate-Limit-Limit'] = ratelimit.limit
headers['X-Rate-Limit-Remaining'] = ratelimit.remaining > 0 ? ratelimit.remaining : 0
headers['X-Rate-Limit-Reset'] = ratelimit.reset
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
headers['Retry-After'] = Math.ceil(ratelimit.reset / 1000)
}
// Default options
const defaults = {
namespace: 'ratelimit',
driver: 'memory',
XHeaders: false,
global: {
limit: 60,
duration: 60000
}
}
function realIP (request) {
return request.ip || request.headers['x-real-ip'] || request.headers['x-forwarded-for'] || request.info['remoteAddress']
}
exports.pkg = require('../package.json')
exports.once = true
exports.configKey = 'ratelimit'
|
// read this article for more info on what's going on here
// http://bahmutov.calepin.co/hooking-into-node-loader-for-fun-and-profit.html
// based on https://github.com/bahmutov/node-hook
// based on https://github.com/gotwarlost/istanbul/blob/master/lib/hook.js
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var fs = require('fs')
var Module = require('module')
var serialize = require('./serialize-javascript')
var originalLoaders = {}
var verify =
{
extension: function (str)
{
if (typeof str !== 'string')
{
throw new Error('expected string extension, have ' + str);
}
if (str[0] !== '.')
{
throw new Error('Extension should start with dot, for example .js, have ' + str);
}
},
transform: function (fn)
{
if (typeof fn !== 'function')
{
throw new Error('Transform should be a function, have ' + fn);
}
}
}
// function fallback()
// {
// module._compile(fs.readFileSync(filename), filename)
// }
function hook(extension, transform, options)
{
options = options || {}
if (typeof extension === 'function' && typeof transform === 'undefined')
{
transform = extension
extension = '.js'
}
if (options.verbose)
{
console.log('hooking transform', transform.name, 'for', extension)
}
verify.extension(extension)
verify.transform(transform)
originalLoaders[extension] = Module._extensions[extension]
Module._extensions[extension] = function (module, filename)
{
if (options.verbose)
{
console.log('transforming', filename)
}
// var source = fs.readFileSync(filename, 'utf8')
var result = transform(filename, function fallback()
{
originalLoaders[extension](module, filename)
})
result = serialize(result)
module._compile('module.exports = ' + result, filename)
}
if (options.verbose)
{
console.log('hooked function')
}
}
function unhook(extension)
{
if (typeof extension === 'undefined')
{
extension = '.js'
}
verify.extension(extension)
Module._extensions[extension] = originalLoaders[extension]
}
module.exports =
{
hook: hook,
unhook: unhook
}
|
function ColorPickerController($scope) {
$scope.isConfigured = $scope.model.config && $scope.model.config.items && _.keys($scope.model.config.items).length > 0;
if ($scope.isConfigured) {
for (var key in $scope.model.config.items) {
if (!$scope.model.config.items[key].hasOwnProperty("value"))
$scope.model.config.items[key] = { value: $scope.model.config.items[key], label: $scope.model.config.items[key] };
}
$scope.model.useLabel = isTrue($scope.model.config.useLabel);
initActiveColor();
}
$scope.toggleItem = function (color) {
var currentColor = $scope.model.value.hasOwnProperty("value")
? $scope.model.value.value
: $scope.model.value;
var newColor;
if (currentColor === color.value) {
// deselect
$scope.model.value = $scope.model.useLabel ? { value: "", label: "" } : "";
newColor = "";
}
else {
// select
$scope.model.value = $scope.model.useLabel ? { value: color.value, label: color.label } : color.value;
newColor = color.value;
}
// this is required to re-validate
$scope.propertyForm.modelValue.$setViewValue(newColor);
};
// Method required by the valPropertyValidator directive (returns true if the property editor has at least one color selected)
$scope.validateMandatory = function () {
var isValid = !$scope.model.validation.mandatory || (
$scope.model.value != null
&& $scope.model.value != ""
&& (!$scope.model.value.hasOwnProperty("value") || $scope.model.value.value !== "")
);
return {
isValid: isValid,
errorMsg: "Value cannot be empty",
errorKey: "required"
};
}
$scope.isConfigured = $scope.model.config && $scope.model.config.items && _.keys($scope.model.config.items).length > 0;
// A color is active if it matches the value and label of the model.
// If the model doesn't store the label, ignore the label during the comparison.
$scope.isActiveColor = function (color) {
// no value
if (!$scope.model.value)
return false;
// Complex color (value and label)?
if (!$scope.model.value.hasOwnProperty("value"))
return $scope.model.value === color.value;
return $scope.model.value.value === color.value && $scope.model.value.label === color.label;
};
// Finds the color best matching the model's color,
// and sets the model color to that one. This is useful when
// either the value or label was changed on the data type.
function initActiveColor() {
// no value
if (!$scope.model.value)
return;
// Complex color (value and label)?
if (!$scope.model.value.hasOwnProperty("value"))
return;
var modelColor = $scope.model.value.value;
var modelLabel = $scope.model.value.label;
// Check for a full match or partial match.
var foundItem = null;
// Look for a fully matching color.
for (var key in $scope.model.config.items) {
var item = $scope.model.config.items[key];
if (item.value == modelColor && item.label == modelLabel) {
foundItem = item;
break;
}
}
// Look for a color with a matching value.
if (!foundItem) {
for (var key in $scope.model.config.items) {
var item = $scope.model.config.items[key];
if (item.value == modelColor) {
foundItem = item;
break;
}
}
}
// Look for a color with a matching label.
if (!foundItem) {
for (var key in $scope.model.config.items) {
var item = $scope.model.config.items[key];
if (item.label == modelLabel) {
foundItem = item;
break;
}
}
}
// If a match was found, set it as the active color.
if (foundItem) {
$scope.model.value.value = foundItem.value;
$scope.model.value.label = foundItem.label;
}
}
// figures out if a value is trueish enough
function isTrue(bool) {
return !!bool && bool !== "0" && angular.lowercase(bool) !== "false";
}
}
angular.module("umbraco").controller("Umbraco.PropertyEditors.ColorPickerController", ColorPickerController);
|
'use strict';
import assign from 'object-assign';
import Constants from '../constants/AppConstants';
import BaseStore from './BaseStore';
class ContainerStore extends BaseStore {
constructor() {
super();
this.subscribe(() => this._registerToActions.bind(this));
this._containers = [];
this._loaded = false;
this._statusMessage = {
status: 0,
message: ''
};
}
get state() {
return {
containers: this._containers,
loaded: this._loaded,
statusMessage: this._statusMessage
};
}
getStateById(id) {
if (id) {
for (let container of this._containers) {
if (container.id === id) {
return {container};
}
}
}
return null;
}
_registerToActions(payload) {
switch (payload.actionType) {
case Constants.GET_CONTAINERS:
this._containers = payload.containers;
this._loaded = true;
break;
case Constants.STOP_ALL_CONTAINERS:
for (let c of this._containers) {
c.isRunning = 0;
}
this._statusMessage.status = 1;
this._statusMessage.message = payload.message;
break;
case Constants.STOP_CONTAINER:
for (let c of this._containers) {
if (c.id === payload.id) {
c.isRunning = 0;
}
}
this._statusMessage.status = payload.status;
this._statusMessage.message = payload.message;
break;
case Constants.START_CONTAINER:
for (let c of this._containers) {
if (c.id === payload.id) {
c.isRunning = 1;
}
}
this._statusMessage.status = payload.status;
this._statusMessage.message = payload.message;
break;
}
this.emitChange();
}
}
export default new ContainerStore();
|
// flow-typed signature: 3350ac60247e5d21911065431eacf53e
// flow-typed version: <<STUB>>/@babel/plugin-proposal-class-properties_v^7.0.0/flow_v0.94.0
/**
* This is an autogenerated libdef stub for:
*
* '@babel/plugin-proposal-class-properties'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module '@babel/plugin-proposal-class-properties' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module '@babel/plugin-proposal-class-properties/lib/index' {
declare module.exports: any;
}
// Filename aliases
declare module '@babel/plugin-proposal-class-properties/lib/index.js' {
declare module.exports: $Exports<'@babel/plugin-proposal-class-properties/lib/index'>;
}
|
function checkBoxesTicked() {
// Get the value of both the line graphs together
var lineGraphsCheckedVal = document.getElementById("norm-line-graphs").checked &&
document.getElementById("cumulative-line-graphs").checked;
// Set the line graph check box to that value
document.getElementById("line-graphs").checked = lineGraphsCheckedVal;
// Get the value of all the check boxes together
var totalCheckedVal = document.getElementById("bar-graphs").checked &&
document.getElementById("pie-charts").checked &&
document.getElementById("line-graphs").checked &&
document.getElementById("scatter-graphs").checked;
// Set the all graphs check box to that value
document.getElementById("all-graphs").checked = totalCheckedVal;
}
function tickAllBoxes() {
// Get the value of the all graphs boolean
var checkVal = document.getElementById("all-graphs").checked;
// Set all the boxes to that value
document.getElementById("bar-graphs").checked = checkVal;
document.getElementById("pie-charts").checked = checkVal;
document.getElementById("line-graphs").checked = checkVal;
document.getElementById("norm-line-graphs").checked = checkVal;
document.getElementById("cumulative-line-graphs").checked = checkVal;
document.getElementById("scatter-graphs").checked = checkVal;
}
function tickLineBoxes() {
// Get the value of the line graph boolean
var checkVal = document.getElementById("line-graphs").checked;
// Set all the line graph types to that value
document.getElementById("norm-line-graphs").checked = checkVal;
document.getElementById("cumulative-line-graphs").checked = checkVal;
}
|
/* eslint-env node */
'use strict';
module.exports = {
name: 'affinity-engine-stage'
};
|
ModuleLoader.require([
], function() {
var inlineEditor2;
module("tinymce.plugins.Lists", {
setupModule: function() {
document.getElementById('view').innerHTML = (
'<textarea id="elm1"></textarea>' +
'<div id="elm2"></div>' +
'<div id="lists">' +
'<ul><li>before</li></ul>' +
'<ul id="elm3"><li>x</li></ul>' +
'<ul><li>after</li></ul>' +
'</div>'
);
QUnit.stop();
function wait() {
if (window.editor && window.inlineEditor && inlineEditor2) {
if (!QUnit.started) {
QUnit.start();
QUnit.started = true;
}
} else {
tinymce.util.Delay.setTimeout(wait, 0);
}
}
tinymce.init({
selector: '#elm1',
plugins: "lists",
add_unload_trigger: false,
skin: false,
indent: false,
schema: 'html5',
entities: 'raw',
valid_elements: 'li[style],ol[style],ul[style],dl,dt,dd,em,strong,span,#p,div,br',
valid_styles: {
'*': 'color,font-size,font-family,background-color,font-weight,font-style,text-decoration,float,margin,margin-top,margin-right,margin-bottom,margin-left,display,position,top,left,list-style-type'
},
disable_nodechange: true,
init_instance_callback: function(ed) {
window.editor = ed;
wait();
}
});
tinymce.init({
selector: '#elm2',
inline: true,
add_unload_trigger: false,
skin: false,
plugins: "lists",
disable_nodechange: true,
init_instance_callback: function(ed) {
window.inlineEditor = ed;
wait();
},
valid_styles: {
'*': 'color,font-size,font-family,background-color,font-weight,font-style,text-decoration,float,margin,margin-top,margin-right,margin-bottom,margin-left,display,position,top,left,list-style-type'
}
});
tinymce.init({
selector: '#elm3',
inline: true,
add_unload_trigger: false,
skin: false,
plugins: "lists",
disable_nodechange: true,
init_instance_callback: function(ed) {
inlineEditor2 = ed;
wait();
},
valid_styles: {
'*': 'color,font-size,font-family,background-color,font-weight,font-style,text-decoration,float,margin,margin-top,margin-right,margin-bottom,margin-left,display,position,top,left,list-style-type'
}
});
},
teardown: function() {
editor.settings.forced_root_block = 'p';
},
teardownModule: function() {
inlineEditor2.remove();
inlineEditor2 = null;
}
});
function trimBrs(html) {
return html.toLowerCase().replace(/<br[^>]*>|[\r\n]+/gi, '');
}
function execCommand(cmd, ui, obj) {
if (editor.editorCommands.hasCustomCommand(cmd)) {
editor.execCommand(cmd, ui, obj);
}
}
test('Apply UL list to single P', function() {
editor.getBody().innerHTML = trimBrs(
'<p>a</p>'
);
editor.focus();
Utils.setSelection('p', 0);
execCommand('InsertUnorderedList');
equal(editor.getContent(), '<ul><li>a</li></ul>');
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Apply UL list to single empty P', function() {
editor.getBody().innerHTML = trimBrs(
'<p><br></p>'
);
editor.focus();
Utils.setSelection('p', 0);
execCommand('InsertUnorderedList');
equal(trimBrs(editor.getContent({format: 'raw'})), '<ul><li></li></ul>');
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Apply UL list to multiple Ps', function() {
editor.getBody().innerHTML = trimBrs(
'<p>a</p>' +
'<p>b</p>' +
'<p>c</p>'
);
editor.focus();
Utils.setSelection('p', 0, 'p:last', 0);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply OL list to single P', function() {
editor.getBody().innerHTML = trimBrs(
'<p>a</p>'
);
editor.focus();
Utils.setSelection('p', 0);
execCommand('InsertOrderedList');
equal(editor.getContent(), '<ol><li>a</li></ol>');
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Apply OL list to single empty P', function() {
editor.getBody().innerHTML = trimBrs(
'<p><br></p>'
);
editor.focus();
Utils.setSelection('p', 0);
execCommand('InsertOrderedList');
equal(trimBrs(editor.getContent({format: 'raw'})), '<ol><li></li></ol>');
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Apply OL list to multiple Ps', function() {
editor.getBody().innerHTML = trimBrs(
'<p>a</p>' +
'<p>b</p>' +
'<p>c</p>'
);
editor.focus();
Utils.setSelection('p', 0, 'p:last', 0);
execCommand('InsertOrderedList');
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply OL to UL list', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li', 0, 'li:last', 0);
execCommand('InsertOrderedList');
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply OL to UL list with collapsed selection', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:nth-child(2)');
execCommand('InsertOrderedList');
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply UL to OL list', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('li', 0, 'li:last', 0);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply UL to OL list collapsed selection', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('li:nth-child(2)');
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply UL to P and merge with adjacent lists', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'</ul>' +
'<p>b</p>' +
'<ul>' +
'<li>c</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('p', 1);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply UL to OL and merge with adjacent lists', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'</ul>' +
'<ol><li>b</li></ol>' +
'<ul>' +
'<li>c</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('ol li', 1);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply OL to P and merge with adjacent lists', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a</li>' +
'</ol>' +
'<p>b</p>' +
'<ol>' +
'<li>c</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('p', 1);
execCommand('InsertOrderedList');
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply OL to UL and merge with adjacent lists', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a</li>' +
'</ol>' +
'<ul><li>b</li></ul>' +
'<ol>' +
'<li>c</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ul li', 1);
execCommand('InsertOrderedList');
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply OL to UL and DO not merge with adjacent lists because styles are different (exec has style)', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a</li>' +
'</ol>' +
'<ul><li>b</li></ul>' +
'<ol>' +
'<li>c</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ul li', 1);
execCommand('InsertOrderedList', null, { 'list-style-type': 'lower-alpha' });
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'</ol>' +
'<ol style="list-style-type: lower-alpha;"><li>b</li></ol>' +
'<ol>' +
'<li>c</li>' +
'</ol>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply OL to P and DO not merge with adjacent lists because styles are different (exec has style)', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a</li>' +
'</ol>' +
'<p>b</p>' +
'<ol>' +
'<li>c</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('p', 1);
execCommand('InsertOrderedList', null, { 'list-style-type': 'lower-alpha' });
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'</ol>' +
'<ol style="list-style-type: lower-alpha;"><li>b</li></ol>' +
'<ol>' +
'<li>c</li>' +
'</ol>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply OL to UL and DO not merge with adjacent lists because styles are different (original has style)', function() {
editor.getBody().innerHTML = trimBrs(
'<ol style="list-style-type: upper-roman;">' +
'<li>a</li>' +
'</ol>' +
'<ul><li>b</li></ul>' +
'<ol style="list-style-type: upper-roman;">' +
'<li>c</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ul li', 1);
execCommand('InsertOrderedList');
equal(editor.getContent(),
'<ol style="list-style-type: upper-roman;">' +
'<li>a</li>' +
'</ol>' +
'<ol><li>b</li></ol>' +
'<ol style="list-style-type: upper-roman;">' +
'<li>c</li>' +
'</ol>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply OL to UL should merge with adjacent lists because styles are the same (both have roman)', function() {
editor.getBody().innerHTML = trimBrs(
'<ol style="list-style-type: upper-roman;">' +
'<li>a</li>' +
'</ol>' +
'<ul><li>b</li></ul>' +
'<ol style="list-style-type: upper-roman;">' +
'<li>c</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ul li', 1);
execCommand('InsertOrderedList', false, { 'list-style-type': 'upper-roman' });
equal(editor.getContent(),
'<ol style="list-style-type: upper-roman;">' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply OL to UL should merge with above list because styles are the same (both have lower-roman), but not below list', function() {
editor.getBody().innerHTML = trimBrs(
'<ol style="list-style-type: lower-roman;">' +
'<li>a</li>' +
'</ol>' +
'<ul><li>b</li></ul>' +
'<ol style="list-style-type: upper-roman;">' +
'<li>c</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ul li', 1);
execCommand('InsertOrderedList', false, { 'list-style-type': 'lower-roman' });
equal(editor.getContent(),
'<ol style="list-style-type: lower-roman;">' +
'<li>a</li>' +
'<li>b</li>' +
'</ol>' +
'<ol style="list-style-type: upper-roman;">' +
'<li>c</li>' +
'</ol>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply OL to UL should merge with below lists because styles are the same (both have roman), but not above list', function() {
editor.getBody().innerHTML = trimBrs(
'<ol style="list-style-type: upper-roman;">' +
'<li>a</li>' +
'</ol>' +
'<ul><li>b</li></ul>' +
'<ol style="list-style-type: lower-roman;">' +
'<li>c</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ul li', 1);
execCommand('InsertOrderedList', false, { 'list-style-type': 'lower-roman' });
equal(editor.getContent(),
'<ol style="list-style-type: upper-roman;">' +
'<li>a</li>' +
'</ol>' +
'<ol style="list-style-type: lower-roman;">' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply UL list to single text line', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = (
'a'
);
editor.focus();
Utils.setSelection('body', 0);
execCommand('InsertUnorderedList');
equal(editor.getContent(), '<ul><li>a</li></ul>');
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Apply UL list to single text line with BR', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = (
'a<br>'
);
editor.focus();
Utils.setSelection('body', 0);
execCommand('InsertUnorderedList');
equal(editor.getContent(), '<ul><li>a</li></ul>');
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Apply UL list to multiple lines separated by BR', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = (
'a<br>' +
'b<br>' +
'c'
);
editor.focus();
editor.execCommand('SelectAll');
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply UL list to multiple lines separated by BR and with trailing BR', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = (
'a<br>' +
'b<br>' +
'c<br>'
);
editor.focus();
editor.execCommand('SelectAll');
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
equal(editor.selection.getStart().nodeName, 'LI');
});
test('Apply UL list to multiple formatted lines separated by BR', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = (
'<strong>a</strong><br>' +
'<span>b</span><br>' +
'<em>c</em>'
);
editor.focus();
Utils.setSelection('strong', 0, 'em', 0);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li><strong>a</strong></li>' +
'<li><span>b</span></li>' +
'<li><em>c</em></li>' +
'</ul>'
);
equal(editor.selection.getStart().nodeName, 'STRONG');
equal(editor.selection.getEnd().nodeName, tinymce.Env.ie && tinymce.Env.ie < 9 ? 'LI' : 'EM'); // Old IE will return the end LI not a big deal
});
// Ignore on IE 7, 8 this is a known bug not worth fixing
if (!tinymce.Env.ie || tinymce.Env.ie > 8) {
test('Apply UL list to br line and text block line', function() {
editor.settings.forced_root_block = false;
editor.setContent(
'a' +
'<p>b</p>'
);
var rng = editor.dom.createRng();
rng.setStart(editor.getBody().firstChild, 0);
rng.setEnd(editor.getBody().lastChild.firstChild, 1);
editor.selection.setRng(rng);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>'
);
equal(editor.selection.getStart().nodeName, 'LI');
equal(editor.selection.getEnd().nodeName, 'LI');
});
}
test('Apply UL list to text block line and br line', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = (
'<p>a</p>' +
'b'
);
editor.focus();
var rng = editor.dom.createRng();
rng.setStart(editor.getBody().firstChild.firstChild, 0);
rng.setEnd(editor.getBody().lastChild, 1);
editor.selection.setRng(rng);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>'
);
equal(editor.selection.getStart().nodeName, 'LI');
equal(editor.selection.getEnd().nodeName, 'LI');
});
test('Apply UL list to all BR lines (SelectAll)', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = (
'a<br>' +
'b<br>' +
'c<br>'
);
editor.focus();
editor.execCommand('SelectAll');
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
});
test('Apply UL list to all P lines (SelectAll)', function() {
editor.getBody().innerHTML = (
'<p>a</p>' +
'<p>b</p>' +
'<p>c</p>'
);
editor.focus();
editor.execCommand('SelectAll');
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
});
// Remove
test('Remove UL at single LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li');
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<p>a</p>'
);
equal(editor.selection.getStart().nodeName, 'P');
});
test('Remove UL at start LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li');
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<p>a</p>' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
equal(editor.selection.getStart().nodeName, 'P');
});
test('Remove UL at start empty LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li><br></li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li');
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<p>\u00a0</p>' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'P');
});
test('Remove UL at middle LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:nth-child(2)', 1);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'</ul>' +
'<p>b</p>' +
'<ul>' +
'<li>c</li>' +
'</ul>'
);
equal(editor.selection.getStart().nodeName, 'P');
});
test('Remove UL at middle empty LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li><br></li>' +
'<li>c</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:nth-child(2)', 0);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'</ul>' +
'<p>\u00a0</p>' +
'<ul>' +
'<li>c</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'P');
});
test('Remove UL at end LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:last', 1);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>' +
'<p>c</p>'
);
equal(editor.selection.getStart().nodeName, 'P');
});
test('Remove UL at end empty LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li><br></li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:last', 0);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>' +
'<p>\u00a0</p>'
);
equal(editor.selection.getNode().nodeName, 'P');
});
test('Remove UL at middle LI inside parent OL', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a</li>' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'<li>d</li>' +
'</ul>' +
'<li>e</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ul li:nth-child(2)', 1);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<ul>' +
'<li>b</li>' +
'</ul>' +
'</ol>' +
'<p>c</p>' +
'<ol>' +
'<ul>' +
'<li>d</li>' +
'</ul>' +
'<li>e</li>' +
'</ol>'
);
equal(editor.selection.getStart().nodeName, 'P');
});
test('Remove UL at middle LI inside parent OL (html5)', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'<li>d</li>' +
'</ul>' +
'</li>' +
'<li>e</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ul li:nth-child(2)', 1);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ol>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'</ul>' +
'</li>' +
'</ol>' +
'<p>c</p>' +
'<ol>' +
'<li style="list-style-type: none;">' +
'<ul>' +
'<li>d</li>' +
'</ul>' +
'</li>' +
'<li>e</li>' +
'</ol>'
);
equal(editor.selection.getStart().nodeName, 'P');
});
test('Remove OL on a deep nested LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'<li>c' +
'<ol>' +
'<li>d</li>' +
'<li>e</li>' +
'<li>f</li>' +
'</ol>' +
'</li>' +
'<li>g</li>' +
'<li>h</li>' +
'</ol>' +
'</li>' +
'<li>i</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ol ol ol li:nth-child(2)', 1);
execCommand('InsertOrderedList');
equal(editor.getContent(),
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'<li>c' +
'<ol>' +
'<li>d</li>' +
'</ol>' +
'</li>' +
'</ol>' +
'</li>' +
'</ol>' +
'<p>e</p>' +
'<ol>' +
'<li style="list-style-type: none;">' +
'<ol>' +
'<li style="list-style-type: none;">' +
'<ol>' +
'<li>f</li>' +
'</ol>' +
'</li>' +
'<li>g</li>' +
'<li>h</li>' +
'</ol>' +
'</li>' +
'<li>i</li>' +
'</ol>'
);
equal(editor.selection.getStart().nodeName, 'P');
});
test('Remove UL with single LI in BR mode', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li', 1);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'a'
);
equal(editor.selection.getStart().nodeName, 'BODY');
});
test('Remove UL with multiple LI in BR mode', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:first', 1, 'li:last', 1);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'a<br />' +
'b'
);
equal(editor.selection.getStart().nodeName, 'BODY');
});
test('Remove empty UL between two textblocks', function() {
editor.getBody().innerHTML = trimBrs(
'<div>a</div>' +
'<ul>' +
'<li></li>' +
'</ul>' +
'<div>b</div>'
);
editor.focus();
Utils.setSelection('li:first', 0);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<div>a</div>' +
'<p>\u00a0</p>' +
'<div>b</div>'
);
equal(editor.selection.getNode().nodeName, 'P');
});
test('Remove indented list with single item', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'</ul>' +
'</li>' +
'<li>c</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li li', 0, 'li li', 1);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'</ul>' +
'<p>b</p>' +
'<ul>' +
'<li>c</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'P');
});
test('Remove indented list with multiple items', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>' +
'</li>' +
'<li>d</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li li:first', 0, 'li li:last', 1);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'</ul>' +
'<p>b</p>' +
'<p>c</p>' +
'<ul>' +
'<li>d</li>' +
'</ul>'
);
equal(editor.selection.getStart().firstChild.data, 'b');
equal(editor.selection.getEnd().firstChild.data, 'c');
});
// Ignore on IE 7, 8 this is a known bug not worth fixing
if (!tinymce.Env.ie || tinymce.Env.ie > 8) {
test('Remove empty UL between two textblocks in BR mode', function() {
editor.settings.forced_root_block = false;
editor.getBody().innerHTML = trimBrs(
'<div>a</div>' +
'<ul>' +
'<li></li>' +
'</ul>' +
'<div>b</div>'
);
editor.focus();
Utils.setSelection('li:first', 0);
execCommand('InsertUnorderedList');
equal(editor.getContent(),
'<div>a</div>' +
'<br />' +
'<div>b</div>'
);
equal(editor.selection.getStart().nodeName, 'BR');
});
}
// Outdent
test('Outdent inside LI in beginning of OL in LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('li li', 1);
execCommand('Outdent');
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<li>b' +
'<ol>' +
'<li>c</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Outdent inside LI in middle of OL in LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'<li>c</li>' +
'<li>d</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('li li:nth-child(2)', 1);
execCommand('Outdent');
equal(editor.getContent(),
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'</ol>' +
'</li>' +
'<li>c' +
'<ol>' +
'<li>d</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Outdent inside LI in end of OL in LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('li li:last', 1);
execCommand('Outdent');
equal(editor.getContent(),
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'</ol>' +
'</li>' +
'<li>c</li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
// Nested lists in OL elements
test('Outdent inside LI in beginning of OL in OL', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a</li>' +
'<ol>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ol ol li', 1);
execCommand('Outdent');
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<li>b</li>' +
'<ol>' +
'<li>c</li>' +
'</ol>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Outdent inside LI in middle of OL in OL', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a</li>' +
'<ol>' +
'<li>b</li>' +
'<li>c</li>' +
'<li>d</li>' +
'</ol>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ol ol li:nth-child(2)', 1);
execCommand('Outdent');
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<ol>' +
'<li>b</li>' +
'</ol>' +
'<li>c</li>' +
'<ol>' +
'<li>d</li>' +
'</ol>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Outdent inside first/last LI in inner OL', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>1' +
'<ol>' +
'<li>2</li>' +
'<li>3</li>' +
'</ol>' +
'</li>' +
'<li>4</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ol ol li:nth-child(1)', 0, 'ol ol li:nth-child(2)', 1);
execCommand('Outdent');
equal(editor.getContent(),
'<ol>' +
'<li>1</li>' +
'<li>2</li>' +
'<li>3</li>' +
'<li>4</li>' +
'</ol>'
);
equal(editor.selection.getRng(true).startContainer.nodeValue, '2');
equal(editor.selection.getRng(true).endContainer.nodeValue, '3');
});
test('Outdent inside first LI in inner OL where OL is single child of parent LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a</li>' +
'<li>' +
'<ol>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ol ol li:first', 0);
execCommand('Outdent');
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<li>b' +
'<ol>' +
'<li>c</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Outdent inside LI in end of OL in OL', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a</li>' +
'<ol>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ol ol li:last', 1);
execCommand('Outdent');
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<ol>' +
'<li>b</li>' +
'</ol>' +
'<li>c</li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Outdent inside only child LI in OL in OL', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('ol ol li', 0);
execCommand('Outdent');
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'<li>b</li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Outdent multiple LI in OL and nested OL', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('li', 0, 'li li', 1);
execCommand('Outdent');
equal(editor.getContent(),
'<p>a</p>' +
'<ol>' +
'<li>b</li>' +
'</ol>'
);
});
// Indent
test('Indent single LI in OL', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('li', 0);
execCommand('Indent');
equal(editor.getContent(),
'<ol>' +
'<li>a</li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Indent middle LI in OL', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('li:nth-child(2)', 0);
execCommand('Indent');
equal(editor.getContent(),
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'</ol>' +
'</li>' +
'<li>c</li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Indent single LI in OL and retain OLs list style in the new OL', function() {
editor.getBody().innerHTML = trimBrs(
'<ol style="list-style-type: lower-alpha;">' +
'<li>a</li>' +
'<li>b</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('li:nth-child(2)', 0);
execCommand('Indent');
equal(editor.getContent(),
'<ol style="list-style-type: lower-alpha;">' +
'<li>a' +
'<ol style="list-style-type: lower-alpha;">' +
'<li>b</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
});
test('Indent last LI in OL', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a</li>' +
'<li>b</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('li:last', 0);
execCommand('Indent');
equal(editor.getContent(),
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Indent last LI to same level as middle LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'</ol>' +
'</li>' +
'<li>c</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('li:last', 1);
execCommand('Indent');
equal(editor.getContent(),
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'<li>c</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Indent first LI and nested LI OL', function() {
editor.getBody().innerHTML = trimBrs(
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
editor.focus();
Utils.setSelection('li', 0, 'li li', 0);
execCommand('Indent');
equal(editor.getContent(),
'<ol>' +
'<li>a' +
'<ol>' +
'<li>b</li>' +
'</ol>' +
'</li>' +
'</ol>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Indent second LI to same level as nested LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b' +
'<ul>' +
'<li>c</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:nth-child(2)', 0);
execCommand('Indent');
equal(editor.getContent(),
'<ul>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Indent second LI to same level as nested LI 2', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'</ul>' +
'</li>' +
'<li>cd' +
'<ul>' +
'<li>e</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:nth-child(2)', 1);
execCommand('Indent');
equal(editor.getContent(),
'<ul>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'<li>cd</li>' +
'<li>e</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Indent second and third LI', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:nth-child(2)', 0, 'li:last', 0);
execCommand('Indent');
equal(editor.getContent(),
'<ul>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
});
test('Indent second second li with next sibling to nested li', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b' +
'<ul>' +
'<li>c</li>' +
'</ul>' +
'</li>' +
'<li>d</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('ul > li:nth-child(2)', 1);
execCommand('Indent');
equal(editor.getContent(),
'<ul>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>' +
'</li>' +
'<li>d</li>' +
'</ul>'
);
});
// Backspace
test('Backspace at beginning of single LI in UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(),
'<p>a</p>'
);
equal(editor.selection.getNode().nodeName, 'P');
});
test('Backspace at beginning of first LI in UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(),
'<p>a</p>' +
'<ul>' +
'<li>b</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'P');
});
test('Backspace at beginning of middle LI in UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:nth-child(2)', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(),
'<ul>' +
'<li>ab</li>' +
'<li>c</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Backspace at beginning of start LI in UL inside UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li li', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(),
'<ul>' +
'<li>ab' +
'<ul>' +
'<li>c</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Backspace at beginning of middle LI in UL inside UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'<li>d</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li li:nth-child(2)', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(),
'<ul>' +
'<li>a' +
'<ul>' +
'<li>bc</li>' +
'<li>d</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Backspace at beginning of single LI in UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(),
'<p>a</p>'
);
equal(editor.selection.getNode().nodeName, 'P');
});
test('Backspace at beginning of first LI in UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(),
'<p>a</p>' +
'<ul>' +
'<li>b</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'P');
});
test('Backspace at beginning of middle LI in UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:nth-child(2)', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(),
'<ul>' +
'<li>ab</li>' +
'<li>c</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Backspace at beginning of start LI in UL inside UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li li', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(),
'<ul>' +
'<li>ab' +
'<ul>' +
'<li>c</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Backspace at beginning of middle LI in UL inside UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'<li>d</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li li:nth-child(2)', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(),
'<ul>' +
'<li>a' +
'<ul>' +
'<li>bc</li>' +
'<li>d</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Backspace at beginning of LI with empty LI above in UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li></li>' +
'<li>b</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:nth-child(3)', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>'
);
equal(editor.selection.getNode().innerHTML, 'b');
});
test('Backspace at beginning of LI with BR padded empty LI above in UL', function() {
editor.getBody().innerHTML = (
'<ul>' +
'<li>a</li>' +
'<li><br></li>' +
'<li>b</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:nth-child(3)', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>'
);
equal(editor.selection.getNode().innerHTML, 'b');
});
test('Backspace at empty LI (IE)', function() {
editor.getBody().innerHTML = (
'<ul>' +
'<li>a</li>' +
'<li></li>' +
'<li>b</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:nth-child(2)', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>'
);
equal(editor.selection.getNode().innerHTML, 'a');
});
test('Backspace at beginning of LI with empty LI with STRING and BR above in UL', function() {
editor.getBody().innerHTML = (
'<ul>' +
'<li>a</li>' +
'<li><strong><br></strong></li>' +
'<li>b</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:nth-child(3)', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>'
);
equal(editor.selection.getNode().innerHTML, 'b');
});
test('Backspace at beginning of LI on body UL', function() {
inlineEditor2.focus();
inlineEditor2.selection.setCursorLocation(inlineEditor2.getBody().firstChild.firstChild, 0);
inlineEditor2.plugins.lists.backspaceDelete();
equal(tinymce.$('#lists ul').length, 3);
equal(tinymce.$('#lists li').length, 3);
});
test('Backspace at nested LI with adjacent BR', function() {
editor.getBody().innerHTML = (
'<ul>' +
'<li>1' +
'<ul>' +
'<li>' +
'<br>' +
'<ul>' +
'<li>2</li>' +
'</ul>' +
'</li>' +
'</ul>' +
'</li>' +
'<li>3</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('ul ul ul li', 0);
editor.plugins.lists.backspaceDelete();
equal(editor.getContent(), '<ul><li>1<ul><li>2</li></ul></li><li>3</li></ul>');
equal(editor.selection.getNode().nodeName, 'LI');
});
// Delete
test('Delete at end of single LI in UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li', 1);
editor.plugins.lists.backspaceDelete(true);
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Delete at end of first LI in UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li', 1);
editor.plugins.lists.backspaceDelete(true);
equal(editor.getContent(),
'<ul>' +
'<li>ab</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Delete at end of middle LI in UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li:nth-child(2)', 1);
editor.plugins.lists.backspaceDelete(true);
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>bc</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Delete at end of start LI in UL inside UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li li', 1);
editor.plugins.lists.backspaceDelete(true);
equal(editor.getContent(),
'<ul>' +
'<li>a' +
'<ul>' +
'<li>bc</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Delete at end of middle LI in UL inside UL', function() {
editor.getBody().innerHTML = trimBrs(
'<ul>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'<li>c</li>' +
'<li>d</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li li:nth-child(2)', 1);
editor.plugins.lists.backspaceDelete(true);
equal(editor.getContent(),
'<ul>' +
'<li>a' +
'<ul>' +
'<li>b</li>' +
'<li>cd</li>' +
'</ul>' +
'</li>' +
'</ul>'
);
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Delete at end of LI before empty LI', function() {
editor.getBody().innerHTML = (
'<ul>' +
'<li>a</li>' +
'<li></li>' +
'<li>b</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li', 1);
editor.plugins.lists.backspaceDelete(true);
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>'
);
equal(editor.selection.getNode().innerHTML, 'a');
});
test('Delete at end of LI before BR padded empty LI', function() {
editor.getBody().innerHTML = (
'<ul>' +
'<li>a</li>' +
'<li><br></li>' +
'<li>b</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li', 1);
editor.plugins.lists.backspaceDelete(true);
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>'
);
equal(editor.selection.getNode().innerHTML, 'a');
});
test('Delete at end of LI before empty LI with STRONG', function() {
editor.getBody().innerHTML = (
'<ul>' +
'<li>a</li>' +
'<li><strong><br></strong></li>' +
'<li>b</li>' +
'</ul>'
);
editor.focus();
Utils.setSelection('li', 1);
editor.plugins.lists.backspaceDelete(true);
equal(editor.getContent(),
'<ul>' +
'<li>a</li>' +
'<li>b</li>' +
'</ul>'
);
equal(editor.selection.getNode().innerHTML, 'a');
});
test('Delete at end of LI on body UL', function() {
inlineEditor2.focus();
inlineEditor2.selection.setCursorLocation(inlineEditor2.getBody().firstChild.firstChild, 1);
inlineEditor2.plugins.lists.backspaceDelete(true);
equal(tinymce.$('#lists ul').length, 3);
equal(tinymce.$('#lists li').length, 3);
});
test('Delete at nested LI with adjacent BR', function() {
editor.getBody().innerHTML = (
'<ul>' +
'<li>1' +
'<ul>' +
'<li>' +
'<br>' +
'<ul>' +
'<li>2</li>' +
'</ul>' +
'</li>' +
'</ul>' +
'</li>' +
'<li>3</li>' +
'</ul>'
);
editor.focus();
editor.selection.setCursorLocation(editor.$('ul ul li')[0], 0);
editor.plugins.lists.backspaceDelete(true);
equal(editor.getContent(), '<ul><li>1<ul><li>2</li></ul></li><li>3</li></ul>');
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Delete at BR before text in LI', function() {
editor.getBody().innerHTML = (
'<ul>' +
'<li>1</li>' +
'<li>2<br></li>' +
'<li>3</li>' +
'</ul>'
);
editor.focus();
editor.selection.setCursorLocation(editor.$('li')[1], 1);
editor.plugins.lists.backspaceDelete(false);
equal(editor.getContent(), '<ul><li>1</li><li>2</li><li>3</li></ul>');
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Remove UL in inline body element contained in LI', function() {
inlineEditor.setContent('<ul><li>a</li></ul>');
inlineEditor.selection.setCursorLocation();
inlineEditor.execCommand('InsertUnorderedList');
equal(inlineEditor.getContent(), '<p>a</p>');
});
test('Backspace in LI in UL in inline body element contained within LI', function() {
inlineEditor.setContent('<ul><li>a</li></ul>');
inlineEditor.focus();
inlineEditor.selection.select(inlineEditor.getBody(), true);
inlineEditor.selection.collapse(true);
inlineEditor.plugins.lists.backspaceDelete();
equal(inlineEditor.getContent(), '<p>a</p>');
});
test('Apply DL list to multiple Ps', function() {
editor.getBody().innerHTML = trimBrs(
'<p>a</p>' +
'<p>b</p>' +
'<p>c</p>'
);
editor.focus();
Utils.setSelection('p', 0, 'p:last', 0);
execCommand('InsertDefinitionList');
equal(editor.getContent(),
'<dl>' +
'<dt>a</dt>' +
'<dt>b</dt>' +
'<dt>c</dt>' +
'</dl>'
);
equal(editor.selection.getStart().nodeName, 'DT');
});
test('Apply OL list to single P', function() {
editor.getBody().innerHTML = trimBrs(
'<p>a</p>'
);
editor.focus();
Utils.setSelection('p', 0);
execCommand('InsertDefinitionList');
equal(editor.getContent(), '<dl><dt>a</dt></dl>');
equal(editor.selection.getNode().nodeName, 'DT');
});
test('Apply DL to P and merge with adjacent lists', function() {
editor.getBody().innerHTML = trimBrs(
'<dl>' +
'<dt>a</dt>' +
'</dl>' +
'<p>b</p>' +
'<dl>' +
'<dt>c</dt>' +
'</dl>'
);
editor.focus();
Utils.setSelection('p', 1);
execCommand('InsertDefinitionList');
equal(editor.getContent(),
'<dl>' +
'<dt>a</dt>' +
'<dt>b</dt>' +
'<dt>c</dt>' +
'</dl>'
);
equal(editor.selection.getStart().nodeName, 'DT');
});
test('Indent single DT in DL', function() {
editor.getBody().innerHTML = trimBrs(
'<dl>' +
'<dt>a</dt>' +
'</dl>'
);
editor.focus();
Utils.setSelection('dt', 0);
execCommand('Indent');
equal(editor.getContent(),
'<dl>' +
'<dd>a</dd>' +
'</dl>'
);
equal(editor.selection.getNode().nodeName, 'DD');
});
test('Outdent single DD in DL', function() {
editor.getBody().innerHTML = trimBrs(
'<dl>' +
'<dd>a</dd>' +
'</dl>'
);
editor.focus();
Utils.setSelection('dd', 1);
execCommand('Outdent');
equal(editor.getContent(),
'<dl>' +
'<dt>a</dt>' +
'</dl>'
);
equal(editor.selection.getNode().nodeName, 'DT');
});
test('Apply UL list to single P', function() {
editor.getBody().innerHTML = trimBrs(
'<p>a</p>'
);
editor.focus();
Utils.setSelection('p', 0);
execCommand('InsertUnorderedList');
equal(editor.getContent(), '<ul><li>a</li></ul>');
equal(editor.selection.getNode().nodeName, 'LI');
});
test('Apply UL list to more than two paragraphs', function() {
editor.getBody().innerHTML = trimBrs(
'<p>a</p>' +
'<p>b</p>' +
'<p>c</p>'
);
editor.focus();
Utils.setSelection('p:nth-child(1)', 0, 'p:nth-child(3)', 1);
execCommand('InsertUnorderedList', false, {'list-style-type': null});
equal(editor.getContent(), '<ul><li>a</li><li>b</li><li>c</li></ul>');
});
});
|
tinyMCE.addI18n('cs.media_dlg',{
title:"Vlo\u017Eit/upravit vkl\u00E1dan\u00E1 m\u00E9dia",
general:"Hlavn\u00ED",
advanced:"Pokro\u010Dil\u00E9",
file:"Soubor/URL",
list:"Seznam",
size:"Rozm\u011Bry",
preview:"N\u00E1hled",
constrain_proportions:"Zachovat proporce",
type:"Typ",
id:"ID",
name:"N\u00E1zev",
class_name:"T\u0159\u00EDda",
vspace:"Vert. odsazen\u00ED",
hspace:"Horiz. odsazen\u00ED",
play:"Auto-p\u0159ehr\u00E1v\u00E1n\u00ED",
loop:"Smy\u010Dka",
menu:"Zobrazovat menu",
quality:"Kvalita",
scale:"Pom\u011Br",
align:"Zarovn\u00E1n\u00ED",
salign:"SAlign",
wmode:"WMode",
bgcolor:"Pozad\u00ED",
base:"Base",
flashvars:"Flashvars",
liveconnect:"SWLiveConnect",
autohref:"AutoHREF",
cache:"Cache",
hidden:"Hidden",
controller:"Controller",
kioskmode:"Kiosk mode",
playeveryframe:"Play every frame",
targetcache:"Target cache",
correction:"No correction",
enablejavascript:"Zapnout JavaScript",
starttime:"Po\u010D\u00E1te\u010Dn\u00ED \u010Das",
endtime:"\u010Cas ukon\u010Den\u00ED",
href:"Href",
qtsrcchokespeed:"Choke speed",
target:"C\u00EDl",
volume:"Volume",
autostart:"Auto start",
enabled:"Enabled",
fullscreen:"Fullscreen",
invokeurls:"Invoke URLs",
mute:"Mute",
stretchtofit:"Stretch to fit",
windowlessvideo:"Windowless video",
balance:"Balance",
baseurl:"Base URL",
captioningid:"Captioning id",
currentmarker:"Current marker",
currentposition:"Current position",
defaultframe:"Default frame",
playcount:"Play count",
rate:"Rate",
uimode:"UI Mode",
flash_options:"Flash options",
qt_options:"Quicktime options",
wmp_options:"Windows media player options",
rmp_options:"Real media player options",
shockwave_options:"Shockwave options",
autogotourl:"Auto goto URL",
center:"Center",
imagestatus:"Image status",
maintainaspect:"Maintain aspect",
nojava:"No java",
prefetch:"Prefetch",
shuffle:"Opakov\u00E1n\u00ED",
console:"Konzola",
numloop:"Num loops",
controls:"Controls",
scriptcallbacks:"Script callbacks",
swstretchstyle:"Stretch style",
swstretchhalign:"Stretch H-Align",
swstretchvalign:"Stretch V-Align",
sound:"Hlasitost",
progress:"Progress",
qtsrc:"QT Src",
qt_stream_warn:"Streamed rtsp resources should be added to the QT Src field under the advanced tab.\nYou should also add a non streamed version to the Src field..",
align_top:"Nahoru",
align_right:"Vpravo",
align_bottom:"Dol\u016F",
align_left:"Vlevo",
align_center:"Na st\u0159ed",
align_top_left:"Nahoru vlevo",
align_top_right:"Nahoru vpravo",
align_bottom_left:"Dol\u016F vlevo",
align_bottom_right:"Dol\u016F vpravo",
flv_options:"Flash video options",
flv_scalemode:"Scale mode",
flv_buffer:"Buffer",
flv_startimage:"Start image",
flv_starttime:"Start time",
flv_defaultvolume:"Default volumne",
flv_hiddengui:"Skryt\u00E9 GUI",
flv_autostart:"Autostart",
flv_loop:"Smy\u010Dka",
flv_showscalemodes:"Show scale modes",
flv_smoothvideo:"Vyhlazen\u00E9 video",
flv_jscallback:"JS Callback"
});
|
'use strict';
module.exports = function (app) {
// User Routes
var users = require('../controllers/users.server.controller');
// Setting up the users profile api
app.route('/api/users/me').get(users.me);
app.route('/api/users').put(users.update);
app.route('/api/users/accounts').delete(users.removeOAuthProvider);
app.route('/api/users/password').post(users.changePassword);
app.route('/api/users/picture').post(users.changeProfilePicture);
// Finish by binding the user middleware
app.param('userId', users.userByID);
};
|
ko.bindingHandlers.dateString = {
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor(),
allBindings = allBindingsAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
var dateString = valueUnwrapped;
var parsedDate = moment(valueUnwrapped);
if (parsedDate.isValid()) {
var pattern = allBindings.datePattern || 'DD/MM/YYYY';
dateString = moment(valueUnwrapped).format(pattern);
}
$(element).text(dateString);
}
}
var Filter = function(name, fn) {
var self = this;
self.Name = name;
self.Fn = fn;
self.Active = ko.observable(false);
self.DisplayName = ko.computed(function() {
return self.Active()
? "Show " + self.Name
: "Hide " + self.Name;
});
self.Toggle = function() {
self.Active(!self.Active());
};
};
$(document).ready(function () {
var ViewModel = function() {
var self = this;
var hub = $.connection.deployStatusHub;
var mapping = {
key: function (data) {
return ko.utils.unwrapObservable(data.Id);
},
'BranchRelatedTrellos': {
key: function (data) {
return ko.utils.unwrapObservable(data.Id);
}
},
'EnvironmentTaggedTrellos': {
key: function (data) {
return ko.utils.unwrapObservable(data.Id);
}
},
'Builds': {
key: function (data) {
return ko.utils.unwrapObservable(data.Id);
}
}
}
self.Name = ko.observable("Contacting server...");
self.LastUpdated = ko.observable("never");
self.Environments = ko.mapping.fromJS([], mapping);
var nameSort = function(a, b) {
return a.Name() < b.Name() ? -1 : 1;
};
self.SortFunctions = ko.observableArray([
{
Name: "Is Deployable",
Fn: function(a, b) {
var firstLength = a.EnvironmentTaggedTrellos().length;
var secondLength = b.EnvironmentTaggedTrellos().length;
if (firstLength === secondLength)
return nameSort(a, b);
return firstLength < secondLength ? -1 : 1;
}
},
{
Name: "Name",
Fn: nameSort
}
]);
self.SelectedSortFunction = ko.observable(self.SortFunctions()[0]);
self.ShowDisabledEnvironments =
new Filter("Disabled", function (environment) {
return environment.IsDisabled() === false;
});
self.SortedEnvironments = ko.computed(function() {
var environments = self.Environments();
var sortFn = self.SelectedSortFunction();
if (self.ShowDisabledEnvironments.Active())
environments = environments.filter(self.ShowDisabledEnvironments.Fn);
var sorted = environments.sort(sortFn.Fn);
return sorted;
}, self);
var updateEnvironments = function (environments) {
if (environments.length === 0)
return; // keep old state on server restarts
ko.mapping.fromJS(environments, self.Environments);
var allDropdowns = $('.ui.dropdown');
for (var i = 0; i < allDropdowns.length; i++) {
var dropDown = $(allDropdowns[i]);
if (dropDown.data("dropdown") !== true) {
dropDown.data("dropdown", true);
dropDown.dropdown();
}
}
};
var updateDeploySystemStatus = function (newDeploySystemStatus) {
updateEnvironments(newDeploySystemStatus.Environments);
self.Name(newDeploySystemStatus.Name);
self.LastUpdated(newDeploySystemStatus.LastUpdated);
};
var startAndInitialise = function () {
$.connection.hub.start().done(function () {
hub.server.getDeploySystemStatus().done(updateDeploySystemStatus);
});
}
hub.client.deploySystemStatusChanged = updateDeploySystemStatus;
startAndInitialise();
$.connection.hub.disconnected(function () {
setTimeout(function () {
startAndInitialise();
}, 5); // Restart connection after 5 seconds.
});
};
ko.applyBindings(new ViewModel());
});
|
var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var should = require('should');
var MistRender = require('../bin/mist-render.js');
var MistClean = require('../bin/mist-clean.js');
var ninjaExec = path.join(process.cwd(), 'bin/ninja/ninja');
var fixtureDir = path.join(__dirname, path.basename(__filename, '.js'));
describe('basic render', function() {
var ninjaFile = path.join(fixtureDir, 'build.ninja');
it('should render', function() {
MistRender({out: ninjaFile, cwd: fixtureDir});
fs.existsSync(ninjaFile).should.equal(true);
});
it('should build', function(done) {
exec('cd ' + fixtureDir + ' && ' + ninjaExec, function(err, out, stderr) {
done(err);
});
});
var capturedStdout = '';
it('should run', function(done) {
exec('cd ' + fixtureDir + ' && ./basic', function(err, out, stderr) {
if (err) done(err);
capturedStdout = out;
done();
});
});
it('should say \'hello\'', function() {
capturedStdout.should.equal('Hello, world!\n');
});
it('should clean', function(done) {
MistClean({cwd: fixtureDir, exitcb: function(code) {
if (code !== 0) {
done(new Error('Exited with non-zero code: ' + code));
} else {
done();
}
}});
});
after(function() {
require(path.join(fixtureDir, 'purge.js'));
});
});
|
module.exports = function( THREE ){
/**
* @author qiao / https://github.com/qiao
* @author mrdoob / http://mrdoob.com
* @author alteredq / http://alteredqualia.com/
* @author WestLangley / http://github.com/WestLangley
* @author erich666 / http://erichaines.com
*/
// This set of controls performs orbiting, dollying (zooming), and panning.
// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
//
// Orbit - left mouse / touch: one finger move
// Zoom - middle mouse, or mousewheel / touch: two finger spread or squish
// Pan - right mouse, or arrow keys / touch: three finter swipe
THREE.OrbitControls = function ( object, domElement ) {
this.object = object;
this.domElement = ( domElement !== undefined ) ? domElement : document;
// Set to false to disable this control
this.enabled = true;
// "target" sets the location of focus, where the object orbits around
this.target = new THREE.Vector3();
// How far you can dolly in and out ( PerspectiveCamera only )
this.minDistance = 0;
this.maxDistance = Infinity;
// How far you can zoom in and out ( OrthographicCamera only )
this.minZoom = 0;
this.maxZoom = Infinity;
// How far you can orbit vertically, upper and lower limits.
// Range is 0 to Math.PI radians.
this.minPolarAngle = 0; // radians
this.maxPolarAngle = Math.PI; // radians
// How far you can orbit horizontally, upper and lower limits.
// If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
this.minAzimuthAngle = - Infinity; // radians
this.maxAzimuthAngle = Infinity; // radians
// Set to true to enable damping (inertia)
// If damping is enabled, you must call controls.update() in your animation loop
this.enableDamping = false;
this.dampingFactor = 0.25;
// This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
// Set to false to disable zooming
this.enableZoom = true;
this.zoomSpeed = 1.0;
// Set to false to disable rotating
this.enableRotate = true;
this.rotateSpeed = 1.0;
// Set to false to disable panning
this.enablePan = true;
this.keyPanSpeed = 7.0; // pixels moved per arrow key push
// Set to true to automatically rotate around the target
// If auto-rotate is enabled, you must call controls.update() in your animation loop
this.autoRotate = false;
this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
// Set to false to disable use of the keys
this.enableKeys = true;
// The four arrow keys
this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 };
// Mouse buttons
this.mouseButtons = { ORBIT: THREE.MOUSE.LEFT, ZOOM: THREE.MOUSE.MIDDLE, PAN: THREE.MOUSE.RIGHT };
// for reset
this.target0 = this.target.clone();
this.position0 = this.object.position.clone();
this.zoom0 = this.object.zoom;
//
// public methods
//
this.getPolarAngle = function () {
return spherical.phi;
};
this.getAzimuthalAngle = function () {
return spherical.theta;
};
this.reset = function () {
scope.target.copy( scope.target0 );
scope.object.position.copy( scope.position0 );
scope.object.zoom = scope.zoom0;
scope.object.updateProjectionMatrix();
scope.dispatchEvent( changeEvent );
scope.update();
state = STATE.NONE;
};
// this method is exposed, but perhaps it would be better if we can make it private...
this.update = function() {
var offset = new THREE.Vector3();
// so camera.up is the orbit axis
var quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) );
var quatInverse = quat.clone().inverse();
var lastPosition = new THREE.Vector3();
var lastQuaternion = new THREE.Quaternion();
return function () {
var position = scope.object.position;
offset.copy( position ).sub( scope.target );
// rotate offset to "y-axis-is-up" space
offset.applyQuaternion( quat );
// angle from z-axis around y-axis
spherical.setFromVector3( offset );
if ( scope.autoRotate && state === STATE.NONE ) {
rotateLeft( getAutoRotationAngle() );
}
spherical.theta += sphericalDelta.theta;
spherical.phi += sphericalDelta.phi;
// restrict theta to be between desired limits
spherical.theta = Math.max( scope.minAzimuthAngle, Math.min( scope.maxAzimuthAngle, spherical.theta ) );
// restrict phi to be between desired limits
spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) );
spherical.makeSafe();
spherical.radius *= scale;
// restrict radius to be between desired limits
spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) );
// move target to panned location
scope.target.add( panOffset );
offset.setFromSpherical( spherical );
// rotate offset back to "camera-up-vector-is-up" space
offset.applyQuaternion( quatInverse );
position.copy( scope.target ).add( offset );
scope.object.lookAt( scope.target );
if ( scope.enableDamping === true ) {
sphericalDelta.theta *= ( 1 - scope.dampingFactor );
sphericalDelta.phi *= ( 1 - scope.dampingFactor );
} else {
sphericalDelta.set( 0, 0, 0 );
}
scale = 1;
panOffset.set( 0, 0, 0 );
// update condition is:
// min(camera displacement, camera rotation in radians)^2 > EPS
// using small-angle approximation cos(x/2) = 1 - x^2 / 8
if ( zoomChanged ||
lastPosition.distanceToSquared( scope.object.position ) > EPS ||
8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) {
scope.dispatchEvent( changeEvent );
lastPosition.copy( scope.object.position );
lastQuaternion.copy( scope.object.quaternion );
zoomChanged = false;
return true;
}
return false;
};
}();
this.dispose = function() {
scope.domElement.removeEventListener( 'contextmenu', onContextMenu, false );
scope.domElement.removeEventListener( 'mousedown', onMouseDown, false );
scope.domElement.removeEventListener( 'mousewheel', onMouseWheel, false );
scope.domElement.removeEventListener( 'MozMousePixelScroll', onMouseWheel, false ); // firefox
scope.domElement.removeEventListener( 'touchstart', onTouchStart, false );
scope.domElement.removeEventListener( 'touchend', onTouchEnd, false );
scope.domElement.removeEventListener( 'touchmove', onTouchMove, false );
document.removeEventListener( 'mousemove', onMouseMove, false );
document.removeEventListener( 'mouseup', onMouseUp, false );
document.removeEventListener( 'mouseout', onMouseUp, false );
window.removeEventListener( 'keydown', onKeyDown, false );
//scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
};
//
// internals
//
var scope = this;
var changeEvent = { type: 'change' };
var startEvent = { type: 'start' };
var endEvent = { type: 'end' };
var STATE = { NONE : - 1, ROTATE : 0, DOLLY : 1, PAN : 2, TOUCH_ROTATE : 3, TOUCH_DOLLY : 4, TOUCH_PAN : 5 };
var state = STATE.NONE;
var EPS = 0.000001;
// current position in spherical coordinates
var spherical = new THREE.Spherical();
var sphericalDelta = new THREE.Spherical();
var scale = 1;
var panOffset = new THREE.Vector3();
var zoomChanged = false;
var rotateStart = new THREE.Vector2();
var rotateEnd = new THREE.Vector2();
var rotateDelta = new THREE.Vector2();
var panStart = new THREE.Vector2();
var panEnd = new THREE.Vector2();
var panDelta = new THREE.Vector2();
var dollyStart = new THREE.Vector2();
var dollyEnd = new THREE.Vector2();
var dollyDelta = new THREE.Vector2();
function getAutoRotationAngle() {
return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
}
function getZoomScale() {
return Math.pow( 0.95, scope.zoomSpeed );
}
function rotateLeft( angle ) {
sphericalDelta.theta -= angle;
}
function rotateUp( angle ) {
sphericalDelta.phi -= angle;
}
var panLeft = function() {
var v = new THREE.Vector3();
return function panLeft( distance, objectMatrix ) {
v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
v.multiplyScalar( - distance );
panOffset.add( v );
};
}();
var panUp = function() {
var v = new THREE.Vector3();
return function panUp( distance, objectMatrix ) {
v.setFromMatrixColumn( objectMatrix, 1 ); // get Y column of objectMatrix
v.multiplyScalar( distance );
panOffset.add( v );
};
}();
// deltaX and deltaY are in pixels; right and down are positive
var pan = function() {
var offset = new THREE.Vector3();
return function( deltaX, deltaY ) {
var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
if ( scope.object instanceof THREE.PerspectiveCamera ) {
// perspective
var position = scope.object.position;
offset.copy( position ).sub( scope.target );
var targetDistance = offset.length();
// half of the fov is center to top of screen
targetDistance *= Math.tan( ( scope.object.fov / 2 ) * Math.PI / 180.0 );
// we actually don't use screenWidth, since perspective camera is fixed to screen height
panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix );
panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );
} else if ( scope.object instanceof THREE.OrthographicCamera ) {
// orthographic
panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix );
panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix );
} else {
// camera neither orthographic nor perspective
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
scope.enablePan = false;
}
};
}();
function dollyIn( dollyScale ) {
if ( scope.object instanceof THREE.PerspectiveCamera ) {
scale /= dollyScale;
} else if ( scope.object instanceof THREE.OrthographicCamera ) {
scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) );
scope.object.updateProjectionMatrix();
zoomChanged = true;
} else {
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
scope.enableZoom = false;
}
}
function dollyOut( dollyScale ) {
if ( scope.object instanceof THREE.PerspectiveCamera ) {
scale *= dollyScale;
} else if ( scope.object instanceof THREE.OrthographicCamera ) {
scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) );
scope.object.updateProjectionMatrix();
zoomChanged = true;
} else {
console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
scope.enableZoom = false;
}
}
//
// event callbacks - update the object state
//
function handleMouseDownRotate( event ) {
//console.log( 'handleMouseDownRotate' );
rotateStart.set( event.clientX, event.clientY );
}
function handleMouseDownDolly( event ) {
//console.log( 'handleMouseDownDolly' );
dollyStart.set( event.clientX, event.clientY );
}
function handleMouseDownPan( event ) {
//console.log( 'handleMouseDownPan' );
panStart.set( event.clientX, event.clientY );
}
function handleMouseMoveRotate( event ) {
//console.log( 'handleMouseMoveRotate' );
rotateEnd.set( event.clientX, event.clientY );
rotateDelta.subVectors( rotateEnd, rotateStart );
var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
// rotating across whole screen goes 360 degrees around
rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed );
// rotating up and down along whole screen attempts to go 360, but limited to 180
rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed );
rotateStart.copy( rotateEnd );
scope.update();
}
function handleMouseMoveDolly( event ) {
//console.log( 'handleMouseMoveDolly' );
dollyEnd.set( event.clientX, event.clientY );
dollyDelta.subVectors( dollyEnd, dollyStart );
if ( dollyDelta.y > 0 ) {
dollyIn( getZoomScale() );
} else if ( dollyDelta.y < 0 ) {
dollyOut( getZoomScale() );
}
dollyStart.copy( dollyEnd );
scope.update();
}
function handleMouseMovePan( event ) {
//console.log( 'handleMouseMovePan' );
panEnd.set( event.clientX, event.clientY );
panDelta.subVectors( panEnd, panStart );
pan( panDelta.x, panDelta.y );
panStart.copy( panEnd );
scope.update();
}
function handleMouseUp( event ) {
//console.log( 'handleMouseUp' );
}
function handleMouseWheel( event ) {
//console.log( 'handleMouseWheel' );
var delta = 0;
if ( event.wheelDelta !== undefined ) {
// WebKit / Opera / Explorer 9
delta = event.wheelDelta;
} else if ( event.detail !== undefined ) {
// Firefox
delta = - event.detail;
}
if ( delta > 0 ) {
dollyOut( getZoomScale() );
} else if ( delta < 0 ) {
dollyIn( getZoomScale() );
}
scope.update();
}
function handleKeyDown( event ) {
//console.log( 'handleKeyDown' );
switch ( event.keyCode ) {
case scope.keys.UP:
pan( 0, scope.keyPanSpeed );
scope.update();
break;
case scope.keys.BOTTOM:
pan( 0, - scope.keyPanSpeed );
scope.update();
break;
case scope.keys.LEFT:
pan( scope.keyPanSpeed, 0 );
scope.update();
break;
case scope.keys.RIGHT:
pan( - scope.keyPanSpeed, 0 );
scope.update();
break;
}
}
function handleTouchStartRotate( event ) {
//console.log( 'handleTouchStartRotate' );
rotateStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
}
function handleTouchStartDolly( event ) {
//console.log( 'handleTouchStartDolly' );
var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
var distance = Math.sqrt( dx * dx + dy * dy );
dollyStart.set( 0, distance );
}
function handleTouchStartPan( event ) {
//console.log( 'handleTouchStartPan' );
panStart.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
}
function handleTouchMoveRotate( event ) {
//console.log( 'handleTouchMoveRotate' );
rotateEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
rotateDelta.subVectors( rotateEnd, rotateStart );
var element = scope.domElement === document ? scope.domElement.body : scope.domElement;
// rotating across whole screen goes 360 degrees around
rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed );
// rotating up and down along whole screen attempts to go 360, but limited to 180
rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed );
rotateStart.copy( rotateEnd );
scope.update();
}
function handleTouchMoveDolly( event ) {
//console.log( 'handleTouchMoveDolly' );
var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
var distance = Math.sqrt( dx * dx + dy * dy );
dollyEnd.set( 0, distance );
dollyDelta.subVectors( dollyEnd, dollyStart );
if ( dollyDelta.y > 0 ) {
dollyOut( getZoomScale() );
} else if ( dollyDelta.y < 0 ) {
dollyIn( getZoomScale() );
}
dollyStart.copy( dollyEnd );
scope.update();
}
function handleTouchMovePan( event ) {
//console.log( 'handleTouchMovePan' );
panEnd.set( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
panDelta.subVectors( panEnd, panStart );
pan( panDelta.x, panDelta.y );
panStart.copy( panEnd );
scope.update();
}
function handleTouchEnd( event ) {
//console.log( 'handleTouchEnd' );
}
//
// event handlers - FSM: listen for events and reset state
//
function onMouseDown( event ) {
if ( scope.enabled === false ) return;
event.preventDefault();
if ( event.button === scope.mouseButtons.ORBIT ) {
if ( scope.enableRotate === false ) return;
handleMouseDownRotate( event );
state = STATE.ROTATE;
} else if ( event.button === scope.mouseButtons.ZOOM ) {
if ( scope.enableZoom === false ) return;
handleMouseDownDolly( event );
state = STATE.DOLLY;
} else if ( event.button === scope.mouseButtons.PAN ) {
if ( scope.enablePan === false ) return;
handleMouseDownPan( event );
state = STATE.PAN;
}
if ( state !== STATE.NONE ) {
document.addEventListener( 'mousemove', onMouseMove, false );
document.addEventListener( 'mouseup', onMouseUp, false );
document.addEventListener( 'mouseout', onMouseUp, false );
scope.dispatchEvent( startEvent );
}
}
function onMouseMove( event ) {
if ( scope.enabled === false ) return;
event.preventDefault();
if ( state === STATE.ROTATE ) {
if ( scope.enableRotate === false ) return;
handleMouseMoveRotate( event );
} else if ( state === STATE.DOLLY ) {
if ( scope.enableZoom === false ) return;
handleMouseMoveDolly( event );
} else if ( state === STATE.PAN ) {
if ( scope.enablePan === false ) return;
handleMouseMovePan( event );
}
}
function onMouseUp( event ) {
if ( scope.enabled === false ) return;
handleMouseUp( event );
document.removeEventListener( 'mousemove', onMouseMove, false );
document.removeEventListener( 'mouseup', onMouseUp, false );
document.removeEventListener( 'mouseout', onMouseUp, false );
scope.dispatchEvent( endEvent );
state = STATE.NONE;
}
function onMouseWheel( event ) {
if ( scope.enabled === false || scope.enableZoom === false || ( state !== STATE.NONE && state !== STATE.ROTATE ) ) return;
event.preventDefault();
event.stopPropagation();
handleMouseWheel( event );
scope.dispatchEvent( startEvent ); // not sure why these are here...
scope.dispatchEvent( endEvent );
}
function onKeyDown( event ) {
if ( scope.enabled === false || scope.enableKeys === false || scope.enablePan === false ) return;
handleKeyDown( event );
}
function onTouchStart( event ) {
if ( scope.enabled === false ) return;
switch ( event.touches.length ) {
case 1: // one-fingered touch: rotate
if ( scope.enableRotate === false ) return;
handleTouchStartRotate( event );
state = STATE.TOUCH_ROTATE;
break;
case 2: // two-fingered touch: dolly
if ( scope.enableZoom === false ) return;
handleTouchStartDolly( event );
state = STATE.TOUCH_DOLLY;
break;
case 3: // three-fingered touch: pan
if ( scope.enablePan === false ) return;
handleTouchStartPan( event );
state = STATE.TOUCH_PAN;
break;
default:
state = STATE.NONE;
}
if ( state !== STATE.NONE ) {
scope.dispatchEvent( startEvent );
}
}
function onTouchMove( event ) {
if ( scope.enabled === false ) return;
event.preventDefault();
event.stopPropagation();
switch ( event.touches.length ) {
case 1: // one-fingered touch: rotate
if ( scope.enableRotate === false ) return;
if ( state !== STATE.TOUCH_ROTATE ) return; // is this needed?...
handleTouchMoveRotate( event );
break;
case 2: // two-fingered touch: dolly
if ( scope.enableZoom === false ) return;
if ( state !== STATE.TOUCH_DOLLY ) return; // is this needed?...
handleTouchMoveDolly( event );
break;
case 3: // three-fingered touch: pan
if ( scope.enablePan === false ) return;
if ( state !== STATE.TOUCH_PAN ) return; // is this needed?...
handleTouchMovePan( event );
break;
default:
state = STATE.NONE;
}
}
function onTouchEnd( event ) {
if ( scope.enabled === false ) return;
handleTouchEnd( event );
scope.dispatchEvent( endEvent );
state = STATE.NONE;
}
function onContextMenu( event ) {
event.preventDefault();
}
//
scope.domElement.addEventListener( 'contextmenu', onContextMenu, false );
scope.domElement.addEventListener( 'mousedown', onMouseDown, false );
scope.domElement.addEventListener( 'mousewheel', onMouseWheel, false );
scope.domElement.addEventListener( 'MozMousePixelScroll', onMouseWheel, false ); // firefox
scope.domElement.addEventListener( 'touchstart', onTouchStart, false );
scope.domElement.addEventListener( 'touchend', onTouchEnd, false );
scope.domElement.addEventListener( 'touchmove', onTouchMove, false );
window.addEventListener( 'keydown', onKeyDown, false );
// force an update at start
this.update();
};
THREE.OrbitControls.prototype = Object.create( THREE.EventDispatcher.prototype );
THREE.OrbitControls.prototype.constructor = THREE.OrbitControls;
Object.defineProperties( THREE.OrbitControls.prototype, {
center: {
get: function () {
console.warn( 'THREE.OrbitControls: .center has been renamed to .target' );
return this.target;
}
},
// backward compatibility
noZoom: {
get: function () {
console.warn( 'THREE.OrbitControls: .noZoom has been deprecated. Use .enableZoom instead.' );
return ! this.enableZoom;
},
set: function ( value ) {
console.warn( 'THREE.OrbitControls: .noZoom has been deprecated. Use .enableZoom instead.' );
this.enableZoom = ! value;
}
},
noRotate: {
get: function () {
console.warn( 'THREE.OrbitControls: .noRotate has been deprecated. Use .enableRotate instead.' );
return ! this.enableRotate;
},
set: function ( value ) {
console.warn( 'THREE.OrbitControls: .noRotate has been deprecated. Use .enableRotate instead.' );
this.enableRotate = ! value;
}
},
noPan: {
get: function () {
console.warn( 'THREE.OrbitControls: .noPan has been deprecated. Use .enablePan instead.' );
return ! this.enablePan;
},
set: function ( value ) {
console.warn( 'THREE.OrbitControls: .noPan has been deprecated. Use .enablePan instead.' );
this.enablePan = ! value;
}
},
noKeys: {
get: function () {
console.warn( 'THREE.OrbitControls: .noKeys has been deprecated. Use .enableKeys instead.' );
return ! this.enableKeys;
},
set: function ( value ) {
console.warn( 'THREE.OrbitControls: .noKeys has been deprecated. Use .enableKeys instead.' );
this.enableKeys = ! value;
}
},
staticMoving : {
get: function () {
console.warn( 'THREE.OrbitControls: .staticMoving has been deprecated. Use .enableDamping instead.' );
return ! this.enableDamping;
},
set: function ( value ) {
console.warn( 'THREE.OrbitControls: .staticMoving has been deprecated. Use .enableDamping instead.' );
this.enableDamping = ! value;
}
},
dynamicDampingFactor : {
get: function () {
console.warn( 'THREE.OrbitControls: .dynamicDampingFactor has been renamed. Use .dampingFactor instead.' );
return this.dampingFactor;
},
set: function ( value ) {
console.warn( 'THREE.OrbitControls: .dynamicDampingFactor has been renamed. Use .dampingFactor instead.' );
this.dampingFactor = value;
}
}
} );
};
|
import Koa from 'koa'
import convert from 'koa-convert'
import webpack from 'webpack'
import webpackConfig from '../build/webpack.config'
import historyApiFallback from 'koa-connect-history-api-fallback'
import serve from 'koa-static'
import proxy from 'koa-proxy'
import _debug from 'debug'
import config from '../config'
import webpackDevMiddleware from './middleware/webpack-dev'
import webpackHMRMiddleware from './middleware/webpack-hmr'
const debug = _debug('app:server')
const paths = config.utils_paths
const app = new Koa()
// Enable koa-proxy if it has been enabled in the config.
if (config.proxy && config.proxy.enabled) {
app.use(convert(proxy(config.proxy.options)))
}
// This rewrites all routes requests to the root /index.html file
// (ignoring file requests). If you want to implement isomorphic
// rendering, you'll want to remove this middleware.
app.use(convert(historyApiFallback({
verbose: false
})))
// ------------------------------------
// Apply Webpack HMR Middleware
// ------------------------------------
if (config.env === 'development') {
const compiler = webpack(webpackConfig)
// Enable webpack-dev and webpack-hot middleware
const { publicPath } = webpackConfig.output
app.use(webpackDevMiddleware(compiler, publicPath))
app.use(webpackHMRMiddleware(compiler))
// Serve static assets from ~/src/static since Webpack is unaware of
// these files. This middleware doesn't need to be enabled outside
// of development since this directory will be copied into ~/dist
// when the application is compiled.
app.use(convert(serve(paths.client('static'))))
}
else {
debug(
'Server is being run outside of live development mode, meaning it will ' +
'only serve the compiled application bundle in ~/dist. Generally you ' +
'do not need an application server for this and can instead use a web ' +
'server such as nginx to serve your static files. See the "deployment" ' +
'section in the README for more information on deployment strategies.'
)
// Serving ~/dist by default. Ideally these files should be served by
// the web server and not the app server, but this helps to demo the
// server in production.
app.use(convert(serve(paths.dist())))
}
export default app
|
/*!
* remark v1.0.6 (http://getbootstrapadmin.com/remark)
* Copyright 2015 amazingsurge
* Licensed under the Themeforest Standard Licenses
*/
(function(document, window, $) {
'use strict';
var Site = window.Site;
$(document).ready(function($) {
Site.run();
$('.wb-search').magnificPopup({
type: 'image',
closeOnContentClick: true,
mainClass: 'mfp-fade',
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
}
});
});
})(document, window, jQuery);
|
// api/hooks/sails-permissions.js
module.exports = require('sails-permissions/api/hooks/sails-permissions');
|
'use strict';
/**
* Key command controller tests.
*/
describe('Key command controller', function () {
});
|
{
"AFN_currencyISO" : "AFN",
"AFN_currencySymbol" : "Af",
"ALK_currencyISO" : "AFN",
"ALK_currencySymbol" : "Af",
"ALL_currencyISO" : "AFN",
"ALL_currencySymbol" : "Af",
"AMD_currencyISO" : "AFN",
"AMD_currencySymbol" : "Af",
"ANG_currencyISO" : "ANG",
"ANG_currencySymbol" : "NAf.",
"AOA_currencyISO" : "AOA",
"AOA_currencySymbol" : "Kz",
"AOK_currencyISO" : "AOA",
"AOK_currencySymbol" : "Kz",
"AON_currencyISO" : "AOA",
"AON_currencySymbol" : "Kz",
"AOR_currencyISO" : "AOA",
"AOR_currencySymbol" : "Kz",
"ARA_currencyISO" : "ARA",
"ARA_currencySymbol" : "₳",
"ARL_currencyISO" : "ARL",
"ARL_currencySymbol" : "$L",
"ARM_currencyISO" : "ARM",
"ARM_currencySymbol" : "m$n",
"ARP_currencyISO" : "ARM",
"ARP_currencySymbol" : "m$n",
"ARS_currencyISO" : "ARS",
"ARS_currencySymbol" : "AR$",
"ATS_currencyISO" : "ARS",
"ATS_currencySymbol" : "AR$",
"AUD_currencyISO" : "AUD",
"AUD_currencySymbol" : "AU$",
"AWG_currencyISO" : "AWG",
"AWG_currencySymbol" : "Afl.",
"AZM_currencyISO" : "AWG",
"AZM_currencySymbol" : "Afl.",
"AZN_currencyISO" : "AZN",
"AZN_currencySymbol" : "man.",
"BAD_currencyISO" : "AZN",
"BAD_currencySymbol" : "man.",
"BAM_currencyISO" : "BAM",
"BAM_currencySymbol" : "KM",
"BAN_currencyISO" : "BAM",
"BAN_currencySymbol" : "KM",
"BBD_currencyISO" : "BBD",
"BBD_currencySymbol" : "Bds$",
"BDT_currencyISO" : "BDT",
"BDT_currencySymbol" : "Tk",
"BEC_currencyISO" : "BDT",
"BEC_currencySymbol" : "Tk",
"BEF_currencyISO" : "BEF",
"BEF_currencySymbol" : "BF",
"BEL_currencyISO" : "BEF",
"BEL_currencySymbol" : "BF",
"BGL_currencyISO" : "BEF",
"BGL_currencySymbol" : "BF",
"BGM_currencyISO" : "BEF",
"BGM_currencySymbol" : "BF",
"BGN_currencyISO" : "BEF",
"BGN_currencySymbol" : "BF",
"BGO_currencyISO" : "BEF",
"BGO_currencySymbol" : "BF",
"BHD_currencyISO" : "BHD",
"BHD_currencySymbol" : "BD",
"BIF_currencyISO" : "BIF",
"BIF_currencySymbol" : "FBu",
"BMD_currencyISO" : "BMD",
"BMD_currencySymbol" : "BD$",
"BND_currencyISO" : "BND",
"BND_currencySymbol" : "BN$",
"BOB_currencyISO" : "BOB",
"BOB_currencySymbol" : "Bs",
"BOL_currencyISO" : "BOB",
"BOL_currencySymbol" : "Bs",
"BOP_currencyISO" : "BOP",
"BOP_currencySymbol" : "$b.",
"BOV_currencyISO" : "BOP",
"BOV_currencySymbol" : "$b.",
"BRB_currencyISO" : "BOP",
"BRB_currencySymbol" : "$b.",
"BRC_currencyISO" : "BOP",
"BRC_currencySymbol" : "$b.",
"BRE_currencyISO" : "BOP",
"BRE_currencySymbol" : "$b.",
"BRL_currencyISO" : "BRL",
"BRL_currencySymbol" : "R$",
"BRN_currencyISO" : "BRL",
"BRN_currencySymbol" : "R$",
"BRR_currencyISO" : "BRL",
"BRR_currencySymbol" : "R$",
"BRZ_currencyISO" : "BRL",
"BRZ_currencySymbol" : "R$",
"BSD_currencyISO" : "BSD",
"BSD_currencySymbol" : "BS$",
"BTN_currencyISO" : "BTN",
"BTN_currencySymbol" : "Nu.",
"BUK_currencyISO" : "BTN",
"BUK_currencySymbol" : "Nu.",
"BWP_currencyISO" : "BWP",
"BWP_currencySymbol" : "BWP",
"BYB_currencyISO" : "BWP",
"BYB_currencySymbol" : "BWP",
"BYR_currencyISO" : "BWP",
"BYR_currencySymbol" : "BWP",
"BZD_currencyISO" : "BZD",
"BZD_currencySymbol" : "BZ$",
"CAD_currencyISO" : "CAD",
"CAD_currencySymbol" : "CA$",
"CDF_currencyISO" : "CDF",
"CDF_currencySymbol" : "CDF",
"CHE_currencyISO" : "CDF",
"CHE_currencySymbol" : "CDF",
"CHF_currencyISO" : "CDF",
"CHF_currencySymbol" : "CDF",
"CHW_currencyISO" : "CDF",
"CHW_currencySymbol" : "CDF",
"CLE_currencyISO" : "CLE",
"CLE_currencySymbol" : "Eº",
"CLF_currencyISO" : "CLE",
"CLF_currencySymbol" : "Eº",
"CLP_currencyISO" : "CLP",
"CLP_currencySymbol" : "CL$",
"CNX_currencyISO" : "CLP",
"CNX_currencySymbol" : "CL$",
"CNY_currencyISO" : "CNY",
"CNY_currencySymbol" : "CN¥",
"COP_currencyISO" : "COP",
"COP_currencySymbol" : "CO$",
"COU_currencyISO" : "COP",
"COU_currencySymbol" : "CO$",
"CRC_currencyISO" : "CRC",
"CRC_currencySymbol" : "₡",
"CSD_currencyISO" : "CRC",
"CSD_currencySymbol" : "₡",
"CSK_currencyISO" : "CRC",
"CSK_currencySymbol" : "₡",
"CUC_currencyISO" : "CUC",
"CUC_currencySymbol" : "CUC$",
"CUP_currencyISO" : "CUP",
"CUP_currencySymbol" : "CU$",
"CVE_currencyISO" : "CVE",
"CVE_currencySymbol" : "CV$",
"CYP_currencyISO" : "CYP",
"CYP_currencySymbol" : "CY£",
"CZK_currencyISO" : "CZK",
"CZK_currencySymbol" : "Kč",
"DDM_currencyISO" : "CZK",
"DDM_currencySymbol" : "Kč",
"DEM_currencyISO" : "DEM",
"DEM_currencySymbol" : "DM",
"DJF_currencyISO" : "DJF",
"DJF_currencySymbol" : "Fdj",
"DKK_currencyISO" : "DKK",
"DKK_currencySymbol" : "Dkr",
"DOP_currencyISO" : "DOP",
"DOP_currencySymbol" : "RD$",
"DZD_currencyISO" : "DZD",
"DZD_currencySymbol" : "DA",
"ECS_currencyISO" : "DZD",
"ECS_currencySymbol" : "DA",
"ECV_currencyISO" : "DZD",
"ECV_currencySymbol" : "DA",
"EEK_currencyISO" : "EEK",
"EEK_currencySymbol" : "Ekr",
"EGP_currencyISO" : "EGP",
"EGP_currencySymbol" : "EG£",
"ERN_currencyISO" : "ERN",
"ERN_currencySymbol" : "Nfk",
"ESA_currencyISO" : "ERN",
"ESA_currencySymbol" : "Nfk",
"ESB_currencyISO" : "ERN",
"ESB_currencySymbol" : "Nfk",
"ESP_currencyISO" : "ESP",
"ESP_currencySymbol" : "Pts",
"ETB_currencyISO" : "ETB",
"ETB_currencySymbol" : "Br",
"EUR_currencyISO" : "EUR",
"EUR_currencySymbol" : "€",
"FIM_currencyISO" : "FIM",
"FIM_currencySymbol" : "mk",
"FJD_currencyISO" : "FJD",
"FJD_currencySymbol" : "FJ$",
"FKP_currencyISO" : "FKP",
"FKP_currencySymbol" : "FK£",
"FRF_currencyISO" : "FRF",
"FRF_currencySymbol" : "₣",
"GBP_currencyISO" : "GBP",
"GBP_currencySymbol" : "£",
"GEK_currencyISO" : "GBP",
"GEK_currencySymbol" : "£",
"GEL_currencyISO" : "GBP",
"GEL_currencySymbol" : "£",
"GHC_currencyISO" : "GHC",
"GHC_currencySymbol" : "₵",
"GHS_currencyISO" : "GHS",
"GHS_currencySymbol" : "GH₵",
"GIP_currencyISO" : "GIP",
"GIP_currencySymbol" : "GI£",
"GMD_currencyISO" : "GMD",
"GMD_currencySymbol" : "GMD",
"GNF_currencyISO" : "GNF",
"GNF_currencySymbol" : "FG",
"GNS_currencyISO" : "GNF",
"GNS_currencySymbol" : "FG",
"GQE_currencyISO" : "GNF",
"GQE_currencySymbol" : "FG",
"GRD_currencyISO" : "GRD",
"GRD_currencySymbol" : "₯",
"GTQ_currencyISO" : "GTQ",
"GTQ_currencySymbol" : "GTQ",
"GWE_currencyISO" : "GTQ",
"GWE_currencySymbol" : "GTQ",
"GWP_currencyISO" : "GTQ",
"GWP_currencySymbol" : "GTQ",
"GYD_currencyISO" : "GYD",
"GYD_currencySymbol" : "GY$",
"HKD_currencyISO" : "HKD",
"HKD_currencySymbol" : "HK$",
"HNL_currencyISO" : "HNL",
"HNL_currencySymbol" : "HNL",
"HRD_currencyISO" : "HNL",
"HRD_currencySymbol" : "HNL",
"HRK_currencyISO" : "HRK",
"HRK_currencySymbol" : "kn",
"HTG_currencyISO" : "HTG",
"HTG_currencySymbol" : "HTG",
"HUF_currencyISO" : "HUF",
"HUF_currencySymbol" : "Ft",
"IDR_currencyISO" : "IDR",
"IDR_currencySymbol" : "Rp",
"IEP_currencyISO" : "IEP",
"IEP_currencySymbol" : "IR£",
"ILP_currencyISO" : "ILP",
"ILP_currencySymbol" : "I£",
"ILR_currencyISO" : "ILP",
"ILR_currencySymbol" : "I£",
"ILS_currencyISO" : "ILS",
"ILS_currencySymbol" : "₪",
"INR_currencyISO" : "INR",
"INR_currencySymbol" : "Rs",
"IQD_currencyISO" : "INR",
"IQD_currencySymbol" : "Rs",
"IRR_currencyISO" : "INR",
"IRR_currencySymbol" : "Rs",
"ISJ_currencyISO" : "INR",
"ISJ_currencySymbol" : "Rs",
"ISK_currencyISO" : "ISK",
"ISK_currencySymbol" : "Ikr",
"ITL_currencyISO" : "ITL",
"ITL_currencySymbol" : "IT₤",
"JMD_currencyISO" : "JMD",
"JMD_currencySymbol" : "J$",
"JOD_currencyISO" : "JOD",
"JOD_currencySymbol" : "JD",
"JPY_currencyISO" : "JPY",
"JPY_currencySymbol" : "JP¥",
"KES_currencyISO" : "KES",
"KES_currencySymbol" : "Ksh",
"KGS_currencyISO" : "KES",
"KGS_currencySymbol" : "Ksh",
"KHR_currencyISO" : "KES",
"KHR_currencySymbol" : "Ksh",
"KMF_currencyISO" : "KMF",
"KMF_currencySymbol" : "CF",
"KPW_currencyISO" : "KMF",
"KPW_currencySymbol" : "CF",
"KRH_currencyISO" : "KMF",
"KRH_currencySymbol" : "CF",
"KRO_currencyISO" : "KMF",
"KRO_currencySymbol" : "CF",
"KRW_currencyISO" : "KRW",
"KRW_currencySymbol" : "₩",
"KWD_currencyISO" : "KWD",
"KWD_currencySymbol" : "KD",
"KYD_currencyISO" : "KYD",
"KYD_currencySymbol" : "KY$",
"KZT_currencyISO" : "KYD",
"KZT_currencySymbol" : "KY$",
"LAK_currencyISO" : "LAK",
"LAK_currencySymbol" : "₭",
"LBP_currencyISO" : "LBP",
"LBP_currencySymbol" : "LB£",
"LKR_currencyISO" : "LKR",
"LKR_currencySymbol" : "SLRs",
"LRD_currencyISO" : "LRD",
"LRD_currencySymbol" : "L$",
"LSL_currencyISO" : "LSL",
"LSL_currencySymbol" : "LSL",
"LTL_currencyISO" : "LTL",
"LTL_currencySymbol" : "Lt",
"LTT_currencyISO" : "LTL",
"LTT_currencySymbol" : "Lt",
"LUC_currencyISO" : "LTL",
"LUC_currencySymbol" : "Lt",
"LUF_currencyISO" : "LTL",
"LUF_currencySymbol" : "Lt",
"LUL_currencyISO" : "LTL",
"LUL_currencySymbol" : "Lt",
"LVL_currencyISO" : "LVL",
"LVL_currencySymbol" : "Ls",
"LVR_currencyISO" : "LVL",
"LVR_currencySymbol" : "Ls",
"LYD_currencyISO" : "LYD",
"LYD_currencySymbol" : "LD",
"MAD_currencyISO" : "LYD",
"MAD_currencySymbol" : "LD",
"MAF_currencyISO" : "LYD",
"MAF_currencySymbol" : "LD",
"MCF_currencyISO" : "LYD",
"MCF_currencySymbol" : "LD",
"MDC_currencyISO" : "LYD",
"MDC_currencySymbol" : "LD",
"MDL_currencyISO" : "LYD",
"MDL_currencySymbol" : "LD",
"MGA_currencyISO" : "LYD",
"MGA_currencySymbol" : "LD",
"MGF_currencyISO" : "LYD",
"MGF_currencySymbol" : "LD",
"MKD_currencyISO" : "LYD",
"MKD_currencySymbol" : "LD",
"MKN_currencyISO" : "LYD",
"MKN_currencySymbol" : "LD",
"MLF_currencyISO" : "LYD",
"MLF_currencySymbol" : "LD",
"MMK_currencyISO" : "MMK",
"MMK_currencySymbol" : "MMK",
"MNT_currencyISO" : "MNT",
"MNT_currencySymbol" : "₮",
"MOP_currencyISO" : "MOP",
"MOP_currencySymbol" : "MOP$",
"MRO_currencyISO" : "MRO",
"MRO_currencySymbol" : "UM",
"MTL_currencyISO" : "MTL",
"MTL_currencySymbol" : "Lm",
"MTP_currencyISO" : "MTP",
"MTP_currencySymbol" : "MT£",
"MUR_currencyISO" : "MUR",
"MUR_currencySymbol" : "MURs",
"MVP_currencyISO" : "MUR",
"MVP_currencySymbol" : "MURs",
"MVR_currencyISO" : "MUR",
"MVR_currencySymbol" : "MURs",
"MWK_currencyISO" : "MUR",
"MWK_currencySymbol" : "MURs",
"MXN_currencyISO" : "MXN",
"MXN_currencySymbol" : "MX$",
"MXP_currencyISO" : "MXN",
"MXP_currencySymbol" : "MX$",
"MXV_currencyISO" : "MXN",
"MXV_currencySymbol" : "MX$",
"MYR_currencyISO" : "MYR",
"MYR_currencySymbol" : "RM",
"MZE_currencyISO" : "MYR",
"MZE_currencySymbol" : "RM",
"MZM_currencyISO" : "MZM",
"MZM_currencySymbol" : "Mt",
"MZN_currencyISO" : "MZN",
"MZN_currencySymbol" : "MTn",
"NAD_currencyISO" : "NAD",
"NAD_currencySymbol" : "N$",
"NGN_currencyISO" : "NGN",
"NGN_currencySymbol" : "₦",
"NIC_currencyISO" : "NGN",
"NIC_currencySymbol" : "₦",
"NIO_currencyISO" : "NIO",
"NIO_currencySymbol" : "C$",
"NLG_currencyISO" : "NLG",
"NLG_currencySymbol" : "fl",
"NOK_currencyISO" : "NOK",
"NOK_currencySymbol" : "Nkr",
"NPR_currencyISO" : "NPR",
"NPR_currencySymbol" : "NPRs",
"NZD_currencyISO" : "NZD",
"NZD_currencySymbol" : "NZ$",
"OMR_currencyISO" : "NZD",
"OMR_currencySymbol" : "NZ$",
"PAB_currencyISO" : "PAB",
"PAB_currencySymbol" : "B/.",
"PEI_currencyISO" : "PEI",
"PEI_currencySymbol" : "I/.",
"PEN_currencyISO" : "PEN",
"PEN_currencySymbol" : "S/.",
"PES_currencyISO" : "PEN",
"PES_currencySymbol" : "S/.",
"PGK_currencyISO" : "PGK",
"PGK_currencySymbol" : "PGK",
"PHP_currencyISO" : "PHP",
"PHP_currencySymbol" : "₱",
"PKR_currencyISO" : "PKR",
"PKR_currencySymbol" : "PKRs",
"PLN_currencyISO" : "PLN",
"PLN_currencySymbol" : "zł",
"PLZ_currencyISO" : "PLN",
"PLZ_currencySymbol" : "zł",
"PTE_currencyISO" : "PTE",
"PTE_currencySymbol" : "Esc",
"PYG_currencyISO" : "PYG",
"PYG_currencySymbol" : "₲",
"QAR_currencyISO" : "QAR",
"QAR_currencySymbol" : "QR",
"RHD_currencyISO" : "RHD",
"RHD_currencySymbol" : "RH$",
"ROL_currencyISO" : "RHD",
"ROL_currencySymbol" : "RH$",
"RON_currencyISO" : "RON",
"RON_currencySymbol" : "RON",
"RSD_currencyISO" : "RSD",
"RSD_currencySymbol" : "din.",
"RUB_currencyISO" : "RSD",
"RUB_currencySymbol" : "din.",
"RUR_currencyISO" : "RSD",
"RUR_currencySymbol" : "din.",
"RWF_currencyISO" : "RSD",
"RWF_currencySymbol" : "din.",
"SAR_currencyISO" : "SAR",
"SAR_currencySymbol" : "SR",
"SBD_currencyISO" : "SBD",
"SBD_currencySymbol" : "SI$",
"SCR_currencyISO" : "SCR",
"SCR_currencySymbol" : "SRe",
"SDD_currencyISO" : "SDD",
"SDD_currencySymbol" : "LSd",
"SDG_currencyISO" : "SDD",
"SDG_currencySymbol" : "LSd",
"SDP_currencyISO" : "SDD",
"SDP_currencySymbol" : "LSd",
"SEK_currencyISO" : "SEK",
"SEK_currencySymbol" : "Skr",
"SGD_currencyISO" : "SGD",
"SGD_currencySymbol" : "S$",
"SHP_currencyISO" : "SHP",
"SHP_currencySymbol" : "SH£",
"SIT_currencyISO" : "SHP",
"SIT_currencySymbol" : "SH£",
"SKK_currencyISO" : "SKK",
"SKK_currencySymbol" : "Sk",
"SLL_currencyISO" : "SLL",
"SLL_currencySymbol" : "Le",
"SOS_currencyISO" : "SOS",
"SOS_currencySymbol" : "Ssh",
"SRD_currencyISO" : "SRD",
"SRD_currencySymbol" : "SR$",
"SRG_currencyISO" : "SRG",
"SRG_currencySymbol" : "Sf",
"SSP_currencyISO" : "SRG",
"SSP_currencySymbol" : "Sf",
"STD_currencyISO" : "STD",
"STD_currencySymbol" : "Db",
"SUR_currencyISO" : "STD",
"SUR_currencySymbol" : "Db",
"SVC_currencyISO" : "SVC",
"SVC_currencySymbol" : "SV₡",
"SYP_currencyISO" : "SYP",
"SYP_currencySymbol" : "SY£",
"SZL_currencyISO" : "SZL",
"SZL_currencySymbol" : "SZL",
"THB_currencyISO" : "THB",
"THB_currencySymbol" : "฿",
"TJR_currencyISO" : "THB",
"TJR_currencySymbol" : "฿",
"TJS_currencyISO" : "THB",
"TJS_currencySymbol" : "฿",
"TMM_currencyISO" : "TMM",
"TMM_currencySymbol" : "TMM",
"TMT_currencyISO" : "TMM",
"TMT_currencySymbol" : "TMM",
"TND_currencyISO" : "TND",
"TND_currencySymbol" : "DT",
"TOP_currencyISO" : "TOP",
"TOP_currencySymbol" : "T$",
"TPE_currencyISO" : "TOP",
"TPE_currencySymbol" : "T$",
"TRL_currencyISO" : "TRL",
"TRL_currencySymbol" : "TRL",
"TRY_currencyISO" : "TRY",
"TRY_currencySymbol" : "TL",
"TTD_currencyISO" : "TTD",
"TTD_currencySymbol" : "TT$",
"TWD_currencyISO" : "TWD",
"TWD_currencySymbol" : "NT$",
"TZS_currencyISO" : "TZS",
"TZS_currencySymbol" : "TSh",
"UAH_currencyISO" : "UAH",
"UAH_currencySymbol" : "₴",
"UAK_currencyISO" : "UAH",
"UAK_currencySymbol" : "₴",
"UGS_currencyISO" : "UAH",
"UGS_currencySymbol" : "₴",
"UGX_currencyISO" : "UGX",
"UGX_currencySymbol" : "USh",
"USD_currencyISO" : "USD",
"USD_currencySymbol" : "US$",
"USN_currencyISO" : "USD",
"USN_currencySymbol" : "US$",
"USS_currencyISO" : "USD",
"USS_currencySymbol" : "US$",
"UYI_currencyISO" : "USD",
"UYI_currencySymbol" : "US$",
"UYP_currencyISO" : "USD",
"UYP_currencySymbol" : "US$",
"UYU_currencyISO" : "UYU",
"UYU_currencySymbol" : "$U",
"UZS_currencyISO" : "UYU",
"UZS_currencySymbol" : "$U",
"VEB_currencyISO" : "UYU",
"VEB_currencySymbol" : "$U",
"VEF_currencyISO" : "VEF",
"VEF_currencySymbol" : "Bs.F.",
"VND_currencyISO" : "VND",
"VND_currencySymbol" : "₫",
"VNN_currencyISO" : "VND",
"VNN_currencySymbol" : "₫",
"VUV_currencyISO" : "VUV",
"VUV_currencySymbol" : "VT",
"WST_currencyISO" : "WST",
"WST_currencySymbol" : "WS$",
"XAF_currencyISO" : "XAF",
"XAF_currencySymbol" : "FCFA",
"XAG_currencyISO" : "XAF",
"XAG_currencySymbol" : "FCFA",
"XAU_currencyISO" : "XAF",
"XAU_currencySymbol" : "FCFA",
"XBA_currencyISO" : "XAF",
"XBA_currencySymbol" : "FCFA",
"XBB_currencyISO" : "XAF",
"XBB_currencySymbol" : "FCFA",
"XBC_currencyISO" : "XAF",
"XBC_currencySymbol" : "FCFA",
"XBD_currencyISO" : "XAF",
"XBD_currencySymbol" : "FCFA",
"XCD_currencyISO" : "XCD",
"XCD_currencySymbol" : "EC$",
"XDR_currencyISO" : "XCD",
"XDR_currencySymbol" : "EC$",
"XEU_currencyISO" : "XCD",
"XEU_currencySymbol" : "EC$",
"XFO_currencyISO" : "XCD",
"XFO_currencySymbol" : "EC$",
"XFU_currencyISO" : "XCD",
"XFU_currencySymbol" : "EC$",
"XOF_currencyISO" : "XOF",
"XOF_currencySymbol" : "CFA",
"XPD_currencyISO" : "XOF",
"XPD_currencySymbol" : "CFA",
"XPF_currencyISO" : "XPF",
"XPF_currencySymbol" : "CFPF",
"XPT_currencyISO" : "XPF",
"XPT_currencySymbol" : "CFPF",
"XRE_currencyISO" : "XPF",
"XRE_currencySymbol" : "CFPF",
"XSU_currencyISO" : "XPF",
"XSU_currencySymbol" : "CFPF",
"XTS_currencyISO" : "XPF",
"XTS_currencySymbol" : "CFPF",
"XUA_currencyISO" : "XPF",
"XUA_currencySymbol" : "CFPF",
"XXX_currencyISO" : "ꅉꀋꐚꌠꌋꆀꎆꃀꀋꈁꀐꌠ",
"XXX_currencySymbol" : "XXX",
"YDD_currencyISO" : "ꅉꀋꐚꌠꌋꆀꎆꃀꀋꈁꀐꌠ",
"YDD_currencySymbol" : "XXX",
"YER_currencyISO" : "YER",
"YER_currencySymbol" : "YR",
"YUD_currencyISO" : "YER",
"YUD_currencySymbol" : "YR",
"YUM_currencyISO" : "YER",
"YUM_currencySymbol" : "YR",
"YUN_currencyISO" : "YER",
"YUN_currencySymbol" : "YR",
"YUR_currencyISO" : "YER",
"YUR_currencySymbol" : "YR",
"ZAL_currencyISO" : "YER",
"ZAL_currencySymbol" : "YR",
"ZAR_currencyISO" : "ZAR",
"ZAR_currencySymbol" : "R",
"ZMK_currencyISO" : "ZMK",
"ZMK_currencySymbol" : "ZK",
"ZRN_currencyISO" : "ZRN",
"ZRN_currencySymbol" : "NZ",
"ZRZ_currencyISO" : "ZRZ",
"ZRZ_currencySymbol" : "ZRZ",
"ZWD_currencyISO" : "ZWD",
"ZWD_currencySymbol" : "Z$",
"ZWL_currencyISO" : "ZWD",
"ZWL_currencySymbol" : "Z$",
"ZWR_currencyISO" : "ZWD",
"ZWR_currencySymbol" : "Z$",
"currencyFormat" : "¤ #,##0.00",
"currencyPatternPlural" : "e u",
"currencyPatternSingular" : "{0} {1}",
"decimalFormat" : "#,##0.###",
"decimalSeparator" : ".",
"defaultCurrency" : "CNY",
"exponentialSymbol" : "E",
"groupingSeparator" : ",",
"infinitySign" : "∞",
"minusSign" : "-",
"nanSymbol" : "NaN",
"numberZero" : "0",
"perMilleSign" : "‰",
"percentFormat" : "#,##0%",
"percentSign" : "%",
"plusSign" : "+",
"scientificFormat" : "#E0"
}
|
import HelloWebpackCSS from '../components/hello-webpack-css'
export default () => <HelloWebpackCSS />
|
import chai from 'chai';
import { scaleOrdinal, scaleLinear, scaleLog } from 'd3';
const expect = chai.expect;
import {
clampedScale,
domainToRange,
getScale,
getScaleTypes,
rangeToDomain,
} from '../scale';
import {
percentOfRange,
} from '../domain';
describe('scale utilities', () => {
describe('getScaleTypes()', () => {
it('provides a list of scale names', () => {
const scaleTypes = getScaleTypes();
expect(scaleTypes).to.not.be.empty;
expect(scaleTypes).to.contain('linear');
});
});
describe.skip('getScale()', () => {
it('returns specified type of scale', () => {
expect(getScale('ordinal')).to.be.equal(scaleOrdinal);
});
it('provides a default of `linear`', () => {
expect(getScale()).to.be.equal(scaleLinear);
});
});
describe('domainToRange()', () => {
it('inverts two points on the domain', () => {
const scale = scaleLinear().range([0, 100]);
expect(domainToRange(scale, scale.domain())).to.deep.equal([0, 100]);
expect(domainToRange(scale, [0.1, 0.9])).to.deep.equal([10, 90]);
});
});
describe('rangeToDomain()', () => {
it('inverts two points on the range', () => {
const scale = scaleLinear().range([0, 100]);
expect(rangeToDomain(scale, scale.range())).to.deep.equal([0, 1]);
expect(rangeToDomain(scale, [10, 90])).to.deep.equal([0.1, 0.9]);
});
});
describe('clampedScale', () => {
it('sets the base scale', () => {
const scale = clampedScale()
.base(scaleLinear())
.domain([0, 1])
.range([0, 1]);
expect(scale(0)).to.equal(0);
expect(scale(1)).to.equal(1);
expect(scale(0.5)).to.equal(0.5);
});
it('can update its base scale', () => {
const initialScale = clampedScale()
.base(scaleLinear())
.domain([1, 10])
.range([0, 1]);
expect(initialScale(5.5)).to.equal(0.5);
const logScale = scaleLog().base(Math.E);
const updatedScale = initialScale
.base(logScale);
expect(updatedScale(1)).to.equal(0);
expect(updatedScale(10)).to.equal(1);
// arbitrarily round to 8 sig figs
expect(updatedScale(5.5).toFixed(8)).to.equal(
percentOfRange(Math.log(5.5), [Math.log(1), Math.log(10)]).toFixed(8)
);
});
it('sets the domain of the scale', () => {
const scale = clampedScale().base(scaleLinear());
const cachedDomain = scale.domain();
scale.domain([100, 200]);
const newDomain = scale.domain();
expect(newDomain).to.not.deep.equal(cachedDomain);
expect(newDomain).to.deep.equal([100, 200]);
});
it('sets the range of the scale', () => {
const scale = clampedScale().base(scaleLinear());
const cachedRange = scale.range();
scale.range([100, 200]);
const newRange = scale.range();
expect(newRange).to.not.deep.equal(cachedRange);
expect(newRange).to.deep.equal([100, 200]);
});
it('returns a copy of the scale', () => {
const scale = clampedScale()
.base(scaleLinear())
.domain([0, 100])
.range([0, 1000]);
expect(scale).to.equal(scale);
expect(scale(50)).to.equal(500);
const copy = scale.copy();
expect(copy).to.not.equal(scale);
expect(copy(50)).to.equal(500);
});
it('is clamped, and returns a specified value for anything outside of its clamps', () => {
const scale = clampedScale('foo').base(scaleLinear())
.domain([0, 1])
.range([0, 1])
.clamps([0.25, 0.75]);
expect(scale(0.3)).to.equal(0.3);
expect(scale(0.1)).to.equal('foo');
});
it('can have it\'s tolerance adjusted for whether a value is within its domain', () => {
const scale = clampedScale('foo', 0.001)
.base(scaleLinear())
.domain([0, 1])
.range([0, 1])
.clamps([0.25, 0.75]);
expect(scale(0.3)).to.equal(0.3);
expect(scale(0.24)).to.equal('foo');
expect(scale(0.249)).to.equal(0.249);
expect(scale(0.2408)).to.equal('foo');
expect(scale(0.7)).to.equal(0.7);
expect(scale(0.751)).to.equal(0.751);
expect(scale(0.7509)).to.equal(0.7509);
expect(scale(0.752)).to.equal('foo');
});
});
});
|
/* global isIFrameWithoutSrc:true */
import hammerhead from '../deps/hammerhead';
import * as styleUtils from './style';
import * as domUtils from './dom';
export const getElementRectangle = hammerhead.utils.position.getElementRectangle;
export const getOffsetPosition = hammerhead.utils.position.getOffsetPosition;
export const offsetToClientCoords = hammerhead.utils.position.offsetToClientCoords;
export function getIframeClientCoordinates (iframe) {
const { left, top } = getOffsetPosition(iframe);
const clientPosition = offsetToClientCoords({ x: left, y: top });
const iframeBorders = styleUtils.getBordersWidth(iframe);
const iframePadding = styleUtils.getElementPadding(iframe);
const iframeRectangleLeft = clientPosition.x + iframeBorders.left + iframePadding.left;
const iframeRectangleTop = clientPosition.y + iframeBorders.top + iframePadding.top;
return {
left: iframeRectangleLeft,
top: iframeRectangleTop,
right: iframeRectangleLeft + styleUtils.getWidth(iframe),
bottom: iframeRectangleTop + styleUtils.getHeight(iframe)
};
}
export function isElementVisible (el) {
if (domUtils.isTextNode(el))
return !styleUtils.isNotVisibleNode(el);
const elementRectangle = getElementRectangle(el);
if (!domUtils.isContentEditableElement(el)) {
if (elementRectangle.width === 0 || elementRectangle.height === 0)
return false;
}
if (domUtils.isMapElement(el)) {
const mapContainer = domUtils.getMapContainer(domUtils.closest(el, 'map'));
return mapContainer ? isElementVisible(mapContainer) : false;
}
if (styleUtils.isSelectVisibleChild(el)) {
const select = domUtils.getSelectParent(el);
const childRealIndex = domUtils.getChildVisibleIndex(select, el);
const realSelectSizeValue = styleUtils.getSelectElementSize(select);
const topVisibleIndex = Math.max(styleUtils.getScrollTop(select) / styleUtils.getOptionHeight(select), 0);
const bottomVisibleIndex = topVisibleIndex + realSelectSizeValue - 1;
const optionVisibleIndex = Math.max(childRealIndex - topVisibleIndex, 0);
return optionVisibleIndex >= topVisibleIndex && optionVisibleIndex <= bottomVisibleIndex;
}
if (domUtils.isSVGElement(el))
return styleUtils.get(el, 'visibility') !== 'hidden' && styleUtils.get(el, 'display') !== 'none';
return styleUtils.hasDimensions(el) && styleUtils.get(el, 'visibility') !== 'hidden';
}
export function getClientDimensions (target) {
if (!domUtils.isDomElement(target)) {
const clientPoint = offsetToClientCoords(target);
return {
width: 0,
height: 0,
border: {
bottom: 0,
left: 0,
right: 0,
top: 0
},
scroll: {
left: 0,
top: 0
},
left: clientPoint.x,
right: clientPoint.x,
top: clientPoint.y,
bottom: clientPoint.y
};
}
const isHtmlElement = /html/i.test(target.tagName);
const body = isHtmlElement ? target.getElementsByTagName('body')[0] : null;
const elementBorders = styleUtils.getBordersWidth(target);
const elementRect = target.getBoundingClientRect();
const elementScroll = styleUtils.getElementScroll(target);
const isElementInIframe = domUtils.isElementInIframe(target);
let elementLeftPosition = isHtmlElement ? 0 : elementRect.left;
let elementTopPosition = isHtmlElement ? 0 : elementRect.top;
let elementHeight = isHtmlElement ? target.clientHeight : elementRect.height;
let elementWidth = isHtmlElement ? target.clientWidth : elementRect.width;
const isCompatMode = target.ownerDocument.compatMode === 'BackCompat';
if (isHtmlElement && body && (typeof isIFrameWithoutSrc === 'boolean' && isIFrameWithoutSrc || isCompatMode)) {
elementHeight = body.clientHeight;
elementWidth = body.clientWidth;
}
if (isElementInIframe) {
const iframeElement = domUtils.getIframeByElement(target);
if (iframeElement) {
const iframeOffset = getOffsetPosition(iframeElement);
const clientOffset = offsetToClientCoords({
x: iframeOffset.left,
y: iframeOffset.top
});
const iframeBorders = styleUtils.getBordersWidth(iframeElement);
elementLeftPosition += clientOffset.x + iframeBorders.left;
elementTopPosition += clientOffset.y + iframeBorders.top;
if (isHtmlElement) {
elementBorders.bottom += iframeBorders.bottom;
elementBorders.left += iframeBorders.left;
elementBorders.right += iframeBorders.right;
elementBorders.top += iframeBorders.top;
}
}
}
const hasRightScrollbar = !isHtmlElement && styleUtils.getInnerWidth(target) !== target.clientWidth;
const rightScrollbarWidth = hasRightScrollbar ? domUtils.getScrollbarSize() : 0;
const hasBottomScrollbar = !isHtmlElement && styleUtils.getInnerHeight(target) !== target.clientHeight;
const bottomScrollbarHeight = hasBottomScrollbar ? domUtils.getScrollbarSize() : 0;
return {
width: elementWidth,
height: elementHeight,
left: elementLeftPosition,
top: elementTopPosition,
border: elementBorders,
bottom: elementTopPosition + elementHeight,
right: elementLeftPosition + elementWidth,
scroll: {
left: elementScroll.left,
top: elementScroll.top
},
scrollbar: {
right: rightScrollbarWidth,
bottom: bottomScrollbarHeight
}
};
}
export function containsOffset (el, offsetX, offsetY) {
const dimensions = getClientDimensions(el);
const width = Math.max(el.scrollWidth, dimensions.width);
const height = Math.max(el.scrollHeight, dimensions.height);
const maxX = dimensions.scrollbar.right + dimensions.border.left + dimensions.border.right + width;
const maxY = dimensions.scrollbar.bottom + dimensions.border.top + dimensions.border.bottom + height;
return (typeof offsetX === 'undefined' || offsetX >= 0 && maxX >= offsetX) &&
(typeof offsetY === 'undefined' || offsetY >= 0 && maxY >= offsetY);
}
export function getEventAbsoluteCoordinates (ev) {
const el = ev.target || ev.srcElement;
const pageCoordinates = getEventPageCoordinates(ev);
const curDocument = domUtils.findDocument(el);
let xOffset = 0;
let yOffset = 0;
if (domUtils.isElementInIframe(curDocument.documentElement)) {
const currentIframe = domUtils.getIframeByElement(curDocument);
if (currentIframe) {
const iframeOffset = getOffsetPosition(currentIframe);
const iframeBorders = styleUtils.getBordersWidth(currentIframe);
xOffset = iframeOffset.left + iframeBorders.left;
yOffset = iframeOffset.top + iframeBorders.top;
}
}
return {
x: pageCoordinates.x + xOffset,
y: pageCoordinates.y + yOffset
};
}
export function getEventPageCoordinates (ev) {
const curCoordObject = /^touch/.test(ev.type) && ev.targetTouches ? ev.targetTouches[0] || ev.changedTouches[0] : ev;
const bothPageCoordinatesAreZero = curCoordObject.pageX === 0 && curCoordObject.pageY === 0;
const notBothClientCoordinatesAreZero = curCoordObject.clientX !== 0 || curCoordObject.clientY !== 0;
if ((curCoordObject.pageX === null || bothPageCoordinatesAreZero && notBothClientCoordinatesAreZero) &&
curCoordObject.clientX !== null) {
const currentDocument = domUtils.findDocument(ev.target || ev.srcElement);
const html = currentDocument.documentElement;
const body = currentDocument.body;
return {
x: Math.round(curCoordObject.clientX + (html && html.scrollLeft || body && body.scrollLeft || 0) -
(html.clientLeft || 0)),
y: Math.round(curCoordObject.clientY + (html && html.scrollTop || body && body.scrollTop || 0) -
(html.clientTop || 0))
};
}
return {
x: Math.round(curCoordObject.pageX),
y: Math.round(curCoordObject.pageY)
};
}
export function getElementFromPoint (x, y) {
let el = null;
const func = document.getElementFromPoint || document.elementFromPoint;
try {
// Permission denied to access property 'getElementFromPoint' error in iframe
el = func.call(document, x, y);
}
catch (ex) {
return null;
}
//NOTE: elementFromPoint returns null when is's a border of an iframe
if (el === null)
el = func.call(document, x - 1, y - 1);
while (el && el.shadowRoot && el.shadowRoot.elementFromPoint) {
const shadowEl = el.shadowRoot.elementFromPoint(x, y);
if (!shadowEl || el === shadowEl)
break;
el = shadowEl;
}
return el;
}
export function getIframePointRelativeToParentFrame (pos, iframeWin) {
const iframe = domUtils.findIframeByWindow(iframeWin);
const iframeOffset = getOffsetPosition(iframe);
const iframeBorders = styleUtils.getBordersWidth(iframe);
const iframePadding = styleUtils.getElementPadding(iframe);
return offsetToClientCoords({
x: pos.x + iframeOffset.left + iframeBorders.left + iframePadding.left,
y: pos.y + iframeOffset.top + iframeBorders.top + iframePadding.top
});
}
export function clientToOffsetCoord (coords, currentDocument) {
const doc = currentDocument || document;
return {
x: coords.x + styleUtils.getScrollLeft(doc),
y: coords.y + styleUtils.getScrollTop(doc)
};
}
export function findCenter (el) {
const rectangle = getElementRectangle(el);
return {
x: Math.round(rectangle.left + rectangle.width / 2),
y: Math.round(rectangle.top + rectangle.height / 2)
};
}
export function getClientPosition (el) {
const { left, top } = getOffsetPosition(el);
const clientCoords = offsetToClientCoords({ x: left, y: top });
clientCoords.x = Math.round(clientCoords.x);
clientCoords.y = Math.round(clientCoords.y);
return clientCoords;
}
export function getElementClientRectangle (el) {
const rect = getElementRectangle(el);
const clientPos = offsetToClientCoords({
x: rect.left,
y: rect.top
});
return {
height: rect.height,
left: clientPos.x,
top: clientPos.y,
width: rect.width
};
}
export function calcRelativePosition (dimensions, toDimensions) {
return {
left: Math.ceil(dimensions.left - (toDimensions.left + toDimensions.border.left)),
right: Math.floor(toDimensions.right - toDimensions.border.right - toDimensions.scrollbar.right -
dimensions.right),
top: Math.ceil(dimensions.top - (toDimensions.top + toDimensions.border.top)),
bottom: Math.floor(toDimensions.bottom - toDimensions.border.bottom - toDimensions.scrollbar.bottom -
dimensions.bottom)
};
}
export function isInRectangle ({ x, y }, rectangle) {
return x >= rectangle.left && x <= rectangle.right && y >= rectangle.top && y <= rectangle.bottom;
}
export function getLineYByXCoord (startLinePoint, endLinePoint, x) {
if (endLinePoint.x - startLinePoint.x === 0)
return null;
const equationSlope = (endLinePoint.y - startLinePoint.y) / (endLinePoint.x - startLinePoint.x);
const equationYIntercept = startLinePoint.x * (startLinePoint.y - endLinePoint.y) /
(endLinePoint.x - startLinePoint.x) + startLinePoint.y;
return Math.round(equationSlope * x + equationYIntercept);
}
export function getLineXByYCoord (startLinePoint, endLinePoint, y) {
if (endLinePoint.y - startLinePoint.y === 0)
return null;
const equationSlope = (endLinePoint.x - startLinePoint.x) / (endLinePoint.y - startLinePoint.y);
const equationXIntercept = startLinePoint.y * (startLinePoint.x - endLinePoint.x) /
(endLinePoint.y - startLinePoint.y) + startLinePoint.x;
return Math.round(equationSlope * y + equationXIntercept);
}
|
(function( App ){
'use strict';
/**
* example:
* {{view App.Select2SelectView
id="mySelect"
contentBinding="App.staticData"
optionValuePath="content.id"
optionLabelPath="content.label"
selectionBinding="controller.selectedId"}}
{{view App.Select2SelectView
class="pull-right select-num-rows"
contentBinding="availableRows"
valueBinding="numRows"}}
*
* advanced
* promptTranslation='my.translation' // will be translated using Em.I18n
* createAction='actionName' // action must be present in current controller
* createTranslation='my.create.translation' // same as promptTranslation
*
* the createAction gets:
* @param name {String} the entered name
* @param obj {JQuery} the jquery object of this select2 instance
*
* the changeAction gets:
* @param name {String} (the entered name)
* @param obj {JQuery} jquery object of this select2 instance
*
*/
Ember.Select2 = Ember.Select.extend({
prompt: Em.I18n.t('please_select'),
classNames: ['input-xlarge'],
search: true,
willInsertElement: function(){
if( this.get('noPrompt') )
this.set('prompt','');
if( this.get('promptTranslation') )
this.set('prompt', Em.I18n.t(this.get('promptTranslation')));
},
didInsertElement: function() {
Ember.run.scheduleOnce('afterRender', this, 'processChildElements');
},
processChildElements: function() {
var self = this;
var options = {};
if( !this.get('search') )
options.minimumResultsForSearch = -1;
this.$().select2( options ).on('select2-open', function(){
if( !self.get('createAction') )
return;
if( $('#select2-drop .select2-input').data('emberized') )
return;
$('#select2-drop .select2-input').data('emberized',true);
$('#select2-drop .select2-input').on('keyup', function(e){
if( e.keyCode === 27 )
self.$().select2('close');
if( $('#select2-drop .select2-results').length < 2 && this.value.length > 0 )
$('#select2-drop .select2-no-results').text( Em.I18n.t(self.get('createTranslation')));
else if( this.value.length > 0 )
$('#select2-drop .select2-no-results').text( Em.I18n.t(self.get('promptTranslation')));
if( e.keyCode !== 13 )
return;
self.get('controller').send(self.get('createAction'), this.value, self.$() );
self.$().select2('close');
});
})
.on('change', function(){
if( self.get('changeAction') )
self.get('controller').send(self.get('changeAction'), this.value, self.$() );
});
if( self.get('selectFirst') && self.get('content.length') > 0 )
self.$().select2('val', self.get('content.firstObject.id'));
},
willDestroyElement: function () {
this.$().select2("destroy");
},
selectedDidChange : function(){
var self = this;
setTimeout(function(){
if( !self.$() ){ return; } // exit if view has gone meantime
self.$().select2('val', self.get('value'));
},100);
}.observes('selection.@each')
});
Ember.Countries = Ember.Select.extend({
prompt: Em.I18n.t('select_country'),
classNames: ['input-xlarge'],
willInsertElement: function(){
var self = this;
this.set('optionLabelPath', 'content.text');
this.set('optionValuePath', 'content.id');
var response = countryCodes[$('html').attr('lang')];
var countries = [];
for( var code in response )
countries.push({ id: code, text: response[code] });
countries.sort(function(a,b){
if( a.text.toLowerCase() < b.text.toLowerCase() ) return -1;
if( a.text.toLowerCase() > b.text.toLowerCase() ) return 1;
if( a.text.toLowerCase() === b.text.toLowerCase() ) return 0;
});
self.set('content', countries);
setTimeout(function(){
if( self.get('value') )
self.$().select2('val', self.get('value'));
else if( App.get('_currentDomain.preferences.defaultCountry') )
self.$().select2('val', App.get('_currentDomain.preferences.defaultCountry'));
},100);
},
didInsertElement: function() {
Ember.run.scheduleOnce('afterRender', this, 'processChildElements');
},
processChildElements: function() {
var self = this;
this.$().select2();
},
willDestroyElement: function () {
this.$().select2("destroy");
},
selectedDidChange : function(){
var self = this;
setTimeout(function(){
if( self.get('value') )
self.$().select2('val', self.get('value'));
},100);
}.observes('value')
});
/**
* TypeaheadTextFieldView
* example:
* {{view App.Select2AjaxTextFieldView
source="/caminio/get/data.json?q=%QUERY"
optionValuePath="content.id"
optionLabelPath="content.label"
valueBinding="controller.selectedId"}}
{{view App.Select2SelectView
class="pull-right select-num-rows"
contentBinding="availableRows"
valueBinding="numRows"}}
*
* advanced
* promptTranslation='my.translation' // will be translated using Em.I18n
* createAction='actionName' // action must be present in current controller
* createTranslation='my.create.translation' // same as promptTranslation
*
* the createAction gets:
* @param name {String} name (the entered name)
* @param elem {JQuery} the jquery object of this select2 instance
*
* the transformResultsAction gets:
* @param data {Array}
* @param page {JQuery} the current page if paging support is enabled
*
* and should return a select2 compatible result array
*
*/
Ember.Typeahead = Ember.TextField.extend({
classNames: ['input-xlarge'],
didInsertElement: function() {
Ember.run.scheduleOnce('afterRender', this, 'processChildElements');
},
processChildElements: function() {
var self = this;
var sources;
if( this.get('source') )
sources = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace( self.get('optionValuePath') ),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: this.get('source')
});
else if( this.get('localContent') )
sources = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace( self.get('optionValuePath')),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: $.map( this.get('localContent'), function(c){ return { value: c }; })
});
if( !sources )
return;
sources.initialize();
this.$().typeahead( null, {
displayKey: self.get('optionValuePath'),
source: sources.ttAdapter()
});
},
willDestroyElement: function () {
this.$().typeahead('destroy');
}
});
})( App );
|
var webpack = require('webpack');
var path = require('path');
var isProduction = process.env.NODE_ENV === 'production';
var node_modules = path.resolve(__dirname, 'node_modules');
var config = {
entry: {
// split vendor to another file
vendors: ['react', 'cerebral', 'immutable-store', 'event-emitter'],
app: path.resolve(__dirname, 'src', 'main.js'),
},
// devtool: 'source-map',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.css$/,
loader: 'style!css'
}, {
test: /\.js$/,
loader: 'babel?optional=es7.decorators',
exclude: node_modules
}, {
test: /\.json$/,
loader: 'json'
}]
},
plugins: [
// split vendor to another file
new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'),
]
};
module.exports = config;
|
/*globals define*/
/*jshint node:true, browser:true*/
/**
* Generated by PluginGenerator from webgme on Fri Jul 17 2015 22:13:17 GMT-0500 (CDT).
*/
define([
'plugin/PluginConfig',
'plugin/PluginBase',
'plugin/OtherPlugin/OtherPlugin/meta'
], function (PluginConfig, PluginBase, MetaTypes) {
'use strict';
/**
* Initializes a new instance of OtherPlugin.
* @class
* @augments {PluginBase}
* @classdesc This class represents the plugin OtherPlugin.
* @constructor
*/
var OtherPlugin = function () {
// Call base class' constructor.
PluginBase.call(this);
this.metaTypes = MetaTypes;
};
// Prototypal inheritance from PluginBase.
OtherPlugin.prototype = Object.create(PluginBase.prototype);
OtherPlugin.prototype.constructor = OtherPlugin;
/**
* Gets the name of the OtherPlugin.
* @returns {string} The name of the plugin.
* @public
*/
OtherPlugin.prototype.getName = function () {
return 'New Plugin';
};
/**
* Gets the semantic version (semver.org) of the OtherPlugin.
* @returns {string} The version of the plugin.
* @public
*/
OtherPlugin.prototype.getVersion = function () {
return '0.1.0';
};
/**
* Main function for the plugin to execute. This will perform the execution.
* Notes:
* - Always log with the provided logger.[error,warning,info,debug].
* - Do NOT put any user interaction logic UI, etc. inside this method.
* - callback always has to be called even if error happened.
*
* @param {function(string, plugin.PluginResult)} callback - the result callback
*/
OtherPlugin.prototype.main = function (callback) {
// Use self to access core, project, result, logger etc from PluginBase.
// These are all instantiated at this point.
var self = this;
self.updateMETA(self.metaTypes);
// Using the logger.
self.logger.debug('This is a debug message.');
self.logger.info('This is an info message.');
self.logger.warn('This is a warning message.');
self.logger.error('This is an error message.');
// This will save the changes. If you don't want to save;
// exclude self.save and call callback directly from this scope.
self.result.setSuccess(true);
self.save('added obj', function (err) {
callback(null, self.result);
});
};
return OtherPlugin;
});
|
var grunt = require('grunt');
var fs = require('fs');
var path = require('path');
// In Nodejs 0.8.0, existsSync moved from path -> fs.
var existsSync = fs.existsSync || path.existsSync;
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports['jade-no_runtime'] = function (test){
'use strict';
test.expect(4);
var actual, expected, runtimeExists;
// OLD - Test there is no runtime output
runtimeExists = existsSync('tmp/old/jade-html/runtime.html') || existsSync('tmp/old/jade-html/runtime.js');
test.equal(runtimeExists, false, 'should NOT generate a module for the runtime');
// OLD - Test helloworld.jade output
actual = grunt.file.read('tmp/old/jade-no_runtime/helloworld.js');
expected = grunt.file.read('test/fixtures/no_runtime/helloworld_expected.js');
test.equal(actual, expected, 'should generate an HTML file for the template');
// NEW - Test there is no runtime output
runtimeExists = existsSync('tmp/new/jade-html/runtime.html') || existsSync('tmp/new/jade-html/runtime.js');
test.equal(runtimeExists, false, 'should NOT generate a module for the runtime');
// NEW - Test helloworld.jade output
actual = grunt.file.read('tmp/new/jade-no_runtime/helloworld.js');
expected = grunt.file.read('test/fixtures/no_runtime/helloworld_expected.js');
test.equal(actual, expected, 'should generate an HTML file for the template');
test.done();
};
|
import gql from 'util/GraphQL';
import { loadFixtures, unloadFixtures } from 'util/fixtures';
import fixtures from '../__fixtures__/GetCategory';
describe('GetCategory', () => {
beforeAll(() => loadFixtures(fixtures));
it('Get specified category and articleCategories with NORMAL status', async () => {
expect(
await gql`
{
GetCategory(id: "c1") {
title
articleCategories(status: NORMAL) {
totalCount
edges {
node {
articleId
category {
id
title
}
status
}
cursor
score
}
pageInfo {
firstCursor
lastCursor
}
}
}
}
`()
).toMatchSnapshot();
});
it('Get specified category and articleCategories with DELETED status', async () => {
expect(
await gql`
{
GetCategory(id: "c1") {
title
articleCategories(status: DELETED) {
totalCount
edges {
node {
articleId
category {
id
title
}
status
}
cursor
score
}
pageInfo {
firstCursor
lastCursor
}
}
}
}
`()
).toMatchSnapshot();
});
afterAll(() => unloadFixtures(fixtures));
});
|
var crypto = require('crypto');
var Memcached = function(){
var cache = {};
this.cas = function(key, value, cas, callback){
var err,
curr_value = cache[key],
curr_hash = crypto.createHash('md5').update(curr_value).digest('hex');
if (curr_hash === cas){
try{
cache[key] = value;
} catch (e) {
err = e;
}
} else {
err = new Error('CAS does not match current value');
}
if (callback){
callback(err);
}
}
this.get = function(key, callback){
var err,
data = {};
if (key in cache){
data[key] = cache[key];
} else {
err = new Error("Key not found.");
}
if (callback){
callback(err, data);
}
}
this.gets = function(key, callback){
var hash,
err,
data = {},
val = cache[key];
if (key in cache){
hash = crypto.createHash('md5').update(val).digest('hex');
} else {
err = new Error("Key not found.");
}
data[key] = val;
data.cas = hash;
if (callback){
callback(err, data);
}
}
this.flush = function(callback){
cache = {};
callback();
}
this.set = function(key, value, callback){
var err;
try{
cache[key] = value;
} catch (e) {
err = e;
}
if (callback){
callback(err);
}
}
}
module.exports.Memcached = Memcached;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MdDelete = function MdDelete(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm31.6 6.6v3.4h-23.2v-3.4h5.7l1.8-1.6h8.2l1.8 1.6h5.7z m-21.6 25v-20h20v20c0 1.8-1.6 3.4-3.4 3.4h-13.2c-1.8 0-3.4-1.6-3.4-3.4z' })
)
);
};
exports.default = MdDelete;
module.exports = exports['default'];
|
var server = require('./server')
, assert = require('assert')
, request = require('../main.js')
, Cookie = require('../vendor/cookie')
, Jar = require('../vendor/cookie/jar')
var s = server.createServer()
s.listen(s.port, function () {
var server = 'http://127.0.0.1:' + s.port;
var hits = {}
var passed = 0;
bouncer(301, 'temp')
bouncer(302, 'perm')
bouncer(302, 'nope')
function bouncer(code, label) {
var landing = label+'_landing';
s.on('/'+label, function (req, res) {
hits[label] = true;
res.writeHead(code, {
'location':server + '/'+landing,
'set-cookie': 'ham=eggs'
})
res.end()
})
s.on('/'+landing, function (req, res) {
if (req.method !== 'GET') { // We should only accept GET redirects
console.error("Got a non-GET request to the redirect destination URL");
res.writeHead(400);
res.end();
return;
}
// Make sure the cookie doesn't get included twice, see #139:
// Make sure cookies are set properly after redirect
assert.equal(req.headers.cookie, 'foo=bar; quux=baz; ham=eggs');
hits[landing] = true;
res.writeHead(200)
res.end(landing)
})
}
// Permanent bounce
var jar = new Jar()
jar.add(new Cookie('quux=baz'))
request({uri: server+'/perm', jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 200) throw new Error('Status is not 200: '+res.statusCode)
assert.ok(hits.perm, 'Original request is to /perm')
assert.ok(hits.perm_landing, 'Forward to permanent landing URL')
assert.equal(body, 'perm_landing', 'Got permanent landing content')
passed += 1
done()
})
// Temporary bounce
request({uri: server+'/temp', jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 200) throw new Error('Status is not 200: '+res.statusCode)
assert.ok(hits.temp, 'Original request is to /temp')
assert.ok(hits.temp_landing, 'Forward to temporary landing URL')
assert.equal(body, 'temp_landing', 'Got temporary landing content')
passed += 1
done()
})
// Prevent bouncing.
request({uri:server+'/nope', jar: jar, headers: {cookie: 'foo=bar'}, followRedirect:false}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 302) throw new Error('Status is not 302: '+res.statusCode)
assert.ok(hits.nope, 'Original request to /nope')
assert.ok(!hits.nope_landing, 'No chasing the redirect')
assert.equal(res.statusCode, 302, 'Response is the bounce itself')
passed += 1
done()
})
// Should not follow post redirects by default
request.post(server+'/temp', { jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 301) throw new Error('Status is not 301: '+res.statusCode)
assert.ok(hits.temp, 'Original request is to /temp')
assert.ok(!hits.temp_landing, 'No chasing the redirect when post')
assert.equal(res.statusCode, 301, 'Response is the bounce itself')
passed += 1
done()
})
// Should follow post redirects when followAllRedirects true
request.post({uri:server+'/temp', followAllRedirects:true, jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 200) throw new Error('Status is not 200: '+res.statusCode)
assert.ok(hits.temp, 'Original request is to /temp')
assert.ok(hits.temp_landing, 'Forward to temporary landing URL')
assert.equal(body, 'temp_landing', 'Got temporary landing content')
passed += 1
done()
})
request.post({uri:server+'/temp', followAllRedirects:false, jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 301) throw new Error('Status is not 301: '+res.statusCode)
assert.ok(hits.temp, 'Original request is to /temp')
assert.ok(!hits.temp_landing, 'No chasing the redirect')
assert.equal(res.statusCode, 301, 'Response is the bounce itself')
passed += 1
done()
})
// Should not follow delete redirects by default
request.del(server+'/temp', { jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode < 301) throw new Error('Status is not a redirect.')
assert.ok(hits.temp, 'Original request is to /temp')
assert.ok(!hits.temp_landing, 'No chasing the redirect when delete')
assert.equal(res.statusCode, 301, 'Response is the bounce itself')
passed += 1
done()
})
// Should not follow delete redirects even if followRedirect is set to true
request.del(server+'/temp', { followRedirect: true, jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 301) throw new Error('Status is not 301: '+res.statusCode)
assert.ok(hits.temp, 'Original request is to /temp')
assert.ok(!hits.temp_landing, 'No chasing the redirect when delete')
assert.equal(res.statusCode, 301, 'Response is the bounce itself')
passed += 1
done()
})
// Should follow delete redirects when followAllRedirects true
request.del(server+'/temp', {followAllRedirects:true, jar: jar, headers: {cookie: 'foo=bar'}}, function (er, res, body) {
if (er) throw er
if (res.statusCode !== 200) throw new Error('Status is not 200: '+res.statusCode)
assert.ok(hits.temp, 'Original request is to /temp')
assert.ok(hits.temp_landing, 'Forward to temporary landing URL')
assert.equal(body, 'temp_landing', 'Got temporary landing content')
passed += 1
done()
})
var reqs_done = 0;
function done() {
reqs_done += 1;
if(reqs_done == 9) {
console.log(passed + ' tests passed.')
s.close()
}
}
})
|
'use strict';
angular.module('SmartAdmin.Forms').directive('smartClockpicker', function () {
return {
restrict: 'A',
compile: function (tElement, tAttributes) {
tElement.removeAttr('smart-clockpicker data-smart-clockpicker');
var options = {
placement: 'top',
donetext: 'Done'
}
tElement.clockpicker(options);
}
}
});
|
'use strict';
describe('Service: accordion', function () {
// load the service's module
beforeEach(module('uiAccordion'));
// instantiate service
var accordionService, accordionGroupService;
beforeEach(inject(function (_accordion_, _accordionGroup_) {
accordionService = _accordion_;
accordionGroupService = _accordionGroup_;
}));
it('should create accordion object', function () {
var accordion = accordionService.createAccordion();
expect(accordion.constructor.name).toBe("Accordion");
expect(accordion.groups.length).toBe(0);
expect(accordion.options.closeOthers).toBe(true);
});
it('should add accordion group', function () {
var accordion = accordionService.createAccordion();
var grp = accordionGroupService.createAccordionGrp();
accordion.addGroup(grp);
var grps = accordion.getGroups();
expect(grps.length).toBe(1);
expect(grps[0]).toBe(grp);
});
it('should close other groups', function () {
var accordion = accordionService.createAccordion();
var grp1 = accordionGroupService.createAccordionGrp();
grp1.options = accordionGroupService.defaultAccordionGroupOptions();
accordion.addGroup(grp1);
var grp2 = accordionGroupService.createAccordionGrp();
grp2.options = accordionGroupService.defaultAccordionGroupOptions();
accordion.addGroup(grp2);
var grp3 = accordionGroupService.createAccordionGrp();
grp3.options = accordionGroupService.defaultAccordionGroupOptions();
accordion.addGroup(grp3);
spyOn(grp1, '$animate');
spyOn(grp3, '$animate');
spyOn(grp2, '$animate');
accordion.closeOthers(grp1);
expect(grp2.$animate).toHaveBeenCalledWith('slideUp', 'beforeHide', 'animateClose');
expect(grp3.$animate).toHaveBeenCalledWith('slideUp', 'beforeHide', 'animateClose');
expect(grp1.$animate).not.toHaveBeenCalled();
});
it('should not close other groups', function () {
var accordion = accordionService.createAccordion();
accordion.options.closeOthers = false;
var grp1 = accordionGroupService.createAccordionGrp();
grp1.options = accordionGroupService.defaultAccordionGroupOptions();
accordion.addGroup(grp1);
var grp2 = accordionGroupService.createAccordionGrp();
grp2.options = accordionGroupService.defaultAccordionGroupOptions();
accordion.addGroup(grp2);
var grp3 = accordionGroupService.createAccordionGrp();
grp3.options = accordionGroupService.defaultAccordionGroupOptions();
accordion.addGroup(grp3);
spyOn(grp1, '$animate');
spyOn(grp3, '$animate');
spyOn(grp2, '$animate');
accordion.closeOthers(grp1);
expect(grp2.$animate).not.toHaveBeenCalled();
expect(grp3.$animate).not.toHaveBeenCalled();
expect(grp1.$animate).not.toHaveBeenCalled();
});
it('should apply state', function () {
var accordion = accordionService.createAccordion();
var grp1 = accordionGroupService.createAccordionGrp();
grp1.options = accordionGroupService.defaultAccordionGroupOptions();
grp1.options.open = true;
accordion.addGroup(grp1);
var grp2 = accordionGroupService.createAccordionGrp();
grp2.options = accordionGroupService.defaultAccordionGroupOptions();
accordion.addGroup(grp2);
var grp3 = accordionGroupService.createAccordionGrp();
grp3.options = accordionGroupService.defaultAccordionGroupOptions();
accordion.addGroup(grp3);
spyOn(grp1, '$animate');
spyOn(grp3, '$animate');
spyOn(grp2, '$animate');
accordion.applyState(grp1);
expect(grp1.$animate).toHaveBeenCalledWith('slideDown', 'beforeOpen', 'animateOpen');
expect(grp2.$animate).toHaveBeenCalledWith('slideUp', 'beforeHide', 'animateClose');
expect(grp3.$animate).toHaveBeenCalledWith('slideUp', 'beforeHide', 'animateClose');
});
it('should not apply state', function () {
var accordion = accordionService.createAccordion();
var grp1 = accordionGroupService.createAccordionGrp();
grp1.options = accordionGroupService.defaultAccordionGroupOptions();
accordion.addGroup(grp1);
var grp2 = accordionGroupService.createAccordionGrp();
grp2.options = accordionGroupService.defaultAccordionGroupOptions();
accordion.addGroup(grp2);
var grp3 = accordionGroupService.createAccordionGrp();
grp3.options = accordionGroupService.defaultAccordionGroupOptions();
accordion.addGroup(grp3);
spyOn(grp1, '$animate');
spyOn(grp3, '$animate');
spyOn(grp2, '$animate');
accordion.applyState();
accordion.applyState(grp1);
expect(grp1.$animate).not.toHaveBeenCalledWith('slideDown', 'beforeOpen', 'animateOpen');
expect(grp2.$animate).not.toHaveBeenCalledWith('slideUp', 'beforeHide', 'animateClose');
expect(grp3.$animate).not.toHaveBeenCalledWith('slideUp', 'beforeHide', 'animateClose');
});
});
|
var gulp = require("gulp"),
Script = require("./script");
/*
* 脚本编译
*
* 将 *.app.less 编译成为同目录下的*.app.css
*
* 优先级 (最大级若存在且不为空文件,则只编译最大级别到 *.app.css。若*.app.js以上级别的文件都为空文件,则不进行编译 )
*
*
* *.app.css <_ *.app.less
*/
gulp.task("less", function () {
return Script.less();
});
/*
* 脚本编译 (release)
*
* 将 *.app.less 编译成为同目录下的*.app.css
*
* 优先级 (最大级若存在且不为空文件,则只编译最大级别到 *.app.css。若*.app.js以上级别的文件都为空文件,则不进行编译 )
*
*
* *.app.css <_ *.app.less
*/
gulp.task("less:release", function () {
return Script.less_release();
});
|
describe('mdNavBar', function() {
var el, $compile, $scope, $timeout, ctrl, tabContainer, $material, $mdConstant;
/** @ngInject */
var injectLocals = function(
_$compile_, $rootScope, _$timeout_, _$material_, _$mdConstant_) {
$compile = _$compile_;
$scope = $rootScope.$new();
$timeout = _$timeout_;
$material = _$material_;
$mdConstant = _$mdConstant_;
};
beforeEach(function() {
module('material.components.navBar', 'ngAnimateMock');
inject(injectLocals);
});
afterEach(function() {
el && el.remove();
});
function create(template) {
el = $compile(template)($scope);
angular.element(document.body).append(el);
$scope.$apply();
ctrl = el.controller('mdNavBar');
tabContainer = angular.element(el[0].querySelector('._md-nav-bar-list'));
$timeout.flush();
$material.flushOutstandingAnimations();
}
function createTabs() {
create(
'<md-nav-bar md-selected-nav-item="selectedTabRoute" ' +
' md-no-ink-bar="noInkBar" ' +
' nav-bar-aria-label="{{ariaLabel}}">' +
' <md-nav-item md-nav-href="#1" name="tab1">' +
' tab1' +
' </md-nav-item>' +
' <md-nav-item md-nav-href="#2" name="tab2">' +
' tab2' +
' </md-nav-item>' +
' <md-nav-item md-nav-href="#3" name="tab3">' +
' tab3' +
' </md-nav-item>' +
'</md-nav-bar>');
}
describe('tabs', function() {
it('shows current tab as selected', function() {
$scope.selectedTabRoute = 'tab1';
createTabs();
var tab1 = getTab('tab1');
expect(tab1).toHaveClass('md-active');
expect(tab1).toHaveClass('md-primary');
});
it('shows non-selected tabs as unselected', function() {
$scope.selectedTabRoute = 'tab1';
createTabs();
expect(getTab('tab2')).toHaveClass('md-unselected');
expect(getTab('tab3')).toHaveClass('md-unselected');
});
it('changes current tab when selectedTabRoute changes', function() {
$scope.selectedTabRoute = 'tab1';
createTabs();
updateSelectedTabRoute('tab2');
expect(getTab('tab2')).toHaveClass('md-active');
expect(getTab('tab2')).toHaveClass('md-primary');
expect(getTab('tab1')).not.toHaveClass('md-active');
expect(getTab('tab1')).not.toHaveClass('md-primary');
});
it('does not select tabs when selectedTabRoute is empty', function() {
$scope.selectedTabRoute = 'tab1';
createTabs();
updateSelectedTabRoute('');
expect(getTab('tab3')).not.toHaveClass('md-active');
expect(getTab('tab3')).not.toHaveClass('md-primary');
expect(getTab('tab2')).not.toHaveClass('md-active');
expect(getTab('tab2')).not.toHaveClass('md-primary');
expect(getTab('tab1')).not.toHaveClass('md-active');
expect(getTab('tab1')).not.toHaveClass('md-primary');
expect(getInkbarEl().style.display).toBe('none');
updateSelectedTabRoute('tab1');
expect(getTab('tab3')).not.toHaveClass('md-active');
expect(getTab('tab3')).not.toHaveClass('md-primary');
expect(getTab('tab2')).not.toHaveClass('md-active');
expect(getTab('tab2')).not.toHaveClass('md-primary');
expect(getTab('tab1')).toHaveClass('md-active');
expect(getTab('tab1')).toHaveClass('md-primary');
expect(getInkbarEl().style.display).toBe('');
});
it('requires navigation attribute to be present', function() {
expect(function() {
create('<md-nav-item name="fooo">footab</md-nav-item>');
}).toThrow();
});
it('does not allow multiple navigation attributes', function() {
expect(function() {
create(
'<md-nav-item md-nav-href="a" md-nav-sref="b" name="fooo">' +
'footab</md-nav-item>');
}).toThrow();
});
it('allows empty navigation attribute', function() {
// be permissive; this helps with test writing
expect(function() {
create(
'<md-nav-bar>' +
'<md-nav-item md-nav-href="" name="fooo">' + 'footab</md-nav-item>' +
'<md-nav-bar>');
}).not.toThrow();
});
it('uses nav item text for name if no name supplied', function() {
create(
'<md-nav-bar md-selected-nav-item="selectedTabRoute" nav-bar-aria-label="{{ariaLabel}}">' +
' <md-nav-item md-nav-href="#1">' +
' footab ' +
' </md-nav-item>' +
' <md-nav-item md-nav-href="#2" name="tab2">' +
' tab2' +
' </md-nav-item>' +
' <md-nav-item md-nav-href="#3" name="tab3">' +
' tab3' +
' </md-nav-item>' +
'</md-nav-bar>');
expect(getTab('footab').length).toBe(1);
});
it('updates md-selected-nav-item on tab change', function() {
$scope.selectedTabRoute = 'tab1';
createTabs();
var tab2Ctrl = getTabCtrl('tab2');
tab2Ctrl.getButtonEl().click();
$scope.$apply();
expect($scope.selectedTabRoute).toBe('tab2');
});
it('adds ui-sref-opts attribute to nav item when sref-opts attribute is ' +
'defined', function() {
create(
'<md-nav-bar md-selected-nav-item="selected" nav-bar-aria-label="nav">' +
'<md-nav-item md-nav-sref="page1">' +
'tab1' +
'</md-nav-item>' +
'<md-nav-item md-nav-sref="page2" sref-opts="{reload:true,notify:true}">' +
'tab2' +
'</md-nav-item>' +
'</md-nav-bar>'
);
expect(getTab('tab2').attr('ui-sref-opts'))
.toBe('{"reload":true,"notify":true}');
});
});
describe('inkbar', function() {
it('moves to new tab', function() {
$scope.selectedTabRoute = 'tab1';
createTabs();
// b/c there is no css in the karma test, we have to interrogate the
// inkbar style property directly
expect(parseInt(getInkbarEl().style.left))
.toBeCloseTo(getTab('tab1')[0].offsetLeft, 0.1);
updateSelectedTabRoute('tab3');
expect(parseInt(getInkbarEl().style.left))
.toBeCloseTo(getTab('tab3')[0].offsetLeft, 0.1);
});
it('should hide if md-no-ink-bar is enabled', function() {
$scope.noInkBar = false;
$scope.selectedTabRoute = 'tab1';
createTabs();
expect(getInkbarEl().offsetParent).toBeTruthy();
$scope.$apply('noInkBar = true');
expect(getInkbarEl().offsetParent).not.toBeTruthy();
$scope.$apply('noInkBar = false');
expect(getInkbarEl().offsetParent).toBeTruthy();
});
});
describe('a11y', function() {
it('sets aria-checked on the selected tab', function() {
$scope.selectedTabRoute = 'tab1';
createTabs();
expect(getTab('tab1').parent().attr('aria-selected')).toBe('true');
expect(getTab('tab2').parent().attr('aria-selected')).toBe('false');
expect(getTab('tab3').parent().attr('aria-selected')).toBe('false');
updateSelectedTabRoute('tab3');
expect(getTab('tab1').parent().attr('aria-selected')).toBe('false');
expect(getTab('tab2').parent().attr('aria-selected')).toBe('false');
expect(getTab('tab3').parent().attr('aria-selected')).toBe('true');
});
it('sets aria-label on the listbox', function() {
var label = 'top level navigation for my site';
$scope.ariaLabel = label;
$scope.selectedTabRoute = 'tab1';
createTabs();
expect(tabContainer[0].getAttribute('aria-label')).toBe(label);
});
it('sets focus on the selected tab when the navbar receives focus',
function() {
$scope.selectedTabRoute = 'tab2';
createTabs();
expect(getTab('tab2')).not.toHaveClass('md-focused');
ctrl.onFocus();
$scope.$apply();
expect(getTab('tab2')).toHaveClass('md-focused');
expect(document.activeElement).toBe(getTab('tab2')[0]);
});
it('removes tab focus when the tab blurs', function() {
$scope.selectedTabRoute = 'tab2';
createTabs();
tabContainer.triggerHandler('focus');
expect(getTab('tab2')).toHaveClass('md-focused');
getTab('tab2').triggerHandler('blur');
expect(getTab('tab2')).not.toHaveClass('md-focused');
});
it('up/left moves focus back', function() {
$scope.selectedTabRoute = 'tab3';
createTabs();
tabContainer.triggerHandler('focus');
tabContainer.triggerHandler({
type: 'keydown',
keyCode: $mdConstant.KEY_CODE.UP_ARROW,
});
tabContainer.triggerHandler({
type: 'keydown',
keyCode: $mdConstant.KEY_CODE.LEFT_ARROW,
});
$scope.$apply();
expect(getTab('tab1')).toHaveClass('md-focused');
expect(document.activeElement).toBe(getTab('tab1')[0]);
expect(getTab('tab2')).not.toHaveClass('md-focused');
expect(getTab('tab3')).not.toHaveClass('md-focused');
});
it('down/right moves focus forward', function() {
$scope.selectedTabRoute = 'tab1';
createTabs();
tabContainer.triggerHandler('focus');
tabContainer.triggerHandler({
type: 'keydown',
keyCode: $mdConstant.KEY_CODE.DOWN_ARROW,
});
tabContainer.triggerHandler({
type: 'keydown',
keyCode: $mdConstant.KEY_CODE.RIGHT_ARROW,
});
$scope.$apply();
expect(getTab('tab1')).not.toHaveClass('md-focused');
expect(getTab('tab2')).not.toHaveClass('md-focused');
expect(getTab('tab3')).toHaveClass('md-focused');
expect(document.activeElement).toBe(getTab('tab3')[0]);
});
it('enter selects a tab', function() {
$scope.selectedTabRoute = 'tab2';
createTabs();
var tab2Ctrl = getTabCtrl('tab2');
spyOn(tab2Ctrl.getButtonEl(), 'click');
tabContainer.triggerHandler('focus');
tabContainer.triggerHandler({
type: 'keydown',
keyCode: $mdConstant.KEY_CODE.ENTER,
});
$scope.$apply();
$timeout.flush();
expect(tab2Ctrl.getButtonEl().click).toHaveBeenCalled();
});
});
function getTab(tabName) {
return angular.element(getTabCtrl(tabName).getButtonEl());
}
function getTabCtrl(tabName) {
return ctrl._getTabByName(tabName);
}
function getInkbarEl() {
return el.find('md-nav-ink-bar')[0];
}
function updateSelectedTabRoute(newRoute) {
$scope.selectedTabRoute = newRoute;
$scope.$apply();
$timeout.flush();
}
});
|
/*
* Copyright (C) 2015 Glyptodon LLC
*
* 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.
*/
var Guacamole = Guacamole || {};
/**
* Abstract audio channel which queues and plays arbitrary audio data.
* @constructor
*/
Guacamole.AudioChannel = function() {
/**
* Reference to this AudioChannel.
* @private
*/
var channel = this;
/**
* When the next packet should play.
* @private
*/
var next_packet_time = 0;
/**
* Queues up the given data for playing by this channel once all previously
* queued data has been played. If no data has been queued, the data will
* play immediately.
*
* @param {String} mimetype The mimetype of the data provided.
* @param {Number} duration The duration of the data provided, in
* milliseconds.
* @param {Blob} data The blob data to play.
*/
this.play = function(mimetype, duration, data) {
var packet =
new Guacamole.AudioChannel.Packet(mimetype, data);
var now = Guacamole.AudioChannel.getTimestamp();
// If underflow is detected, reschedule new packets relative to now.
if (next_packet_time < now)
next_packet_time = now;
// Schedule next packet
packet.play(next_packet_time);
next_packet_time += duration;
};
};
// Define context if available
if (window.AudioContext) {
try {Guacamole.AudioChannel.context = new AudioContext();}
catch (e){}
}
// Fallback to Webkit-specific AudioContext implementation
else if (window.webkitAudioContext) {
try {Guacamole.AudioChannel.context = new webkitAudioContext();}
catch (e){}
}
/**
* Returns a base timestamp which can be used for scheduling future audio
* playback. Scheduling playback for the value returned by this function plus
* N will cause the associated audio to be played back N milliseconds after
* the function is called.
*
* @return {Number} An arbitrary channel-relative timestamp, in milliseconds.
*/
Guacamole.AudioChannel.getTimestamp = function() {
// If we have an audio context, use its timestamp
if (Guacamole.AudioChannel.context)
return Guacamole.AudioChannel.context.currentTime * 1000;
// If we have high-resolution timers, use those
if (window.performance) {
if (window.performance.now)
return window.performance.now();
if (window.performance.webkitNow)
return window.performance.webkitNow();
}
// Fallback to millisecond-resolution system time
return new Date().getTime();
};
/**
* Abstract representation of an audio packet.
*
* @constructor
*
* @param {String} mimetype The mimetype of the data contained by this packet.
* @param {Blob} data The blob of sound data contained by this packet.
*/
Guacamole.AudioChannel.Packet = function(mimetype, data) {
/**
* Schedules this packet for playback at the given time.
*
* @function
* @param {Number} when The time this packet should be played, in
* milliseconds.
*/
this.play = function(when) { /* NOP */ }; // Defined conditionally depending on support
// If audio API available, use it.
if (Guacamole.AudioChannel.context) {
var readyBuffer = null;
// By default, when decoding finishes, store buffer for future
// playback
var handleReady = function(buffer) {
readyBuffer = buffer;
};
// Read data and start decoding
var reader = new FileReader();
reader.onload = function() {
Guacamole.AudioChannel.context.decodeAudioData(
reader.result,
function(buffer) { handleReady(buffer); }
);
};
reader.readAsArrayBuffer(data);
// Set up buffer source
var source = Guacamole.AudioChannel.context.createBufferSource();
source.connect(Guacamole.AudioChannel.context.destination);
// Use noteOn() instead of start() if necessary
if (!source.start)
source.start = source.noteOn;
var play_when;
function playDelayed(buffer) {
source.buffer = buffer;
source.start(play_when / 1000);
}
/** @ignore */
this.play = function(when) {
play_when = when;
// If buffer available, play it NOW
if (readyBuffer)
playDelayed(readyBuffer);
// Otherwise, play when decoded
else
handleReady = playDelayed;
};
}
else {
var play_on_load = false;
// Create audio element to house and play the data
var audio = null;
try { audio = new Audio(); }
catch (e) {}
if (audio) {
// Read data and start decoding
var reader = new FileReader();
reader.onload = function() {
var binary = "";
var bytes = new Uint8Array(reader.result);
// Produce binary string from bytes in buffer
for (var i=0; i<bytes.byteLength; i++)
binary += String.fromCharCode(bytes[i]);
// Convert to data URI
audio.src = "data:" + mimetype + ";base64," + window.btoa(binary);
// Play if play was attempted but packet wasn't loaded yet
if (play_on_load)
audio.play();
};
reader.readAsArrayBuffer(data);
function play() {
// If audio data is ready, play now
if (audio.src)
audio.play();
// Otherwise, play when loaded
else
play_on_load = true;
}
/** @ignore */
this.play = function(when) {
// Calculate time until play
var now = Guacamole.AudioChannel.getTimestamp();
var delay = when - now;
// Play now if too late
if (delay < 0)
play();
// Otherwise, schedule later playback
else
window.setTimeout(play, delay);
};
}
}
};
|
var filesys = require('fs'),
pathsys = require('path'),
readFekitConfig = require('./readFekitConfig.js');
var fekitModule = 'fekit_modules';
var level = 0;
function resolveModule(modulePath) {
var configPath = pathsys.resolve(modulePath, 'fekit.config'),
packageJsonPath = pathsys.resolve(modulePath, 'package.json');
var moduleName = pathsys.basename(modulePath);
var fekitConfig = readFekitConfig(configPath),
output = {};
if (fekitConfig) {
output.main = fekitConfig.json.main || 'src/index.js';
} else {
output = {
name: moduleName,
main: 'src/index.js',
version: 'no version',
author: 'Qunar team'
}
}
filesys.writeFileSync(packageJsonPath, JSON.stringify(output, null, '\t'));
}
function handleDir(projectPath, isSubModule) {
var modulePath,
stat,
modules,
fekitModulesPath,
padding = [];
for(var i = 0; i < level; i++) padding.push(' ');
fekitModulesPath = isSubModule ? pathsys.join(projectPath, fekitModule) : projectPath;
if (filesys.existsSync(fekitModulesPath)) {
modules = filesys.readdirSync(fekitModulesPath);
for (var j = 0; j < modules.length; j++) {
console.log(padding.join('') + '--' + modules[j]);
modulePath = pathsys.join(fekitModulesPath, modules[j]);
stat = filesys.statSync(modulePath);
if (stat.isDirectory()) {
resolveModule(modulePath);
// 递归检查所有子fekit_modules文件夹
if (filesys.existsSync(pathsys.join(modulePath, fekitModule))) {
level++;
handleDir(modulePath, true);
level--;
}
}
}
}
}
function transform(root) {
var projects = filesys.readdirSync(root),
projectPath,
stat;
for (var i = 0; i < projects.length; i++) {
projectPath = pathsys.join(root, projects[i]);
if (projects[i] === fekitModule) {
console.log('------ Resolved Fekit Modules List ------');
handleDir(projectPath);
}
}
}
module.exports = transform;
|
// Generated by CoffeeScript 1.9.3
var CONCURRENT_DESTROY, ERRORMSG, LIMIT_UPDATE, MAX_RETRIES, Message, Process, RemoveAllMessagesFromMailbox, async, log, ref,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
extend = 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,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
ERRORMSG = "DS has crashed ? waiting 4s before try again";
ref = require('../utils/constants'), MAX_RETRIES = ref.MAX_RETRIES, CONCURRENT_DESTROY = ref.CONCURRENT_DESTROY, LIMIT_UPDATE = ref.LIMIT_UPDATE;
Process = require('./_base');
async = require('async');
Message = require('../models/message');
log = require('../utils/logging')('process:removebymailbox');
module.exports = RemoveAllMessagesFromMailbox = (function(superClass) {
extend(RemoveAllMessagesFromMailbox, superClass);
function RemoveAllMessagesFromMailbox() {
this.destroyMessages = bind(this.destroyMessages, this);
this.shouldDestroy = bind(this.shouldDestroy, this);
this.fetchMessages = bind(this.fetchMessages, this);
this.step = bind(this.step, this);
this.notFinished = bind(this.notFinished, this);
return RemoveAllMessagesFromMailbox.__super__.constructor.apply(this, arguments);
}
RemoveAllMessagesFromMailbox.prototype.code = 'remove-all-from-box';
RemoveAllMessagesFromMailbox.prototype.initialize = function(options, callback) {
this.mailboxID = options.mailboxID;
this.toDestroyMailboxIDs = options.toDestroyMailboxIDs || [];
this.retries = MAX_RETRIES;
this.batch;
return async.doWhilst(this.step, this.notFinished, callback);
};
RemoveAllMessagesFromMailbox.prototype.notFinished = function() {
return this.batch.length > 0;
};
RemoveAllMessagesFromMailbox.prototype.step = function(callback) {
return this.fetchMessages((function(_this) {
return function(err) {
if (err) {
return callback(err);
}
if (_this.batch.length === 0) {
return callback(null);
}
return _this.destroyMessages(function(err) {
if (err && _this.retries > 0) {
log.warn(ERRORMSG, err);
_this.retries--;
return setTimeout(callback, 4000);
} else if (err) {
return callback(err);
} else {
_this.retries = MAX_RETRIES;
return callback(null);
}
});
};
})(this));
};
RemoveAllMessagesFromMailbox.prototype.fetchMessages = function(callback) {
return Message.rawRequest('byMailboxRequest', {
limit: LIMIT_UPDATE,
startkey: ['uid', this.mailboxID, -1],
endkey: ['uid', this.mailboxID, {}],
include_docs: true,
reduce: false
}, (function(_this) {
return function(err, rows) {
if (err) {
return callback(err);
}
_this.batch = rows.map(function(row) {
return new Message(row.doc);
});
return callback(null);
};
})(this));
};
RemoveAllMessagesFromMailbox.prototype.shouldDestroy = function(message) {
var boxID, ref1, uid;
ref1 = message.mailboxIDs;
for (boxID in ref1) {
uid = ref1[boxID];
if (indexOf.call(this.toDestroyMailboxIDs, boxID) < 0) {
return false;
}
}
return true;
};
RemoveAllMessagesFromMailbox.prototype.destroyMessages = function(callback) {
return async.eachLimit(this.batch, CONCURRENT_DESTROY, (function(_this) {
return function(message, cb) {
if (_this.shouldDestroy(message)) {
return message.destroy(cb);
} else {
return message.removeFromMailbox({
id: _this.mailboxID
}, false, cb);
}
};
})(this), callback);
};
return RemoveAllMessagesFromMailbox;
})(Process);
|
define({
"taskUrl": "가시권역 서비스 URL",
"portalURL": "ArcGIS Online 기관 또는 Portal for ArcGIS의 URL을 지정합니다.",
"portalURLError": "ArcGIS Online 기관 또는 Portal for ArcGIS에 구성된 URL이 유효하지 않습니다.",
"privilegeError": "귀하의 사용자 역할은 분석을 수행할 수 없습니다. 분석을 수행하려면 내 기관의 관리자가 특정 <a href=”http://doc.arcgis.com/en/arcgis-online/reference/roles.htm” target=”_blank”>권한</a>을 부여해야 합니다.",
"noServiceError": "고도 분석 서비스를 사용할 수 없습니다. ArcGIS Online 기관 또는 Portal for ArcGIS의 구성을 확인하세요.",
"serviceURLPlaceholder": "가시권역 지오프로세싱 작업 URL을 입력하세요.",
"setTask": "설정",
"setTaskTitle": "가시권역 지오프로세싱 작업 설정",
"serviceURLError": "이 위젯으로 구성하려는 지오프로세싱 작업이 올바르지 않습니다. 올바른 가시권역 지오프로세싱 작업 URL을 선택하세요.",
"defaultMilsForAnglesLabel": "밀을 각도의 기본 단위로 설정",
"defaultObserverHeightLabel": "기본 관측자 높이 단위",
"defaultObservableDistanceLabel": "기본 관측 가능 거리 단위",
"units": {
"miles": "마일",
"kilometers": "킬로미터",
"feet": "피트",
"meters": "미터",
"yards": "야드",
"nauticalMiles": "해리"
}
});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M10 9V5l-7 7 7 7v-4.1c5 0 8.5 1.6 11 5.1-1-5-4-10-11-11z"
}), 'ReplySharp');
exports.default = _default;
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
|
/*
* HP Enterprise | TSRnD Bengaluru, India
* @author: Akshay Kr Singh
* @date: 1/28/2017
* @email: akshay.singh@hpe.com
*/
module.exports = {
"db": {
"url": "mongodb://db-admin:db-admin@3.234.160.235:27017/wiperr-dev",
"name": "db",
"connector": "mongodb"
}
};
|
import sortBy from "lodash/sortBy";
export default {
/**
* [Please add a description.]
*
* Priority:
*
* - 0 We want this to be at the **very** bottom
* - 1 Default node position
* - 2 Priority over normal nodes
* - 3 We want this to be at the **very** top
*/
name: "internal.blockHoist",
visitor: {
Block: {
exit({ node }) {
let hasChange = false;
for (let i = 0; i < node.body.length; i++) {
const bodyNode = node.body[i];
if (bodyNode && bodyNode._blockHoist != null) {
hasChange = true;
break;
}
}
if (!hasChange) return;
node.body = sortBy(node.body, function(bodyNode) {
let priority = bodyNode && bodyNode._blockHoist;
if (priority == null) priority = 1;
if (priority === true) priority = 2;
// Higher priorities should move toward the top.
return -1 * priority;
});
},
},
},
};
|
'use strict';
module.exports = function(req, res, next) {
req.second = true;
next();
};
|
import avatar from "./avatar";
import upload from "./upload";
export default {
avatar,
upload,
};
export {
avatar,
upload,
};
|
function iconHover() {
var image = document.getElementById("plan-icon");
var link = document.getElementById("applicationLink");
if (!("ontouchstart" in document.documentElement) &&
! (navigator.maxTouchPoints > 0) &&
! (navigator.msMaxTouchPoints > 0) ){
link.addEventListener("mouseover", function(){
if (window.location.hash == "#l=en") {
image.src="img/coming-soon-icon.svg";
}
else {
image.src="img/a-venir-icon.svg"
}
}, false);
link.addEventListener("mouseout", function(){
image.src="img/plan-icon.svg";}, false);
};
};
//Set language and update URL hash
function langtoggle(l){
if (l == 'en' ){
local_lang = lang.en,
window.location.hash = "#l=en";
}
else if (l == 'fr') {
local_lang = lang.fr,
window.location.hash = "#l=fr";
}
for(var key in local_lang) {
document.getElementById(key).innerHTML = local_lang[key];
}
}
//Check URL hash; set appropriate page language.
function loadLanguage() {
var hash = window.location.hash;
if (hash == '#l=en') {
langtoggle('en')
}
else {
langtoggle('fr')
}
}
//Generate flag link/image from country JS file
function generateFlag() {
var flagContainer = document.getElementById('flag');
var newLink = document.createElement('a');
var newImg = document.createElement('img');
newLink.href = flag["href"];
newImg.setAttribute('src',flag["src"]);
newImg.className += " img-responsive";
newLink.appendChild(newImg);
flagContainer.appendChild(newLink);
}
//Generate background image from country JS file
function generateBcgImg() {
document.getElementById('intro').style.background = bcgImage["src"];
}
//Generate partner logos from country JS file
function generatePartnerLogos() {
var logoContainer = document.getElementById('PartnerLogos');
for(var key in partners)
{
var partner = partners[key];
var newDiv = document.createElement('div');
var newLink = document.createElement('a');
var newImg = document.createElement('img');
newDiv.setAttribute('id',key);
newDiv.className += "col-xs-6" + " col-md-4" + " col-lg-3";
newLink.href = partner["href"];
newImg.className += " img-responsive";
newImg.setAttribute('src',partner["src"]);
newImg.setAttribute('alt',partner["alt"]);
newLink.appendChild(newImg);
newDiv.appendChild(newLink);
logoContainer.appendChild(newDiv);
}
}
//Generate app logos from country JS file
function generateAppLogos() {
var appLogoContainer = document.getElementById('AppLogos');
for(var key in apps)
{
var app = apps[key];
var newDiv = document.createElement('div');
var newLink = document.createElement('a');
var newImg = document.createElement('img');
newDiv.setAttribute('id',key);
newDiv.className += "col-xs-6" + " col-lg-3" + " appIcon";
newLink.href = app["href"];
newLink.target = "_blank";
newImg.className += " img-responsive";
newImg.setAttribute('src',app["src"]);
newImg.setAttribute('alt',app["alt"]);
newLink.appendChild(newImg);
newDiv.appendChild(newLink);
appLogoContainer.appendChild(newDiv);
//Trigger hover events
newImg.addEventListener("mouseover", function(){
var divSource = $(this).closest('div').attr('id');
this.setAttribute('src', apps[divSource]["srcActive"])}, false);
newImg.addEventListener("mouseout", function(){
var divSource = $(this).closest('div').attr('id');
this.setAttribute('src', apps[divSource]["src"])}, false);;
}
};
window.addEventListener("DOMContentLoaded", function() {
loadLanguage();
generateFlag();
generateBcgImg();
iconHover();
generatePartnerLogos();
generateAppLogos();
}, false);
SocialShareKit.init();
|
// example 1
type Type = Name | ListType;
type Name = {kind: 'Name', value: string};
type ListType = {kind: 'ListType', name: string};
function getTypeASTName(typeAST: Type): string {
if (typeAST.kind === 'Name') {
return typeAST.value; // OK, since typeAST: Name
} else {
return typeAST.name; // OK, since typeAST: ListType
}
}
// example 2
import type {ASTNode} from './ast_node';
var Node = require('./node1'); // Node = "Node1"
function foo(x: ASTNode) {
if (x.kind === Node) {
return x.prop1.charAt(0); // typeAST: Node1, but x.prop1 may be undefined
}
return null;
}
// example 3
type Apple = { kind: 'Fruit', taste: 'Bad' }
type Orange = { kind: 'Fruit', taste: 'Good' }
type Broccoli = { kind: 'Veg', taste: 'Bad', raw: 'No' }
type Carrot = { kind: 'Veg', taste: 'Good', raw: 'Maybe' }
type Breakfast = Apple | Orange | Broccoli | Carrot
function bar(x: Breakfast) {
if (x.kind === 'Fruit') { (x.taste: 'Good'); } // error, Apple.taste = Bad
else (x.raw: 'No'); // error, Carrot.raw = Maybe
}
function qux(x: Breakfast) {
if (x.taste === 'Good') {
(x.raw: 'Yes' | 'No'); // 2 errors:
// Orange.raw doesn't exist
// Carrot.raw is neither Yes nor No
}
}
// example 4
function list(n) {
if (n > 0) return { kind: "cons", next: list(n-1) };
return { kind: "nil" };
}
function length(l) {
switch (l.kind) {
case "cons": return 1 + length(l.next);
default: return 0;
}
}
function check(n) {
if (n >= 0) return (n === (length(list(n))));
return true;
}
// example 5
var EnumKind = { A: 1, B: 2, C: 3};
type A = { kind: 1, A: number };
type B = { kind: 2, B: number };
type C = { kind: 3, C: number };
function kind(x: A | B | C): number {
switch (x.kind) {
case EnumKind.A: return x.A;
case EnumKind.B: return x.B;
default: return x.A; // error, x: C and property A not found in type C
}
}
kind({ kind: EnumKind.A, A: 1 });
// example 6
type Citizen = { citizen: true };
type NonCitizen = { citizen: false, nationality: string }
function nationality(x: Citizen | NonCitizen) {
if (x.citizen) return "Shire"
else return x.nationality;
}
let tests = [
// non-existent props
function test7(x: A) {
if (x.kindTypo === 1) { // typos are allowed to be tested
(x.kindTypo: string); // typos can't be used, though
}
},
// nested objects
function test8(x: {foo: {bar: 1}}) {
if (x.foo.bar === 1) {}
if (x.fooTypo.bar === 1) {} // error, fooTypo doesn't exist
},
// invalid RHS
function(x: A) {
if (x.kind === (null).toString()) {} // error, method on null
if ({kind: 1}.kind === (null).toString()) {} // error, method on null
},
// non-objects on LHS
function(
x: Array<string>, y: string, z: number, q: boolean,
r: Object, s: Function, t: () => void
) {
if (x.length === 0) {}
if (x.legnth === 0) { // Error, typos
(x.legnth: number); // inside the block, it's a number
(x.legnth: string); // error: number literal 0 !~> string
}
if (y.length === 0) {}
if (y.legnth === 0) { // Error, typo
(y.legnth: number); // inside the block, it's a number
(y.legnth: string); // error: number literal 0 !~> string
}
if (z.toString === 0) {}
if (z.toStirng === 0) { // Error, typo
(z.toStirng: number); // inside the block, it's a number
(z.toStirng: string); // error: number literal 0 !~> string
}
if (q.valueOf === 0) {}
if (q.valeuOf === 0) { // Error, typo
(q.valeuOf: number); // inside the block, it's a number
(q.valeuOf: string); // error: number literal 0 !~> string
}
if (r.toStirng === 0) { // typos are allowed to be tested
(r.toStirng: empty); // props on AnyObjT are `any`
}
if (s.call === 0) {}
if (s.calll === 0) { // typos are allowed to be tested
(t.calll: empty); // ok, props on functions are `any` :/
}
if (t.call === 0) {}
if (t.calll === 0) { // typos are allowed to be tested
(t.calll: empty); // ok, props on functions are `any` :/
}
},
// sentinel props become the RHS
function(x: { str: string, num: number, bool: boolean }) {
if (x.str === 'str') {
(x.str: 'not str'); // error: 'str' !~> 'not str'
}
if (x.num === 123) {
(x.num: 456); // error: 123 !~> 456
}
if (x.bool === true) {
(x.bool: false); // error: true !~> false
}
// even if it doesn't exist...
if (x.badStr === 'bad') { // Error, reading unknown property
(x.badStr: empty); // error: 'bad' !~> empty
}
if (x.badNum === 123) { // Error, reading unknown property
(x.badNum: empty); // error: 123 !~> empty
}
if (x.badBool === true) { // Error, reading unknown property
(x.badBool: empty); // error: true !~> empty
}
},
// type mismatch
function(x: { foo: 123, y: string } | { foo: 'foo', z: string }) {
if (x.foo === 123) {
(x.y: string);
x.z; // error
} else {
(x.z: string);
x.y; // error
}
if (x.foo === 'foo') {
(x.z: string);
x.y; // error
} else {
(x.y: string);
x.z; // error
}
},
// type mismatch, but one is not a literal
function(x: { foo: number, y: string } | { foo: 'foo', z: string }) {
if (x.foo === 123) {
(x.y: string); // ok, because 123 !== 'foo'
x.z; // error
} else {
x.y; // error: x.foo could be a string
x.z; // error: could still be either case (if foo was a different number)
}
if (x.foo === 'foo') {
(x.z: string);
x.y; // error
} else {
(x.y: string);
x.z; // error
}
},
// type mismatch, neither is a literal
function(x: { foo: number, y: string } | { foo: string, z: string }) {
if (x.foo === 123) {
(x.y: string); // ok, because 123 !== string
x.z; // error
} else {
x.y; // error: x.foo could be a string
x.z; // error: could still be either case (if foo was a different number)
}
if (x.foo === 'foo') {
(x.z: string);
x.y; // error
} else {
x.y; // error: x.foo could be a different string
x.z; // error: x.foo could be a number
}
},
// type mismatch, neither is a literal, test is not a literal either
function(
x: { foo: number, y: string } | { foo: string, z: string },
num: number
) {
if (x.foo === num) {
x.y; // error: flow isn't smart enough to figure this out yet
x.z; // error
}
},
// null
function(x: { foo: null, y: string } | { foo: 'foo', z: string }) {
if (x.foo === null) {
(x.y: string);
x.z; // error
} else {
(x.z: string);
x.y; // error
}
if (x.foo === 'foo') {
(x.z: string);
x.y; // error
} else {
(x.y: string);
x.z; // error
}
},
// void
function(x: { foo: void, y: string } | { foo: 'foo', z: string }) {
if (x.foo === undefined) {
(x.y: string);
x.z; // error
} else {
(x.z: string);
x.y; // error
}
if (x.foo === 'foo') {
(x.z: string);
x.y; // error
} else {
(x.y: string);
x.z; // error
}
},
];
|
// Icelandic
jQuery.extend(jQuery.fn.pickadate.defaults, {
monthsFull: [ 'janúar', 'febrúar', 'mars', 'apríl', 'maí', 'júní', 'júlí', 'ágúst', 'september', 'október', 'nóvember', 'desember' ],
monthsShort: [ 'jan', 'feb', 'mar', 'apr', 'maí', 'jún', 'júl', 'ágú', 'sep', 'okt', 'nóv', 'des' ],
weekdaysFull: [ 'sunnudagur', 'mánudagur', 'þriðjudagur', 'miðvikudagur', 'fimmtudagur', 'föstudagur', 'laugardagur' ],
weekdaysShort: [ 'sun', 'mán', 'þri', 'mið', 'fim', 'fös', 'lau' ],
today: 'Í dag',
clear: 'Hreinsa',
firstDay: 1,
format: 'dd. mmmm yyyy',
formatSubmit: 'yyyy/mm/dd'
});
|
/*!
* jQuery JavaScript Library v1.6
* http://jquery.com/
*
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Mon May 2 13:50:00 2011 -0400
*/
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
navigator = window.navigator,
location = window.location;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Check for digits
rdigit = /\d/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// The deferred used on DOM ready
readyList,
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector );
}
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = (context ? context.ownerDocument || context : document);
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.6",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + (this.selector ? " " : "") + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.done( fn );
return this;
},
eq: function( i ) {
return i === -1 ?
this.slice( i ) :
this.slice( i, +i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).unbind( "ready" );
}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery._Deferred();
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
// A crude way of determining if an object is a window
isWindow: function( obj ) {
return obj && typeof obj === "object" && "setInterval" in obj;
},
isNaN: function( obj ) {
return obj == null || !rdigit.test( obj ) || isNaN( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw msg;
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return (new Function( "return " + data ))();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
// (xml & tmp used internally)
parseXML: function( data , xml , tmp ) {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
tmp = xml.documentElement;
if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// The extra typeof function check is to prevent crashes
// in Safari 2 (See: #3039)
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type( array );
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array ) {
if ( indexOf ) {
return indexOf.call( array, elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
},
merge: function( first, second ) {
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
if ( typeof context === "string" ) {
var tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
var args = slice.call( arguments, 2 ),
proxy = function() {
return fn.apply( context, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can be optionally by executed if its a function
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},
now: function() {
return (new Date()).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
sub: function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
// Expose jQuery to the global object
return jQuery;
})();
var // Promise methods
promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ),
// Static reference to slice
sliceDeferred = [].slice;
jQuery.extend({
// Create a simple deferred (one callbacks list)
_Deferred: function() {
var // callbacks list
callbacks = [],
// stored [ context , args ]
fired,
// to avoid firing when already doing so
firing,
// flag to know if the deferred has been cancelled
cancelled,
// the deferred itself
deferred = {
// done( f1, f2, ...)
done: function() {
if ( !cancelled ) {
var args = arguments,
i,
length,
elem,
type,
_fired;
if ( fired ) {
_fired = fired;
fired = 0;
}
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
deferred.done.apply( deferred, elem );
} else if ( type === "function" ) {
callbacks.push( elem );
}
}
if ( _fired ) {
deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
}
}
return this;
},
// resolve with given context and args
resolveWith: function( context, args ) {
if ( !cancelled && !fired && !firing ) {
// make sure args are available (#8421)
args = args || [];
firing = 1;
try {
while( callbacks[ 0 ] ) {
callbacks.shift().apply( context, args );
}
}
finally {
fired = [ context, args ];
firing = 0;
}
}
return this;
},
// resolve with this as context and given arguments
resolve: function() {
deferred.resolveWith( this, arguments );
return this;
},
// Has this deferred been resolved?
isResolved: function() {
return !!( firing || fired );
},
// Cancel
cancel: function() {
cancelled = 1;
callbacks = [];
return this;
}
};
return deferred;
},
// Full fledged deferred (two callbacks list)
Deferred: function( func ) {
var deferred = jQuery._Deferred(),
failDeferred = jQuery._Deferred(),
promise;
// Add errorDeferred methods, then and promise
jQuery.extend( deferred, {
then: function( doneCallbacks, failCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks );
return this;
},
always: function() {
return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments );
},
fail: failDeferred.done,
rejectWith: failDeferred.resolveWith,
reject: failDeferred.resolve,
isRejected: failDeferred.isResolved,
pipe: function( fnDone, fnFail ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ]
}, function( handler, data ) {
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if ( jQuery.isFunction( fn ) ) {
deferred[ handler ](function() {
returned = fn.apply( this, arguments );
if ( jQuery.isFunction( returned.promise ) ) {
returned.promise().then( newDefer.resolve, newDefer.reject );
} else {
newDefer[ action ]( returned );
}
});
} else {
deferred[ handler ]( newDefer[ action ] );
}
});
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
if ( obj == null ) {
if ( promise ) {
return promise;
}
promise = obj = {};
}
var i = promiseMethods.length;
while( i-- ) {
obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ];
}
return obj;
}
});
// Make sure only one callback list will be used
deferred.done( failDeferred.cancel ).fail( deferred.cancel );
// Unexpose cancel
delete deferred.cancel;
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
return deferred;
},
// Deferred helper
when: function( firstParam ) {
var args = arguments,
i = 0,
length = args.length,
count = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
// Strange bug in FF4:
// Values changed onto the arguments object sometimes end up as undefined values
// outside the $.when method. Cloning the object into a fresh array solves the issue
deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) );
}
};
}
if ( length > 1 ) {
for( ; i < length; i++ ) {
if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var div = document.createElement( "div" ),
all,
a,
select,
opt,
input,
marginDiv,
support,
fragment,
body,
bodyStyle,
tds,
events,
eventName,
i,
isSupported;
// Preliminary tests
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName( "*" );
a = div.getElementsByTagName( "a" )[ 0 ];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return {};
}
// First batch of supports tests
select = document.createElement( "select" );
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName( "input" )[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName( "tbody" ).length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName( "link" ).length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute( "href" ) === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.55$/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", function click() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
div.detachEvent( "onclick", click );
});
div.cloneNode( true ).fireEvent( "onclick" );
}
// Check if a radio maintains it's value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
input.setAttribute("checked", "checked");
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.firstChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
div.innerHTML = "";
// Figure out if the W3C box model works as expected
div.style.width = div.style.paddingLeft = "1px";
// We use our own, invisible, body
body = document.createElement( "body" );
bodyStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
// Set background to avoid IE crashes when removing (#9028)
background: "none"
};
for ( i in bodyStyle ) {
body.style[ i ] = bodyStyle[ i ];
}
body.appendChild( div );
document.documentElement.appendChild( body );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
support.boxModel = div.offsetWidth === 2;
if ( "zoom" in div.style ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.style.display = "inline";
div.style.zoom = 1;
support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "";
div.innerHTML = "<div style='width:4px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
}
div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE < 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
div.innerHTML = "";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if ( document.defaultView && document.defaultView.getComputedStyle ) {
marginDiv = document.createElement( "div" );
marginDiv.style.width = "0";
marginDiv.style.marginRight = "0";
div.appendChild( marginDiv );
support.reliableMarginRight =
( parseInt( document.defaultView.getComputedStyle( marginDiv, null ).marginRight, 10 ) || 0 ) === 0;
}
// Remove the body element we added
body.innerHTML = "";
document.documentElement.removeChild( body );
// Technique from Juriy Zaytsev
// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for( i in {
submit: 1,
change: 1,
focusin: 1
} ) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
return support;
})();
// Keep track of boxModel
jQuery.boxModel = jQuery.support.boxModel;
var rbrace = /^(?:\{.*\}|\[.*\])$/,
rmultiDash = /([a-z])([A-Z])/g;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ jQuery.expando ] = id = ++jQuery.uuid;
} else {
id = jQuery.expando;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
// metadata on plain JS objects when the object is serialized using
// JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
} else {
cache[ id ] = jQuery.extend(cache[ id ], name);
}
}
thisCache = cache[ id ];
// Internal jQuery data is stored in a separate object inside the object's data
// cache in order to avoid key collisions between internal data and user-defined
// data
if ( pvt ) {
if ( !thisCache[ internalKey ] ) {
thisCache[ internalKey ] = {};
}
thisCache = thisCache[ internalKey ];
}
if ( data !== undefined ) {
thisCache[ name ] = data;
}
// TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
// not attempt to inspect the internal events object using jQuery.data, as this
// internal data object is undocumented and subject to change.
if ( name === "events" && !thisCache[name] ) {
return thisCache[ internalKey ] && thisCache[ internalKey ].events;
}
return getByName ? thisCache[ name ] : thisCache;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var internalKey = jQuery.expando, isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
// See jQuery.data for more information
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
if ( thisCache ) {
delete thisCache[ name ];
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !isEmptyDataObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( pvt ) {
delete cache[ id ][ internalKey ];
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
var internalCache = cache[ id ][ internalKey ];
// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
if ( jQuery.support.deleteExpando || cache != window ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the entire user cache at once because it's faster than
// iterating through each key, but we need to continue to persist internal
// data if it existed
if ( internalCache ) {
cache[ id ] = {};
// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
// metadata on plain JS objects when the object is serialized using
// JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
cache[ id ][ internalKey ] = internalCache;
// Otherwise, we need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
} else if ( isNode ) {
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( jQuery.support.deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
} else {
elem[ jQuery.expando ] = null;
}
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var data = null;
if ( typeof key === "undefined" ) {
if ( this.length ) {
data = jQuery.data( this[0] );
if ( this[0].nodeType === 1 ) {
var attr = this[0].attributes, name;
for ( var i = 0, l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( this[0], name, data[ name ] );
}
}
}
}
return data;
} else if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
var parts = key.split(".");
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
// Try to fetch any internally stored data first
if ( data === undefined && this.length ) {
data = jQuery.data( this[0], key );
data = dataAttr( this[0], key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else {
return this.each(function() {
var $this = jQuery( this ),
args = [ parts[0], value ];
$this.triggerHandler( "setData" + parts[1] + "!", args );
jQuery.data( this, key, value );
$this.triggerHandler( "changeData" + parts[1] + "!", args );
});
}
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
!jQuery.isNaN( data ) ? parseFloat( data ) :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON
// property to be considered empty objects; this property always exists in
// order to make sure JSON.stringify does not expose internal metadata
function isEmptyDataObject( obj ) {
for ( var name in obj ) {
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function handleQueueMarkDefer( elem, type, src ) {
var deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
defer = jQuery.data( elem, deferDataKey, undefined, true );
if ( defer &&
( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) &&
( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) {
// Give room for hard-coded callbacks to fire first
// and eventually mark/queue something else on the element
setTimeout( function() {
if ( !jQuery.data( elem, queueDataKey, undefined, true ) &&
!jQuery.data( elem, markDataKey, undefined, true ) ) {
jQuery.removeData( elem, deferDataKey, true );
defer.resolve();
}
}, 0 );
}
}
jQuery.extend({
_mark: function( elem, type ) {
if ( elem ) {
type = (type || "fx") + "mark";
jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true );
}
},
_unmark: function( force, elem, type ) {
if ( force !== true ) {
type = elem;
elem = force;
force = false;
}
if ( elem ) {
type = type || "fx";
var key = type + "mark",
count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 );
if ( count ) {
jQuery.data( elem, key, count, true );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
},
queue: function( elem, type, data ) {
if ( elem ) {
type = (type || "fx") + "queue";
var q = jQuery.data( elem, type, undefined, true );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !q || jQuery.isArray(data) ) {
q = jQuery.data( elem, type, jQuery.makeArray(data), true );
} else {
q.push( data );
}
}
return q || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift(),
defer;
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift("inprogress");
}
fn.call(elem, function() {
jQuery.dequeue(elem, type);
});
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue", true );
handleQueueMarkDefer( elem, type, "queue" );
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
if ( typeof type !== "string" ) {
data = type;
type = "fx";
}
if ( data === undefined ) {
return jQuery.queue( this[0], type );
}
return this.each(function() {
var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/home.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
return this.queue( type, function() {
var elem = this;
setTimeout(function() {
jQuery.dequeue( elem, type );
}, time );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, object ) {
if ( typeof type !== "string" ) {
object = type;
type = undefined;
}
type = type || "fx";
var defer = jQuery.Deferred(),
elements = this,
i = elements.length,
count = 1,
deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark";
function resolve() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
}
while( i-- ) {
if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) {
count++;
tmp.done( resolve );
}
}
resolve();
return defer.promise();
}
});
var rclass = /[\n\t\r]/g,
rspace = /\s+/,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rspecial = /^(?:data-|aria-)/,
rinvalidChar = /\:/,
formHook;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.attr );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.prop );
},
removeProp: function( name ) {
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this);
self.addClass( value.call(this, i, self.attr("class") || "") );
});
}
if ( value && typeof value === "string" ) {
var classNames = (value || "").split( rspace );
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 ) {
if ( !elem.className ) {
elem.className = value;
} else {
var className = " " + elem.className + " ",
setClass = elem.className;
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
setClass += " " + classNames[c];
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
self.removeClass( value.call(this, i, self.attr("class")) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
var classNames = (value || "").split( rspace );
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
var className = (" " + elem.className + " ").replace(rclass, " ");
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[c] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this);
self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ";
for ( var i = 0, l = this.length; i < l; i++ ) {
if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
return (elem.value || "").replace(rreturn, "");
}
return undefined;
}
var isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var self = jQuery(this), val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
// If set returns undefined, fall back to normal setting
if ( !hooks || ("set" in hooks && hooks.set( this, val, "value" ) === undefined) ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
var option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attrFix: {
// Always normalize to ensure hook usage
tabindex: "tabIndex",
readonly: "readOnly"
},
attr: function( elem, name, value, pass ) {
var nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return undefined;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value );
}
var ret, hooks,
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// Normalize the name if needed
name = notxml && jQuery.attrFix[ name ] || name;
// Get the appropriate hook, or the formHook
// if getSetAttribute is not supported and we have form objects in IE6/7
hooks = jQuery.attrHooks[ name ] ||
( formHook && (jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ?
formHook :
undefined );
if ( value !== undefined ) {
if ( value === null || (value === false && !rspecial.test( name )) ) {
jQuery.removeAttr( elem, name );
return undefined;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
// Set boolean attributes to the same name
if ( value === true && !rspecial.test( name ) ) {
value = name;
}
elem.setAttribute( name, "" + value );
return value;
}
} else {
if ( hooks && "get" in hooks && notxml ) {
return hooks.get( elem, name );
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
}
},
removeAttr: function( elem, name ) {
if ( elem.nodeType === 1 ) {
name = jQuery.attrFix[ name ] || name;
if ( jQuery.support.getSetAttribute ) {
// Use removeAttribute in browsers that support it
elem.removeAttribute( name );
} else {
jQuery.attr( elem, name, "" );
elem.removeAttributeNode( elem.getAttributeNode( name ) );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.getAttribute("value");
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabIndex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
},
propFix: {},
prop: function( elem, name, value ) {
var nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return undefined;
}
var ret, hooks,
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// Try to normalize/fix the name
name = notxml && jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return (elem[ name ] = value);
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== undefined ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {}
});
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !jQuery.support.getSetAttribute ) {
jQuery.attrFix = jQuery.extend( jQuery.attrFix, {
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder"
});
// Use this for any attribute on a form in IE6/7
formHook = jQuery.attrHooks.name = jQuery.attrHooks.value = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
if ( name === "value" && !jQuery.nodeName( elem, "button" ) ) {
return elem.getAttribute( name );
}
ret = elem.getAttributeNode( name );
// Return undefined if not specified instead of empty string
return ret && ret.specified ?
ret.nodeValue :
undefined;
},
set: function( elem, value, name ) {
// Check form objects in IE (multiple bugs related)
// Only use nodeValue if the attribute node exists on the form
var ret = elem.getAttributeNode( name );
if ( ret ) {
ret.nodeValue = value;
return value;
}
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return (elem.style.cssText = "" + value);
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
});
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0);
}
}
});
});
var hasOwn = Object.prototype.hasOwnProperty,
rnamespaces = /\.(.*)$/,
rformElems = /^(?:textarea|input|select)$/i,
rperiod = /\./g,
rspaces = / /g,
rescape = /[^\w\s.|`]/g,
fcleanup = function( nm ) {
return nm.replace(rescape, "\\$&");
};
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code originated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function( elem, types, handler, data ) {
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
} else if ( !handler ) {
// Fixes bug #7229. Fix recommended by jdalton
return;
}
var handleObjIn, handleObj;
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
}
// Make sure that the function being executed has a unique ID
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure
var elemData = jQuery._data( elem );
// If no elemData is found then we must be trying to bind to one of the
// banned noData elements
if ( !elemData ) {
return;
}
var events = elemData.events,
eventHandle = elemData.handle;
if ( !events ) {
elemData.events = events = {};
}
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) :
undefined;
};
}
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native events in IE.
eventHandle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = types.split(" ");
var type, i = 0, namespaces;
while ( (type = types[ i++ ]) ) {
handleObj = handleObjIn ?
jQuery.extend({}, handleObjIn) :
{ handler: handler, data: data };
// Namespaced event handlers
if ( type.indexOf(".") > -1 ) {
namespaces = type.split(".");
type = namespaces.shift();
handleObj.namespace = namespaces.slice(0).sort().join(".");
} else {
namespaces = [];
handleObj.namespace = "";
}
handleObj.type = type;
if ( !handleObj.guid ) {
handleObj.guid = handler.guid;
}
// Get the current list of functions bound to this event
var handlers = events[ type ],
special = jQuery.event.special[ type ] || {};
// Init the event handler queue
if ( !handlers ) {
handlers = events[ type ] = [];
// Check for a special event handler
// Only use addEventListener/attachEvent if the special
// events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add the function to the element's handler list
handlers.push( handleObj );
// Keep track of which events have been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, pos ) {
// don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
}
var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
events = elemData && elemData.events;
if ( !elemData || !events ) {
return;
}
// types is actually an event object here
if ( types && types.type ) {
handler = types.handler;
types = types.type;
}
// Unbind all events for the element
if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
types = types || "";
for ( type in events ) {
jQuery.event.remove( elem, type + types );
}
return;
}
// Handle multiple events separated by a space
// jQuery(...).unbind("mouseover mouseout", fn);
types = types.split(" ");
while ( (type = types[ i++ ]) ) {
origType = type;
handleObj = null;
all = type.indexOf(".") < 0;
namespaces = [];
if ( !all ) {
// Namespaced event handlers
namespaces = type.split(".");
type = namespaces.shift();
namespace = new RegExp("(^|\\.)" +
jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
}
eventType = events[ type ];
if ( !eventType ) {
continue;
}
if ( !handler ) {
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( all || namespace.test( handleObj.namespace ) ) {
jQuery.event.remove( elem, origType, handleObj.handler, j );
eventType.splice( j--, 1 );
}
}
continue;
}
special = jQuery.event.special[ type ] || {};
for ( j = pos || 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( handler.guid === handleObj.guid ) {
// remove the given handler for the given type
if ( all || namespace.test( handleObj.namespace ) ) {
if ( pos == null ) {
eventType.splice( j--, 1 );
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
if ( pos != null ) {
break;
}
}
}
// remove generic event handler if no more handlers exist
if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
ret = null;
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
var handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
delete elemData.events;
delete elemData.handle;
if ( jQuery.isEmptyObject( elemData ) ) {
jQuery.removeData( elem, undefined, true );
}
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Event object or event type
var type = event.type || event,
namespaces = [],
exclusive;
if ( type.indexOf("!") >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.exclusive = exclusive;
event.namespace = namespaces.join(".");
event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)");
// triggerHandler() and global events don't bubble or run the default action
if ( onlyHandlers || !elem ) {
event.preventDefault();
event.stopPropagation();
}
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
jQuery.each( jQuery.cache, function() {
// internalKey variable is just used to make it easier to find
// and potentially change this stuff later; currently it just
// points to jQuery.expando
var internalKey = jQuery.expando,
internalCache = this[ internalKey ];
if ( internalCache && internalCache.events && internalCache.events[ type ] ) {
jQuery.event.trigger( event, data, internalCache.handle.elem );
}
});
return;
}
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
event.target = elem;
// Clone any incoming data and prepend the event, creating the handler arg list
data = data ? jQuery.makeArray( data ) : [];
data.unshift( event );
var cur = elem,
// IE doesn't like method names with a colon (#3533, #8272)
ontype = type.indexOf(":") < 0 ? "on" + type : "";
// Fire event on the current element, then bubble up the DOM tree
do {
var handle = jQuery._data( cur, "handle" );
event.currentTarget = cur;
if ( handle ) {
handle.apply( cur, data );
}
// Trigger an inline bound script
if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) {
event.result = false;
event.preventDefault();
}
// Bubble up to document, then to window
cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window;
} while ( cur && !event.isPropagationStopped() );
// If nobody prevented the default action, do it now
if ( !event.isDefaultPrevented() ) {
var old,
special = jQuery.event.special[ type ] || {};
if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction)() check here because IE6/7 fails that test.
// IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch.
try {
if ( ontype && elem[ type ] ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
jQuery.event.triggered = type;
elem[ type ]();
}
} catch ( ieError ) {}
if ( old ) {
elem[ ontype ] = old;
}
jQuery.event.triggered = undefined;
}
}
return event.result;
},
handle: function( event ) {
event = jQuery.event.fix( event || window.event );
// Snapshot the handlers list since a called handler may add/remove events.
var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0),
run_all = !event.exclusive && !event.namespace,
args = Array.prototype.slice.call( arguments, 0 );
// Use the fix-ed Event rather than the (read-only) native event
args[0] = event;
event.currentTarget = this;
for ( var j = 0, l = handlers.length; j < l; j++ ) {
var handleObj = handlers[ j ];
// Triggered event must 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event.
if ( run_all || event.namespace_re.test( handleObj.namespace ) ) {
// Pass in a reference to the handler function itself
// So that we can later remove it
event.handler = handleObj.handler;
event.data = handleObj.data;
event.handleObj = handleObj;
var ret = handleObj.handler.apply( this, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
return event.result;
},
props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// store a copy of the original event object
// and "clone" to set read-only properties
var originalEvent = event;
event = jQuery.Event( originalEvent );
for ( var i = this.props.length, prop; i; ) {
prop = this.props[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary
if ( !event.target ) {
// Fixes #1925 where srcElement might not be defined either
event.target = event.srcElement || document;
}
// check if target is a textnode (safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && event.fromElement ) {
event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
}
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
var eventDocument = event.target.ownerDocument || document,
doc = eventDocument.documentElement,
body = eventDocument.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}
// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
event.which = event.charCode != null ? event.charCode : event.keyCode;
}
// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if ( !event.metaKey && event.ctrlKey ) {
event.metaKey = event.ctrlKey;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}
return event;
},
// Deprecated, use jQuery.guid instead
guid: 1E8,
// Deprecated, use jQuery.proxy instead
proxy: jQuery.proxy,
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady,
teardown: jQuery.noop
},
live: {
add: function( handleObj ) {
jQuery.event.add( this,
liveConvert( handleObj.origType, handleObj.selector ),
jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
},
remove: function( handleObj ) {
jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj );
}
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !this.preventDefault ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// timeStamp is buggy for some events on Firefox(#3843)
// So we won't rely on the native value
this.timeStamp = jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function( event ) {
// Check if mouse(over|out) are still within the same parent element
var parent = event.relatedTarget;
// Firefox sometimes assigns relatedTarget a XUL element
// which we cannot access the parentNode property of
try {
// Chrome does something similar, the parentNode property
// can be accessed but is null.
if ( parent && parent !== document && !parent.parentNode ) {
return;
}
// Traverse up the tree
while ( parent && parent !== this ) {
parent = parent.parentNode;
}
if ( parent !== this ) {
// set the correct event type
event.type = event.data;
// handle event if we actually just moused on to a non sub-element
jQuery.event.handle.apply( this, arguments );
}
// assuming we've left the element since we most likely mousedover a xul element
} catch(e) { }
},
// In case of event delegation, we only need to rename the event.type,
// liveHandler will take care of the rest.
delegate = function( event ) {
event.type = event.data;
jQuery.event.handle.apply( this, arguments );
};
// Create mouseenter and mouseleave events
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
setup: function( data ) {
jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
},
teardown: function( data ) {
jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
}
};
});
// submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function( data, namespaces ) {
if ( !jQuery.nodeName( this, "form" ) ) {
jQuery.event.add(this, "click.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
trigger( "submit", this, arguments );
}
});
jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
trigger( "submit", this, arguments );
}
});
} else {
return false;
}
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialSubmit" );
}
};
}
// change delegation, happens here so we have bind.
if ( !jQuery.support.changeBubbles ) {
var changeFilters,
getVal = function( elem ) {
var type = elem.type, val = elem.value;
if ( type === "radio" || type === "checkbox" ) {
val = elem.checked;
} else if ( type === "select-multiple" ) {
val = elem.selectedIndex > -1 ?
jQuery.map( elem.options, function( elem ) {
return elem.selected;
}).join("-") :
"";
} else if ( jQuery.nodeName( elem, "select" ) ) {
val = elem.selectedIndex;
}
return val;
},
testChange = function testChange( e ) {
var elem = e.target, data, val;
if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) {
return;
}
data = jQuery._data( elem, "_change_data" );
val = getVal(elem);
// the current data will be also retrieved by beforeactivate
if ( e.type !== "focusout" || elem.type !== "radio" ) {
jQuery._data( elem, "_change_data", val );
}
if ( data === undefined || val === data ) {
return;
}
if ( data != null || val ) {
e.type = "change";
e.liveFired = undefined;
jQuery.event.trigger( e, arguments[1], elem );
}
};
jQuery.event.special.change = {
filters: {
focusout: testChange,
beforedeactivate: testChange,
click: function( e ) {
var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) {
testChange.call( this, e );
}
},
// Change has to be called before submit
// Keydown will be called before keypress, which is used in submit-event delegation
keydown: function( e ) {
var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) ||
(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
type === "select-multiple" ) {
testChange.call( this, e );
}
},
// Beforeactivate happens also before the previous element is blurred
// with this event you can't trigger a change event, but you can store
// information
beforeactivate: function( e ) {
var elem = e.target;
jQuery._data( elem, "_change_data", getVal(elem) );
}
},
setup: function( data, namespaces ) {
if ( this.type === "file" ) {
return false;
}
for ( var type in changeFilters ) {
jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
}
return rformElems.test( this.nodeName );
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialChange" );
return rformElems.test( this.nodeName );
}
};
changeFilters = jQuery.event.special.change.filters;
// Handle when the input is .focus()'d
changeFilters.focus = changeFilters.beforeactivate;
}
function trigger( type, elem, args ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
// Don't pass args or remember liveFired; they apply to the donor event.
var event = jQuery.extend( {}, args[ 0 ] );
event.type = type;
event.originalEvent = {};
event.liveFired = undefined;
jQuery.event.handle.call( elem, event );
if ( event.isDefaultPrevented() ) {
args[ 0 ].preventDefault();
}
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0;
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
function handler( donor ) {
// Donor event is always a native one; fix it and switch its type.
// Let focusin/out handler cancel the donor focus/blur event.
var e = jQuery.event.fix( donor );
e.type = fix;
e.originalEvent = {};
jQuery.event.trigger( e, null, e.target );
if ( e.isDefaultPrevented() ) {
donor.preventDefault();
}
}
});
}
jQuery.each(["bind", "one"], function( i, name ) {
jQuery.fn[ name ] = function( type, data, fn ) {
var handler;
// Handle object literals
if ( typeof type === "object" ) {
for ( var key in type ) {
this[ name ](key, data, type[key], fn);
}
return this;
}
if ( arguments.length === 2 || data === false ) {
fn = data;
data = undefined;
}
if ( name === "one" ) {
handler = function( event ) {
jQuery( this ).unbind( event, handler );
return fn.apply( this, arguments );
};
handler.guid = fn.guid || jQuery.guid++;
} else {
handler = fn;
}
if ( type === "unload" && name !== "one" ) {
this.one( type, data, fn );
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.add( this[i], type, handler, data );
}
}
return this;
};
});
jQuery.fn.extend({
unbind: function( type, fn ) {
// Handle object literals
if ( typeof type === "object" && !type.preventDefault ) {
for ( var key in type ) {
this.unbind(key, type[key]);
}
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.remove( this[i], type, fn );
}
}
return this;
},
delegate: function( selector, types, data, fn ) {
return this.live( types, data, fn, selector );
},
undelegate: function( selector, types, fn ) {
if ( arguments.length === 0 ) {
return this.unbind( "live" );
} else {
return this.die( types, null, fn, selector );
}
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
var liveMap = {
focus: "focusin",
blur: "focusout",
mouseenter: "mouseover",
mouseleave: "mouseout"
};
jQuery.each(["live", "die"], function( i, name ) {
jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
var type, i = 0, match, namespaces, preType,
selector = origSelector || this.selector,
context = origSelector ? this : jQuery( this.context );
if ( typeof types === "object" && !types.preventDefault ) {
for ( var key in types ) {
context[ name ]( key, data, types[key], selector );
}
return this;
}
if ( name === "die" && !types &&
origSelector && origSelector.charAt(0) === "." ) {
context.unbind( origSelector );
return this;
}
if ( data === false || jQuery.isFunction( data ) ) {
fn = data || returnFalse;
data = undefined;
}
types = (types || "").split(" ");
while ( (type = types[ i++ ]) != null ) {
match = rnamespaces.exec( type );
namespaces = "";
if ( match ) {
namespaces = match[0];
type = type.replace( rnamespaces, "" );
}
if ( type === "hover" ) {
types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
continue;
}
preType = type;
if ( liveMap[ type ] ) {
types.push( liveMap[ type ] + namespaces );
type = type + namespaces;
} else {
type = (liveMap[ type ] || type) + namespaces;
}
if ( name === "live" ) {
// bind live handler
for ( var j = 0, l = context.length; j < l; j++ ) {
jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
}
} else {
// unbind live handler
context.unbind( "live." + liveConvert( type, selector ), fn );
}
}
return this;
};
});
function liveHandler( event ) {
var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
elems = [],
selectors = [],
events = jQuery._data( this, "events" );
// Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911)
if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) {
return;
}
if ( event.namespace ) {
namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
}
event.liveFired = this;
var live = events.live.slice(0);
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
selectors.push( handleObj.selector );
} else {
live.splice( j--, 1 );
}
}
match = jQuery( event.target ).closest( selectors, event.currentTarget );
for ( i = 0, l = match.length; i < l; i++ ) {
close = match[i];
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) {
elem = close.elem;
related = null;
// Those two events require additional checking
if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
event.type = handleObj.preType;
related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
// Make sure not to accidentally match a child element with the same selector
if ( related && jQuery.contains( elem, related ) ) {
related = elem;
}
}
if ( !related || related !== elem ) {
elems.push({ elem: elem, handleObj: handleObj, level: close.level });
}
}
}
}
for ( i = 0, l = elems.length; i < l; i++ ) {
match = elems[i];
if ( maxLevel && match.level > maxLevel ) {
break;
}
event.currentTarget = match.elem;
event.data = match.handleObj.data;
event.handleObj = match.handleObj;
ret = match.handleObj.origHandler.apply( match.elem, arguments );
if ( ret === false || event.isPropagationStopped() ) {
maxLevel = match.level;
if ( ret === false ) {
stop = false;
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
return stop;
}
function liveConvert( type, selector ) {
return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&");
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true,
rBackslash = /\\/g,
rNonWord = /\W/;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var match,
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
var left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rBackslash, "" );
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
var found, item,
filter = Expr.filter[ type ],
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw "Syntax error, unrecognized expression: " + msg;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !rNonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rNonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( match[1] );
}
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace( rBackslash, "" ) + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rBackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rBackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace(/^\+|\s*/g, '');
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1] = match[1].replace( rBackslash, "" );
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
},
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
},
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
},
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
},
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
},
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
},
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
},
reset: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "reset" === elem.type;
},
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
},
focus: function( elem ) {
return elem === elem.ownerDocument.activeElement;
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( name );
}
},
CHILD: function( elem, match ) {
var type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
var first = match[2],
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// If the nodes are siblings (or identical) we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += Sizzle.getText( elem.childNodes );
}
}
return ret;
};
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime(),
root = document.documentElement;
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
};
Expr.filter.ID = function( elem, match ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
// release memory in IE
root = form = null;
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
// See if we find a selector to speed up
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// Speed-up: Sizzle("TAG")
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
// Speed-up: Sizzle(".CLASS")
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
if ( context.nodeType === 9 ) {
// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
// Speed-up: Sizzle("#ID")
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
}
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( /'/g, "\\$&" );
}
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
try {
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
} catch(pseudoError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
if ( matches ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9 fails this)
var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
var ret = matches.call( node, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || !disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9, so check for that
node.document && node.document.nodeType !== 11 ) {
return ret;
}
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem.sizcache = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem.sizcache = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
POS = jQuery.expr.match.POS,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var self = this,
i, l;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
var ret = this.pushStack( "", "find", selector ),
length, n, r;
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && ( typeof selector === "string" ?
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
// Array
if ( jQuery.isArray( selectors ) ) {
var match, selector,
matches = {},
level = 1;
if ( cur && selectors.length ) {
for ( i = 0, l = selectors.length; i < l; i++ ) {
selector = selectors[i];
if ( !matches[ selector ] ) {
matches[ selector ] = POS.test( selector ) ?
jQuery( selector, context || this.context ) :
selector;
}
}
while ( cur && cur.ownerDocument && cur !== context ) {
for ( selector in matches ) {
match = matches[ selector ];
if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) {
ret.push({ selector: selector, elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
}
return ret;
}
// String
var pos = POS.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
if ( !elem || typeof elem === "string" ) {
return jQuery.inArray( this[0],
// If it receives a string, the selector is used
// If it receives nothing, the siblings are used
elem ? jQuery( elem ) : this.parent().children() );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
andSelf: function() {
return this.add( this.prevObject );
}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return jQuery.nth( elem, 2, "nextSibling" );
},
prev: function( elem ) {
return jQuery.nth( elem, 2, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( elem.parentNode.firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
nth: function( cur, result, dir, elem ) {
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return (elem === qualifier) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
});
}
var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnocache = /<(?:script|object|embed|option|style)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function(i) {
var self = jQuery( this );
self.text( text.call(this, i, self.text()) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.text( this );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
return this.each(function() {
jQuery( this ).wrapAll( html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery(arguments[0]);
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
},
after: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery(arguments[0]).toArray() );
return set;
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnocache.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
var self = jQuery( this );
self.html( value.call(this, i, self.html()) );
});
} else {
this.empty().append( value );
}
return this;
},
replaceWith: function( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
}
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable || (l > 1 && i < lastIndex) ?
jQuery.clone( fragment, true, true ) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, evalScript );
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var internalKey = jQuery.expando,
oldData = jQuery.data( src ),
curData = jQuery.data( dest, oldData );
// Switch to use the internal data object, if it exists, for the next
// stage of data copying
if ( (oldData = oldData[ internalKey ]) ) {
var events = oldData.events;
curData = curData[ internalKey ] = jQuery.extend({}, oldData);
if ( events ) {
delete curData.handle;
curData.events = {};
for ( var type in events ) {
for ( var i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
}
}
}
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type
// attribute) to identify the type of content to display
if ( nodeName === "object" ) {
dest.outerHTML = src.outerHTML;
} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
if ( src.checked ) {
dest.defaultChecked = dest.checked = src.checked;
}
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults,
doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ args[0] ];
if ( cacheresults && cacheresults !== 1 ) {
fragment = cacheresults;
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( "getElementsByTagName" in elem ) {
return elem.getElementsByTagName( "*" );
} else if ( "querySelectorAll" in elem ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( elem.type === "checkbox" || elem.type === "radio" ) {
elem.defaultChecked = elem.checked;
}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( elem.getElementsByTagName ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var clone = elem.cloneNode(true),
srcElements,
destElements,
i;
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName
// instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var checkScriptType;
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
var ret = [];
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div");
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( var j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
}
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( i = 0; i < len; i++ ) {
findInputs( elem[i] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else {
if ( ret[i].nodeType === 1 ) {
var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( ret[i] );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ] && cache[ id ][ internalKey ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
function evalScript( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rdashAlpha = /-([a-z])/ig,
// fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g,
rnumpx = /^-?\d+(?:px)?$/i,
rnum = /^-?\d/,
rrelNum = /^[+\-]=/,
rrelNumFilter = /[^+\-\.\de]+/g,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssWidth = [ "Left", "Right" ],
cssHeight = [ "Top", "Bottom" ],
curCSS,
getComputedStyle,
currentStyle,
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn.css = function( name, value ) {
// Setting 'undefined' is a no-op
if ( arguments.length === 2 && value === undefined ) {
return this;
}
return jQuery.access( this, name, value, true, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
});
};
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity", "opacity" );
return ret === "" ? "1" : ret;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"zIndex": true,
"fontWeight": true,
"opacity": true,
"zoom": true,
"lineHeight": true,
"widows": true,
"orphans": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// Make sure that NaN and null values aren't set. See: #7116
if ( type === "number" && isNaN( value ) || value == null ) {
return;
}
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && rrelNum.test( value ) ) {
value = +value.replace( rrelNumFilter, "" ) + parseFloat( jQuery.css( elem, name ) );
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra ) {
var ret, hooks;
// Make sure that we're working with the right name
name = jQuery.camelCase( name );
hooks = jQuery.cssHooks[ name ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {};
// Remember the old values, and insert the new ones
for ( var name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
},
camelCase: function( string ) {
return string.replace( rdashAlpha, fcamelCase );
}
});
// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
jQuery.each(["height", "width"], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
var val;
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
val = getWH( elem, name, extra );
} else {
jQuery.swap( elem, cssShow, function() {
val = getWH( elem, name, extra );
});
}
if ( val <= 0 ) {
val = curCSS( elem, name, name );
if ( val === "0px" && currentStyle ) {
val = currentStyle( elem, name, name );
}
if ( val != null ) {
// Should return "auto" instead of 0, use 0 for
// temporary backwards-compat
return val === "" || val === "auto" ? "0px" : val;
}
}
if ( val < 0 || val == null ) {
val = elem.style[ name ];
// Should return "auto" instead of 0, use 0 for
// temporary backwards-compat
return val === "" || val === "auto" ? "0px" : val;
}
return typeof val === "string" ? val : val + "px";
}
},
set: function( elem, value ) {
if ( rnumpx.test( value ) ) {
// ignore negative width and height values #1599
value = parseFloat(value);
if ( value >= 0 ) {
return value + "px";
}
} else {
return value;
}
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( parseFloat( RegExp.$1 ) / 100 ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle;
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// Set the alpha filter to set the opacity
var opacity = jQuery.isNaN( value ) ?
"" :
"alpha(opacity=" + value * 100 + ")",
filter = currentStyle && currentStyle.filter || style.filter || "";
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery(function() {
// This hook cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
var ret;
jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
ret = curCSS( elem, "margin-right", "marginRight" );
} else {
ret = elem.style.marginRight;
}
});
return ret;
}
};
}
});
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) {
var ret, defaultView, computedStyle;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( !(defaultView = elem.ownerDocument.defaultView) ) {
return undefined;
}
if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left,
ret = elem.currentStyle && elem.currentStyle[ name ],
rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ],
style = elem.style;
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
// Remember the original values
left = style.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : (ret || 0);
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWH( elem, name, extra ) {
var which = name === "width" ? cssWidth : cssHeight,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight;
if ( extra === "border" ) {
return val;
}
jQuery.each( which, function() {
if ( !extra ) {
val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0;
}
if ( extra === "margin" ) {
val += parseFloat(jQuery.css( elem, "margin" + this )) || 0;
} else {
val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0;
}
});
return val;
}
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Document location
ajaxLocation,
// Document location segments
ajaxLocParts;
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for(; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters ),
selection;
for(; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.bind( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function ( target, settings ) {
if ( !settings ) {
// Only one parameter, we extend ajaxSettings
settings = target;
target = jQuery.extend( true, jQuery.ajaxSettings, settings );
} else {
// target was provided, we extend into it
jQuery.extend( true, target, jQuery.ajaxSettings, settings );
}
// Flatten fields we don't want deep extended
for( var field in { context: 1, url: 1 } ) {
if ( field in settings ) {
target[ field ] = settings[ field ];
} else if( field in jQuery.ajaxSettings ) {
target[ field ] = jQuery.ajaxSettings[ field ];
}
}
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": "*/*"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery._Deferred(),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, statusText, responses, headers ) {
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status ? 4 : 0;
var isSuccess,
success,
error,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = statusText;
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.done;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefiler, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already
jqXHR.abort();
return false;
}
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( status < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
jQuery.error( e );
}
}
}
return jqXHR;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && obj != null && typeof obj === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for( key in s.converters ) {
if( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
var jsc = jQuery.now(),
jsre = /(\=)\?(&|$)|\?\?/i;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var inspectData = s.contentType === "application/x-www-form-urlencoded" &&
( typeof s.data === "string" );
if ( s.dataTypes[ 0 ] === "jsonp" ||
s.jsonp !== false && ( jsre.test( s.url ) ||
inspectData && jsre.test( s.data ) ) ) {
var responseContainer,
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
previous = window[ jsonpCallback ],
url = s.url,
data = s.data,
replace = "$1" + jsonpCallback + "$2";
if ( s.jsonp !== false ) {
url = url.replace( jsre, replace );
if ( s.url === url ) {
if ( inspectData ) {
data = data.replace( jsre, replace );
}
if ( s.data === data ) {
// Add callback manually
url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
}
}
s.url = url;
s.data = data;
// Install callback
window[ jsonpCallback ] = function( response ) {
responseContainer = [ response ];
};
// Clean-up function
jqXHR.always(function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
});
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0,
xhrCallbacks;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var xhr = s.xhr(),
handle,
i;
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/home.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
responses.text = xhr.responseText;
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if ( !s.async || xhr.readyState === 4 ) {
callback();
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var elemdisplay = {},
iframe, iframeDoc,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
],
fxNow,
requestAnimationFrame = window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame;
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName));
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data(elem, "olddisplay") || "";
}
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
if ( this[i].style ) {
var display = jQuery.css( this[i], "display" );
if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) {
jQuery._data( this[i], "olddisplay", display );
}
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
if ( this[i].style ) {
this[i].style.display = "none";
}
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
},
fadeTo: function( speed, to, easing, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed(speed, easing, callback);
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
return this[ optall.queue === false ? "each" : "queue" ](function() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend({}, optall),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p,
display, e,
parts, start, end, unit;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
for ( p in prop ) {
// property name normalization
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
val = prop[name];
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call(this);
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height
// animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
if ( !jQuery.support.inlineBlockNeedsLayout ) {
this.style.display = "inline-block";
} else {
display = defaultDisplay(this.nodeName);
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( display === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.display = "inline";
this.style.zoom = 1;
}
}
}
}
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
opt.animatedProperties[name] = jQuery.isArray( val ) ?
val[1]:
opt.specialEasing && opt.specialEasing[name] || opt.easing || 'swing';
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[p];
if ( rfxtypes.test(val) ) {
e[ val === "toggle" ? hidden ? "show" : "hide" : val ]();
} else {
parts = rfxnum.exec(val);
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ name ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ((end || 1) / e.cur()) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ((parts[1] === "-=" ? -1 : 1) * end) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
});
},
stop: function( clearQueue, gotoEnd ) {
if ( clearQueue ) {
this.queue([]);
}
this.each(function() {
var timers = jQuery.timers,
i = timers.length;
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
// go in reverse order so anything added to the queue during the loop is ignored
while ( i-- ) {
if ( timers[i].elem === this ) {
if (gotoEnd) {
// force the next step to be the last
timers[i](true);
}
timers.splice(i, 1);
}
}
});
// start the next in the queue if the last step wasn't forced
if ( !gotoEnd ) {
this.dequeue();
}
return this;
}
});
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout( clearFxNow, 0 );
return ( fxNow = jQuery.now() );
}
function clearFxNow() {
fxNow = undefined;
}
// Generate parameters to create a standard animation
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show", 1),
slideUp: genFx("hide", 1),
slideToggle: genFx("toggle", 1),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.extend({
speed: function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
// Queueing
opt.old = opt.complete;
opt.complete = function( noUnmark ) {
if ( opt.queue !== false ) {
jQuery.dequeue( this );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
};
return opt;
},
easing: {
linear: function( p, n, firstNum, diff ) {
return firstNum + diff * p;
},
swing: function( p, n, firstNum, diff ) {
return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
options.orig = options.orig || {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
},
// Get the current size
cur: function() {
if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
return this.elem[ this.prop ];
}
var parsed,
r = jQuery.css( this.elem, this.prop );
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx,
raf;
this.startTime = fxNow || createFxNow();
this.start = from;
this.end = to;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
this.now = this.start;
this.pos = this.state = 0;
function t( gotoEnd ) {
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && jQuery.timers.push(t) && !timerId ) {
// Use requestAnimationFrame instead of setInterval if available
if ( requestAnimationFrame ) {
timerId = 1;
raf = function() {
// When timerId gets set to null at any point, this stops
if ( timerId ) {
requestAnimationFrame( raf );
fx.tick();
}
};
requestAnimationFrame( raf );
} else {
timerId = setInterval( fx.tick, fx.interval );
}
}
},
// Simple 'show' function
show: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any
// flash of content
this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur());
// Start by showing the element
jQuery( this.elem ).show();
},
// Simple 'hide' function
hide: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
this.options.hide = true;
// Begin the animation
this.custom(this.cur(), 0);
},
// Each step of an animation
step: function( gotoEnd ) {
var t = fxNow || createFxNow(),
done = true,
elem = this.elem,
options = this.options,
i, n;
if ( gotoEnd || t >= options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
options.animatedProperties[ this.prop ] = true;
for ( i in options.animatedProperties ) {
if ( options.animatedProperties[i] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
jQuery.each( [ "", "X", "Y" ], function (index, value) {
elem.style[ "overflow" + value ] = options.overflow[index];
});
}
// Hide the element if the "hide" operation was done
if ( options.hide ) {
jQuery(elem).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show ) {
for ( var p in options.animatedProperties ) {
jQuery.style( elem, p, options.orig[p] );
}
}
// Execute the complete function
options.complete.call( elem );
}
return false;
} else {
// classical easing cannot be used with an Infinity duration
if ( options.duration == Infinity ) {
this.now = t;
} else {
n = t - this.startTime;
this.state = n / options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[options.animatedProperties[this.prop]](this.state, n, 0, 1, options.duration);
this.now = this.start + ((this.end - this.start) * this.pos);
}
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
var timers = jQuery.timers,
i = timers.length;
while ( i-- ) {
if ( !timers[i]() ) {
timers.splice(i, 1);
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
// Try to restore the default display value of an element
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var elem = jQuery( "<" + nodeName + ">" ).appendTo( "body" ),
display = elem.css( "display" );
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// No iframe to use yet, so create it
if ( !iframe ) {
iframe = document.createElement( "iframe" );
iframe.frameBorder = iframe.width = iframe.height = 0;
}
document.body.appendChild( iframe );
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake html
// document to it, Webkit & Firefox won't allow reusing the iframe document
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write( "<!doctype><html><body></body></html>" );
}
elem = iframeDoc.createElement( nodeName );
iframeDoc.body.appendChild( elem );
display = jQuery.css( elem, "display" );
document.body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0], box;
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
try {
box = elem.getBoundingClientRect();
} catch(e) {}
var doc = elem.ownerDocument,
docElem = doc.documentElement;
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
jQuery.fn.offset = function( options ) {
var elem = this[0];
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
jQuery.offset.initialize();
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
doc = elem.ownerDocument,
docElem = doc.documentElement,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.offset = {
initialize: function() {
var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0,
html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } );
container.innerHTML = html;
body.insertBefore( container, body.firstChild );
innerDiv = container.firstChild;
checkDiv = innerDiv.firstChild;
td = innerDiv.nextSibling.firstChild.firstChild;
this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
checkDiv.style.position = "fixed";
checkDiv.style.top = "20px";
// safari subtracts parent border width here which is 5px
this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
checkDiv.style.position = checkDiv.style.top = "";
innerDiv.style.overflow = "hidden";
innerDiv.style.position = "relative";
this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);
body.removeChild( container );
jQuery.offset.initialize = jQuery.noop;
},
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
jQuery.offset.initialize();
if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if (options.top != null) {
props.top = (options.top - curOffset.top) + curTop;
}
if (options.left != null) {
props.left = (options.left - curOffset.left) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( i, name ) {
var method = "scroll" + name;
jQuery.fn[ method ] = function( val ) {
var elem, win;
if ( val === undefined ) {
elem = this[ 0 ];
if ( !elem ) {
return null;
}
win = getWindow( elem );
// Return the scroll offset
return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!i ? val : jQuery( win ).scrollLeft(),
i ? val : jQuery( win ).scrollTop()
);
} else {
this[ method ] = val;
}
});
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function( i, name ) {
var type = name.toLowerCase();
// innerHeight and innerWidth
jQuery.fn["inner" + name] = function() {
return this[0] ?
parseFloat( jQuery.css( this[0], type, "padding" ) ) :
null;
};
// outerHeight and outerWidth
jQuery.fn["outer" + name] = function( margin ) {
return this[0] ?
parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) :
null;
};
jQuery.fn[ type ] = function( size ) {
// Get window width or height
var elem = this[0];
if ( !elem ) {
return size == null ? null : this;
}
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
self[ type ]( size.call( this, i, self[ type ]() ) );
});
}
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
var docElemProp = elem.document.documentElement[ "client" + name ];
return elem.document.compatMode === "CSS1Compat" && docElemProp ||
elem.document.body[ "client" + name ] || docElemProp;
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
// Get or set width or height on the element
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );
return jQuery.isNaN( ret ) ? orig : ret;
// Set the width or height on the element (default to pixels if value is unitless)
} else {
return this.css( type, typeof size === "string" ? size : size + "px" );
}
};
});
window.jQuery = window.$ = jQuery;
})(window);
|
define(function(require) {
'use strict';
var L10nManager = require('backend/modules/L10nManager');
var React = require('react');
var L10nSpan = React.createClass({
propTypes: {
l10nId: React.PropTypes.string.isRequired,
l10nParams: React.PropTypes.object
},
getDefaultProps: function() {
return {
l10nId: '',
l10nParams: {}
};
},
getInitialState: function() {
return {
translation: ''
};
},
componentDidMount: function() {
this._updateL10nTranslation();
L10nManager.on('language-initialized', () => {
this._updateL10nTranslation();
});
L10nManager.on('language-changed', () => {
this._updateL10nTranslation();
});
},
_updateL10nTranslation: function() {
L10nManager
.get(this.props.l10nId, this.props.l10nParams)
.then((translation) => {
this.setState({
translation: translation
});
});
},
render: function() {
/* jshint ignore:start */
var translation = this.state.translation;
return (
<span>{translation}</span>
);
/* jshint ignore:end */
}
});
return L10nSpan;
});
|
/*
* Facebox (for jQuery)
* version: 1.3
* @requires jQuery v1.2 or later
* @homepage https://github.com/defunkt/facebox
*
* Licensed under the MIT:
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright Forever Chris Wanstrath, Kyle Neath
*
* Usage:
*
* jQuery(document).ready(function() {
* jQuery('a[rel*=facebox]').facebox()
* })
*
* <a href="#terms" rel="facebox">Terms</a>
* Loads the #terms div in the box
*
* <a href="terms.html" rel="facebox">Terms</a>
* Loads the terms.html page in the box
*
* <a href="terms.png" rel="facebox">Terms</a>
* Loads the terms.png image in the box
*
*
* You can also use it programmatically:
*
* jQuery.facebox('some html')
* jQuery.facebox('some html', 'my-groovy-style')
*
* The above will open a facebox with "some html" as the content.
*
* jQuery.facebox(function($) {
* $.get('blah.html', function(data) { $.facebox(data) })
* })
*
* The above will show a loading screen before the passed function is called,
* allowing for a better ajaxy experience.
*
* The facebox function can also display an ajax page, an image, or the contents of a div:
*
* jQuery.facebox({ ajax: 'remote.html' })
* jQuery.facebox({ ajax: 'remote.html' }, 'my-groovy-style')
* jQuery.facebox({ image: 'stairs.jpg' })
* jQuery.facebox({ image: 'stairs.jpg' }, 'my-groovy-style')
* jQuery.facebox({ div: '#box' })
* jQuery.facebox({ div: '#box' }, 'my-groovy-style')
*
* Want to close the facebox? Trigger the 'close.facebox' document event:
*
* jQuery(document).trigger('close.facebox')
*
* Facebox also has a bunch of other hooks:
*
* loading.facebox
* beforeReveal.facebox
* reveal.facebox (aliased as 'afterReveal.facebox')
* init.facebox
* afterClose.facebox
*
* Simply bind a function to any of these hooks:
*
* $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
*
*/
(function($) {
$.facebox = function(data, klass) {
$.facebox.loading()
if (data.ajax) fillFaceboxFromAjax(data.ajax, klass)
else if (data.image) fillFaceboxFromImage(data.image, klass)
else if (data.div) fillFaceboxFromHref(data.div, klass)
else if ($.isFunction(data)) data.call($)
else $.facebox.reveal(data, klass)
}
/*
* Public, $.facebox methods
*/
$.extend($.facebox, {
settings: {
opacity : 0.2,
overlay : true,
loadingImage : '/facebox/loading.gif',
closeImage : '/facebox/closelabel.png',
imageTypes : [ 'png', 'jpg', 'jpeg', 'gif' ],
faceboxHtml : '\
<div id="facebox" style="display:none;"> \
<div class="popup"> \
<div class="content"> \
</div> \
<a href="#" class="close"></a> \
</div> \
</div>'
},
loading: function() {
init()
if ($('#facebox .loading').length == 1) return true
showOverlay()
$('#facebox .content').empty().
append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>')
$('#facebox').show().css({
top: getPageScroll()[1] + (getPageHeight() / 10),
left: $(window).width() / 2 - ($('#facebox .popup').outerWidth() / 2)
})
$(document).bind('keydown.facebox', function(e) {
if (e.keyCode == 27) $.facebox.close()
return true
})
$(document).trigger('loading.facebox')
},
reveal: function(data, klass) {
$(document).trigger('beforeReveal.facebox')
if (klass) $('#facebox .content').addClass(klass)
$('#facebox .content').append(data)
$('#facebox .loading').remove()
$('#facebox .popup').children().fadeIn('normal')
$('#facebox').css('left', $(window).width() / 2 - ($('#facebox .popup').outerWidth() / 2))
$(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
},
close: function() {
$(document).trigger('close.facebox')
return false
}
})
/*
* Public, $.fn methods
*/
$.fn.facebox = function(settings) {
if ($(this).length == 0) return
init(settings)
function clickHandler() {
$.facebox.loading(true)
// support for rel="facebox.inline_popup" syntax, to add a class
// also supports deprecated "facebox[.inline_popup]" syntax
var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
if (klass) klass = klass[1]
fillFaceboxFromHref(this.href, klass)
return false
}
return this.bind('click.facebox', clickHandler)
}
/*
* Private methods
*/
// called one time to setup facebox on this page
function init(settings) {
if ($.facebox.settings.inited) return true
else $.facebox.settings.inited = true
$(document).trigger('init.facebox')
makeCompatible()
var imageTypes = $.facebox.settings.imageTypes.join('|')
$.facebox.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')$', 'i')
if (settings) $.extend($.facebox.settings, settings)
$('body').append($.facebox.settings.faceboxHtml)
var preload = [ new Image(), new Image() ]
preload[0].src = $.facebox.settings.closeImage
preload[1].src = $.facebox.settings.loadingImage
$('#facebox').find('.b:first, .bl').each(function() {
preload.push(new Image())
preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
})
$('#facebox .close')
.click($.facebox.close)
.append('<img src="'
+ $.facebox.settings.closeImage
+ '" class="close_image" title="close">')
}
// getPageScroll() by quirksmode.com
function getPageScroll() {
var xScroll, yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;
}
return new Array(xScroll,yScroll)
}
// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
var windowHeight
if (self.innerHeight) { // all except Explorer
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowHeight = document.body.clientHeight;
}
return windowHeight
}
// Backwards compatibility
function makeCompatible() {
var $s = $.facebox.settings
$s.loadingImage = $s.loading_image || $s.loadingImage
$s.closeImage = $s.close_image || $s.closeImage
$s.imageTypes = $s.image_types || $s.imageTypes
$s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
}
// Figures out what you want to display and displays it
// formats are:
// div: #id
// image: blah.extension
// ajax: anything else
function fillFaceboxFromHref(href, klass) {
// div
if (href.match(/#/)) {
var url = window.location.href.split('#')[0]
var target = href.replace(url,'')
if (target == '#') return
$.facebox.reveal($(target).html(), klass)
// image
} else if (href.match($.facebox.settings.imageTypesRegexp)) {
fillFaceboxFromImage(href, klass)
// ajax
} else {
fillFaceboxFromAjax(href, klass)
}
}
function fillFaceboxFromImage(href, klass) {
var image = new Image()
image.onload = function() {
$.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
}
image.src = href
}
function fillFaceboxFromAjax(href, klass) {
$.get(href, function(data) { $.facebox.reveal(data, klass) })
}
function skipOverlay() {
return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null
}
function showOverlay() {
if (skipOverlay()) return
if ($('#facebox_overlay').length == 0)
$("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')
$('#facebox_overlay').hide().addClass("facebox_overlayBG")
.css('opacity', $.facebox.settings.opacity)
.click(function() { $(document).trigger('close.facebox') })
.fadeIn(200)
return false
}
function hideOverlay() {
if (skipOverlay()) return
$('#facebox_overlay').fadeOut(200, function(){
$("#facebox_overlay").removeClass("facebox_overlayBG")
$("#facebox_overlay").addClass("facebox_hide")
$("#facebox_overlay").remove()
})
return false
}
/*
* Bindings
*/
$(document).bind('close.facebox', function() {
$(document).unbind('keydown.facebox')
$('#facebox').fadeOut(function() {
$('#facebox .content').removeClass().addClass('content')
$('#facebox .loading').remove()
$(document).trigger('afterClose.facebox')
})
hideOverlay()
})
})(jQuery);
|
/* ************************************ */
/* Define helper functions */
/* ************************************ */
function evalAttentionChecks() {
var check_percent = 1
if (run_attention_checks) {
var attention_check_trials = jsPsych.data.getTrialsOfType('attention-check')
var checks_passed = 0
for (var i = 0; i < attention_check_trials.length; i++) {
if (attention_check_trials[i].correct === true) {
checks_passed += 1
}
}
check_percent = checks_passed / attention_check_trials.length
}
return check_percent
}
var randomDraw = function(lst) {
var index = Math.floor(Math.random() * (lst.length))
return lst[index]
}
var makeTrialList = function(len, stim, data) {
//choice array: numeric key codes for the numbers 1-4
var choice_array = choices
// 1 is a switch trial: ensure half the trials are switch trials
var switch_trials = jsPsych.randomization.repeat([0, 1], len / 2)
//create test array
output_list = []
//randomize first trial
var trial_index = jsPsych.randomization.shuffle(['global', 'local'])[0]
if (trial_index == 'global') {
tmpi = Math.floor(Math.random() * (stim.length / 2))
} else {
tmpi = Math.floor(Math.random() * (stim.length / 2)) + stim.length / 2
}
var tmp_obj = {}
tmp_obj.stimulus = stim[tmpi]
var tmp_data = $.extend({}, data[tmpi])
tmp_data.switch = 0
tmp_data.correct_response = choice_array[task_shapes.indexOf(data[tmpi][trial_index + '_shape'])]
tmp_obj.data = tmp_data
output_list.push(tmp_obj)
/* randomly sample from either the global or local stimulus lists (first and half part of the stim/data arrays)
On stay trials randomly select an additional stimulus from that array. On switch trials choose from the other list. */
for (i = 1; i < switch_trials.length; i++) {
tmp_obj = {}
if (switch_trials[i] == 1) {
if (trial_index == 'global') {
trial_index = 'local'
} else {
trial_index = 'global'
}
}
if (trial_index == 'global') {
tmpi = Math.floor(Math.random() * (stim.length / 2))
} else {
tmpi = Math.floor(Math.random() * (stim.length / 2)) + stim.length / 2
}
tmp_obj.stimulus = stim[tmpi]
tmp_data = $.extend({}, data[tmpi])
tmp_data.switch = switch_trials[i]
tmp_data.correct_response = choice_array[task_shapes.indexOf(data[tmpi][trial_index +
'_shape'
])]
tmp_obj.data = tmp_data
output_list.push(tmp_obj)
}
return output_list
}
var getInstructFeedback = function() {
return '<div class = centerbox><p class = center-block-text>' + feedback_instruct_text +
'</p></div>'
}
/* ************************************ */
/* Define experimental variables */
/* ************************************ */
// generic task variables
var run_attention_checks = false
var attention_check_thresh = 0.65
var sumInstructTime = 0 //ms
var instructTimeThresh = 0 ///in seconds
// task specific variables
var choices = [49, 50, 51, 52]
var current_trial = 0
var task_colors = jsPsych.randomization.shuffle(['blue', 'black'])
var task_shapes = ['circle', 'X', 'triangle', 'square']
var path = '/static/experiments/local_global_shape/images/'
var prefix = '<div class = centerbox><img src = "'
var postfix = '"</img></div>'
var stim = []
var data = []
var images = []
for (c = 0; c < task_colors.length; c++) {
if (c === 0) {
condition = 'global'
} else {
condition = 'local'
}
for (g = 0; g < task_shapes.length; g++) {
for (l = 0; l < task_shapes.length; l++) {
images.push([path + task_colors[c] + '_' + task_shapes[g] + 'of' + task_shapes[l] +
's.png'])
stim.push(prefix + path + task_colors[c] + '_' + task_shapes[g] + 'of' + task_shapes[l] +
's.png' + postfix)
data.push({
condition: condition,
global_shape: task_shapes[g],
local_shape: task_shapes[l]
})
}
}
}
//preload images
jsPsych.pluginAPI.preloadImages(images)
//Set up experiment stimulus order
var practice_trials = makeTrialList(36, stim, data) //36
for (i = 0; i < practice_trials.length; i++) {
practice_trials[i].key_answer = practice_trials[i].data.correct_response
}
var test_trials = makeTrialList(96, stim, data) //96
/* ************************************ */
/* Set up jsPsych blocks */
/* ************************************ */
// Set up attention check node
var attention_check_block = {
type: 'attention-check',
data: {
trial_id: "attention_check"
},
timing_response: 180000,
response_ends_trial: true,
timing_post_trial: 200
}
var attention_node = {
timeline: [attention_check_block],
conditional_function: function() {
return run_attention_checks
}
}
//Set up post task questionnaire
var post_task_block = {
type: 'survey-text',
data: {
trial_id: "post task questions"
},
questions: ['<p class = center-block-text style = "font-size: 20px">Please summarize what you were asked to do in this task.</p>',
'<p class = center-block-text style = "font-size: 20px">Do you have any comments about this task?</p>'],
rows: [15, 15],
columns: [60,60]
};
/* define static blocks */
var end_block = {
type: 'poldrack-text',
data: {
trial_id: "end",
exp_id: 'local_global_shape'
},
timing_response: 180000,
text: '<div class = centerbox><p class = center-block-text>Thanks for completing this task!</p><p class = center-block-text>Press <strong>enter</strong> to continue.</p></div>',
cont_key: [13],
timing_post_trial: 0
};
var feedback_instruct_text =
'Welcome to the experiment. This experiment will take about 8 minutes. Press <strong>enter</strong> to begin.'
var feedback_instruct_block = {
type: 'poldrack-text',
cont_key: [13],
data: {
trial_id: "instruction"
},
text: getInstructFeedback,
timing_post_trial: 0,
timing_response: 180000
};
/// This ensures that the subject does not read through the instructions too quickly. If they do it too quickly, then we will go over the loop again.
var instructions_block = {
type: 'poldrack-instructions',
data: {
trial_id: "instruction"
},
pages: [
'<div class = centerbox><p class = block-text>In this experiment you will see blue or black shapes made up of smaller shapes, like the image below. All of the smaller shapes will always be the same shape. Both the large shape and the smaller shapes can either be a circle, X, triangle or square.</p><div class = instructionImgBox><img src = "/static/experiments/local_global_shape/images/blue_squareofcircles.png" height = 200 width = 200></img></div></div>',
'<div class = centerbox><p class = block-text>Your task is to respond based on how many lines either the large or small shapes have, depending on the color. If the shape is ' +
task_colors[0] + ' respond based on how many lines the large shape has. If the shape is ' +
task_colors[1] +
' respond based on how many lines the small shape has.</p><p class = block-text>Use the number keys to respond 1 for a circle, 2 for an X, 3 for a triangle and 4 for a square.</p></div>',
'<div class = centerbox><p class = block-text>For instance, for the shape below you would press 3 because it is ' +
task_colors[1] +
' which means you should respond based on the smaller shapes. If the shape was instead ' +
task_colors[0] +
' you would press 2.</p><div class = instructionImgBox><img src = "/static/experiments/local_global_shape/images/' +
task_colors[1] + '_Xoftriangles.png" height = 200 width = 200></img></div></div>'
],
allow_keys: false,
show_clickable_nav: true,
timing_post_trial: 1000
};
var instruction_node = {
timeline: [feedback_instruct_block, instructions_block],
/* This function defines stopping criteria */
loop_function: function(data) {
for (i = 0; i < data.length; i++) {
if ((data[i].trial_type == 'poldrack-instructions') && (data[i].rt != -1)) {
rt = data[i].rt
sumInstructTime = sumInstructTime + rt
}
}
if (sumInstructTime <= instructTimeThresh * 1000) {
feedback_instruct_text =
'Read through instructions too quickly. Please take your time and make sure you understand the instructions. Press <strong>enter</strong> to continue.'
return true
} else if (sumInstructTime > instructTimeThresh * 1000) {
feedback_instruct_text =
'Done with instructions. Press <strong>enter</strong> to continue.'
return false
}
}
}
var start_practice_block = {
type: 'poldrack-text',
timing_response: 180000,
data: {
trial_id: "practice_intro"
},
text: '<div class = centerbox><p class = center-block-text>We will start with some practice. During practice you will get feedback about whether you responded correctly. You will not get feedback during the rest of the experiment.</p><p class = center-block-text>Press <strong>enter</strong> to begin.</p></div>',
cont_key: [13],
timing_post_trial: 1000
};
var start_test_block = {
type: 'poldrack-text',
timing_response: 180000,
data: {
trial_id: "test_intro"
},
text: '<div class = centerbox><p class = center-block-text>We will now start the test. Remember, if the shape is ' +
task_colors[0] + ' respond based on how many lines the large shape has. If the shape is ' +
task_colors[1] +
' respond based on how many lines the small shape has.</p><p class = center-block-text>Press <strong>enter</strong> to begin.</p></div>',
cont_key: [13],
timing_post_trial: 1000,
on_finish: function() {
current_trial = 0
}
};
/* define practice block */
var practice_block = {
type: 'poldrack-categorize',
timeline: practice_trials,
is_html: true,
data: {
trial_id: "stim",
exp_stage: "practice"
},
correct_text: '<div class = centerbox><div style="color:green"; class = center-text>Correct!</div></div>',
incorrect_text: '<div class = centerbox><div style="color:red"; class = center-text>Incorrect</div></div>',
timeout_message: '<div class = centerbox><div class = center-text>Respond faster!</div></div>',
choices: choices,
timing_feedback_duration: 1000,
show_stim_with_feedback: false,
timing_response: 2000,
timing_post_trial: 500,
on_finish: function(data) {
jsPsych.data.addDataToLastTrial({
trial_num: current_trial
})
current_trial += 1
}
}
/* define test block */
var test_block = {
type: 'poldrack-single-stim',
timeline: test_trials,
data: {
trial_id: "stim",
exp_stage: "test"
},
is_html: true,
choices: choices,
timing_post_trial: 500,
timing_response: 2000,
on_finish: function(data) {
correct = false
if (data.key_press === data.correct_response) {
correct = true
}
jsPsych.data.addDataToLastTrial({
correct: correct,
trial_num: current_trial
})
current_trial += 1
}
};
/* create experiment definition array */
var local_global_shape_experiment = [];
local_global_shape_experiment.push(instruction_node);
local_global_shape_experiment.push(start_practice_block);
local_global_shape_experiment.push(practice_block);
local_global_shape_experiment.push(start_test_block);
local_global_shape_experiment.push(test_block);
local_global_shape_experiment.push(attention_node)
local_global_shape_experiment.push(post_task_block)
local_global_shape_experiment.push(end_block);
|
define({
root: ({
instruction: "Select and configure layers that will be shown in Attribute Table initially.",
label: "Layer",
show: "Show",
actions: "Configure Layer Fields",
field: "Field",
alias: "Alias",
visible: "Visible",
linkField: "Link Field",
noLayers: "No feature layers are available",
back: "Back",
exportCSV: "Allow exporting to CSV",
expand: "Initially expand the widget",
filterByExtent: "Enable Filter by Map Extent by default",
restore: "Restore to default value",
ok: "OK",
cancel: "Cancel",
includePoint: "Inlcude point coordinates to the exported file",
configureLayerFields: "Configure Layer Fields",
result: "Saved successfully",
warning: "Please select the Show option first.",
fieldCheckWarning: "At least one field must be selected.",
unsupportQueryWarning: "The layer needs to support query operation to display in Attribute Table widget. Make sure the query capability in the service is turned on.",
unsupportQueryLayers: "The following layer needs to support query operation to display in Attribute Table widget. Make sure the query capability in the service is turned on.",
fieldName: "Name",
fieldAlias: "Alias",
fieldVisibility: "Visibility",
fieldActions: "Actions"
}),
"ar": 1,
"cs": 1,
"da": 1,
"de": 1,
"el": 1,
"es": 1,
"et": 1,
"fi": 1,
"fr": 1,
"he": 1,
"hr": 1,
"it": 1,
"ja": 1,
"ko": 1,
"lt": 1,
"lv": 1,
"nb": 1,
"nl": 1,
"pl": 1,
"pt-br": 1,
"pt-pt": 1,
"ro": 1,
"ru": 1,
"sr": 1,
"sv": 1,
"th": 1,
"tr": 1,
"vi": 1,
"zh-cn": 1,
"zh-hk": 1,
"zh-tw": 1
});
|
'use strict';
/* global describe, it, beforeEach */
let assert = require('assert');
let Cycle = require('@cycle/core');
let CycleDOM = require('../../src/cycle-dom');
let {Rx} = Cycle;
let {h, makeHTMLDriver} = CycleDOM;
describe('renderAsHTML()', function () {
it('should output HTML when given a simple vtree stream', function (done) {
function app() {
return {
html: Rx.Observable.just(h('div.test-element', ['Foobar']))
};
}
let [requests, responses] = Cycle.run(app, {
html: makeHTMLDriver()
});
responses.html.subscribe(html => {
assert.strictEqual(html, '<div class="test-element">Foobar</div>');
done();
});
});
it('should output simple HTML Observable at `.get(\':root\')`', function (done) {
function app() {
return {
html: Rx.Observable.just(h('div.test-element', ['Foobar']))
};
}
let [requests, responses] = Cycle.run(app, {
html: makeHTMLDriver()
});
responses.html.get(':root').subscribe(html => {
assert.strictEqual(html, '<div class="test-element">Foobar</div>');
done();
});
});
it('should render a simple nested custom element as HTML', function (done) {
function myElement() {
return {
DOM: Rx.Observable.just(h('h3.myelementclass'))
};
}
function app() {
return {
DOM: Rx.Observable.just(h('div.test-element', [h('my-element')]))
};
}
let [requests, responses] = Cycle.run(app, {
DOM: makeHTMLDriver({'my-element': myElement})
});
responses.DOM.subscribe(html => {
assert.strictEqual(html,
'<div class="test-element">' +
'<h3 class="myelementclass"></h3>' +
'</div>'
);
done();
});
});
it('should render double nested custom elements as HTML', function (done) {
function myElement() {
return {
html: Rx.Observable.just(h('h3.myelementclass'))
};
}
function niceElement() {
return {
html: Rx.Observable.just(h('div.a-nice-element', [
String('foobar'), h('my-element')
]))
};
}
function app() {
return {
html: Rx.Observable.just(h('div.test-element', [h('nice-element')]))
};
}
let customElements = {
'my-element': myElement,
'nice-element': niceElement
};
let html$ = Cycle.run(app, {
html: makeHTMLDriver(customElements)
})[1].html;
html$.subscribe(html => {
assert.strictEqual(html,
'<div class="test-element">' +
'<div class="a-nice-element">' +
'foobar<h3 class="myelementclass"></h3>' +
'</div>' +
'</div>'
);
done();
});
});
it('should HTML-render a nested custom element with props', function (done) {
function myElement(ext) {
return {
DOM: ext.props.get('foobar')
.map(foobar => h('h3.myelementclass', String(foobar).toUpperCase()))
};
}
function app() {
return {
DOM: Rx.Observable.just(
h('div.test-element', [
h('my-element', {foobar: 'yes'})
])
)
};
}
let [requests, responses] = Cycle.run(app, {
DOM: makeHTMLDriver({'my-element': myElement})
});
responses.DOM.subscribe(html => {
assert.strictEqual(html,
'<div class="test-element">' +
'<h3 class="myelementclass">YES</h3>' +
'</div>'
);
done();
});
});
it('should HTML-render a nested custom element with props (2)', function (done) {
function myElement(ext) {
return {
DOM: ext.props.get('*')
.map(props => h('h3.myelementclass', String(props.foobar).toUpperCase()))
};
}
function app() {
return {
DOM: Rx.Observable.just(
h('div.test-element', [
h('my-element', {foobar: 'yes'})
])
)
};
}
let [requests, responses] = Cycle.run(app, {
DOM: makeHTMLDriver({'my-element': myElement})
});
responses.DOM.subscribe(html => {
assert.strictEqual(html,
'<div class="test-element">' +
'<h3 class="myelementclass">YES</h3>' +
'</div>'
);
done();
});
});
it('should render a complex custom element tree as HTML', function (done) {
function xFoo() {
return {
html: Rx.Observable.just(h('h1.fooclass'))
};
}
function xBar() {
return {
html: Rx.Observable.just(h('h2.barclass'))
};
}
function app() {
return {
html: Rx.Observable.just(
h('.test-element', [
h('div', [
h('h2.a', 'a'),
h('h4.b', 'b'),
h('x-foo')
]),
h('div', [
h('h3.c', 'c'),
h('div', [
h('p.d', 'd'),
h('x-bar')
])
])
])
)
};
}
let [requests, responses] = Cycle.run(app, {
html: makeHTMLDriver({
'x-foo': xFoo,
'x-bar': xBar
})
});
responses.html.subscribe(html => {
assert.strictEqual(html,
'<div class="test-element">' +
'<div>' +
'<h2 class="a">a</h2>' +
'<h4 class="b">b</h4>' +
'<h1 class="fooclass"></h1>' +
'</div>' +
'<div>' +
'<h3 class="c">c</h3>' +
'<div>' +
'<p class="d">d</p>' +
'<h2 class="barclass"></h2>' +
'</div>' +
'</div>' +
'</div>'
);
done();
});
});
});
|
/*jshint expr:true */
'use strict';
const Crawler = require('../lib/crawler');
const expect = require('chai').expect;
const sinon = require('sinon');
// settings for nock to mock http server
const nock = require('nock');
// init variables
let cb;
let crawler;
describe('Direct feature tests', function() {
before(function() {
nock.cleanAll();
nock('http://test.crawler.com').get('/').reply(200, 'ok').persist();
});
beforeEach(function() {
cb = sinon.spy();
crawler = new Crawler({
jQuery: false,
rateLimit: 100,
preRequest: (options, done) => {
cb('preRequest');
done();
},
callback: (err, res, done) => {
if (err) {
cb('error');
} else {
cb('callback');
}
done();
}
});
crawler.on('request', () => {
cb('Event:request');
});
});
it('should not trigger preRequest or callback of crawler instance', function(finishTest) {
crawler.direct({
uri: 'http://test.crawler.com/',
callback: (error, res) => {
expect(error).to.be.null;
expect(res.statusCode).to.equal(200);
expect(res.body).to.equal('ok');
expect(cb.called).to.be.false;
finishTest();
}
});
});
it('should be sent directly regardless of current queue of crawler', function(finishTest) {
crawler.queue({
uri: 'http://test.crawler.com/',
callback: (error, res, done) => {
expect(error).to.be.null;
crawler.direct({
uri: 'http://test.crawler.com/',
callback: () => {
expect(cb.getCalls().length).to.equal(2);
cb('direct');
}
});
done();
}
});
crawler.queue('http://test.crawler.com/');
crawler.queue('http://test.crawler.com/');
crawler.queue({
uri: 'http://test.crawler.com/',
callback: (error, res, done) => {
expect(error).to.be.null;
let seq = ['preRequest','Event:request','direct','preRequest','Event:request','callback','preRequest','Event:request','callback','preRequest','Event:request'];
expect(cb.getCalls().map(c => c.args[0]).join()).to.equal(seq.join());
expect(cb.getCalls().length).to.equal(11);
done();
finishTest();
}
});
});
it('should not trigger Event:request by default', function(finishTest) {
crawler.direct({
uri: 'http://test.crawler.com/',
callback: (error, res) => {
expect(error).to.be.null;
expect(res.statusCode).to.equal(200);
expect(res.body).to.equal('ok');
expect(cb.called).to.be.false;
finishTest();
}
});
});
it('should trigger Event:request if specified in options', function(finishTest) {
crawler.direct({
uri: 'http://test.crawler.com/',
skipEventRequest: false,
callback: (error, res) => {
expect(error).to.be.null;
expect(res.statusCode).to.equal(200);
expect(res.body).to.equal('ok');
expect(cb.calledOnce).to.be.true;
expect(cb.firstCall.args[0]).to.equal('Event:request');
finishTest();
}
});
});
});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M10 10v4c0 .55.45 1 1 1s1-.45 1-1V4h2v10c0 .55.45 1 1 1s1-.45 1-1V4h1c.55 0 1-.45 1-1s-.45-1-1-1h-6.83C8.08 2 6.22 3.53 6.02 5.61 5.79 7.99 7.66 10 10 10zm-2 7v-1.79c0-.45-.54-.67-.85-.35l-2.79 2.79c-.2.2-.2.51 0 .71l2.79 2.79c.31.31.85.09.85-.36V19h11c.55 0 1-.45 1-1s-.45-1-1-1H8z"
}), 'FormatTextdirectionRToLRounded');
exports.default = _default;
|
var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
var env = config.build.env
var webpackConfig = merge(baseWebpackConfig, {
entry: {
app: './src/main.js',
vendor: ['vue', 'vuex', 'vue-router', 'es6-promise', 'fastclick', 'axios']
},
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true
})
},
devtool: config.build.productionSourceMap ? '#source-map' : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: true
}),
// chunkhash 稳定化
new webpack.HashedModuleIdsPlugin(),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css')
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: {
safe: true
}
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
minifyJS: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency',
inlineSource: 'manifest.*js$' // embed all javascript and css inline
}),
// Inline Manifest Source
new HtmlWebpackInlineSourcePlugin(),
// Move common modules into the parent chunk
new webpack.optimize.CommonsChunkPlugin({
names: ["app"],
// (choose the chunks, or omit for all chunks)
children: true,
// (select all children of chosen chunks)
async: true,
// (create an async commons chunk)
minChunks: 2,
// (3 children must share the module before it's moved)
}),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: Infinity
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
chunks: ['vendor']
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
var CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
|
import Vue from 'vue';
import { HomePage } from 'src/pages/home';
describe('home/HomePage.vue', () => {
it('should render correct contents', () => {
const vm = new Vue({
el: document.createElement('div'),
render: (h) => h(HomePage)
});
expect(vm.$el.className).to.equal('invite-hot');
});
});
|
import { createContext } from 'react';
const FormModalNavigationContext = createContext();
export default FormModalNavigationContext;
|
'use strict'
var RouteConfig = function(application) {
this.application = application;
};
var registerRoutes = function() {
var config = loadRouteConfig();
var routesLength = config.routes.length;
for(var i = 0; i < routesLength; i++) {
var routeItem = config.routes[i];
var Controller = loadController(routeItem);
var route = getRoute(routeItem);
var method = getMethod(routeItem);
registerRoute(this.application, Controller, route, method);
}
createConfigRoute(this.application);
};
var loadRouteConfig = function() {
var config;
try {
config = require('./route.config.json');
if(!config.routes || config.routes.length === 0) {
throw '"routes" not defined';
}
}
catch(e) {
throw 'Unable to parse "lib/config/route.config.json": ' + e;
}
return config;
};
var loadController = function(routeItem) {
var Controller;
if(!routeItem || !routeItem.controller) {
throw 'Undefined "controller" property in "lib/config/route.config.json"';
}
try {
Controller = require(routeItem.controller);
}
catch(e) {
throw 'Unable to load ' + routeItem.controller + ": " + e;
}
return Controller;
};
var getRoute = function(routeItem) {
if(!routeItem || !routeItem.route || routeItem.route.length === 0) {
throw 'Undefined or empty "route" property in "lib/config/route.config.json"';
}
return routeItem.route;
};
var getMethod = function(routeItem) {
if(!routeItem || !routeItem.method || routeItem.method.length === 0) {
throw 'Undefined or empty "method" property in "lib/config/route.config.json"';
}
var method = routeItem.method.toLowerCase();
switch(method) {
case 'get':
case 'put':
case 'post':
case 'delete':
return method;
break;
default:
throw 'Invalid REST "method" property in "lib/config/route.config.json": ' + method;
}
};
var registerRoute = function(application, Controller, route, method) {
application.route(route)[method](function(req, res, next) {
var controller = req.dependencyInjector.get(Controller);
controller[method](req, res, next);
});
};
var createConfigRoute = function(application) {
application.route('/config').get(function(req, res, next) {
res.status(200).json(settings);
});
};
RouteConfig.prototype = {
registerRoutes: registerRoutes
};
module.exports = RouteConfig;
|
/**
* jqMobi is a query selector class for HTML5 mobile apps on a WebkitBrowser.
* Since most mobile devices (Android, iOS, webOS) use a WebKit browser, you only need to target one browser.
* We are able to increase the speed greatly by removing support for legacy desktop browsers and taking advantage of browser features, like native JSON parsing and querySelectorAll
* MIT License
* @author AppMobi
* @api private
*/
if (!window.jq || typeof (jq) !== "function") {
/**
* This is our master jq object that everything is built upon.
* $ is a pointer to this object
* @title jqMobi
* @api private
*/
var jq = (function(window) {
var undefined, document = window.document,
emptyArray = [],
slice = emptyArray.slice,
classCache = [],
eventHandlers = [],
_eventID = 1,
jsonPHandlers = [],
_jsonPID = 1,
fragementRE=/^\s*<(\w+)[^>]*>/,
_attrCache={},
_propCache={};
/**
* internal function to use domfragments for insertion
*
* @api private
*/
function _insertFragments(jqm,container,insert){
var frag=document.createDocumentFragment();
if(insert){
for(var j=jqm.length-1;j>=0;j--)
{
frag.insertBefore(jqm[j],frag.firstChild);
}
container.insertBefore(frag,container.firstChild);
}
else {
for(var j=0;j<jqm.length;j++)
frag.appendChild(jqm[j]);
container.appendChild(frag);
}
frag=null;
}
/**
* Internal function to test if a class name fits in a regular expression
* @param {String} name to search against
* @return {Boolean}
* @api private
*/
function classRE(name) {
return name in classCache ? classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)'));
}
/**
* Internal function that returns a array of unique elements
* @param {Array} array to compare against
* @return {Array} array of unique elements
* @api private
*/
function unique(arr) {
for (var i = 0; i < arr.length; i++) {
if (arr.indexOf(arr[i]) != i) {
arr.splice(i, 1);
i--;
}
}
return arr;
}
/**
* Given a set of nodes, it returns them as an array. Used to find
* siblings of an element
* @param {Nodelist} Node list to search
* @param {Object} [element] to find siblings off of
* @return {Array} array of sibblings
* @api private
*/
function siblings(nodes, element) {
var elems = [];
if (nodes == undefined)
return elems;
for (; nodes; nodes = nodes.nextSibling) {
if (nodes.nodeType == 1 && nodes !== element) {
elems.push(nodes);
}
}
return elems;
}
/**
* This is the internal jqMobi object that gets extended and added on to it
* This is also the start of our query selector engine
* @param {String|Element|Object|Array} selector
* @param {String|Element|Object} [context]
*/
var $jqm = function(toSelect, what) {
this.length = 0;
if (!toSelect) {
return this;
} else if (toSelect instanceof $jqm && what == undefined) {
return toSelect;
} else if ($.isFunction(toSelect)) {
return $(document).ready(toSelect);
} else if ($.isArray(toSelect) && toSelect.length != undefined) { //Passing in an array or object
for (var i = 0; i < toSelect.length; i++)
this[this.length++] = toSelect[i];
return this;
} else if ($.isObject(toSelect) && $.isObject(what)) { //var tmp=$("span"); $("p").find(tmp);
if (toSelect.length == undefined) {
if (toSelect.parentNode == what)
this[this.length++] = toSelect;
} else {
for (var i = 0; i < toSelect.length; i++)
if (toSelect[i].parentNode == what)
this[this.length++] = toSelect[i];
}
return this;
} else if ($.isObject(toSelect) && what == undefined) { //Single object
this[this.length++] = toSelect;
return this;
} else if (what !== undefined) {
if (what instanceof $jqm) {
return what.find(toSelect);
}
} else {
what = document;
}
return this.selector(toSelect, what);
};
/**
* This calls the $jqm function
* @param {String|Element|Object|Array} selector
* @param {String|Element|Object} [context]
*/
var $ = function(selector, what) {
return new $jqm(selector, what);
};
/**
* this is the query selector library for elements
* @param {String} selector
* @param {String|Element|Object} [context]
* @api private
*/
function _selectorAll(selector, what){
try{
return what.querySelectorAll(selector);
} catch(e){
return [];
}
};
function _selector(selector, what) {
selector=selector.trim();
if (selector[0] === "#" && selector.indexOf(" ") === -1 && selector.indexOf(">") === -1) {
if (what == document)
_shimNodes(what.getElementById(selector.replace("#", "")),this);
else
_shimNodes(_selectorAll(selector, what),this);
} else if (selector[0] === "<" && selector[selector.length - 1] === ">") //html
{
var tmp = document.createElement("div");
tmp.innerHTML = selector.trim();
_shimNodes(tmp.childNodes,this);
} else {
_shimNodes((_selectorAll(selector, what)),this);
}
return this;
}
function _shimNodes(nodes,obj){
if(!nodes)
return;
if(nodes.nodeType)
return obj[obj.length++]=nodes;
for(var i=0,iz=nodes.length;i<iz;i++)
obj[obj.length++]=nodes[i];
}
/**
* Checks to see if the parameter is a $jqm object
```
var foo=$('#header');
$.is$(foo);
```
* @param {Object} element
* @return {Boolean}
* @title $.is$(param)
*/
$.is$ = function(obj){return obj instanceof $jqm;}
/**
* Map takes in elements and executes a callback function on each and returns a collection
```
$.map([1,2],function(ind){return ind+1});
```
* @param {Array|Object} elements
* @param {Function} callback
* @return {Object} jqMobi object with elements in it
* @title $.map(elements,callback)
*/
$.map = function(elements, callback) {
var value, values = [],
i, key;
if ($.isArray(elements))
for (i = 0; i < elements.length; i++) {
value = callback(elements[i], i);
if (value !== undefined)
values.push(value);
}
else if ($.isObject(elements))
for (key in elements) {
if (!elements.hasOwnProperty(key))
continue;
value = callback(elements[key], key);
if (value !== undefined)
values.push(value);
}
return $([values]);
};
/**
* Iterates through elements and executes a callback. Returns if false
```
$.each([1,2],function(ind){console.log(ind);});
```
* @param {Array|Object} elements
* @param {Function} callback
* @return {Array} elements
* @title $.each(elements,callback)
*/
$.each = function(elements, callback) {
var i, key;
if ($.isArray(elements))
for (i = 0; i < elements.length; i++) {
if (callback(i, elements[i]) === false)
return elements;
}
else if ($.isObject(elements))
for (key in elements) {
if (!elements.hasOwnProperty(key))
continue;
if (callback(key, elements[key]) === false)
return elements;
}
return elements;
};
/**
* Extends an object with additional arguments
```
$.extend({foo:'bar'});
$.extend(element,{foo:'bar'});
```
* @param {Object} [target] element
* @param any number of additional arguments
* @return {Object} [target]
* @title $.extend(target,{params})
*/
$.extend = function(target) {
if (target == undefined)
target = this;
if (arguments.length === 1) {
for (var key in target)
this[key] = target[key];
return this;
} else {
slice.call(arguments, 1).forEach(function(source) {
for (var key in source)
target[key] = source[key];
});
}
return target;
};
/**
* Checks to see if the parameter is an array
```
var arr=[];
$.isArray(arr);
```
* @param {Object} element
* @return {Boolean}
* @example $.isArray([1]);
* @title $.isArray(param)
*/
$.isArray = function(obj) {
return obj instanceof Array && obj['push'] != undefined; //ios 3.1.3 doesn't have Array.isArray
};
/**
* Checks to see if the parameter is a function
```
var func=function(){};
$.isFunction(func);
```
* @param {Object} element
* @return {Boolean}
* @title $.isFunction(param)
*/
$.isFunction = function(obj) {
return typeof obj === "function";
};
/**
* Checks to see if the parameter is a object
```
var foo={bar:'bar'};
$.isObject(foo);
```
* @param {Object} element
* @return {Boolean}
* @title $.isObject(param)
*/
$.isObject = function(obj) {
return typeof obj === "object";
};
/**
* Prototype for jqm object. Also extens $.fn
*/
$.fn = $jqm.prototype = {
constructor: $jqm,
forEach: emptyArray.forEach,
reduce: emptyArray.reduce,
push: emptyArray.push,
indexOf: emptyArray.indexOf,
concat: emptyArray.concat,
selector: _selector,
oldElement: undefined,
slice: emptyArray.slice,
/**
* This is a utility function for .end()
* @param {Object} params
* @return {Object} a jqMobi with params.oldElement set to this
* @api private
*/
setupOld: function(params) {
if (params == undefined)
return $();
params.oldElement = this;
return params;
},
/**
* This is a wrapper to $.map on the selected elements
```
$().map(function(){this.value+=ind});
```
* @param {Function} callback
* @return {Object} a jqMobi object
* @title $().map(function)
*/
map: function(fn) {
return $.map(this, function(el, i) {
return fn.call(el, i, el);
});
},
/**
* Iterates through all elements and applys a callback function
```
$().each(function(){console.log(this.value)});
```
* @param {Function} callback
* @return {Object} a jqMobi object
* @title $().each(function)
*/
each: function(callback) {
this.forEach(function(el, idx) {
callback.call(el, idx, el);
});
return this;
},
/**
* This is executed when DOMContentLoaded happens, or after if you've registered for it.
```
$(document).ready(function(){console.log('I'm ready');});
```
* @param {Function} callback
* @return {Object} a jqMobi object
* @title $().ready(function)
*/
ready: function(callback) {
if (document.readyState === "complete" || document.readyState === "loaded"||(!$.os.ie&&document.readyState==="interactive")) //IE10 fires interactive too early
callback();
else
document.addEventListener("DOMContentLoaded", callback, false);
return this;
},
/**
* Searches through the collection and reduces them to elements that match the selector
```
$("#foo").find('.bar');
$("#foo").find($('.bar'));
$("#foo").find($('.bar').get());
```
* @param {String|Object|Array} selector
* @return {Object} a jqMobi object filtered
* @title $().find(selector)
*/
find: function(sel) {
if (this.length === 0)
return undefined;
var elems = [];
var tmpElems;
for (var i = 0; i < this.length; i++) {
tmpElems = ($(sel, this[i]));
for (var j = 0; j < tmpElems.length; j++) {
elems.push(tmpElems[j]);
}
}
return $(unique(elems));
},
/**
* Gets or sets the innerHTML for the collection.
* If used as a get, the first elements innerHTML is returned
```
$("#foo").html(); //gets the first elements html
$("#foo").html('new html');//sets the html
$("#foo").html('new html',false); //Do not do memory management cleanup
```
* @param {String} html to set
* @param {Bool} [cleanup] - set to false for performance tests and if you do not want to execute memory management cleanup
* @return {Object} a jqMobi object
* @title $().html([html])
*/
html: function(html,cleanup) {
if (this.length === 0)
return undefined;
if (html === undefined)
return this[0].innerHTML;
for (var i = 0; i < this.length; i++) {
if(cleanup!==false)
$.cleanUpContent(this[i], false, true);
this[i].innerHTML = html;
}
return this;
},
/**
* Gets or sets the innerText for the collection.
* If used as a get, the first elements innerText is returned
```
$("#foo").text(); //gets the first elements text;
$("#foo").text('new text'); //sets the text
```
* @param {String} text to set
* @return {Object} a jqMobi object
* @title $().text([text])
*/
text: function(text) {
if (this.length === 0)
return undefined;
if (text === undefined)
return this[0].textContent;
for (var i = 0; i < this.length; i++) {
this[i].textContent = text;
}
return this;
},
/**
* Gets or sets a css property for the collection
* If used as a get, the first elements css property is returned
```
$().css("background"); // Gets the first elements background
$().css("background","red") //Sets the elements background to red
```
* @param {String} attribute to get
* @param {String} value to set as
* @return {Object} a jqMobi object
* @title $().css(attribute,[value])
*/
css: function(attribute, value, obj) {
var toAct = obj != undefined ? obj : this[0];
if (this.length === 0)
return undefined;
if (value == undefined && typeof (attribute) === "string") {
var styles = window.getComputedStyle(toAct);
return toAct.style[attribute] ? toAct.style[attribute]: window.getComputedStyle(toAct)[attribute] ;
}
for (var i = 0; i < this.length; i++) {
if ($.isObject(attribute)) {
for (var j in attribute) {
this[i].style[j] = attribute[j];
}
} else {
this[i].style[attribute] = value;
}
}
return this;
},
/**
* Gets or sets css vendor specific css properties
* If used as a get, the first elements css property is returned
```
$().css("background"); // Gets the first elements background
$().css("background","red") //Sets the elements background to red
```
* @param {String} attribute to get
* @param {String} value to set as
* @return {Object} a jqMobi object
* @title $().css(attribute,[value])
*/
vendorCss:function(attribute,value,obj){
return this.css($.feat.cssPrefix+attribute,value,obj);
},
/**
* Sets the innerHTML of all elements to an empty string
```
$().empty();
```
* @return {Object} a jqMobi object
* @title $().empty()
*/
empty: function() {
for (var i = 0; i < this.length; i++) {
$.cleanUpContent(this[i], false, true);
this[i].innerHTML = '';
}
return this;
},
/**
* Sets the elements display property to "none".
* This will also store the old property into an attribute for hide
```
$().hide();
```
* @return {Object} a jqMobi object
* @title $().hide()
*/
hide: function() {
if (this.length === 0)
return this;
for (var i = 0; i < this.length; i++) {
if (this.css("display", null, this[i]) != "none") {
this[i].setAttribute("jqmOldStyle", this.css("display", null, this[i]));
this[i].style.display = "none";
}
}
return this;
},
/**
* Shows all the elements by setting the css display property
* We look to see if we were retaining an old style (like table-cell) and restore that, otherwise we set it to block
```
$().show();
```
* @return {Object} a jqMobi object
* @title $().show()
*/
show: function() {
if (this.length === 0)
return this;
for (var i = 0; i < this.length; i++) {
if (this.css("display", null, this[i]) == "none") {
this[i].style.display = this[i].getAttribute("jqmOldStyle") ? this[i].getAttribute("jqmOldStyle") : 'block';
this[i].removeAttribute("jqmOldStyle");
}
}
return this;
},
/**
* Toggle the visibility of a div
```
$().toggle();
$().toggle(true); //force showing
```
* @param {Boolean} [show] -force the hiding or showing of the element
* @return {Object} a jqMobi object
* @title $().toggle([show])
*/
toggle: function(show) {
var show2 = show === true ? true : false;
for (var i = 0; i < this.length; i++) {
if (window.getComputedStyle(this[i])['display'] !== "none" || (show !== undefined && show2 === false)) {
this[i].setAttribute("jqmOldStyle", this[i].style.display)
this[i].style.display = "none";
} else {
this[i].style.display = this[i].getAttribute("jqmOldStyle") != undefined ? this[i].getAttribute("jqmOldStyle") : 'block';
this[i].removeAttribute("jqmOldStyle");
}
}
return this;
},
/**
* Gets or sets an elements value
* If used as a getter, we return the first elements value. If nothing is in the collection, we return undefined
```
$().value; //Gets the first elements value;
$().value="bar"; //Sets all elements value to bar
```
* @param {String} [value] to set
* @return {String|Object} A string as a getter, jqMobi object as a setter
* @title $().val([value])
*/
val: function(value) {
if (this.length === 0)
return (value === undefined) ? undefined : this;
if (value == undefined)
return this[0].value;
for (var i = 0; i < this.length; i++) {
this[i].value = value;
}
return this;
},
/**
* Gets or sets an attribute on an element
* If used as a getter, we return the first elements value. If nothing is in the collection, we return undefined
```
$().attr("foo"); //Gets the first elements 'foo' attribute
$().attr("foo","bar");//Sets the elements 'foo' attribute to 'bar'
$().attr("foo",{bar:'bar'}) //Adds the object to an internal cache
```
* @param {String|Object} attribute to act upon. If it's an object (hashmap), it will set the attributes based off the kvp.
* @param {String|Array|Object|function} [value] to set
* @return {String|Object|Array|Function} If used as a getter, return the attribute value. If a setter, return a jqMobi object
* @title $().attr(attribute,[value])
*/
attr: function(attr, value) {
if (this.length === 0)
return (value === undefined) ? undefined : this;
if (value === undefined && !$.isObject(attr)) {
var val = (this[0].jqmCacheId&&_attrCache[this[0].jqmCacheId][attr])?(this[0].jqmCacheId&&_attrCache[this[0].jqmCacheId][attr]):this[0].getAttribute(attr);
return val;
}
for (var i = 0; i < this.length; i++) {
if ($.isObject(attr)) {
for (var key in attr) {
$(this[i]).attr(key,attr[key]);
}
}
else if($.isArray(value)||$.isObject(value)||$.isFunction(value))
{
if(!this[i].jqmCacheId)
this[i].jqmCacheId=$.uuid();
if(!_attrCache[this[i].jqmCacheId])
_attrCache[this[i].jqmCacheId]={}
_attrCache[this[i].jqmCacheId][attr]=value;
}
else if (value == null && value !== undefined)
{
this[i].removeAttribute(attr);
if(this[i].jqmCacheId&&_attrCache[this[i].jqmCacheId][attr])
delete _attrCache[this[i].jqmCacheId][attr];
}
else{
this[i].setAttribute(attr, value);
}
}
return this;
},
/**
* Removes an attribute on the elements
```
$().removeAttr("foo");
```
* @param {String} attributes that can be space delimited
* @return {Object} jqMobi object
* @title $().removeAttr(attribute)
*/
removeAttr: function(attr) {
var that = this;
for (var i = 0; i < this.length; i++) {
attr.split(/\s+/g).forEach(function(param) {
that[i].removeAttribute(param);
if(that[i].jqmCacheId&&_attrCache[that[i].jqmCacheId][attr])
delete _attrCache[that[i].jqmCacheId][attr];
});
}
return this;
},
/**
* Gets or sets a property on an element
* If used as a getter, we return the first elements value. If nothing is in the collection, we return undefined
```
$().prop("foo"); //Gets the first elements 'foo' property
$().prop("foo","bar");//Sets the elements 'foo' property to 'bar'
$().prop("foo",{bar:'bar'}) //Adds the object to an internal cache
```
* @param {String|Object} property to act upon. If it's an object (hashmap), it will set the attributes based off the kvp.
* @param {String|Array|Object|function} [value] to set
* @return {String|Object|Array|Function} If used as a getter, return the property value. If a setter, return a jqMobi object
* @title $().prop(property,[value])
*/
prop: function(prop, value) {
if (this.length === 0)
return (value === undefined) ? undefined : this;
if (value === undefined && !$.isObject(prop)) {
var res;
var val = (this[0].jqmCacheId&&_propCache[this[0].jqmCacheId][prop])?(this[0].jqmCacheId&&_propCache[this[0].jqmCacheId][prop]):!(res=this[0][prop])&&prop in this[0]?this[0][prop]:res;
return val;
}
for (var i = 0; i < this.length; i++) {
if ($.isObject(prop)) {
for (var key in prop) {
$(this[i]).prop(key,prop[key]);
}
}
else if($.isArray(value)||$.isObject(value)||$.isFunction(value))
{
if(!this[i].jqmCacheId)
this[i].jqmCacheId=$.uuid();
if(!_propCache[this[i].jqmCacheId])
_propCache[this[i].jqmCacheId]={}
_propCache[this[i].jqmCacheId][prop]=value;
}
else if (value == null && value !== undefined)
{
$(this[i]).removeProp(prop);
}
else{
this[i][prop]= value;
}
}
return this;
},
/**
* Removes a property on the elements
```
$().removeProp("foo");
```
* @param {String} properties that can be space delimited
* @return {Object} jqMobi object
* @title $().removeProp(attribute)
*/
removeProp: function(prop) {
var that = this;
for (var i = 0; i < this.length; i++) {
prop.split(/\s+/g).forEach(function(param) {
if(that[i][param])
delete that[i][param];
if(that[i].jqmCacheId&&_propCache[that[i].jqmCacheId][prop]){
delete _propCache[that[i].jqmCacheId][prop];
}
});
}
return this;
},
/**
* Removes elements based off a selector
```
$().remove(".foo");//Remove off a string selector
var element=$("#foo").get();
$().remove(element); //Remove by an element
$().remove($(".foo")); //Remove by a collection
```
* @param {String|Object|Array} selector to filter against
* @return {Object} jqMobi object
* @title $().remove(selector)
*/
remove: function(selector) {
var elems = $(this).filter(selector);
if (elems == undefined)
return this;
for (var i = 0; i < elems.length; i++) {
$.cleanUpContent(elems[i], true, true);
elems[i].parentNode.removeChild(elems[i]);
}
return this;
},
/**
* Adds a css class to elements.
```
$().addClass("selected");
```
* @param {String} classes that are space delimited
* @return {Object} jqMobi object
* @title $().addClass(name)
*/
addClass: function(name) {
for (var i = 0; i < this.length; i++) {
var cls = this[i].className;
var classList = [];
var that = this;
name.split(/\s+/g).forEach(function(cname) {
if (!that.hasClass(cname, that[i]))
classList.push(cname);
});
this[i].className += (cls ? " " : "") + classList.join(" ");
this[i].className = this[i].className.trim();
}
return this;
},
/**
* Removes a css class from elements.
```
$().removeClass("foo"); //single class
$().removeClass("foo selected");//remove multiple classess
```
* @param {String} classes that are space delimited
* @return {Object} jqMobi object
* @title $().removeClass(name)
*/
removeClass: function(name) {
for (var i = 0; i < this.length; i++) {
if (name == undefined) {
this[i].className = '';
return this;
}
var classList = this[i].className;
name.split(/\s+/g).forEach(function(cname) {
classList = classList.replace(classRE(cname), " ");
});
if (classList.length > 0)
this[i].className = classList.trim();
else
this[i].className = "";
}
return this;
},
/**
* Replaces a css class on elements.
```
$().replaceClass("on", "off");
```
* @param {String} classes that are space delimited
* @param {String} classes that are space delimited
* @return {Object} jqMobi object
* @title $().replaceClass(old, new)
*/
replaceClass: function(name, newName) {
for (var i = 0; i < this.length; i++) {
if (name == undefined) {
this[i].className = newName;
continue;
}
var classList = this[i].className;
name.split(/\s+/g).concat(newName.split(/\s+/g)).forEach(function(cname) {
classList = classList.replace(classRE(cname), " ");
});
classList=classList.trim();
if (classList.length > 0){
this[i].className = (classList+" "+newName).trim();
} else
this[i].className = newName;
}
return this;
},
/**
* Checks to see if an element has a class.
```
$().hasClass('foo');
$().hasClass('foo',element);
```
* @param {String} class name to check against
* @param {Object} [element] to check against
* @return {Boolean}
* @title $().hasClass(name,[element])
*/
hasClass: function(name, element) {
if (this.length === 0)
return false;
if (!element)
element = this[0];
return classRE(name).test(element.className);
},
/**
* Appends to the elements
* We boil everything down to a jqMobi object and then loop through that.
* If it's HTML, we create a dom element so we do not break event bindings.
* if it's a script tag, we evaluate it.
```
$().append("<div></div>"); //Creates the object from the string and appends it
$().append($("#foo")); //Append an object;
```
* @param {String|Object} Element/string to add
* @param {Boolean} [insert] insert or append
* @return {Object} jqMobi object
* @title $().append(element,[insert])
*/
append: function(element, insert) {
if (element && element.length != undefined && element.length === 0)
return this;
if ($.isArray(element) || $.isObject(element))
element = $(element);
var i;
for (i = 0; i < this.length; i++) {
if (element.length && typeof element != "string") {
element = $(element);
_insertFragments(element,this[i],insert);
} else {
var obj =fragementRE.test(element)?$(element):undefined;
if (obj == undefined || obj.length == 0) {
obj = document.createTextNode(element);
}
if (obj.nodeName != undefined && obj.nodeName.toLowerCase() == "script" && (!obj.type || obj.type.toLowerCase() === 'text/javascript')) {
window.eval(obj.innerHTML);
} else if(obj instanceof $jqm) {
_insertFragments(obj,this[i],insert);
}
else {
insert != undefined ? this[i].insertBefore(obj, this[i].firstChild) : this[i].appendChild(obj);
}
}
}
return this;
},
/**
* Appends the current collection to the selector
```
$().appendTo("#foo"); //Append an object;
```
* @param {String|Object} Selector to append to
* @param {Boolean} [insert] insert or append
* @title $().appendTo(element,[insert])
*/
appendTo:function(selector,insert){
var tmp=$(selector);
tmp.append(this);
},
/**
* Prepends the current collection to the selector
```
$().prependTo("#foo"); //Prepend an object;
```
* @param {String|Object} Selector to prepent to
* @title $().prependTo(element)
*/
prependTo:function(selector){
var tmp=$(selector);
tmp.append(this,true);
},
/**
* Prepends to the elements
* This simply calls append and sets insert to true
```
$().prepend("<div></div>");//Creates the object from the string and appends it
$().prepend($("#foo")); //Prepends an object
```
* @param {String|Object} Element/string to add
* @return {Object} jqMobi object
* @title $().prepend(element)
*/
prepend: function(element) {
return this.append(element, 1);
},
/**
* Inserts collection before the target (adjacent)
```
$().insertBefore(jq("#target"));
```
* @param {String|Object} Target
* @title $().insertBefore(target);
*/
insertBefore: function(target, after) {
if (this.length == 0)
return this;
target = $(target).get(0);
if (!target || target.length == 0)
return this;
for (var i = 0; i < this.length; i++)
{
after ? target.parentNode.insertBefore(this[i], target.nextSibling) : target.parentNode.insertBefore(this[i], target);
}
return this;
},
/**
* Inserts collection after the target (adjacent)
```
$().insertAfter(jq("#target"));
```
* @param {String|Object} target
* @title $().insertAfter(target);
*/
insertAfter: function(target) {
this.insertBefore(target, true);
},
/**
* Returns the raw DOM element.
```
$().get(); //returns the first element
$().get(2);// returns the third element
```
* @param {Int} [index]
* @return {Object} raw DOM element
* @title $().get([index])
*/
get: function(index) {
index = index == undefined ? 0 : index;
if (index < 0)
index += this.length;
return (this[index]) ? this[index] : undefined;
},
/**
* Returns the offset of the element, including traversing up the tree
```
$().offset();
```
* @return {Object} with left, top, width and height properties
* @title $().offset()
*/
offset: function() {
if (this.length === 0)
return undefined;
if(this[0]==window)
return {
left:0,
top:0,
right:0,
bottom:0,
width:window.innerWidth,
height:window.innerHeight
}
else
var obj = this[0].getBoundingClientRect();
return {
left: obj.left + window.pageXOffset,
top: obj.top + window.pageYOffset,
right: obj.right + window.pageXOffset,
bottom: obj.bottom + window.pageYOffset,
width: obj.right-obj.left,
height: obj.bottom-obj.top
};
},
/**
* returns the height of the element, including padding on IE
```
$().height();
```
* @return {string} height with "px"
* @title $().height()
*/
height:function(){
return this.offset().height;
},
/**
* returns the width of the element, including padding on IE
```
$().width();
```
* @return {string} width with "px"
* @title $().width()
*/
width:function(){
return this.offset().width;
},
/**
* Returns the parent nodes of the elements based off the selector
```
$("#foo").parent('.bar');
$("#foo").parent($('.bar'));
$("#foo").parent($('.bar').get());
```
* @param {String|Array|Object} [selector]
* @return {Object} jqMobi object with unique parents
* @title $().parent(selector)
*/
parent: function(selector) {
if (this.length == 0)
return undefined;
var elems = [];
for (var i = 0; i < this.length; i++) {
if (this[i].parentNode)
elems.push(this[i].parentNode);
}
return this.setupOld($(unique(elems)).filter(selector));
},
/**
* Returns the child nodes of the elements based off the selector
```
$("#foo").children('.bar'); //Selector
$("#foo").children($('.bar')); //Objects
$("#foo").children($('.bar').get()); //Single element
```
* @param {String|Array|Object} [selector]
* @return {Object} jqMobi object with unique children
* @title $().children(selector)
*/
children: function(selector) {
if (this.length == 0)
return undefined;
var elems = [];
for (var i = 0; i < this.length; i++) {
elems = elems.concat(siblings(this[i].firstChild));
}
return this.setupOld($((elems)).filter(selector));
},
/**
* Returns the siblings of the element based off the selector
```
$("#foo").siblings('.bar'); //Selector
$("#foo").siblings($('.bar')); //Objects
$("#foo").siblings($('.bar').get()); //Single element
```
* @param {String|Array|Object} [selector]
* @return {Object} jqMobi object with unique siblings
* @title $().siblings(selector)
*/
siblings: function(selector) {
if (this.length == 0)
return undefined;
var elems = [];
for (var i = 0; i < this.length; i++) {
if (this[i].parentNode)
elems = elems.concat(siblings(this[i].parentNode.firstChild, this[i]));
}
return this.setupOld($(elems).filter(selector));
},
/**
* Returns the closest element based off the selector and optional context
```
$("#foo").closest('.bar'); //Selector
$("#foo").closest($('.bar')); //Objects
$("#foo").closest($('.bar').get()); //Single element
```
* @param {String|Array|Object} selector
* @param {Object} [context]
* @return {Object} Returns a jqMobi object with the closest element based off the selector
* @title $().closest(selector,[context]);
*/
closest: function(selector, context) {
if (this.length == 0)
return undefined;
var elems = [],
cur = this[0];
var start = $(selector, context);
if (start.length == 0)
return $();
while (cur && start.indexOf(cur) == -1) {
cur = cur !== context && cur !== document && cur.parentNode;
}
return $(cur);
},
/**
* Filters elements based off the selector
```
$("#foo").filter('.bar'); //Selector
$("#foo").filter($('.bar')); //Objects
$("#foo").filter($('.bar').get()); //Single element
```
* @param {String|Array|Object} selector
* @return {Object} Returns a jqMobi object after the filter was run
* @title $().filter(selector);
*/
filter: function(selector) {
if (this.length == 0)
return undefined;
if (selector == undefined)
return this;
var elems = [];
for (var i = 0; i < this.length; i++) {
var val = this[i];
if (val.parentNode && $(selector, val.parentNode).indexOf(val) >= 0)
elems.push(val);
}
return this.setupOld($(unique(elems)));
},
/**
* Basically the reverse of filter. Return all elements that do NOT match the selector
```
$("#foo").not('.bar'); //Selector
$("#foo").not($('.bar')); //Objects
$("#foo").not($('.bar').get()); //Single element
```
* @param {String|Array|Object} selector
* @return {Object} Returns a jqMobi object after the filter was run
* @title $().not(selector);
*/
not: function(selector) {
if (this.length == 0)
return undefined;
var elems = [];
for (var i = 0; i < this.length; i++) {
var val = this[i];
if (val.parentNode && $(selector, val.parentNode).indexOf(val) == -1)
elems.push(val);
}
return this.setupOld($(unique(elems)));
},
/**
* Gets or set data-* attribute parameters on elements
* When used as a getter, it's only the first element
```
$().data("foo"); //Gets the data-foo attribute for the first element
$().data("foo","bar"); //Sets the data-foo attribute for all elements
$().data("foo",{bar:'bar'});//object as the data
```
* @param {String} key
* @param {String|Array|Object} value
* @return {String|Object} returns the value or jqMobi object
* @title $().data(key,[value]);
*/
data: function(key, value) {
return this.attr('data-' + key, value);
},
/**
* Rolls back the jqMobi elements when filters were applied
* This can be used after .not(), .filter(), .children(), .parent()
```
$().filter(".panel").end(); //This will return the collection BEFORE filter is applied
```
* @return {Object} returns the previous jqMobi object before filter was applied
* @title $().end();
*/
end: function() {
return this.oldElement != undefined ? this.oldElement : $();
},
/**
* Clones the nodes in the collection.
```
$().clone();// Deep clone of all elements
$().clone(false); //Shallow clone
```
* @param {Boolean} [deep] - do a deep copy or not
* @return {Object} jqMobi object of cloned nodes
* @title $().clone();
*/
clone: function(deep) {
deep = deep === false ? false : true;
if (this.length == 0)
return undefined;
var elems = [];
for (var i = 0; i < this.length; i++) {
elems.push(this[i].cloneNode(deep));
}
return $(elems);
},
/**
* Returns the number of elements in the collection
```
$().size();
```
* @return {Int}
* @title $().size();
*/
size: function() {
return this.length;
},
/**
* Serailizes a form into a query string
```
$().serialize(grouping);
```
* @param {String} [grouping] - optional grouping to the fields -e.g users[name]
* @return {String}
* @title $().serialize(grouping)
*/
serialize: function(grouping) {
if (this.length == 0)
return "";
var params = {};
for (var i = 0; i < this.length; i++)
{
this.slice.call(this[i].elements).forEach(function(elem) {
var type = elem.getAttribute("type");
if (elem.nodeName.toLowerCase() != "fieldset" && !elem.disabled && type != "submit"
&& type != "reset" && type != "button" && ((type != "radio" && type != "checkbox") || elem.checked))
params[elem.getAttribute("name")] = elem.value;
});
}
return $.param(params,grouping);
},
/* added in 1.2 */
/**
* Reduce the set of elements based off index
```
$().eq(index)
```
* @param {Int} index - Index to filter by. If negative, it will go back from the end
* @return {Object} jqMobi object
* @title $().eq(index)
*/
eq:function(ind){
return $(this.get(ind));
},
/**
* Returns the index of the selected element in the collection
```
$().index(elem)
```
* @param {String|Object} element to look for. Can be a selector or object
* @return integer - index of selected element
* @title $().index(elem)
*/
index:function(elem){
return elem?this.indexOf($(elem)[0]):this.parent().children().indexOf(this[0]);
},
/**
* Returns boolean if the object is a type of the selector
```
$().is(selector)
```
* param {String|Object|Function} selector to act upon
* @return boolean
* @title $().is(selector)
*/
is:function(selector){
return !!selector&&this.filter(selector).length>0;
}
};
/* AJAX functions */
function empty() {
}
var ajaxSettings = {
type: 'GET',
beforeSend: empty,
success: empty,
error: empty,
complete: empty,
context: undefined,
timeout: 0,
crossDomain: null
};
/**
* Execute a jsonP call, allowing cross domain scripting
* options.url - URL to call
* options.success - Success function to call
* options.error - Error function to call
```
$.jsonP({url:'mysite.php?callback=?&foo=bar',success:function(){},error:function(){}});
```
* @param {Object} options
* @title $.jsonP(options)
*/
$.jsonP = function(options) {
var callbackName = 'jsonp_callback' + (++_jsonPID);
var abortTimeout = "",
context;
var script = document.createElement("script");
var abort = function() {
$(script).remove();
if (window[callbackName])
window[callbackName] = empty;
};
window[callbackName] = function(data) {
clearTimeout(abortTimeout);
$(script).remove();
delete window[callbackName];
options.success.call(context, data);
};
script.src = options.url.replace(/=\?/, '=' + callbackName);
if(options.error)
{
script.onerror=function(){
clearTimeout(abortTimeout);
options.error.call(context, "", 'error');
}
}
$('head').append(script);
if (options.timeout > 0)
abortTimeout = setTimeout(function() {
options.error.call(context, "", 'timeout');
}, options.timeout);
return {};
};
/**
* Execute an Ajax call with the given options
* options.type - Type of request
* options.beforeSend - function to execute before sending the request
* options.success - success callback
* options.error - error callback
* options.complete - complete callback - callled with a success or error
* options.timeout - timeout to wait for the request
* options.url - URL to make request against
* options.contentType - HTTP Request Content Type
* options.headers - Object of headers to set
* options.dataType - Data type of request
* options.data - data to pass into request. $.param is called on objects
```
var opts={
type:"GET",
success:function(data){},
url:"mypage.php",
data:{bar:'bar'},
}
$.ajax(opts);
```
* @param {Object} options
* @title $.ajax(options)
*/
$.ajax = function(opts) {
var xhr;
try {
var settings = opts || {};
for (var key in ajaxSettings) {
if (typeof(settings[key]) == 'undefined')
settings[key] = ajaxSettings[key];
}
if (!settings.url)
settings.url = window.location;
if (!settings.contentType)
settings.contentType = "application/x-www-form-urlencoded";
if (!settings.headers)
settings.headers = {};
if(!('async' in settings)||settings.async!==false)
settings.async=true;
if (!settings.dataType)
settings.dataType = "text/html";
else {
switch (settings.dataType) {
case "script":
settings.dataType = 'text/javascript, application/javascript';
break;
case "json":
settings.dataType = 'application/json';
break;
case "xml":
settings.dataType = 'application/xml, text/xml';
break;
case "html":
settings.dataType = 'text/html';
break;
case "text":
settings.dataType = 'text/plain';
break;
default:
settings.dataType = "text/html";
break;
case "jsonp":
return $.jsonP(opts);
break;
}
}
if ($.isObject(settings.data))
settings.data = $.param(settings.data);
if (settings.type.toLowerCase() === "get" && settings.data) {
if (settings.url.indexOf("?") === -1)
settings.url += "?" + settings.data;
else
settings.url += "&" + settings.data;
}
if (/=\?/.test(settings.url)) {
return $.jsonP(settings);
}
if (settings.crossDomain === null) settings.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(settings.url) &&
RegExp.$2 != window.location.host;
if(!settings.crossDomain)
settings.headers = $.extend({'X-Requested-With': 'XMLHttpRequest'}, settings.headers);
var abortTimeout;
var context = settings.context;
var protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol;
//ok, we are really using xhr
xhr = new window.XMLHttpRequest();
xhr.onreadystatechange = function() {
var mime = settings.dataType;
if (xhr.readyState === 4) {
clearTimeout(abortTimeout);
var result, error = false;
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0&&protocol=='file:') {
if (mime === 'application/json' && !(/^\s*$/.test(xhr.responseText))) {
try {
result = JSON.parse(xhr.responseText);
} catch (e) {
error = e;
}
} else if (mime === 'application/xml, text/xml') {
result = xhr.responseXML;
} else
result = xhr.responseText;
//If we're looking at a local file, we assume that no response sent back means there was an error
if(xhr.status===0&&result.length===0)
error=true;
if (error)
settings.error.call(context, xhr, 'parsererror', error);
else {
settings.success.call(context, result, 'success', xhr);
}
} else {
error = true;
settings.error.call(context, xhr, 'error');
}
settings.complete.call(context, xhr, error ? 'error' : 'success');
}
};
xhr.open(settings.type, settings.url, settings.async);
if (settings.withCredentials) xhr.withCredentials = true;
if (settings.contentType)
settings.headers['Content-Type'] = settings.contentType;
for (var name in settings.headers)
xhr.setRequestHeader(name, settings.headers[name]);
if (settings.beforeSend.call(context, xhr, settings) === false) {
xhr.abort();
return false;
}
if (settings.timeout > 0)
abortTimeout = setTimeout(function() {
xhr.onreadystatechange = empty;
xhr.abort();
settings.error.call(context, xhr, 'timeout');
}, settings.timeout);
xhr.send(settings.data);
} catch (e) {
console.log(e);
}
return xhr;
};
/**
* Shorthand call to an Ajax GET request
```
$.get("mypage.php?foo=bar",function(data){});
```
* @param {String} url to hit
* @param {Function} success
* @title $.get(url,success)
*/
$.get = function(url, success) {
return this.ajax({
url: url,
success: success
});
};
/**
* Shorthand call to an Ajax POST request
```
$.post("mypage.php",{bar:'bar'},function(data){});
```
* @param {String} url to hit
* @param {Object} [data] to pass in
* @param {Function} success
* @param {String} [dataType]
* @title $.post(url,[data],success,[dataType])
*/
$.post = function(url, data, success, dataType) {
if (typeof (data) === "function") {
success = data;
data = {};
}
if (dataType === undefined)
dataType = "html";
return this.ajax({
url: url,
type: "POST",
data: data,
dataType: dataType,
success: success
});
};
/**
* Shorthand call to an Ajax request that expects a JSON response
```
$.getJSON("mypage.php",{bar:'bar'},function(data){});
```
* @param {String} url to hit
* @param {Object} [data]
* @param {Function} [success]
* @title $.getJSON(url,data,success)
*/
$.getJSON = function(url, data, success) {
if (typeof (data) === "function") {
success = data;
data = {};
}
return this.ajax({
url: url,
data: data,
success: success,
dataType: "json"
});
};
/**
* Converts an object into a key/value par with an optional prefix. Used for converting objects to a query string
```
var obj={
foo:'foo',
bar:'bar'
}
var kvp=$.param(obj,'data');
```
* @param {Object} object
* @param {String} [prefix]
* @return {String} Key/value pair representation
* @title $.param(object,[prefix];
*/
$.param = function(obj, prefix) {
var str = [];
if (obj instanceof $jqm) {
obj.each(function() {
var k = prefix ? prefix + "[]" : this.id,
v = this.value;
str.push((k) + "=" + encodeURIComponent(v));
});
} else {
for (var p in obj) {
var k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push($.isObject(v) ? $.param(v, k) : (k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
};
/**
* Used for backwards compatibility. Uses native JSON.parse function
```
var obj=$.parseJSON("{\"bar\":\"bar\"}");
```
* @params {String} string
* @return {Object}
* @title $.parseJSON(string)
*/
$.parseJSON = function(string) {
return JSON.parse(string);
};
/**
* Helper function to convert XML into the DOM node representation
```
var xmlDoc=$.parseXML("<xml><foo>bar</foo></xml>");
```
* @param {String} string
* @return {Object} DOM nodes
* @title $.parseXML(string)
*/
$.parseXML = function(string) {
return (new DOMParser).parseFromString(string, "text/xml");
};
/**
* Helper function to parse the user agent. Sets the following
* .os.webkit
* .os.android
* .os.ipad
* .os.iphone
* .os.webos
* .os.touchpad
* .os.blackberry
* .os.opera
* .os.fennec
* @api private
*/
function detectUA($, userAgent) {
$.os = {};
$.os.webkit = userAgent.match(/WebKit\/([\d.]+)/) ? true : false;
$.os.android = userAgent.match(/(Android)\s+([\d.]+)/) || userAgent.match(/Silk-Accelerated/) ? true : false;
$.os.androidICS = $.os.android && userAgent.match(/(Android)\s4/) ? true : false;
$.os.ipad = userAgent.match(/(iPad).*OS\s([\d_]+)/) ? true : false;
$.os.iphone = !$.os.ipad && userAgent.match(/(iPhone\sOS)\s([\d_]+)/) ? true : false;
$.os.webos = userAgent.match(/(webOS|hpwOS)[\s\/]([\d.]+)/) ? true : false;
$.os.touchpad = $.os.webos && userAgent.match(/TouchPad/) ? true : false;
$.os.ios = $.os.ipad || $.os.iphone;
$.os.playbook = userAgent.match(/PlayBook/) ? true : false;
$.os.blackberry = $.os.playbook || userAgent.match(/BlackBerry/) ? true : false;
$.os.blackberry10 = $.os.blackberry && userAgent.match(/Safari\/536/) ? true : false;
$.os.chrome = userAgent.match(/Chrome/) ? true : false;
$.os.opera = userAgent.match(/Opera/) ? true : false;
$.os.fennec = userAgent.match(/fennec/i) ? true :userAgent.match(/Firefox/)?true: false;
$.os.ie = userAgent.match(/MSIE 10.0/i)?true:false
$.os.supportsTouch = ((window.DocumentTouch && document instanceof window.DocumentTouch) || 'ontouchstart' in window);
//features
$.feat = {};
var head=document.documentElement.getElementsByTagName("head")[0];
$.feat.nativeTouchScroll = typeof(head.style["-webkit-overflow-scrolling"])!=="undefined"||$.os.ie;
$.feat.cssPrefix=$.os.webkit?"Webkit":$.os.fennec?"Moz":$.os.ie?"ms":$.os.opera?"O":"";
$.feat.cssTransformStart=!$.os.opera?"3d(":"(";
$.feat.cssTransformEnd=!$.os.opera?",0)":")";
if($.os.android&&!$.os.webkit)
$.os.android=false;
}
detectUA($, navigator.userAgent);
$.__detectUA = detectUA; //needed for unit tests
if (typeof String.prototype.trim !== 'function') {
/**
* Helper function for iOS 3.1.3
*/
String.prototype.trim = function() {
this.replace(/(\r\n|\n|\r)/gm, "").replace(/^\s+|\s+$/, '');
return this
};
}
/**
* Utility function to create a psuedo GUID
```
var id= $.uuid();
```
* @title $.uuid
*/
$.uuid = function () {
var S4 = function () {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};
$.getCssMatrix=function(ele){
if(ele==undefined) return window.WebKitCSSMatrix||window.MSCSSMatrix|| {a:0,b:0,c:0,d:0,e:0,f:0};
try{
if(window.WebKitCSSMatrix)
return new WebKitCSSMatrix(window.getComputedStyle(ele).webkitTransform)
else if(window.MSCSSMatrix)
return new MSCSSMatrix(window.getComputedStyle(ele).transform);
else {
//fake css matrix
var mat = window.getComputedStyle(ele)[$.feat.cssPrefix+'Transform'].replace(/[^0-9\-.,]/g, '').split(',');
return {a:+mat[0],b:+mat[1],c:+mat[2],d:+mat[3], e: +mat[4], f:+mat[5]};
}
}
catch(e){
return {a:0,b:0,c:0,d:0,e:0,f:0};
}
}
/**
Zepto.js events
@api private
*/
//The following is modified from Zepto.js / events.js
//We've removed depricated jQuery events like .live and allow anonymous functions to be removed
var handlers = {},
_jqmid = 1;
/**
* Gets or sets the expando property on a javascript element
* Also increments the internal counter for elements;
* @param {Object} element
* @return {Int} jqmid
* @api private
*/
function jqmid(element) {
return element._jqmid || (element._jqmid = _jqmid++);
}
/**
* Searches through a local array that keeps track of event handlers for proxying.
* Since we listen for multiple events, we match up the event, function and selector.
* This is used to find, execute, remove proxied event functions
* @param {Object} element
* @param {String} [event]
* @param {Function} [function]
* @param {String|Object|Array} [selector]
* @return {Function|null} handler function or false if not found
* @api private
*/
function findHandlers(element, event, fn, selector) {
event = parse(event);
if (event.ns)
var matcher = matcherFor(event.ns);
return (handlers[jqmid(element)] || []).filter(function(handler) {
return handler && (!event.e || handler.e == event.e) && (!event.ns || matcher.test(handler.ns)) && (!fn || handler.fn == fn || (typeof handler.fn === 'function' && typeof fn === 'function' && "" + handler.fn === "" + fn)) && (!selector || handler.sel == selector);
});
}
/**
* Splits an event name by "." to look for namespaces (e.g touch.click)
* @param {String} event
* @return {Object} an object with the event name and namespace
* @api private
*/
function parse(event) {
var parts = ('' + event).split('.');
return {
e: parts[0],
ns: parts.slice(1).sort().join(' ')
};
}
/**
* Regular expression checker for event namespace checking
* @param {String} namespace
* @return {Regex} regular expression
* @api private
*/
function matcherFor(ns) {
return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)');
}
/**
* Utility function that will loop through events that can be a hash or space delimited and executes the function
* @param {String|Object} events
* @param {Function} fn
* @param {Iterator} [iterator]
* @api private
*/
function eachEvent(events, fn, iterator) {
if ($.isObject(events))
$.each(events, iterator);
else
events.split(/\s/).forEach(function(type) {
iterator(type, fn)
});
}
/**
* Helper function for adding an event and creating the proxy handler function.
* All event handlers call this to wire event listeners up. We create proxy handlers so they can be removed then.
* This is needed for delegate/on
* @param {Object} element
* @param {String|Object} events
* @param {Function} function that will be executed when event triggers
* @param {String|Array|Object} [selector]
* @param {Function} [getDelegate]
* @api private
*/
function add(element, events, fn, selector, getDelegate) {
var id = jqmid(element),
set = (handlers[id] || (handlers[id] = []));
eachEvent(events, fn, function(event, fn) {
var delegate = getDelegate && getDelegate(fn, event),
callback = delegate || fn;
var proxyfn = function(event) {
var result = callback.apply(element, [event].concat(event.data));
if (result === false)
event.preventDefault();
return result;
};
var handler = $.extend(parse(event), {
fn: fn,
proxy: proxyfn,
sel: selector,
del: delegate,
i: set.length
});
set.push(handler);
element.addEventListener(handler.e, proxyfn, false);
});
element=null;
}
/**
* Helper function to remove event listeners. We look through each event and then the proxy handler array to see if it exists
* If found, we remove the listener and the entry from the proxy array. If no function is specified, we remove all listeners that match
* @param {Object} element
* @param {String|Object} events
* @param {Function} [fn]
* @param {String|Array|Object} [selector]
* @api private
*/
function remove(element, events, fn, selector) {
var id = jqmid(element);
eachEvent(events || '', fn, function(event, fn) {
findHandlers(element, event, fn, selector).forEach(function(handler) {
delete handlers[id][handler.i];
element.removeEventListener(handler.e, handler.proxy, false);
});
});
}
$.event = {
add: add,
remove: remove
}
/**
* Binds an event to each element in the collection and executes the callback
```
$().bind('click',function(){console.log('I clicked '+this.id);});
```
* @param {String|Object} event
* @param {Function} callback
* @return {Object} jqMobi object
* @title $().bind(event,callback)
*/
$.fn.bind = function(event, callback) {
for (var i = 0; i < this.length; i++) {
add(this[i], event, callback);
}
return this;
};
/**
* Unbinds an event to each element in the collection. If a callback is passed in, we remove just that one, otherwise we remove all callbacks for those events
```
$().unbind('click'); //Unbinds all click events
$().unbind('click',myFunc); //Unbinds myFunc
```
* @param {String|Object} event
* @param {Function} [callback]
* @return {Object} jqMobi object
* @title $().unbind(event,[callback]);
*/
$.fn.unbind = function(event, callback) {
for (var i = 0; i < this.length; i++) {
remove(this[i], event, callback);
}
return this;
};
/**
* Binds an event to each element in the collection that will only execute once. When it executes, we remove the event listener then right away so it no longer happens
```
$().one('click',function(){console.log('I was clicked once');});
```
* @param {String|Object} event
* @param {Function} [callback]
* @return jqMobi object
* @title $().one(event,callback);
*/
$.fn.one = function(event, callback) {
return this.each(function(i, element) {
add(this, event, callback, null, function(fn, type) {
return function() {
var result = fn.apply(element, arguments);
remove(element, type, fn);
return result;
}
});
});
};
/**
* internal variables
* @api private
*/
var returnTrue = function() {
return true
},
returnFalse = function() {
return false
},
eventMethods = {
preventDefault: 'isDefaultPrevented',
stopImmediatePropagation: 'isImmediatePropagationStopped',
stopPropagation: 'isPropagationStopped'
};
/**
* Creates a proxy function for event handlers
* @param {String} event
* @return {Function} proxy
* @api private
*/
function createProxy(event) {
var proxy = $.extend({
originalEvent: event
}, event);
$.each(eventMethods, function(name, predicate) {
proxy[name] = function() {
this[predicate] = returnTrue;
return event[name].apply(event, arguments);
};
proxy[predicate] = returnFalse;
})
return proxy;
}
/**
* Delegate an event based off the selector. The event will be registered at the parent level, but executes on the selector.
```
$("#div").delegate("p",'click',callback);
```
* @param {String|Array|Object} selector
* @param {String|Object} event
* @param {Function} callback
* @return {Object} jqMobi object
* @title $().delegate(selector,event,callback)
*/
$.fn.delegate = function(selector, event, callback) {
for (var i = 0; i < this.length; i++) {
var element = this[i];
add(element, event, callback, selector, function(fn) {
return function(e) {
var evt, match = $(e.target).closest(selector, element).get(0);
if (match) {
evt = $.extend(createProxy(e), {
currentTarget: match,
liveFired: element
});
return fn.apply(match, [evt].concat([].slice.call(arguments, 1)));
}
}
});
}
return this;
};
/**
* Unbinds events that were registered through delegate. It acts upon the selector and event. If a callback is specified, it will remove that one, otherwise it removes all of them.
```
$("#div").undelegate("p",'click',callback);//Undelegates callback for the click event
$("#div").undelegate("p",'click');//Undelegates all click events
```
* @param {String|Array|Object} selector
* @param {String|Object} event
* @param {Function} callback
* @return {Object} jqMobi object
* @title $().undelegate(selector,event,[callback]);
*/
$.fn.undelegate = function(selector, event, callback) {
for (var i = 0; i < this.length; i++) {
remove(this[i], event, callback, selector);
}
return this;
}
/**
* Similar to delegate, but the function parameter order is easier to understand.
* If selector is undefined or a function, we just call .bind, otherwise we use .delegate
```
$("#div").on("click","p",callback);
```
* @param {String|Array|Object} selector
* @param {String|Object} event
* @param {Function} callback
* @return {Object} jqMobi object
* @title $().on(event,selector,callback);
*/
$.fn.on = function(event, selector, callback) {
return selector === undefined || $.isFunction(selector) ? this.bind(event, selector) : this.delegate(selector, event, callback);
};
/**
* Removes event listeners for .on()
* If selector is undefined or a function, we call unbind, otherwise it's undelegate
```
$().off("click","p",callback); //Remove callback function for click events
$().off("click","p") //Remove all click events
```
* @param {String|Object} event
* @param {String|Array|Object} selector
* @param {Sunction} callback
* @return {Object} jqMobi object
* @title $().off(event,selector,[callback])
*/
$.fn.off = function(event, selector, callback) {
return selector === undefined || $.isFunction(selector) ? this.unbind(event, selector) : this.undelegate(selector, event, callback);
};
/**
This triggers an event to be dispatched. Usefull for emulating events, etc.
```
$().trigger("click",{foo:'bar'});//Trigger the click event and pass in data
```
* @param {String|Object} event
* @param {Object} [data]
* @return {Object} jqMobi object
* @title $().trigger(event,data);
*/
$.fn.trigger = function(event, data, props) {
if (typeof event == 'string')
event = $.Event(event, props);
event.data = data;
for (var i = 0; i < this.length; i++) {
this[i].dispatchEvent(event)
}
return this;
};
/**
* Creates a custom event to be used internally.
* @param {String} type
* @param {Object} [properties]
* @return {event} a custom event that can then be dispatched
* @title $.Event(type,props);
*/
$.Event = function(type, props) {
var event = document.createEvent('Events'),
bubbles = true;
if (props)
for (var name in props)
(name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name]);
event.initEvent(type, bubbles, true, null, null, null, null, null, null, null, null, null, null, null, null);
return event;
};
/* The following are for events on objects */
/**
* Bind an event to an object instead of a DOM Node
```
$.bind(this,'event',function(){});
```
* @param {Object} object
* @param {String} event name
* @param {Function} function to execute
* @title $.bind(object,event,function);
*/
$.bind = function(obj, ev, f){
if(!obj.__events) obj.__events = {};
if(!$.isArray(ev)) ev = [ev];
for(var i=0; i<ev.length; i++){
if(!obj.__events[ev[i]]) obj.__events[ev[i]] = [];
obj.__events[ev[i]].push(f);
}
};
/**
* Trigger an event to an object instead of a DOM Node
```
$.trigger(this,'event',arguments);
```
* @param {Object} object
* @param {String} event name
* @param {Array} arguments
* @title $.trigger(object,event,argments);
*/
$.trigger = function(obj, ev, args){
var ret = true;
if(!obj.__events) return ret;
if(!$.isArray(ev)) ev = [ev];
if(!$.isArray(args)) args = [];
for(var i=0; i<ev.length; i++){
if(obj.__events[ev[i]]){
var evts = obj.__events[ev[i]];
for(var j = 0; j<evts.length; j++)
if($.isFunction(evts[j]) && evts[j].apply(obj, args)===false)
ret = false;
}
}
return ret;
};
/**
* Unbind an event to an object instead of a DOM Node
```
$.unbind(this,'event',function(){});
```
* @param {Object} object
* @param {String} event name
* @param {Function} function to execute
* @title $.unbind(object,event,function);
*/
$.unbind = function(obj, ev, f){
if(!obj.__events) return ret;
if(!$.isArray(ev)) ev = [ev];
for(var i=0; i<ev.length; i++){
if(obj.__events[ev[i]]){
var evts = obj.__events[ev[i]];
for(var j = 0; j<evts.length; j++){
if(f==undefined)
delete evts[j];
if(evts[j]==f) {
evts.splice(j,1);
break;
}
}
}
}
};
/**
* Creates a proxy function so you can change the 'this' context in the function
* Update: now also allows multiple argument call or for you to pass your own arguments
```
var newObj={foo:bar}
$("#main").bind("click",$.proxy(function(evt){console.log(this)},newObj);
or
( $.proxy(function(foo, bar){console.log(this+foo+bar)}, newObj) )('foo', 'bar');
or
( $.proxy(function(foo, bar){console.log(this+foo+bar)}, newObj, ['foo', 'bar']) )();
```
* @param {Function} Callback
* @param {Object} Context
* @title $.proxy(callback,context);
*/
$.proxy=function(f, c, args){
return function(){
if(args) return f.apply(c, args); //use provided arguments
return f.apply(c, arguments); //use scope function call arguments
}
}
/**
* Removes listeners on a div and its children recursively
```
cleanUpNode(node,kill)
```
* @param {HTMLDivElement} the element to clean up recursively
* @api private
*/
function cleanUpNode(node, kill){
//kill it before it lays eggs!
if(kill && node.dispatchEvent){
var e = $.Event('destroy', {bubbles:false});
node.dispatchEvent(e);
}
//cleanup itself
var id = jqmid(node);
if(id && handlers[id]){
for(var key in handlers[id])
node.removeEventListener(handlers[id][key].e, handlers[id][key].proxy, false);
delete handlers[id];
}
}
function cleanUpContent(node, kill){
if(!node) return;
//cleanup children
var children = node.childNodes;
if(children && children.length > 0)
for(var child in children)
cleanUpContent(children[child], kill);
cleanUpNode(node, kill);
}
var cleanUpAsap = function(els, kill){
for(var i=0;i<els.length;i++){
cleanUpContent(els[i], kill);
}
}
/**
* Function to clean up node content to prevent memory leaks
```
$.cleanUpContent(node,itself,kill)
```
* @param {HTMLNode} node
* @param {Bool} kill itself
* @param {kill} Kill nodes
* @title $.cleanUpContent(node,itself,kill)
*/
$.cleanUpContent = function(node, itself, kill){
if(!node) return;
//cleanup children
var cn = node.childNodes;
if(cn && cn.length > 0){
//destroy everything in a few ms to avoid memory leaks
//remove them all and copy objs into new array
$.asap(cleanUpAsap, {}, [slice.apply(cn, [0]), kill]);
}
//cleanUp this node
if(itself) cleanUpNode(node, kill);
}
// Like setTimeout(fn, 0); but much faster
var timeouts = [];
var contexts = [];
var params = [];
/**
* This adds a command to execute in the JS stack, but is faster then setTimeout
```
$.asap(function,context,args)
```
* @param {Function} function
* @param {Object} context
* @param {Array} arguments
*/
$.asap = function(fn, context, args) {
if(!$.isFunction(fn)) throw "$.asap - argument is not a valid function";
timeouts.push(fn);
contexts.push(context?context:{});
params.push(args?args:[]);
//post a message to ourselves so we know we have to execute a function from the stack
window.postMessage("jqm-asap", "*");
}
window.addEventListener("message", function(event) {
if (event.source == window && event.data == "jqm-asap") {
event.stopPropagation();
if (timeouts.length > 0) { //just in case...
(timeouts.shift()).apply(contexts.shift(), params.shift());
}
}
}, true);
//custom events since people want to do $().click instead of $().bind("click")
["click","keydown","keyup","keypress","submit","load","resize","change","select","error"].forEach(function(event){
$.fn[event]=function(cb){
return callback?this.bind(event,callback):this.trigger(event);
}
});
/**
* End of APIS
* @api private
*/
return $;
})(window);
'$' in window || (window.$ = jq);
//Helper function used in jq.mobi.plugins.
if (!window.numOnly) {
window.numOnly = function numOnly(val) {
if (val===undefined || val==='') return 0;
if ( isNaN( parseFloat(val) ) ){
if(val.replace){
val = val.replace(/[^0-9.-]/, "");
} else return 0;
}
return parseFloat(val);
}
}
}
|
/**
* The command line interface for interacting with the Protractor runner.
* It takes care of parsing command line options.
*
* Values from command line options override values from the config.
*/
'use strict';
var args = [];
process.argv.slice(2).forEach(function(arg) {
var flag = arg.split('=')[0];
switch (flag) {
case 'debug':
args.push('--nodeDebug');
args.push('true');
break;
case '-d':
case '--debug':
case '--debug-brk':
args.push('--v8Debug');
args.push('true');
break;
default:
args.push(arg);
break;
}
});
var util = require('util');
var path = require('path');
var child = require('child_process');
var fs = require('fs');
var optimist = require('optimist').
usage('Usage: protractor [options] [configFile]\n' +
'configFile defaults to protractor.conf.js\n' +
'The [options] object will override values from the config file.\n' +
'See the reference config for a full list of options.').
describe('help', 'Print Protractor help menu').
describe('version', 'Print Protractor version').
describe('browser', 'Browsername, e.g. chrome or firefox').
describe('seleniumAddress', 'A running seleium address to use').
describe('seleniumServerJar', 'Location of the standalone selenium jar file').
describe('seleniumPort', 'Optional port for the selenium standalone server').
describe('baseUrl', 'URL to prepend to all relative paths').
describe('rootElement', 'Element housing ng-app, if not html or body').
describe('specs', 'Comma-separated list of files to test').
describe('exclude', 'Comma-separated list of files to exclude').
describe('verbose', 'Print full spec names').
describe('stackTrace', 'Print stack trace on error').
describe('params', 'Param object to be passed to the tests').
describe('framework', 'Test framework to use: jasmine, cucumber or mocha').
alias('browser', 'capabilities.browserName').
alias('name', 'capabilities.name').
alias('platform', 'capabilities.platform').
alias('platform-version', 'capabilities.version').
alias('tags', 'capabilities.tags').
alias('build', 'capabilities.build').
alias('verbose', 'jasmineNodeOpts.isVerbose').
alias('stackTrace', 'jasmineNodeOpts.includeStackTrace').
string('capabilities.tunnel-identifier').
check(function(arg) {
if (arg._.length > 1) {
throw 'Error: more than one config file specified';
}
});
var argv = optimist.parse(args);
if (argv.version) {
util.puts('Version ' + require(path.join(__dirname, '../package.json')).version);
process.exit(0);
}
// WebDriver capabilities properties require dot notation, but optimist parses
// that into an object. Re-flatten it.
var flattenObject = function(obj) {
var prefix = arguments[1] || '';
var out = arguments[2] || {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
typeof obj[prop] === 'object' ?
flattenObject(obj[prop], prefix + prop + '.', out) :
out[prefix + prop] = obj[prop];
}
}
return out;
};
if (argv.capabilities) {
argv.capabilities = flattenObject(argv.capabilities);
}
/**
* Helper to resolve comma separated lists of file pattern strings relative to
* the cwd.
*
* @private
* @param {Array} list
*/
var processFilePatterns_ = function(list) {
var patterns = list.split(',');
patterns.forEach(function(spec, index, arr) {
arr[index] = path.resolve(process.cwd(), spec);
});
return patterns;
};
if (argv.specs) {
argv.specs = processFilePatterns_(argv.specs);
}
if (argv.exclude) {
argv.exclude = processFilePatterns_(argv.exclude);
}
// Use default configuration, if it exists.
var configFile = argv._[0];
if (!configFile) {
if (fs.existsSync('./protractor.conf.js')) {
configFile = './protractor.conf.js';
}
}
if (!configFile && args.length < 3) {
optimist.showHelp();
process.exit(1);
}
// Run the launcher
require('./launcher').init(configFile, argv);
|
var http = require('http');
var express = require('express');
var wsServer = require('ws').Server;
var date = require('date-utils');
var subscriber = require('./subscriber');
startServer([]);
function startServer(init){
var port = process.env.PORT || 8080;
console.log('port:' + port);
var app = express();
app.use(express.static(__dirname + '/public'));
var server = http.createServer(app)
server.listen(port)
var bufferSize = process.env.DATA_BUFFER_SIZE;
var dataBuffer = init;
if (dataBuffer.length > bufferSize){
dataBuffer = dataBuffer.slice(dataBuffer.length - bufferSize);
}
var wss = new wsServer({server: server});
wss.on('connection', function(ws){
ws.send(JSON.stringify(dataBuffer));
});
var _subscriber = new subscriber();
_subscriber.on('message', function(data){
dataBuffer.push(data);
if (dataBuffer.length > bufferSize){
dataBuffer = dataBuffer.slice(dataBuffer.length - bufferSize);
}
wss.clients.forEach(function(c){
c.send(JSON.stringify(dataBuffer));
});
});
}
|
define([
'backbone',
'text!app/tpl/Sidebar.html'
], function(Backbone, Tpl) {
'use strict';
return Backbone.View.extend({
events: {
'change input,select': 'saveSettings'
},
initialize: function(options) {
// Compile Template
this.options = options;
this.template = _.template(Tpl);
},
render: function() {
// Render Sidebar
this.$el.html(this.template(this.options.appView.settings.toJSON()));
return this;
},
/**
* Shape Action
*/
saveSettings: function(e) {
e.preventDefault();
var $el = $(e.target);
this.options.appView.settings.set($el.attr('name'), $el.val());
}
});
});
|
/* ========================================================================
* login.js
* Page/renders: page-login.html
* Plugins used: parsley
* ======================================================================== */
'use strict';
(function (factory) {
if (typeof define === 'function' && define.amd) {
define([
'parsley'
], factory);
} else {
factory();
}
}(function () {
$(function () {
// Login form function
// ================================
var $form = $('form[name=form-login]');
// On button submit click
$form.on('click', 'button[type=submit]', function (e) {
var $this = $(this);
// Run parsley validation
if ($form.parsley().validate()) {
// Disable submit button
$this.prop('disabled', true);
// start nprogress bar
NProgress.start();
// you can do the ajax request here
// this is for demo purpose only
setTimeout(function () {
// done nprogress bar
NProgress.done();
// redirect user
location.href = 'index.html';
}, 500);
} else {
// toggle animation
$form
.removeClass('animation animating shake')
.addClass('animation animating shake')
.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
$(this).removeClass('animation animating shake');
});
}
// prevent default
e.preventDefault();
});
});
}));
|
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _logger = require('../logger');
var logger = _interopRequireWildcard(_logger);
var _utils = require('../utils');
var utils = _interopRequireWildcard(_utils);
var _ask = require('../ask');
var _fs = require('fs');
var fs = _interopRequireWildcard(_fs);
var _handlebars = require('handlebars');
var handlebars = _interopRequireWildcard(_handlebars);
var _bluebird = require('bluebird');
var bluebird = _interopRequireWildcard(_bluebird);
var _chalk = require('chalk');
var _chalk2 = _interopRequireDefault(_chalk);
var _lodash = require('lodash');
// Register handlebars helpers
handlebars.registerHelper('toCamelCase', function (str) {
return utils.toCamelCase(str);
});
handlebars.registerHelper('join', function (items, separator, options) {
if (Array.isArray(items)) {
return items.map(function (item) {
return options.fn(item);
}).join(separator);
}
return items;
});
function getCompiledTemplate(template) {
var templateContent;
try {
templateContent = fs.readFileSync(__dirname + '/templates/' + template, { encoding: 'utf-8' });
} catch (ex) {
throw 'the entered template does not exist';
}
return handlebars.compile(templateContent);
}
function createView(name, template) {
if (name === undefined || name === '') {
throw 'You must provide a name for the new element';
return;
}
var compiled = getCompiledTemplate(templateTypes.view + '.' + template + '.html');
logger.log(_chalk2['default'].bgMagenta('vvvvvv [Here is what we created for you] vvvvvv'));
var resultingFile = compiled({
pageName: utils.ucFirst(name)
});
console.log(resultingFile);
return promptForCreation(name + '.html').then(function (response) {
return writeFile(response, name + '.html', resultingFile);
}).then(function (result) {
logger.ok(result);
})['catch'](function (err) {
logger.err('Issue generating!');
logger.err(err);
});
}
function createViewModel(name, template, inject) {
if (name === undefined || name === '') {
throw 'You must provide a name for the new element';
return;
}
var compiled = getCompiledTemplate(templateTypes.vm + '.' + template + '.js');
logger.log(_chalk2['default'].bgMagenta('vvvvvv [Here is what we created for you] vvvvvv'));
var resultingFile = compiled({
pageName: utils.ucFirst(utils.dashToCamelCase(name)),
isInjectionUsed: inject !== undefined && inject.length > 0,
inject: inject,
injectWithoutImport: (0, _lodash.difference)(inject, ['Element'])
});
console.log(resultingFile);
return promptForCreation(name + '.js').then(function (response) {
return writeFile(response, name + '.js', resultingFile);
}).then(function (result) {
logger.ok(result);
})['catch'](function (err) {
logger.err('Issue generating!');
logger.err(err);
});
}
function promptForCreation(fileName) {
var prompts = [{
type: 'confirm',
name: 'create',
message: 'Like it? Continue creating the file: ' + fileName,
'default': false
}];
return (0, _ask.ask)(prompts);
}
function writeFile(response, fileName, fileContents) {
return new Promise(function (resolve, reject) {
if (response.create === true) {
fs.writeFile('src/' + fileName, fileContents, function (err) {
if (err !== undefined && err !== null) {
reject(err);
} else {
resolve('File ' + fileName + ' successfully created');
}
});
} else {
reject('Aborted by user');
}
});
}
var templateTypes = {
vm: 'viewmodel',
view: 'view'
};
module.exports = {
createViewModel: createViewModel,
createView: createView,
templateType: templateTypes
};
|
/*! Copyright (c) 2011 Piotr Rochala (http://rocha.la)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Improved by keenthemes for Metronic Theme
* Version: 1.3.2
*
*/
(function($) {
jQuery.fn.extend({
slimScroll: function(options) {
var defaults = {
// width in pixels of the visible scroll area
width: 'auto',
// height in pixels of the visible scroll area
height: '250px',
// width in pixels of the scrollbar and rail
size: '7px',
// scrollbar color, accepts any hex/color value
color: '#000',
// scrollbar position - left/right
position: 'right',
// distance in pixels between the side edge and the scrollbar
distance: '1px',
// default scroll position on load - top / bottom / $('selector')
start: 'top',
// sets scrollbar opacity
opacity: .4,
// enables always-on mode for the scrollbar
alwaysVisible: false,
// check if we should hide the scrollbar when user is hovering over
disableFadeOut: false,
// sets visibility of the rail
railVisible: false,
// sets rail color
railColor: '#333',
// sets rail opacity
railOpacity: .2,
// whether we should use jQuery UI Draggable to enable bar dragging
railDraggable: true,
// defautlt CSS class of the slimscroll rail
railClass: 'slimScrollRail',
// defautlt CSS class of the slimscroll bar
barClass: 'slimScrollBar',
// defautlt CSS class of the slimscroll wrapper
wrapperClass: 'slimScrollDiv',
// check if mousewheel should scroll the window if we reach top/bottom
allowPageScroll: false,
// scroll amount applied to each mouse wheel step
wheelStep: 20,
// scroll amount applied when user is using gestures
touchScrollStep: 200,
// sets border radius
borderRadius: '7px',
// sets border radius of the rail
railBorderRadius: '7px',
// sets animation status on a given scroll(added my keenthemes)
animate: true
};
var o = $.extend(defaults, options);
// do it for every partials that matches selector
this.each(function() {
var isOverPanel, isOverBar, isDragg, queueHide, touchDif,
barHeight, percentScroll, lastScroll,
divS = '<div></div>',
minBarHeight = 30,
releaseScroll = false;
// used in event handlers and for better minification
var me = $(this);
//begin: windows phone fix added by keenthemes
if ('ontouchstart' in window && window.navigator.msPointerEnabled) {
me.css("-ms-touch-action", "none");
}
//end: windows phone fix added by keenthemes
// ensure we are not binding it again
if (me.parent().hasClass(o.wrapperClass)) {
// start from last bar position
var offset = me.scrollTop();
// find bar and rail
bar = me.parent().find('.' + o.barClass);
rail = me.parent().find('.' + o.railClass);
getBarHeight();
// check if we should scroll existing instance
if ($.isPlainObject(options)) {
// Pass height: auto to an existing slimscroll object to force a resize after contents have changed
if ('height' in options && options.height == 'auto') {
me.parent().css('height', 'auto');
me.css('height', 'auto');
var height = me.parent().parent().height();
me.parent().css('height', height);
me.css('height', height);
}
if ('scrollTo' in options) {
// jump to a static point
offset = parseInt(o.scrollTo);
} else if ('scrollBy' in options) {
// jump by value pixels
offset += parseInt(o.scrollBy);
} else if ('destroy' in options) {
// remove slimscroll elements
bar.remove();
rail.remove();
me.unwrap();
return;
}
// scroll content by the given offset
scrollContent(offset, false, true);
}
return;
}
// optionally set height to the parent's height
o.height = (options.height == 'auto') ? me.parent().height() : options.height;
// wrap content
var wrapper = $(divS)
.addClass(o.wrapperClass)
.css({
position: 'relative',
overflow: 'hidden',
width: o.width,
height: o.height
});
// update style for the div
me.css({
overflow: 'hidden',
width: o.width,
height: o.height
});
// create scrollbar rail
var rail = $(divS)
.addClass(o.railClass)
.css({
width: o.size,
height: '100%',
position: 'absolute',
top: 0,
display: (o.alwaysVisible && o.railVisible) ? 'block' : 'none',
'border-radius': o.railBorderRadius,
background: o.railColor,
opacity: o.railOpacity,
zIndex: 90
});
// create scrollbar
var bar = $(divS)
.addClass(o.barClass)
.css({
background: o.color,
width: o.size,
position: 'absolute',
top: 0,
opacity: o.opacity,
display: o.alwaysVisible ? 'block' : 'none',
'border-radius': o.borderRadius,
BorderRadius: o.borderRadius,
MozBorderRadius: o.borderRadius,
WebkitBorderRadius: o.borderRadius,
zIndex: 99
});
// set position
var posCss = (o.position == 'right') ? {
right: o.distance
} : {
left: o.distance
};
rail.css(posCss);
bar.css(posCss);
// wrap it
me.wrap(wrapper);
// append to parent div
me.parent().append(bar);
me.parent().append(rail);
// make it draggable and no longer dependent on the jqueryUI
if (o.railDraggable) {
bar.bind("mousedown", function(e) {
var $doc = $(document);
isDragg = true;
t = parseFloat(bar.css('top'));
pageY = e.pageY;
$doc.bind("mousemove.slimscroll", function(e) {
currTop = t + e.pageY - pageY;
bar.css('top', currTop);
scrollContent(0, bar.position().top, false); // scroll content
});
$doc.bind("mouseup.slimscroll", function(e) {
isDragg = false;
hideBar();
$doc.unbind('.slimscroll');
});
return false;
}).bind("selectstart.slimscroll", function(e) {
e.stopPropagation();
e.preventDefault();
return false;
});
}
//begin: windows phone fix added by keenthemes
if ('ontouchstart' in window && window.navigator.msPointerEnabled) {
me.bind('MSPointerDown', function(e, b) {
// record where touch started
touchDif = e.originalEvent.pageY;
});
me.bind('MSPointerMove', function(e) {
// prevent scrolling the page if necessary
e.originalEvent.preventDefault();
// see how far user swiped
var diff = (touchDif - e.originalEvent.pageY) / o.touchScrollStep;
// scroll content
scrollContent(diff, true);
touchDif = e.originalEvent.pageY;
});
}
//end: windows phone fix added by keenthemes
// on rail over
rail.hover(function() {
showBar();
}, function() {
hideBar();
});
// on bar over
bar.hover(function() {
isOverBar = true;
}, function() {
isOverBar = false;
});
// show on parent mouseover
me.hover(function() {
isOverPanel = true;
showBar();
hideBar();
}, function() {
isOverPanel = false;
hideBar();
});
// support for mobile
me.bind('touchstart', function(e, b) {
if (e.originalEvent.touches.length) {
// record where touch started
touchDif = e.originalEvent.touches[0].pageY;
}
});
me.bind('touchmove', function(e) {
// prevent scrolling the page if necessary
if (!releaseScroll) {
e.originalEvent.preventDefault();
}
if (e.originalEvent.touches.length) {
// see how far user swiped
var diff = (touchDif - e.originalEvent.touches[0].pageY) / o.touchScrollStep;
// scroll content
scrollContent(diff, true);
touchDif = e.originalEvent.touches[0].pageY;
}
});
// set up initial height
getBarHeight();
// check start position
if (o.start === 'bottom') {
// scroll content to bottom
bar.css({
top: me.outerHeight() - bar.outerHeight()
});
scrollContent(0, true);
} else if (o.start !== 'top') {
// assume jQuery selector
scrollContent($(o.start).position().top, null, true);
// make sure bar stays hidden
if (!o.alwaysVisible) {
bar.hide();
}
}
// attach scroll events
attachWheel();
function _onWheel(e) {
// use mouse wheel only when mouse is over
if (!isOverPanel) {
return;
}
var e = e || window.event;
var delta = 0;
if (e.wheelDelta) {
delta = -e.wheelDelta / 120;
}
if (e.detail) {
delta = e.detail / 3;
}
var target = e.target || e.srcTarget || e.srcElement;
if ($(target).closest('.' + o.wrapperClass).is(me.parent())) {
// scroll content
scrollContent(delta, true);
}
// stop window scroll
if (e.preventDefault && !releaseScroll) {
e.preventDefault();
}
if (!releaseScroll) {
e.returnValue = false;
}
}
function scrollContent(y, isWheel, isJump) {
releaseScroll = false;
var delta = y;
var maxTop = me.outerHeight() - bar.outerHeight();
if (isWheel) {
// move bar with mouse wheel
delta = parseInt(bar.css('top')) + y * parseInt(o.wheelStep) / 100 * bar.outerHeight();
// move bar, make sure it doesn't go out
delta = Math.min(Math.max(delta, 0), maxTop);
// if scrolling down, make sure a fractional change to the
// scroll position isn't rounded away when the scrollbar's CSS is set
// this flooring of delta would happened automatically when
// bar.css is set below, but we floor here for clarity
delta = (y > 0) ? Math.ceil(delta) : Math.floor(delta);
// scroll the scrollbar
bar.css({
top: delta + 'px'
});
}
// calculate actual scroll amount
percentScroll = parseInt(bar.css('top')) / (me.outerHeight() - bar.outerHeight());
delta = percentScroll * (me[0].scrollHeight - me.outerHeight());
if (isJump) {
delta = y;
var offsetTop = delta / me[0].scrollHeight * me.outerHeight();
offsetTop = Math.min(Math.max(offsetTop, 0), maxTop);
bar.css({
top: offsetTop + 'px'
});
}
// scroll content
if ('scrollTo' in o && o.animate) {
me.animate({
scrollTop: delta
});
} else {
me.scrollTop(delta);
}
// fire scrolling event
me.trigger('slimscrolling', ~~delta);
// ensure bar is visible
showBar();
// trigger hide when scroll is stopped
hideBar();
}
function attachWheel() {
if (window.addEventListener) {
this.addEventListener('DOMMouseScroll', _onWheel, false);
this.addEventListener('mousewheel', _onWheel, false);
} else {
document.attachEvent("onmousewheel", _onWheel)
}
}
function getBarHeight() {
// calculate scrollbar height and make sure it is not too small
barHeight = Math.max((me.outerHeight() / me[0].scrollHeight) * me.outerHeight(), minBarHeight);
bar.css({
height: barHeight + 'px'
});
// hide scrollbar if content is not long enough
var display = barHeight == me.outerHeight() ? 'none' : 'block';
bar.css({
display: display
});
}
function showBar() {
// recalculate bar height
getBarHeight();
clearTimeout(queueHide);
// when bar reached top or bottom
if (percentScroll == ~~percentScroll) {
//release wheel
releaseScroll = o.allowPageScroll;
// publish approporiate event
if (lastScroll != percentScroll) {
var msg = (~~percentScroll == 0) ? 'top' : 'bottom';
me.trigger('slimscroll', msg);
}
} else {
releaseScroll = false;
}
lastScroll = percentScroll;
// show only when required
if (barHeight >= me.outerHeight()) {
//allow window scroll
releaseScroll = true;
return;
}
bar.stop(true, true).fadeIn('fast');
if (o.railVisible) {
rail.stop(true, true).fadeIn('fast');
}
}
function hideBar() {
// only hide when options allow it
if (!o.alwaysVisible) {
queueHide = setTimeout(function() {
if (!(o.disableFadeOut && isOverPanel) && !isOverBar && !isDragg) {
bar.fadeOut('slow');
rail.fadeOut('slow');
}
}, 1000);
}
}
});
// maintain chainability
return this;
}
});
jQuery.fn.extend({
slimscroll: jQuery.fn.slimScroll
});
})(jQuery);
|
'use strict';
var assert = require('assert'),
fs = require('fs'),
path = require('path'),
WritableStream = require('stream').Writable,
SAXParser = require('../../lib').SAXParser,
testUtils = require('../test_utils');
function getFullTestName(test, idx) {
return ['SAX - ', idx, '.', test.name].join('');
}
function sanitizeForComparison(str) {
return testUtils.removeNewLines(str)
.replace(/\s/g, '')
.replace(/'/g, '"')
.toLowerCase();
}
function createBasicTest(html, expected, options) {
return function () {
//NOTE: the idea of the test is to serialize back given HTML using SAXParser handlers
var actual = '',
parser = new SAXParser(options),
chunks = testUtils.makeChunks(html),
lastChunkIdx = chunks.length - 1;
parser.on('doctype', function (name, publicId, systemId) {
actual += '<!DOCTYPE ' + name;
if (publicId !== null)
actual += ' PUBLIC "' + publicId + '"';
else if (systemId !== null)
actual += ' SYSTEM';
if (systemId !== null)
actual += ' "' + systemId + '"';
actual += '>';
});
parser.on('startTag', function (tagName, attrs, selfClosing) {
actual += '<' + tagName;
if (attrs.length) {
for (var i = 0; i < attrs.length; i++)
actual += ' ' + attrs[i].name + '="' + attrs[i].value + '"';
}
actual += selfClosing ? '/>' : '>';
});
parser.on('endTag', function (tagName) {
actual += '</' + tagName + '>';
});
parser.on('text', function (text) {
actual += text;
});
parser.on('comment', function (text) {
actual += '<!--' + text + '-->';
});
parser.once('finish', function () {
expected = sanitizeForComparison(expected);
actual = sanitizeForComparison(actual);
//NOTE: use ok assertion, so output will not be polluted by the whole content of the strings
assert.ok(actual === expected, testUtils.getStringDiffMsg(actual, expected));
});
chunks.forEach(function (chunk, idx) {
if (idx === lastChunkIdx)
parser.end(chunk);
else
parser.write(chunk);
});
};
}
//Basic tests
testUtils
.loadSerializationTestData(path.join(__dirname, '../data/sax'))
.forEach(function (test, idx) {
var testName = getFullTestName(test, idx);
exports[testName] = createBasicTest(test.src, test.expected, test.options);
});
exports['SAX - Piping and .stop()'] = function (done) {
var parser = new SAXParser(),
writable = new WritableStream(),
handlerCallCount = 0,
data = '',
handler = function () {
handlerCallCount++;
if (handlerCallCount === 10)
parser.stop();
};
writable._write = function (chunk, encoding, callback) {
data += chunk;
callback();
};
fs
.createReadStream(path.join(__dirname, '../data/huge-page/huge-page.html'))
.pipe(parser)
.pipe(writable);
parser.on('startTag', handler);
parser.on('endTag', handler);
parser.on('doctype', handler);
parser.on('comment', handler);
parser.on('text', handler);
writable.once('finish', function () {
var expected = fs.readFileSync(path.join(__dirname, '../data/huge-page/huge-page.html')).toString();
assert.strictEqual(handlerCallCount, 10);
assert.strictEqual(data, expected);
done();
});
};
|
const expect = require('chai').expect;
const path = require('path');
const projRoot = process.env.PWD;
const controller = require(path.join(projRoot, 'src/server/controllers/heartbeat'));
module.exports = {
get: get
};
function get(done) {
const data = controller.get();
expect(data).to.be.an('object');
expect(data).to.have.property('message');
expect(data.message).to.equal('OK');
return done();
}
|
/*!
*
* Super simple wysiwyg editor v0.8.14
* https://summernote.org
*
*
* Copyright 2013- Alan Hong. and other contributors
* summernote may be freely distributed under the MIT license.
*
* Date: 2019-12-28T14:35Z
*
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else {
var a = factory();
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 40);
/******/ })
/************************************************************************/
/******/ ({
/***/ 40:
/***/ (function(module, exports) {
(function ($) {
$.extend($.summernote.lang, {
'sr-RS': {
font: {
bold: 'Подебљано',
italic: 'Курзив',
underline: 'Подвучено',
clear: 'Уклони стилове фонта',
height: 'Висина линије',
name: 'Font Family',
strikethrough: 'Прецртано',
subscript: 'Subscript',
superscript: 'Superscript',
size: 'Величина фонта'
},
image: {
image: 'Слика',
insert: 'Уметни слику',
resizeFull: 'Пуна величина',
resizeHalf: 'Умањи на 50%',
resizeQuarter: 'Умањи на 25%',
floatLeft: 'Уз леву ивицу',
floatRight: 'Уз десну ивицу',
floatNone: 'Без равнања',
shapeRounded: 'Shape: Rounded',
shapeCircle: 'Shape: Circle',
shapeThumbnail: 'Shape: Thumbnail',
shapeNone: 'Shape: None',
dragImageHere: 'Превуци слику овде',
dropImage: 'Drop image or Text',
selectFromFiles: 'Изабери из датотеке',
maximumFileSize: 'Maximum file size',
maximumFileSizeError: 'Maximum file size exceeded.',
url: 'Адреса слике',
remove: 'Уклони слику',
original: 'Original'
},
video: {
video: 'Видео',
videoLink: 'Веза ка видеу',
insert: 'Уметни видео',
url: 'URL видео',
providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion или Youku)'
},
link: {
link: 'Веза',
insert: 'Уметни везу',
unlink: 'Уклони везу',
edit: 'Уреди',
textToDisplay: 'Текст за приказ',
url: 'Интернет адреса',
openInNewWindow: 'Отвори у новом прозору'
},
table: {
table: 'Табела',
addRowAbove: 'Add row above',
addRowBelow: 'Add row below',
addColLeft: 'Add column left',
addColRight: 'Add column right',
delRow: 'Delete row',
delCol: 'Delete column',
delTable: 'Delete table'
},
hr: {
insert: 'Уметни хоризонталну линију'
},
style: {
style: 'Стил',
p: 'Нормални',
blockquote: 'Цитат',
pre: 'Код',
h1: 'Заглавље 1',
h2: 'Заглавље 2',
h3: 'Заглавље 3',
h4: 'Заглавље 4',
h5: 'Заглавље 5',
h6: 'Заглавље 6'
},
lists: {
unordered: 'Обична листа',
ordered: 'Нумерисана листа'
},
options: {
help: 'Помоћ',
fullscreen: 'Преко целог екрана',
codeview: 'Изворни код'
},
paragraph: {
paragraph: 'Параграф',
outdent: 'Смањи увлачење',
indent: 'Повечај увлачење',
left: 'Поравнај у лево',
center: 'Центрирано',
right: 'Поравнај у десно',
justify: 'Поравнај обострано'
},
color: {
recent: 'Последња боја',
more: 'Више боја',
background: 'Боја позадине',
foreground: 'Боја текста',
transparent: 'Провидна',
setTransparent: 'Провидна',
reset: 'Опозив',
resetToDefault: 'Подразумевана'
},
shortcut: {
shortcuts: 'Пречице са тастатуре',
close: 'Затвори',
textFormatting: 'Форматирање текста',
action: 'Акција',
paragraphFormatting: 'Форматирање параграфа',
documentStyle: 'Стил документа',
extraKeys: 'Додатне комбинације'
},
help: {
'insertParagraph': 'Insert Paragraph',
'undo': 'Undoes the last command',
'redo': 'Redoes the last command',
'tab': 'Tab',
'untab': 'Untab',
'bold': 'Set a bold style',
'italic': 'Set a italic style',
'underline': 'Set a underline style',
'strikethrough': 'Set a strikethrough style',
'removeFormat': 'Clean a style',
'justifyLeft': 'Set left align',
'justifyCenter': 'Set center align',
'justifyRight': 'Set right align',
'justifyFull': 'Set full align',
'insertUnorderedList': 'Toggle unordered list',
'insertOrderedList': 'Toggle ordered list',
'outdent': 'Outdent on current paragraph',
'indent': 'Indent on current paragraph',
'formatPara': 'Change current block\'s format as a paragraph(P tag)',
'formatH1': 'Change current block\'s format as H1',
'formatH2': 'Change current block\'s format as H2',
'formatH3': 'Change current block\'s format as H3',
'formatH4': 'Change current block\'s format as H4',
'formatH5': 'Change current block\'s format as H5',
'formatH6': 'Change current block\'s format as H6',
'insertHorizontalRule': 'Insert horizontal rule',
'linkDialog.show': 'Show Link Dialog'
},
history: {
undo: 'Поништи',
redo: 'Понови'
},
specialChar: {
specialChar: 'SPECIAL CHARACTERS',
select: 'Select Special characters'
}
}
});
})(jQuery);
/***/ })
/******/ });
});
|
import sum from '../sum';
describe('General Test', () => {
it('adds 1 + 2 equal 3', () => {
expect(sum(1, 2)).toBe(3);
})
})
|
'use strict'
let component = require('omniscient')
let immutable = require('immutable')
let S = require('underscore.string.fp')
let logger = require('@arve.knudsen/js-logger').get('workshopsExplore')
let R = require('ramda')
let h = require('react-hyperscript')
let React = require('react')
let ReactDOM = require('react-dom')
let FocusingInput = require('./focusingInput')
let ajax = require('../ajax')
let router = require('../router')
let {displayDateTextual,} = require('../datetime')
let {partitionWorkshops,} = require('./workshopsCommon')
if (__IS_BROWSER__) {
require('./workshopsExplore.styl')
require('purecss/build/grids-responsive.css')
}
let setSearch = (cursor, text) => {
logger.debug(`Setting search to '${text}'`)
cursor.cursor('workshopsExplore').set('search', text)
}
let createWorkshopLeaderElement = (cursor, i) => {
let workshopLeader = cursor.toJS()
let [numUpcomingWorkshops, numPastWorkshops,] = R.map(R.prop('length'),
partitionWorkshops(workshopLeader))
let workshopLeaderUrl = `/u/${workshopLeader.id}`
return h('li.workshop-leader-item', {
key: i,
'data-id': workshopLeader.id,
}, [
h('a', {href: workshopLeaderUrl,}, [
h('.pure-u-1.pure-u-md-4-24', [
h('.workshop-leader-item-image-wrapper', [
h('img.workshop-leader-item-image', {src: workshopLeader.avatarUrl,}),
]),
]),
]),
h('.pure-u-1.pure-u-md-20-24', [
h('.workshop-leader-item-content', [
h('a', {href: workshopLeaderUrl,}, [
h('.pure-u-24-24', [
h('.workshop-leader-item-name', workshopLeader.name),
]),
h('.pure-u-19-24', [
h('p.workshop-leader-item-about', workshopLeader.blurb),
h('.workshop-leader-item-metadata.muted.small', [
h('.workshop-leader-item-location', workshopLeader.location),
h('.workshop-leader-item-joined', `Joined on ${displayDateTextual(
workshopLeader.created)}`),
]),
]),
]),
h('.pure-u-5-24', [
h('.workshop-leader-item-workshops.muted', [
h('a', {
href: `${workshopLeaderUrl}#workshops`,
}, [
h('.workshop-leader-item-upcoming-workshops',
`${numUpcomingWorkshops} upcoming workshop${
numUpcomingWorkshops !== 1 ? 's' : ''}`),
h('.workshop-leader-item-past-workshops',
`${numPastWorkshops} past workshop${numPastWorkshops !== 1 ? 's': ''}`),
]),
]),
]),
]),
]),
])
}
let Results = component('Results', (cursor) => {
let exploreCursor = cursor.cursor('workshopsExplore')
if (exploreCursor.get('isSearching')) {
return h('p', 'Searching...')
} else {
let resultsCursor = exploreCursor.cursor('searchResults')
logger.debug(`Got ${resultsCursor.toJS().length} search results`)
return resultsCursor.isEmpty() ? h('p', 'No workshop leaders were found, please try again.') :
h('ul.results-container', resultsCursor.map(createWorkshopLeaderElement).toJS())
}
})
let performSearch = (cursor) => {
let query = cursor.getIn([`workshopsExplore`, `search`,])
let searchString = encodeURIComponent(query.replace(' ', '+'))
if (S.isBlank(searchString)) {
router.goTo(`/`)
} else {
router.goTo(`/?q=${searchString}`)
}
}
let SearchBox = component('SearchBox', function (cursor) {
let searchQuery = cursor.cursor('workshopsExplore').get('search')
logger.debug(`SearchBox rendering, query: '${searchQuery}'`)
let hasSearchQuery = !S.isBlank(searchQuery)
return h('.search-box', [
h('span#explore-do-search.search-icon.icon-search.muted', {
onClick: R.partial(performSearch, [cursor,]),
}),
FocusingInput({
id: 'explore-search-input',
value: searchQuery,
placeholder: 'Search MuzHack Workshops',
ref: 'search',
refName: 'search',
onChange: (event) => {
let text = event.currentTarget.value
logger.debug(`Search input detected`)
setSearch(cursor, text)
},
onEnter: R.partial(performSearch, [cursor,]),
}),
hasSearchQuery ? h('span#explore-clear-search.clear-icon.icon-cross.muted', {
onClick: () => {
logger.debug('Clear search clicked')
setSearch(cursor, '')
let node = ReactDOM.findDOMNode(this.refs.search)
logger.debug('Giving focus to search input:', node)
node.select()
},
}) : null,
])
})
module.exports = {
createState: () => {
return immutable.fromJS({
search: '',
searchResults: [
],
})
},
loadData: (cursor, params, queryParams) => {
logger.debug(`Loading workshopLeaders`)
let query = queryParams.q || ''
return ajax.getJson('/api/workshops/search', {query,})
.then((results) => {
logger.debug(`Searching succeeded`)
return results
}, (reason) => {
logger.warn('Searching failed:', reason)
return []
})
.then((searchResults) => {
return {
workshopsExplore: {
isSearching: false,
search: query,
searchResults,
},
}
})
},
render: (cursor) => {
return h('.pure-g', [
h('.pure-u-1', [
h('#explore-pad', [
SearchBox(cursor),
Results(cursor),
]),
]),
])
},
}
|
/**
* name : activeResources.js
* Location : /norris/test/dataLayer/activeResources
*
* History :
* Version Date Programmer
* =================================================
* 0.0.1 2015/05/15 Meneguzzo Francesco
* -------------------------------------------------
* Codifica modulo
* =================================================
*/
'use strict';
var should = require('should');
var storeCheck = undefined;
var modelStub = undefined;
var ActiveResources = require('../../../../lib/dataLayer/ActiveResources.js');
describe('TU46 - ActiveResources()', function() {
it('Should return the correct references when called', function() {
var stub1 = {
graphs: ActiveResources.graphs,
pages: ActiveResources.pages
}
stub1.graphs.push("this is a graph");
stub1.pages.push("this is a page");
var stub2 = {
graphs: ActiveResources.graphs,
pages: ActiveResources.pages
}
stub1.graphs[0].should.be.exactly(stub2.graphs[0]);
stub1.pages[0].should.be.exactly(stub2.pages[0]);
});
});
|
/*global define*/
///////////////////////////////////////////////////////////////////////////
// Copyright © 2015 Esri. 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.
///////////////////////////////////////////////////////////////////////////
define({
"units": {
"miles": "英里",
"kilometers": "公里",
"feet": "英呎",
"meters": "公尺"
},
"layerSetting": {
"layerSettingTabTitle": "搜尋設定",
"buttonSet": "設定",
"selectLayersLabel": "選擇圖層",
"selectLayersHintText": "提示: 用來選擇多邊形圖層及其相關點圖層。",
"selectPrecinctSymbolLabel": "選擇符號以突顯多邊形",
"selectGraphicLocationSymbol": "地址或位置符號",
"graphicLocationSymbolHintText": "提示: 搜尋的地址或按一下的位置所適用的符號",
"precinctSymbolHintText": "提示: 用來顯示所選多邊形的符號",
"selectColorForPoint": "選擇顏色以突顯點",
"selectColorForPointHintText": "提示: 用來顯示所選點的強調顏色"
},
"layerSelector": {
"selectPolygonLayerLabel": "選擇多邊形圖層",
"selectPolygonLayerHintText": "提示: 用來選擇多邊形圖層。",
"selectRelatedPointLayerLabel": "選擇多邊形圖層相關的點圖層",
"selectRelatedPointLayerHintText": "提示: 用來選擇多邊形圖層相關的點圖層",
"polygonLayerNotHavingRelatedLayer": "請選擇具有相關點圖層的多邊形圖層。",
"errorInSelectingPolygonLayer": "請選擇具有相關點圖層的多邊形圖層。",
"errorInSelectingRelatedLayer": "請選擇多邊形圖層相關的點圖層。"
},
"routeSetting": {
"routeSettingTabTitle": "方向設定",
"routeServiceUrl": "路線規劃服務",
"buttonSet": "設定",
"routeServiceUrlHintText": "提示: 按一下「設定」以瀏覽和選擇網路分析路線規劃服務",
"directionLengthUnit": "方向長度單位",
"unitsForRouteHintText": "提示: 用來顯示路線的報告單位",
"selectRouteSymbol": "選擇要顯示路線的符號",
"routeSymbolHintText": "提示: 用來顯示路線的線條符號",
"routingDisabledMsg": "若要啟用方向,請確定在 ArcGIS Online 項目中啟用路線規劃。"
},
"networkServiceChooser": {
"arcgislabel": "從 ArcGIS Online 新增",
"serviceURLabel": "新增服務 URL",
"routeURL": "路徑 URL",
"validateRouteURL": "驗證",
"exampleText": "範例",
"hintRouteURL1": "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/",
"hintRouteURL2": "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World",
"invalidRouteServiceURL": "請指定有效的路線服務。",
"rateLimitExceeded": "已超過比率限制。請稍後再試。",
"errorInvokingService": "使用者名稱或密碼不正確。"
},
"symbolPickerPreviewText": "預覽:"
});
|
const chalk = require('chalk')
const checkpoint = require('../checkpoint')
const figures = require('figures')
const formatCommitMessage = require('../format-commit-message')
const runExec = require('../run-exec')
const runLifecycleScript = require('../run-lifecycle-script')
module.exports = function (newVersion, pkgPrivate, args) {
if (args.skip.tag) return Promise.resolve()
return runLifecycleScript(args, 'pretag')
.then(() => {
return execTag(newVersion, pkgPrivate, args)
})
.then(() => {
return runLifecycleScript(args, 'posttag')
})
}
function execTag (newVersion, pkgPrivate, args) {
var tagOption
if (args.sign) {
tagOption = '-s '
} else {
tagOption = '-a '
}
checkpoint(args, 'tagging release %s', [newVersion])
return runExec(args, 'git tag ' + tagOption + args.tagPrefix + newVersion + ' -m "' + formatCommitMessage(args.message, newVersion) + '"')
.then(() => {
var message = 'git push --follow-tags origin master'
if (pkgPrivate !== true) message += '; npm publish'
checkpoint(args, 'Run `%s` to publish', [message], chalk.blue(figures.info))
})
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:c4dd1d1fdefb8933c974ed0b535ae98025befca15b472d0503a456083d0ad9a7
size 5352
|
import { get } from '../lib/apiService';
export function getAffiliation(affiliationId) {
return get('nominations', `affiliations/${affiliationId}`);
}
export function getAffiliationsByType(type) {
return get('nominations', 'affiliations', { type });
}
export function getAffiliationList(pageNumber = 1, search, sizePerPage = 50) {
return get('nominations', 'affiliations', {
page: pageNumber,
search: search,
sizePerPage
});
}
export function getAllAffiliations() {
return get('nominations', 'affiliations');
}
export function getSchools() {
return get('nominations', 'affiliations', { type: 'cms' });
}
|
import {REQUEST, DISMISS} from './actions';
export default function({hasBeenDismissed}) {
const initialState = {
dismissed: hasBeenDismissed,
visible: false
};
return function(state = initialState, action) {
switch (action.type) {
case REQUEST:
if (!state.dismissed) {
return {
...state,
visible: true
};
}
return state;
case DISMISS:
return {
dismissed: true,
visible: false
};
default:
return state;
}
};
}
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M7 1v5h2V4h10v16H9v-2H7v5h14V1z" /><path d="M9.5 15.5c.29-.12.55-.29.8-.48l-.02.03 1.41.55 1.27-2.2-1.18-.95-.02.03c.02-.16.05-.32.05-.48s-.03-.32-.05-.48l.02.03 1.18-.95-1.26-2.2-1.41.55.02.03c-.26-.19-.52-.36-.81-.48L9.27 7H6.73L6.5 8.5c-.29.12-.55.29-.8.48l.02-.03L4.3 8.4l-1.27 2.2 1.18.95.02-.03c-.01.16-.04.32-.04.48s.03.32.05.48l-.02-.03-1.18.95 1.27 2.2 1.41-.55-.02-.03c.25.19.51.36.8.48l.23 1.5h2.54l.23-1.5zM6 12c0-1.1.9-2 2-2s2 .9 2 2-.9 2-2 2-2-.9-2-2z" /></g></React.Fragment>
, 'PhonelinkSetupSharp');
|
/**
* Requires all tasks in gulp/tasks, including subfolders
* Dependencies:
* - require-dir
*/
var requireDir = require('require-dir');
requireDir('./gulp/tasks', {recurse:true});
|
// This file is used to load the video.js source files into a page
// in the correct order based on dependencies.
// When you create a new source file you will need to add
// it to the list below to use it in sandbox/index.html and
// test/index.html
// You can use the projectRoot variable to adjust relative urls
// that this script loads. By default it's "../", which is what /sandbox
// and /test need. If you had sandbox/newDir/index.html, in index.html you
// would set projectRoot = "../../"
// We could use somehting like requireJS to load files, and at one point
// we used goog.require/provide to load dependencies, but that seems like
// overkill with the small number of files we actually have.
// ADD NEW SOURCE FILES HERE
var sourceFiles = [
"src/js/core.js",
"src/js/core-object.js",
"src/js/events.js",
"src/js/lib.js",
"src/js/component.js",
"src/js/button.js",
"src/js/slider.js",
"src/js/menu.js",
"src/js/player.js",
"src/js/control-bar/control-bar.js",
"src/js/control-bar/play-toggle.js",
"src/js/control-bar/time-display.js",
"src/js/control-bar/fullscreen-toggle.js",
"src/js/control-bar/progress-control.js",
"src/js/control-bar/volume-control.js",
"src/js/control-bar/mute-toggle.js",
"src/js/control-bar/volume-menu-button.js",
"src/js/poster.js",
"src/js/loading-spinner.js",
"src/js/big-play-button.js",
"src/js/media/media.js",
"src/js/media/html5.js",
"src/js/media/flash.js",
"src/js/media/loader.js",
"src/js/tracks.js",
"src/js/json.js",
"src/js/setup.js",
"src/js/plugins.js"
];
// Allow overriding the default project root
var projectRoot = projectRoot || '../';
function loadScripts(scriptsArr){
for (var i = 0; i < scriptsArr.length; i++) {
// Using document.write because that's the easiest way to avoid triggering
// asynchrnous script loading
document.write( "<script src='" + projectRoot + scriptsArr[i] + "'><\/script>" );
}
}
// We use this file in the grunt build script to load the same source file list
// and don't want to load the scripts there.
if (typeof blockSourceLoading === 'undefined') {
loadScripts(sourceFiles);
// Allow for making Flash first
if (window.location.href.indexOf("?flash") !== -1) {
// Using doc.write to load this script to, otherwise when it runs videojs
// is undefined
document.write('<script>videojs.options.techOrder = ["flash"];videojs.options.flash.swf = "../src/swf/video-js.swf";</script>')
}
}
|
var http = require('http'),
path = require('path'),
url = require('url'),
request = require('request'),
_ = require('underscore'),
jschardet = require('jschardet'),
jsdom = require('jsdom'),
zlib = require("zlib"),
fs = require("fs"),
Pool = require('generic-pool').Pool;
// Fallback on iconv-lite if we didn't succeed compiling iconv
// https://github.com/sylvinus/node-crawler/pull/29
var iconv, iconvLite;
try {
iconv = require('iconv').Iconv;
} catch (e) {}
if (!iconv) {
iconvLite = require('iconv-lite');
}
exports.VERSION = "0.2.5";
exports.Crawler = function(options) {
var self = this;
//Default options
self.options = _.extend({
timeout: 60000,
jQuery: true,
jQueryUrl: path.resolve(__dirname,"../vendor/jquery-1.8.3.min.js"),
maxConnections: 10,
priorityRange: 10,
priority: 5,
retries: 3,
forceUTF8: false,
userAgent: "node-crawler/"+exports.VERSION,
autoWindowClose:true,
retryTimeout: 10000,
method: "GET",
cache: false, //false,true, [ttl?]
skipDuplicates: false,
onDrain: false
},options);
// Don't make these options persist to individual queries
var masterOnlyOptions = ["maxConnections", "priorityRange", "onDrain"];
//Setup a worker pool w/ https://github.com/coopernurse/node-pool
self.pool = Pool({
name : 'crawler',
//log : self.options.debug,
max : self.options.maxConnections,
priorityRange: self.options.priorityRange,
create : function(callback) {
callback(1);
},
destroy : function(client) {
}
});
var plannedQueueCallsCount = 0;
var queuedCount = 0;
var release = function(opts) {
queuedCount--;
// console.log("Released... count",queuedCount,plannedQueueCallsCount);
if (opts._poolRef) self.pool.release(opts._poolRef);
// Pool stats are behaving weird - have to implement our own counter
// console.log("POOL STATS",{"name":self.pool.getName(),"size":self.pool.getPoolSize(),"avail":self.pool.availableObjectsCount(),"waiting":self.pool.waitingClientsCount()});
if (queuedCount+plannedQueueCallsCount === 0) {
if (self.options.onDrain) self.options.onDrain();
}
};
self.onDrain = function() {};
self.cache = {};
var useCache = function(opts) {
return (opts.uri && (opts.cache || opts.skipDuplicates) && (opts.method=="GET" || opts.method=="HEAD"));
};
self.request = function(opts) {
// console.log("OPTS",opts);
if (useCache(opts)) {
var cacheData = self.cache[opts.uri];
//If a query has already been made to self URL, don't callback again
if (cacheData) {
// Make sure we actually have cached data, and not just a note
// that the page was already crawled
if (_.isArray(cacheData)) {
self.onContent(null,opts,cacheData[0],true);
} else {
release(opts);
}
return;
}
}
if (opts.debug) {
console.log(opts.method+" "+opts.uri+" ...");
}
// Cloning keeps the opts parameter clean:
// - some versions of "request" apply the second parameter as a
// property called "callback" to the first parameter
// - keeps the query object fresh in case of a retry
// Doing parse/stringify instead of _.clone will do a deep clone and remove functions
var ropts = JSON.parse(JSON.stringify(opts));
if (!ropts.headers) ropts.headers={};
if (ropts.forceUTF8) {
if (!ropts.headers["Accept-Charset"] && !ropts.headers["accept-charset"]) ropts.headers["Accept-Charset"] = 'utf-8;q=0.7,*;q=0.3';
if (!ropts.encoding) ropts.encoding=null;
}
if (typeof ropts.encoding === 'undefined') {
ropts.headers["Accept-Encoding"] = "gzip";
ropts.encoding = null;
}
if (ropts.userAgent) {
ropts.headers["User-Agent"] = ropts.userAgent;
}
if (ropts.proxies && ropts.proxies.length) {
ropts.proxy = ropts.proxies[0];
}
var requestArgs = ["uri","url","qs","method","headers","body","form","json","multipart","followRedirect","followAllRedirects",
"maxRedirects","encoding","pool","timeout","proxy","auth","oauth","strictSSL","jar","aws"];
var req = request(_.pick.apply(this,[ropts].concat(requestArgs)), function(error,response,body) {
if (error) return self.onContent(error, opts);
response.uri = opts.uri;
// Won't be needed after https://github.com/mikeal/request/pull/303 is merged
if (response.headers['content-encoding'] && response.headers['content-encoding'].toLowerCase().indexOf('gzip') >= 0) {
zlib.gunzip(response.body, function (error, body) {
if (error) return self.onContent(error, opts);
if (!opts.forceUTF8) {
response.body = body.toString(req.encoding);
} else {
response.body = body;
}
self.onContent(error,opts,response,false);
});
} else {
self.onContent(error,opts,response,false);
}
});
};
self.onContent = function (error, toQueue, response, fromCache) {
if (error) {
if (toQueue.debug) {
console.log("Error "+error+" when fetching "+toQueue.uri+(toQueue.retries?" ("+toQueue.retries+" retries left)":""));
}
if (toQueue.retries) {
plannedQueueCallsCount++;
setTimeout(function() {
toQueue.retries--;
plannedQueueCallsCount--;
// If there is a "proxies" option, rotate it so that we don't keep hitting the same one
if (toQueue.proxies) {
toQueue.proxies.push(toQueue.proxies.shift());
}
self.queue(toQueue);
},toQueue.retryTimeout);
} else if (toQueue.callback) {
toQueue.callback(error);
}
return release(toQueue);
}
if (!response.body) response.body="";
if (toQueue.debug) {
console.log("Got "+(toQueue.uri||"html")+" ("+response.body.length+" bytes)...");
}
if (toQueue.forceUTF8) {
//TODO check http header or meta equiv?
var detected = jschardet.detect(response.body);
if (detected && detected.encoding) {
if (toQueue.debug) {
console.log("Detected charset "+detected.encoding+" ("+Math.floor(detected.confidence*100)+"% confidence)");
}
if (detected.encoding!="utf-8" && detected.encoding!="ascii") {
if (iconv) {
var iconvObj = new iconv(detected.encoding, "UTF-8//TRANSLIT//IGNORE");
response.body = iconvObj.convert(response.body).toString();
// iconv-lite doesn't support Big5 (yet)
} else if (detected.encoding != "Big5") {
response.body = iconvLite.decode(response.body, detected.encoding);
}
} else if (typeof response.body != "string") {
response.body = response.body.toString();
}
} else {
response.body = response.body.toString("utf8"); //hope for the best
}
} else {
response.body = response.body.toString();
}
if (useCache(toQueue) && !fromCache) {
if (toQueue.cache) {
self.cache[toQueue.uri] = [response];
//If we don't cache but still want to skip duplicates we have to maintain a list of fetched URLs.
} else if (toQueue.skipDuplicates) {
self.cache[toQueue.uri] = true;
}
}
if (!toQueue.callback) return release(toQueue);
response.options = toQueue;
// This could definitely be improved by *also* matching content-type headers
var isHTML = response.body.match(/^\s*</);
if (isHTML && toQueue.jQuery && toQueue.method!="HEAD") {
// TODO support for non-HTML content
// https://github.com/joshfire/node-crawler/issues/9
try {
var jsd = function(src) {
var env = jsdom.env({
"url":toQueue.uri,
"html":response.body,
"src":src,
"done":function(errors,window) {
var callbackError = false;
try {
if (errors) {
toQueue.callback(errors);
} else {
response.window = window;
toQueue.callback(null,response,window.jQuery);
}
} catch (e) {
callbackError = e;
}
// Free jsdom memory
if (toQueue.autoWindowClose) {
try {
window.close();
window = null;
} catch (err) {
console.log("Couldn't window.close : "+err);
}
response.body = null;
response = null;
}
release(toQueue);
if (callbackError) throw callbackError;
}
});
};
// jsdom doesn't support adding local scripts,
// We have to read jQuery from the local fs
if (toQueue.jQueryUrl.match(/^(file\:\/\/|\/)/)) {
// TODO cache this
fs.readFile(toQueue.jQueryUrl.replace(/^file\:\/\//,""),"utf-8",function(err,jq) {
if (err) {
toQueue.callback(err);
release(toQueue);
} else {
try {
jsd([jq]);
} catch (e) {
toQueue.callback(e);
release(toQueue);
}
}
});
} else {
jsd([toQueue.jQueryUrl]);
}
} catch (e) {
toQueue.callback(e);
release(toQueue);
}
} else {
toQueue.callback(null,response);
release(toQueue);
}
};
self.queue = function(item) {
//Did we get a list ? Queue all the URLs.
if (_.isArray(item)) {
for (var i=0;i<item.length;i++) {
self.queue(item[i]);
}
return;
}
queuedCount++;
var toQueue=item;
//Allow passing just strings as URLs
if (_.isString(item)) {
toQueue = {"uri":item};
}
_.defaults(toQueue,self.options);
// Cleanup options
_.each(masterOnlyOptions,function(o) {
delete toQueue[o];
});
// If duplicate skipping is enabled, avoid queueing entirely for URLs we already crawled
if (toQueue.skipDuplicates && self.cache[toQueue.uri]) {
return release(toQueue);
}
self.pool.acquire(function(err, poolRef) {
//TODO - which errback to call?
if (err) {
console.error("pool acquire error:",err);
return release(toQueue);
}
toQueue._poolRef = poolRef;
// We need to check again for duplicates because the cache might have
// been completed since we queued self task.
if (toQueue.skipDuplicates && self.cache[toQueue.uri]) {
return release(toQueue);
}
//Static HTML was given, skip request
if (toQueue.html) {
self.onContent(null,toQueue,{body:toQueue.html},false);
return;
}
//Make a HTTP request
if (typeof toQueue.uri=="function") {
toQueue.uri(function(uri) {
toQueue.uri=uri;
self.request(toQueue);
});
} else {
self.request(toQueue);
}
},toQueue.priority);
};
};
|
/**
* Testing our Button component
*/
import Button from '../index';
import { mount } from 'enzyme';
import React from 'react';
const handleRoute = () => {};
const href = 'http://mxstbr.com';
const children = (<h1>Test</h1>);
const renderComponent = (props = {}) => mount(
<Button href={href} {...props}>
{children}
</Button>
);
describe('<Button />', () => {
it('should render an <a> tag if no route is specified', () => {
const renderedComponent = renderComponent({ href });
expect(renderedComponent.find('a').length).toEqual(1);
});
it('should render a <button> tag to change route if the handleRoute prop is specified', () => {
const renderedComponent = renderComponent({ handleRoute });
expect(renderedComponent.find('button').length).toEqual(1);
});
it('should have children', () => {
const renderedComponent = renderComponent();
expect(renderedComponent.contains(children)).toEqual(true);
});
it('should handle click events', () => {
const onClickSpy = jest.fn();
const renderedComponent = renderComponent({ onClick: onClickSpy });
renderedComponent.find('a').simulate('click');
expect(onClickSpy).toHaveBeenCalled();
});
it('should have a className attribute', () => {
const renderedComponent = renderComponent();
expect(renderedComponent.find('a').prop('className')).toBeDefined();
});
it('should not adopt a type attribute when rendering an <a> tag', () => {
const type = 'text/html';
const renderedComponent = renderComponent({ href, type });
expect(renderedComponent.find('a').prop('type')).toBeUndefined();
});
it('should not adopt a type attribute when rendering a button', () => {
const type = 'submit';
const renderedComponent = renderComponent({ handleRoute, type });
expect(renderedComponent.find('button').prop('type')).toBeUndefined();
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:71723b08bbf195b8908ec9d7dba9c3284281e3dd09eef9711906e81f3c0e26da
size 62894
|
const Promise = require(`bluebird`)
const {
GraphQLObjectType,
GraphQLBoolean,
GraphQLString,
GraphQLInt,
GraphQLFloat,
GraphQLEnumType,
} = require(`graphql`)
const qs = require(`qs`)
const base64Img = require(`base64-img`)
const _ = require(`lodash`)
const ImageFormatType = new GraphQLEnumType({
name: `ContentfulImageFormat`,
values: {
NO_CHANGE: { value: `` },
JPG: { value: `jpg` },
PNG: { value: `png` },
WEBP: { value: `webp` },
},
})
const ImageResizingBehavior = new GraphQLEnumType({
name: `ImageResizingBehavior`,
values: {
NO_CHANGE: {
value: ``,
},
PAD: {
value: `pad`,
description: `Same as the default resizing, but adds padding so that the generated image has the specified dimensions.`,
},
CROP: {
value: `crop`,
description: `Crop a part of the original image to match the specified size.`,
},
FILL: {
value: `fill`,
description: `Crop the image to the specified dimensions, if the original image is smaller than these dimensions, then the image will be upscaled.`,
},
THUMB: {
value: `thumb`,
description: `When used in association with the f parameter below, creates a thumbnail from the image based on a focus area.`,
},
SCALE: {
value: `scale`,
description: `Scale the image regardless of the original aspect ratio.`,
},
},
})
const ImageCropFocusType = new GraphQLEnumType({
name: `ContentfulImageCropFocus`,
values: {
TOP: { value: `top` },
TOP_LEFT: { value: `top_left` },
TOP_RIGHT: { value: `top_right` },
BOTTOM: { value: `bottom` },
BOTTOM_RIGHT: { value: `bottom_left` },
BOTTOM_LEFT: { value: `bottom_right` },
RIGHT: { value: `right` },
LEFT: { value: `left` },
FACES: { value: `faces` },
},
})
const isImage = image =>
_.includes(
[`image/jpeg`, `image/jpg`, `image/png`, `image/webp`, `image/gif`],
_.get(image, `file.contentType`)
)
const getBase64Image = (imgUrl, args = {}) => {
const requestUrl = `https:${imgUrl}?w=20`
// TODO add caching.
return new Promise(resolve => {
base64Img.requestBase64(requestUrl, (a, b, body) => {
resolve(body)
})
})
}
const getBase64ImageAndBasicMeasurements = (image, args) =>
new Promise(resolve => {
getBase64Image(image.file.url, args).then(base64Str => {
let aspectRatio
if (args.width && args.height) {
aspectRatio = args.width / args.height
} else {
aspectRatio =
image.file.details.image.width / image.file.details.image.height
}
resolve({
contentType: image.file.contentType,
base64Str,
aspectRatio,
width: image.file.details.image.width,
height: image.file.details.image.height,
})
})
})
const createUrl = (imgUrl, options = {}) => {
// Convert to Contentful names and filter out undefined/null values.
const args = _.pickBy(
{
w: options.width,
h: options.height,
fl: options.jpegProgressive ? `progressive` : null,
q: options.quality,
fm: options.toFormat ? options.toFormat : ``,
fit: options.resizingBehavior ? options.resizingBehavior : ``,
f: options.cropFocus ? options.cropFocus : ``,
},
_.identity
)
return `${imgUrl}?${qs.stringify(args)}`
}
exports.createUrl = createUrl
const resolveResponsiveResolution = (image, options) => {
if (!isImage(image)) return null
return new Promise(resolve => {
getBase64ImageAndBasicMeasurements(image, options).then(
({ contentType, base64Str, width, height, aspectRatio }) => {
let desiredAspectRatio = aspectRatio
// If we're cropping, calculate the specified aspect ratio.
if (options.height) {
desiredAspectRatio = options.width / options.height
}
// If the user selected a height (so cropping) and fit option
// is not set, we'll set our defaults
if (options.height) {
if (!options.resizingBehavior) {
options.resizingBehavior = `fill`
}
}
// Create sizes (in width) for the image. If the width of the
// image is 800px, the sizes would then be: 800, 1200, 1600,
// 2400.
//
// This is enough sizes to provide close to the optimal image size for every
// device size / screen resolution
let sizes = []
sizes.push(options.width)
sizes.push(options.width * 1.5)
sizes.push(options.width * 2)
sizes.push(options.width * 3)
sizes = sizes.map(Math.round)
// Filter out sizes larger than the image's width.
const filteredSizes = sizes.filter(size => size < width)
// Sort sizes for prettiness.
const sortedSizes = _.sortBy(filteredSizes)
// Create the srcSet.
const srcSet = sortedSizes
.map((size, i) => {
let resolution
switch (i) {
case 0:
resolution = `1x`
break
case 1:
resolution = `1.5x`
break
case 2:
resolution = `2x`
break
case 3:
resolution = `3x`
break
default:
}
const h = Math.round(size / desiredAspectRatio)
return `${createUrl(image.file.url, {
...options,
width: size,
height: h,
})} ${resolution}`
})
.join(`,\n`)
let pickedHeight
if (options.height) {
pickedHeight = options.height
} else {
pickedHeight = options.width / desiredAspectRatio
}
return resolve({
base64: base64Str,
aspectRatio: aspectRatio,
width: Math.round(options.width),
height: Math.round(pickedHeight),
src: createUrl(image.file.url, {
...options,
width: options.width,
}),
srcSet,
})
}
)
})
}
exports.resolveResponsiveResolution = resolveResponsiveResolution
const resolveResponsiveSizes = (image, options) => {
if (!isImage(image)) return null
return new Promise(resolve => {
getBase64ImageAndBasicMeasurements(image, options).then(
({ contentType, base64Str, width, height, aspectRatio }) => {
let desiredAspectRatio = aspectRatio
// If we're cropping, calculate the specified aspect ratio.
if (options.maxHeight) {
desiredAspectRatio = options.maxWidth / options.maxHeight
}
// If the users didn't set a default sizes, we'll make one.
if (!options.sizes) {
options.sizes = `(max-width: ${options.maxWidth}px) 100vw, ${
options.maxWidth
}px`
}
// Create sizes (in width) for the image. If the max width of the container
// for the rendered markdown file is 800px, the sizes would then be: 200,
// 400, 800, 1200, 1600, 2400.
//
// This is enough sizes to provide close to the optimal image size for every
// device size / screen resolution
let sizes = []
sizes.push(options.maxWidth / 4)
sizes.push(options.maxWidth / 2)
sizes.push(options.maxWidth)
sizes.push(options.maxWidth * 1.5)
sizes.push(options.maxWidth * 2)
sizes.push(options.maxWidth * 3)
sizes = sizes.map(Math.round)
// Filter out sizes larger than the image's maxWidth.
const filteredSizes = sizes.filter(size => size < width)
// Add the original image to ensure the largest image possible
// is available for small images.
filteredSizes.push(width)
// Sort sizes for prettiness.
const sortedSizes = _.sortBy(filteredSizes)
// Create the srcSet.
const srcSet = sortedSizes
.map(width => {
const h = Math.round(width / desiredAspectRatio)
return `${createUrl(image.file.url, {
...options,
width,
height: h,
})} ${Math.round(width)}w`
})
.join(`,\n`)
return resolve({
base64: base64Str,
aspectRatio: aspectRatio,
src: createUrl(image.file.url, {
...options,
width: options.maxWidth,
height: options.maxHeight,
}),
srcSet,
sizes: options.sizes,
})
}
)
})
}
exports.resolveResponsiveSizes = resolveResponsiveSizes
const resolveResize = (image, options) => {
if (!isImage(image)) return null
return new Promise(resolve => {
getBase64ImageAndBasicMeasurements(image, options).then(
({ contentType, base64Str, width, height, aspectRatio }) => {
// If the user selected a height (so cropping) and fit option
// is not set, we'll set our defaults
if (options.height) {
if (!options.resizingBehavior) {
options.resizingBehavior = `fill`
}
}
if (options.base64) {
resolve(base64Str)
return
}
const pickedWidth = options.width
let pickedHeight
if (options.height) {
pickedHeight = options.height
} else {
pickedHeight = pickedWidth / aspectRatio
}
resolve({
src: createUrl(image.file.url, options),
width: Math.round(pickedWidth),
height: Math.round(pickedHeight),
aspectRatio,
base64: base64Str,
})
}
)
})
}
exports.resolveResize = resolveResize
exports.extendNodeType = ({ type }) => {
if (type.name !== `ContentfulAsset`) {
return {}
}
return {
resolutions: {
type: new GraphQLObjectType({
name: `ContentfulResolutions`,
fields: {
base64: { type: GraphQLString },
aspectRatio: { type: GraphQLFloat },
width: { type: GraphQLFloat },
height: { type: GraphQLFloat },
src: { type: GraphQLString },
srcSet: { type: GraphQLString },
},
}),
args: {
width: {
type: GraphQLInt,
defaultValue: 400,
},
height: {
type: GraphQLInt,
},
quality: {
type: GraphQLInt,
defaultValue: 50,
},
toFormat: {
type: ImageFormatType,
defaultValue: ``,
},
resizingBehavior: {
type: ImageResizingBehavior,
},
cropFocus: {
type: ImageCropFocusType,
defaultValue: null,
},
},
resolve(image, options, context) {
return resolveResponsiveResolution(image, options)
},
},
sizes: {
type: new GraphQLObjectType({
name: `ContentfulSizes`,
fields: {
base64: { type: GraphQLString },
aspectRatio: { type: GraphQLFloat },
src: { type: GraphQLString },
srcSet: { type: GraphQLString },
sizes: { type: GraphQLString },
},
}),
args: {
maxWidth: {
type: GraphQLInt,
defaultValue: 800,
},
maxHeight: {
type: GraphQLInt,
},
quality: {
type: GraphQLInt,
defaultValue: 50,
},
toFormat: {
type: ImageFormatType,
defaultValue: ``,
},
resizingBehavior: {
type: ImageResizingBehavior,
},
cropFocus: {
type: ImageCropFocusType,
defaultValue: null,
},
sizes: {
type: GraphQLString,
},
},
resolve(image, options, context) {
return resolveResponsiveSizes(image, options)
},
},
responsiveResolution: {
deprecationReason: `We dropped the "responsive" part of the name to make it shorter https://github.com/gatsbyjs/gatsby/pull/2320/`,
type: new GraphQLObjectType({
name: `ContentfulResponsiveResolution`,
fields: {
base64: { type: GraphQLString },
aspectRatio: { type: GraphQLFloat },
width: { type: GraphQLFloat },
height: { type: GraphQLFloat },
src: { type: GraphQLString },
srcSet: { type: GraphQLString },
},
}),
args: {
width: {
type: GraphQLInt,
defaultValue: 400,
},
height: {
type: GraphQLInt,
},
quality: {
type: GraphQLInt,
defaultValue: 50,
},
toFormat: {
type: ImageFormatType,
defaultValue: ``,
},
resizingBehavior: {
type: ImageResizingBehavior,
},
cropFocus: {
type: ImageCropFocusType,
defaultValue: null,
},
},
resolve(image, options, context) {
return resolveResponsiveResolution(image, options)
},
},
responsiveSizes: {
deprecationReason: `We dropped the "responsive" part of the name to make it shorter https://github.com/gatsbyjs/gatsby/pull/2320/`,
type: new GraphQLObjectType({
name: `ContentfulResponsiveSizes`,
fields: {
base64: { type: GraphQLString },
aspectRatio: { type: GraphQLFloat },
src: { type: GraphQLString },
srcSet: { type: GraphQLString },
sizes: { type: GraphQLString },
},
}),
args: {
maxWidth: {
type: GraphQLInt,
defaultValue: 800,
},
maxHeight: {
type: GraphQLInt,
},
quality: {
type: GraphQLInt,
defaultValue: 50,
},
toFormat: {
type: ImageFormatType,
defaultValue: ``,
},
resizingBehavior: {
type: ImageResizingBehavior,
},
cropFocus: {
type: ImageCropFocusType,
defaultValue: null,
},
sizes: {
type: GraphQLString,
},
},
resolve(image, options, context) {
return resolveResponsiveSizes(image, options)
},
},
resize: {
type: new GraphQLObjectType({
name: `ContentfulResize`,
fields: {
src: { type: GraphQLString },
width: { type: GraphQLInt },
height: { type: GraphQLInt },
aspectRatio: { type: GraphQLFloat },
},
}),
args: {
width: {
type: GraphQLInt,
defaultValue: 400,
},
height: {
type: GraphQLInt,
},
quality: {
type: GraphQLInt,
defaultValue: 50,
},
jpegProgressive: {
type: GraphQLBoolean,
defaultValue: true,
},
resizingBehavior: {
type: ImageResizingBehavior,
},
base64: {
type: GraphQLBoolean,
defaultValue: false,
},
toFormat: {
type: ImageFormatType,
defaultValue: ``,
},
cropFocus: {
type: ImageCropFocusType,
defaultValue: null,
},
},
resolve(image, options, context) {
return resolveResize(image, options)
},
},
}
}
|
import { frameworks, url } from "../settings";
import { ClientFunction } from "testcafe";
const assert = require("assert");
const title = `customCss`;
const initSurvey = ClientFunction((framework, json) => {
Survey.defaultBootstrapCss.navigationButton = "btn btn-primary";
Survey.StylesManager.applyTheme("bootstrap");
var model = new Survey.Model(json);
model.onComplete.add(function(model) {
window.SurveyResult = model.data;
});
var myCss = {
matrix: { root: "table table-striped" },
navigationButton: "button btn-lg"
};
if (framework === "knockout") {
model.css = myCss;
model.render("surveyElement");
} else if (framework === "react") {
ReactDOM.render(
React.createElement(Survey.Survey, { model: model, css: myCss }),
document.getElementById("surveyElement")
);
} else if (framework === "vue") {
model.css = myCss;
var app = new Vue({
el: "#surveyElement",
data: {
survey: model
}
});
} else if (framework === "jquery") {
$("#surveyElement").Survey({
model: model,
css: myCss
});
} else if (framework === "angular") {
function onAngularComponentInit() {
Survey.SurveyNG.render("surveyElement", {
model: model,
css: myCss
});
}
var HelloApp = ng.core
.Component({
selector: "ng-app",
template:
'<div id="surveyContainer" class="survey-container contentcontainer codecontainer">' +
'<div id="surveyElement"></div></div>'
})
.Class({
constructor: function() {},
ngOnInit: function() {
onAngularComponentInit();
}
});
document.addEventListener("DOMContentLoaded", function() {
ng.platformBrowserDynamic.bootstrap(HelloApp);
});
}
window.survey = model;
});
const json = {
questions: [
{
type: "matrix",
name: "Quality",
title:
"Please indicate if you agree or disagree with the following statements",
columns: [
{ value: 1, text: "Strongly Disagree" },
{ value: 2, text: "Disagree" },
{ value: 3, text: "Neutral" },
{ value: 4, text: "Agree" },
{ value: 5, text: "Strongly Agree" }
],
rows: [
{ value: "affordable", text: "Product is affordable" },
{ value: "does what it claims", text: "Product does what it claims" },
{
value: "better than others",
text: "Product is better than other products on the market"
},
{ value: "easy to use", text: "Product is easy to use" }
]
}
]
};
frameworks.forEach(framework => {
fixture`${framework} ${title}`.page`${url}${framework}`.beforeEach(
async t => {
await initSurvey(framework, json);
}
);
test(`check custom class`, async t => {
const isCustomClassExist = ClientFunction(() =>
document
.querySelector(`input[value="Complete"]`)
.classList.contains(`btn-lg`)
);
assert(await isCustomClassExist());
});
});
|
import Ember from 'ember';
export default Ember.View.extend({
elementId: "user"
});
|
import gulp from 'gulp';
import del from 'del';
import runSequence from 'run-sequence';
import babel from 'rollup-plugin-babel';
import {rollup} from 'rollup';
import file from 'gulp-file';
const MODULE_NAME = 'myModule';
/**
* @name SRC
* @type {string}
*/
const SRC = './src/**/*.js';
/**
* @name DIST
* @type {string}
*/
const DIST = './dist';
/**
* @name clean
*/
gulp.task('clean', cb => {
return del(DIST, {force: true}, cb);
});
/**
* @name scripts
*/
gulp.task('scripts', () => {
return rollup({
entry: './src/index.js',
plugins: [
babel({
presets: [
[
"es2015",
{
modules: false
}
]
],
"babelrc": false
})
]
})
.then(bundle => bundle.generate({
format: 'umd',
moduleName: MODULE_NAME
}))
.then(bundle => file('index.js', bundle.code, {src: true})
.pipe(gulp.dest(DIST)));
});
/**
* @name build
*/
gulp.task('build', cb => {
return runSequence('clean', 'scripts', cb);
});
/**
* @name dev
*/
gulp.task('dev', ['build'], () => gulp.watch(SRC, ['scripts']));
/**
* @name dist
*/
gulp.task('dist', cb => {
return runSequence('clean', ['scripts'], cb);
});
|
var assert = require('assert');
var html2epub = require('../lib/');
describe('Constructor with no arguments', function() {
var epub = new html2epub();
it('valid UUID', function(done) {
var uuid = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/;
assert.ok(uuid.test(epub.identifier));
done();
});
it('ISO-8601 compliant "modified" meta', function(done) {
var iso = /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$/;
assert.ok(iso.test(epub.modified));
done();
});
it('default ToC settings', function(done) {
assert.strictEqual(epub.headings.replace(/\s/g, ''), 'h1,h2,h3,h4,h5,h6');
assert.strictEqual(epub.depth, 3);
assert.strictEqual(epub.keepAllHeadings, false);
done();
});
it('proper instance', function(done) {
assert.ok( epub instanceof html2epub); // properly created with 'new'
assert.ok(html2epub() instanceof html2epub); // dirty fallback
done();
});
});
describe('Headings extraction', function() {
// TODO: test html2epub.getHeadings()
});
describe('Alice\'s Adventures in Wonderland', function() {
var epub = new html2epub({
basedir: 'examples/alice/'
});
it('spine', function(done) {
assert.deepEqual(epub.spine, [
'00.xhtml',
'01.xhtml',
'02.xhtml',
'03.xhtml',
'04.xhtml',
'05.xhtml',
'06.xhtml',
'07.xhtml',
'08.xhtml',
'09.xhtml',
'10.xhtml',
'11.xhtml',
'12.xhtml',
'13.xhtml'
]);
done();
});
it('ToC with default settings', function(done) {
var pages = epub.parseHeadingsSync();
assert.deepEqual(pages, [
{
href: '00.xhtml',
headings: [{
level: 0,
title: 'Alice’s Adventures in Wonderland',
href: '00.xhtml'
}]
},
{
href: '01.xhtml',
headings: [{
level: 1,
title: 'CHAPTER I. Down the Rabbit-Hole',
href: '01.xhtml'
}]
},
{
href: '02.xhtml',
headings: [{
level: 1,
title: 'CHAPTER II. The Pool of Tears',
href: '02.xhtml'
}]
},
{
href: '03.xhtml',
headings: [{
level: 1,
title: 'CHAPTER III. A Caucus-Race and a Long Tale',
href: '03.xhtml'
}]
},
{
href: '04.xhtml',
headings: [{
level: 1,
title: 'CHAPTER IV. The Rabbit Sends in a Little Bill',
href: '04.xhtml'
}]
},
{
href: '05.xhtml',
headings: [{
level: 1,
title: 'CHAPTER V. Advice from a Caterpillar',
href: '05.xhtml'
}]
},
{
href: '06.xhtml',
headings: [{
level: 1,
title: 'CHAPTER VI. Pig and Pepper',
href: '06.xhtml'
}]
},
{
href: '07.xhtml',
headings: [{
level: 1,
title: 'CHAPTER VII. A Mad Tea-Party',
href: '07.xhtml'
}]
},
{
href: '08.xhtml',
headings: [{
level: 1,
title: 'CHAPTER VIII. The Queen\'s Croquet-Ground',
href: '08.xhtml'
}]
},
{
href: '09.xhtml',
headings: [{
level: 1,
title: 'CHAPTER IX. The Mock Turtle\'s Story',
href: '09.xhtml'
}]
},
{
href: '10.xhtml',
headings: [{
level: 1,
title: 'CHAPTER X. The Lobster Quadrille',
href: '10.xhtml'
}]
},
{
href: '11.xhtml',
headings: [{
level: 1,
title: 'CHAPTER XI. Who Stole the Tarts?',
href: '11.xhtml'
}]
},
{
href: '12.xhtml',
headings: [{
level: 1,
title: 'CHAPTER XII. Alice\'s Evidence',
href: '12.xhtml'
}]
},
{
href: '13.xhtml',
headings: []
}
]);
assert.strictEqual(epub.showToC(pages, 'txt'),
"\n Alice’s Adventures in Wonderland" +
"\n CHAPTER I. Down the Rabbit-Hole" +
"\n CHAPTER II. The Pool of Tears" +
"\n CHAPTER III. A Caucus-Race and a Long Tale" +
"\n CHAPTER IV. The Rabbit Sends in a Little Bill" +
"\n CHAPTER V. Advice from a Caterpillar" +
"\n CHAPTER VI. Pig and Pepper" +
"\n CHAPTER VII. A Mad Tea-Party" +
"\n CHAPTER VIII. The Queen's Croquet-Ground" +
"\n CHAPTER IX. The Mock Turtle's Story" +
"\n CHAPTER X. The Lobster Quadrille" +
"\n CHAPTER XI. Who Stole the Tarts?" +
"\n CHAPTER XII. Alice's Evidence" +
"\n");
done();
});
it('ToC with "keepAllHeadings" headings', function(done) {
epub.keepAllHeadings = true;
var pages = epub.parseHeadingsSync();
assert.deepEqual(pages[0], {
href: '00.xhtml',
headings: [
{
level: 0,
title: 'Alice’s Adventures in Wonderland',
href: '00.xhtml'
},
{
level: 3,
title: 'The Millennium Fulcrum Edition 3.0'
}
]
});
done();
});
it('ToC with "h2" headings', function(done) {
epub.headings = 'h2';
var pages = epub.parseHeadingsSync();
assert.deepEqual(pages, [
{
href: '00.xhtml',
headings: []
},
{
href: '01.xhtml',
headings: [{
level: 0,
title: 'CHAPTER I. Down the Rabbit-Hole',
href: '01.xhtml'
}]
},
{
href: '02.xhtml',
headings: [{
level: 0,
title: 'CHAPTER II. The Pool of Tears',
href: '02.xhtml'
}]
},
{
href: '03.xhtml',
headings: [{
level: 0,
title: 'CHAPTER III. A Caucus-Race and a Long Tale',
href: '03.xhtml'
}]
},
{
href: '04.xhtml',
headings: [{
level: 0,
title: 'CHAPTER IV. The Rabbit Sends in a Little Bill',
href: '04.xhtml'
}]
},
{
href: '05.xhtml',
headings: [{
level: 0,
title: 'CHAPTER V. Advice from a Caterpillar',
href: '05.xhtml'
}]
},
{
href: '06.xhtml',
headings: [{
level: 0,
title: 'CHAPTER VI. Pig and Pepper',
href: '06.xhtml'
}]
},
{
href: '07.xhtml',
headings: [{
level: 0,
title: 'CHAPTER VII. A Mad Tea-Party',
href: '07.xhtml'
}]
},
{
href: '08.xhtml',
headings: [{
level: 0,
title: 'CHAPTER VIII. The Queen\'s Croquet-Ground',
href: '08.xhtml'
}]
},
{
href: '09.xhtml',
headings: [{
level: 0,
title: 'CHAPTER IX. The Mock Turtle\'s Story',
href: '09.xhtml'
}]
},
{
href: '10.xhtml',
headings: [{
level: 0,
title: 'CHAPTER X. The Lobster Quadrille',
href: '10.xhtml'
}]
},
{
href: '11.xhtml',
headings: [{
level: 0,
title: 'CHAPTER XI. Who Stole the Tarts?',
href: '11.xhtml'
}]
},
{
href: '12.xhtml',
headings: [{
level: 0,
title: 'CHAPTER XII. Alice\'s Evidence',
href: '12.xhtml'
}]
},
{
href: '13.xhtml',
headings: []
}
]);
assert.strictEqual(epub.showToC(pages, 'txt'),
"\n CHAPTER I. Down the Rabbit-Hole" +
"\n CHAPTER II. The Pool of Tears" +
"\n CHAPTER III. A Caucus-Race and a Long Tale" +
"\n CHAPTER IV. The Rabbit Sends in a Little Bill" +
"\n CHAPTER V. Advice from a Caterpillar" +
"\n CHAPTER VI. Pig and Pepper" +
"\n CHAPTER VII. A Mad Tea-Party" +
"\n CHAPTER VIII. The Queen's Croquet-Ground" +
"\n CHAPTER IX. The Mock Turtle's Story" +
"\n CHAPTER X. The Lobster Quadrille" +
"\n CHAPTER XI. Who Stole the Tarts?" +
"\n CHAPTER XII. Alice's Evidence" +
"\n");
done();
});
});
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M13 10H3c-.55 0-1 .45-1 1s.45 1 1 1h10c.55 0 1-.45 1-1s-.45-1-1-1zm0-4H3c-.55 0-1 .45-1 1s.45 1 1 1h10c.55 0 1-.45 1-1s-.45-1-1-1zM3 16h6c.55 0 1-.45 1-1s-.45-1-1-1H3c-.55 0-1 .45-1 1s.45 1 1 1zm19.21-3.79.09.09c.39.39.39 1.02 0 1.41l-5.58 5.59c-.39.39-1.02.39-1.41 0l-3.09-3.09a.9959.9959 0 0 1 0-1.41l.09-.09c.39-.39 1.02-.39 1.41 0l2.3 2.3 4.78-4.79c.38-.4 1.02-.4 1.41-.01z"
}), 'PlaylistAddCheckRounded');
|
// Generated by CoffeeScript 1.11.1
/*
clientside HAML compiler for Javascript and Coffeescript (Version 5)
Copyright 2011-12, Ronald Holshausen (https://github.com/uglyog)
Released under the MIT License (http://www.opensource.org/licenses/MIT)
*/
(function() {
var Buffer, CodeGenerator, CoffeeCodeGenerator, ElementGenerator, HamlRuntime, JsCodeGenerator, ProductionJsCodeGenerator, Tokeniser, filters, haml, root,
hasProp = {}.hasOwnProperty,
extend = 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; };
root = this;
/*
Haml runtime functions. These are used both by the compiler and the generated template functions
*/
HamlRuntime = {
/*
Taken from underscore.string.js escapeHTML, and replace the apos entity with character 39 so that it renders
correctly in IE7
*/
escapeHTML: function(str) {
return String(str || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'");
},
/*
Provides the implementation to preserve the whitespace as per the HAML reference
*/
perserveWhitespace: function(str) {
var i, out, re, result;
re = /<[a-zA-Z]+>[^<]*<\/[a-zA-Z]+>/g;
out = '';
i = 0;
result = re.exec(str);
if (result) {
while (result) {
out += str.substring(i, result.index);
out += result[0].replace(/\n/g, '
');
i = result.index + result[0].length;
result = re.exec(str);
}
out += str.substring(i);
} else {
out = str;
}
return out;
},
/*
Generates a error message including the current line in the source where the error occurred
*/
templateError: function(lineNumber, characterNumber, currentLine, error) {
var i, message;
message = error + " at line " + lineNumber + " and character " + characterNumber + ":\n" + currentLine + '\n';
i = 0;
while (i < characterNumber - 1) {
message += '-';
i++;
}
message += '^';
return message;
},
/*
Generates the attributes for the element by combining all the various sources together
*/
generateElementAttributes: function(context, id, classes, objRefFn, attrList, attrFunction, lineNumber, characterNumber, currentLine, handleError) {
var attr, attributes, className, e, ex, hash, html, object, objectId, value;
if (handleError == null) {
handleError = this._raiseError;
}
attributes = {};
attributes = this.combineAttributes(attributes, 'id', id);
if (classes.length > 0 && classes[0].length > 0) {
attributes = this.combineAttributes(attributes, 'class', classes);
}
if (attrList != null) {
for (attr in attrList) {
if (!hasProp.call(attrList, attr)) continue;
value = attrList[attr];
attributes = this.combineAttributes(attributes, attr, value);
}
}
if (objRefFn != null) {
try {
object = objRefFn.call(context, context);
if (object != null) {
objectId = null;
if (object.id != null) {
objectId = object.id;
} else if (object.get) {
objectId = object.get('id');
}
attributes = this.combineAttributes(attributes, 'id', objectId);
className = null;
if (object['class']) {
className = object['class'];
} else if (object.get) {
className = object.get('class');
}
attributes = this.combineAttributes(attributes, 'class', className);
}
} catch (error1) {
e = error1;
handleError(haml.HamlRuntime.templateError(lineNumber, characterNumber, currentLine, "Error evaluating object reference - " + e));
}
}
if (attrFunction != null) {
try {
hash = attrFunction.call(context, context);
if (hash != null) {
hash = this._flattenHash(null, hash);
for (attr in hash) {
if (!hasProp.call(hash, attr)) continue;
value = hash[attr];
attributes = this.combineAttributes(attributes, attr, value);
}
}
} catch (error1) {
ex = error1;
handleError(haml.HamlRuntime.templateError(lineNumber, characterNumber, currentLine, "Error evaluating attribute hash - " + ex));
}
}
html = '';
if (attributes) {
for (attr in attributes) {
if (!hasProp.call(attributes, attr)) continue;
if (haml.hasValue(attributes[attr])) {
if ((attr === 'id' || attr === 'for') && attributes[attr] instanceof Array) {
html += ' ' + attr + '="' + _(attributes[attr]).flatten().join('-') + '"';
} else if (attr === 'class' && attributes[attr] instanceof Array) {
html += ' ' + attr + '="' + _(attributes[attr]).flatten().join(' ') + '"';
} else {
html += ' ' + attr + '="' + haml.attrValue(attr, attributes[attr]) + '"';
}
}
}
}
return html;
},
/*
Returns a white space string with a length of indent * 2
*/
indentText: function(indent) {
var i, text;
text = '';
i = 0;
while (i < indent) {
text += ' ';
i++;
}
return text;
},
/*
Combines the attributes in the attributres hash with the given attribute and value
ID, FOR and CLASS attributes will expand to arrays when multiple values are provided
*/
combineAttributes: function(attributes, attrName, attrValue) {
var classes;
if (haml.hasValue(attrValue)) {
if (attrName === 'id' && attrValue.toString().length > 0) {
if (attributes && attributes.id instanceof Array) {
attributes.id.unshift(attrValue);
} else if (attributes && attributes.id) {
attributes.id = [attributes.id, attrValue];
} else if (attributes) {
attributes.id = attrValue;
} else {
attributes = {
id: attrValue
};
}
} else if (attrName === 'for' && attrValue.toString().length > 0) {
if (attributes && attributes['for'] instanceof Array) {
attributes['for'].unshift(attrValue);
} else if (attributes && attributes['for']) {
attributes['for'] = [attributes['for'], attrValue];
} else if (attributes) {
attributes['for'] = attrValue;
} else {
attributes = {
'for': attrValue
};
}
} else if (attrName === 'class') {
classes = [];
if (attrValue instanceof Array) {
classes = classes.concat(attrValue);
} else {
classes.push(attrValue);
}
if (attributes && attributes['class']) {
attributes['class'] = attributes['class'].concat(classes);
} else if (attributes) {
attributes['class'] = classes;
} else {
attributes = {
'class': classes
};
}
} else if (attrName !== 'id') {
attributes || (attributes = {});
attributes[attrName] = attrValue;
}
}
return attributes;
},
/*
Flattens a deeply nested hash into a single hash by combining the keys with a minus
*/
_flattenHash: function(rootKey, object) {
var attr, flattenedValue, key, keys, newKey, newValue, result, value;
result = {};
if (this._isHash(object)) {
for (attr in object) {
if (!hasProp.call(object, attr)) continue;
value = object[attr];
keys = [];
if (rootKey != null) {
keys.push(rootKey);
}
keys.push(attr);
key = keys.join('-');
flattenedValue = this._flattenHash(key, value);
if (this._isHash(flattenedValue)) {
for (newKey in flattenedValue) {
if (!hasProp.call(flattenedValue, newKey)) continue;
newValue = flattenedValue[newKey];
result[newKey] = newValue;
}
} else {
result[key] = flattenedValue;
}
}
} else if (rootKey != null) {
result[rootKey] = object;
} else {
result = object;
}
return result;
},
_isHash: function(object) {
return (object != null) && typeof object === 'object' && !(object instanceof Array || object instanceof Date);
},
_logError: function(message) {
return typeof console !== "undefined" && console !== null ? console.log(message) : void 0;
},
_raiseError: function(message) {
throw new Error(message);
},
/*
trims the first number of characters from a string
*/
trim: function(str, chars) {
return str.substring(chars);
}
};
/*
HAML Tokiniser: This class is responsible for parsing the haml source into tokens
*/
Tokeniser = (function() {
Tokeniser.prototype.currentLineMatcher = /[^\n]*/g;
Tokeniser.prototype.tokenMatchers = {
whitespace: /[ \t]+/g,
element: /%[a-zA-Z][a-zA-Z0-9]*/g,
idSelector: /#[a-zA-Z_\-][a-zA-Z0-9_\-]*/g,
classSelector: /\.[a-zA-Z0-9_\-]+/g,
identifier: /[a-zA-Z][a-zA-Z0-9\-]*/g,
quotedString: /[\'][^\'\n]*[\']/g,
quotedString2: /[\"][^\"\n]*[\"]/g,
comment: /\-#/g,
escapeHtml: /\&=/g,
unescapeHtml: /\!=/g,
objectReference: /\[[a-zA-Z_@][a-zA-Z0-9_]*\]/g,
doctype: /!!!/g,
continueLine: /\|\s*\n/g,
filter: /:\w+/g
};
function Tokeniser(options) {
var errorFn, successFn, template;
this.buffer = null;
this.bufferIndex = null;
this.prevToken = null;
this.token = null;
if (options.templateId != null) {
template = document.getElementById(options.templateId);
if (template) {
this.buffer = template.text;
this.bufferIndex = 0;
} else {
throw "Did not find a template with ID '" + options.templateId + "'";
}
} else if (options.template != null) {
this.buffer = options.template;
this.bufferIndex = 0;
} else if (options.templateUrl != null) {
errorFn = function(jqXHR, textStatus, errorThrown) {
throw "Failed to fetch haml template at URL " + options.templateUrl + ": " + textStatus + " " + errorThrown;
};
successFn = (function(_this) {
return function(data) {
_this.buffer = data;
return _this.bufferIndex = 0;
};
})(this);
jQuery.ajax({
url: options.templateUrl,
success: successFn,
error: errorFn,
dataType: 'text',
async: false,
beforeSend: function(xhr) {
return xhr.withCredentials = true;
}
});
}
}
/*
Try to match a token with the given regexp
*/
Tokeniser.prototype.matchToken = function(matcher) {
var result;
matcher.lastIndex = this.bufferIndex;
result = matcher.exec(this.buffer);
if ((result != null ? result.index : void 0) === this.bufferIndex) {
return result[0];
}
};
/*
Match a multi-character token
*/
Tokeniser.prototype.matchMultiCharToken = function(matcher, token, tokenStr) {
var matched, ref;
if (!this.token) {
matched = this.matchToken(matcher);
if (matched) {
this.token = token;
this.token.tokenString = (ref = typeof tokenStr === "function" ? tokenStr(matched) : void 0) != null ? ref : matched;
this.token.matched = matched;
return this.advanceCharsInBuffer(matched.length);
}
}
};
/*
Match a single character token
*/
Tokeniser.prototype.matchSingleCharToken = function(ch, token) {
if (!this.token && this.buffer.charAt(this.bufferIndex) === ch) {
this.token = token;
this.token.tokenString = ch;
this.token.matched = ch;
return this.advanceCharsInBuffer(1);
}
};
/*
Match and return the next token in the input buffer
*/
Tokeniser.prototype.getNextToken = function() {
var ch, ch1, str;
if (isNaN(this.bufferIndex)) {
throw haml.HamlRuntime.templateError(this.lineNumber, this.characterNumber, this.currentLine, "An internal parser error has occurred in the HAML parser");
}
this.prevToken = this.token;
this.token = null;
if (this.buffer === null || this.buffer.length === this.bufferIndex) {
this.token = {
eof: true,
token: 'EOF'
};
} else {
this.initLine();
if (!this.token) {
ch = this.buffer.charCodeAt(this.bufferIndex);
ch1 = this.buffer.charCodeAt(this.bufferIndex + 1);
if (ch === 10 || (ch === 13 && ch1 === 10)) {
this.token = {
eol: true,
token: 'EOL'
};
if (ch === 13 && ch1 === 10) {
this.advanceCharsInBuffer(2);
this.token.matched = String.fromCharCode(ch) + String.fromCharCode(ch1);
} else {
this.advanceCharsInBuffer(1);
this.token.matched = String.fromCharCode(ch);
}
this.characterNumber = 0;
this.currentLine = this.getCurrentLine();
}
}
this.matchMultiCharToken(this.tokenMatchers.whitespace, {
ws: true,
token: 'WS'
});
this.matchMultiCharToken(this.tokenMatchers.continueLine, {
continueLine: true,
token: 'CONTINUELINE'
});
this.matchMultiCharToken(this.tokenMatchers.element, {
element: true,
token: 'ELEMENT'
}, function(matched) {
return matched.substring(1);
});
this.matchMultiCharToken(this.tokenMatchers.idSelector, {
idSelector: true,
token: 'ID'
}, function(matched) {
return matched.substring(1);
});
this.matchMultiCharToken(this.tokenMatchers.classSelector, {
classSelector: true,
token: 'CLASS'
}, function(matched) {
return matched.substring(1);
});
this.matchMultiCharToken(this.tokenMatchers.identifier, {
identifier: true,
token: 'IDENTIFIER'
});
this.matchMultiCharToken(this.tokenMatchers.doctype, {
doctype: true,
token: 'DOCTYPE'
});
this.matchMultiCharToken(this.tokenMatchers.filter, {
filter: true,
token: 'FILTER'
}, function(matched) {
return matched.substring(1);
});
if (!this.token) {
str = this.matchToken(this.tokenMatchers.quotedString);
if (!str) {
str = this.matchToken(this.tokenMatchers.quotedString2);
}
if (str) {
this.token = {
string: true,
token: 'STRING',
tokenString: str.substring(1, str.length - 1),
matched: str
};
this.advanceCharsInBuffer(str.length);
}
}
this.matchMultiCharToken(this.tokenMatchers.comment, {
comment: true,
token: 'COMMENT'
});
this.matchMultiCharToken(this.tokenMatchers.escapeHtml, {
escapeHtml: true,
token: 'ESCAPEHTML'
});
this.matchMultiCharToken(this.tokenMatchers.unescapeHtml, {
unescapeHtml: true,
token: 'UNESCAPEHTML'
});
this.matchMultiCharToken(this.tokenMatchers.objectReference, {
objectReference: true,
token: 'OBJECTREFERENCE'
}, function(matched) {
return matched.substring(1, matched.length - 1);
});
if (!this.token && this.buffer && this.buffer.charAt(this.bufferIndex) === '{' && !this.prevToken.ws) {
this.matchJavascriptHash();
}
this.matchSingleCharToken('(', {
openBracket: true,
token: 'OPENBRACKET'
});
this.matchSingleCharToken(')', {
closeBracket: true,
token: 'CLOSEBRACKET'
});
this.matchSingleCharToken('=', {
equal: true,
token: 'EQUAL'
});
this.matchSingleCharToken('/', {
slash: true,
token: 'SLASH'
});
this.matchSingleCharToken('!', {
exclamation: true,
token: 'EXCLAMATION'
});
this.matchSingleCharToken('-', {
minus: true,
token: 'MINUS'
});
this.matchSingleCharToken('&', {
amp: true,
token: 'AMP'
});
this.matchSingleCharToken('<', {
lt: true,
token: 'LT'
});
this.matchSingleCharToken('>', {
gt: true,
token: 'GT'
});
this.matchSingleCharToken('~', {
tilde: true,
token: 'TILDE'
});
if (this.token === null) {
this.token = {
unknown: true,
token: 'UNKNOWN',
matched: this.buffer.charAt(this.bufferIndex)
};
this.advanceCharsInBuffer(1);
}
}
return this.token;
};
/*
Look ahead a number of tokens and return the token found
*/
Tokeniser.prototype.lookAhead = function(numberOfTokens) {
var bufferIndex, characterNumber, currentLine, currentToken, i, lineNumber, prevToken, token;
token = null;
if (numberOfTokens > 0) {
currentToken = this.token;
prevToken = this.prevToken;
currentLine = this.currentLine;
lineNumber = this.lineNumber;
characterNumber = this.characterNumber;
bufferIndex = this.bufferIndex;
i = 0;
while (i++ < numberOfTokens) {
token = this.getNextToken();
}
this.token = currentToken;
this.prevToken = prevToken;
this.currentLine = currentLine;
this.lineNumber = lineNumber;
this.characterNumber = characterNumber;
this.bufferIndex = bufferIndex;
}
return token;
};
/*
Initilise the line and character counters
*/
Tokeniser.prototype.initLine = function() {
if (!this.currentLine && this.currentLine !== "") {
this.currentLine = this.getCurrentLine();
this.lineNumber = 1;
return this.characterNumber = 0;
}
};
/*
Returns the current line in the input buffer
*/
Tokeniser.prototype.getCurrentLine = function(index) {
var line;
this.currentLineMatcher.lastIndex = this.bufferIndex + (index != null ? index : 0);
line = this.currentLineMatcher.exec(this.buffer);
if (line) {
return line[0];
} else {
return '';
}
};
/*
Returns an error string filled out with the line and character counters
*/
Tokeniser.prototype.parseError = function(error) {
return haml.HamlRuntime.templateError(this.lineNumber, this.characterNumber, this.currentLine, error);
};
/*
Skips to the end of the line and returns the string that was skipped
*/
Tokeniser.prototype.skipToEOLorEOF = function() {
var contents, line, text;
text = '';
if (!(this.token.eof || this.token.eol)) {
if (this.token.matched != null) {
text += this.token.matched;
}
this.currentLineMatcher.lastIndex = this.bufferIndex;
line = this.currentLineMatcher.exec(this.buffer);
if (line && line.index === this.bufferIndex) {
contents = (_.str || _).rtrim(line[0]);
if ((_.str || _).endsWith(contents, '|')) {
text += contents.substring(0, contents.length - 1);
this.advanceCharsInBuffer(contents.length - 1);
this.getNextToken();
text += this.parseMultiLine();
} else {
text += line[0];
this.advanceCharsInBuffer(line[0].length);
this.getNextToken();
}
}
}
return text;
};
/*
Parses a multiline code block and returns the parsed text
*/
Tokeniser.prototype.parseMultiLine = function() {
var contents, line, text;
text = '';
while (this.token.continueLine) {
this.currentLineMatcher.lastIndex = this.bufferIndex;
line = this.currentLineMatcher.exec(this.buffer);
if (line && line.index === this.bufferIndex) {
contents = (_.str || _).rtrim(line[0]);
if ((_.str || _).endsWith(contents, '|')) {
text += contents.substring(0, contents.length - 1);
this.advanceCharsInBuffer(contents.length - 1);
}
this.getNextToken();
}
}
return text;
};
/*
Advances the input buffer pointer by a number of characters, updating the line and character counters
*/
Tokeniser.prototype.advanceCharsInBuffer = function(numChars) {
var ch, ch1, i;
i = 0;
while (i < numChars) {
ch = this.buffer.charCodeAt(this.bufferIndex + i);
ch1 = this.buffer.charCodeAt(this.bufferIndex + i + 1);
if (ch === 13 && ch1 === 10) {
this.lineNumber++;
this.characterNumber = 0;
this.currentLine = this.getCurrentLine(i);
i++;
} else if (ch === 10) {
this.lineNumber++;
this.characterNumber = 0;
this.currentLine = this.getCurrentLine(i);
} else {
this.characterNumber++;
}
i++;
}
return this.bufferIndex += numChars;
};
/*
Returns the current line and character counters
*/
Tokeniser.prototype.currentParsePoint = function() {
return {
lineNumber: this.lineNumber,
characterNumber: this.characterNumber,
currentLine: this.currentLine
};
};
/*
Pushes back the current token onto the front of the input buffer
*/
Tokeniser.prototype.pushBackToken = function() {
if (!this.token.eof) {
this.bufferIndex -= this.token.matched.length;
return this.token = this.prevToken;
}
};
/*
Is the current token an end of line or end of input buffer
*/
Tokeniser.prototype.isEolOrEof = function() {
return this.token.eol || this.token.eof;
};
/*
Match a Javascript Hash {...}
*/
Tokeniser.prototype.matchJavascriptHash = function() {
var braceCount, ch, chCode, characterNumberStart, currentIndent, i, lineNumberStart;
currentIndent = this.calculateCurrentIndent();
i = this.bufferIndex + 1;
characterNumberStart = this.characterNumber;
lineNumberStart = this.lineNumber;
braceCount = 1;
while (i < this.buffer.length && (braceCount > 1 || this.buffer.charAt(i) !== '}')) {
ch = this.buffer.charAt(i);
chCode = this.buffer.charCodeAt(i);
if (ch === '{') {
braceCount++;
i++;
} else if (ch === '}') {
braceCount--;
i++;
} else if (chCode === 10 || chCode === 13) {
i++;
} else {
i++;
}
}
if (i === this.buffer.length) {
this.characterNumber = characterNumberStart + 1;
this.lineNumber = lineNumberStart;
throw this.parseError('Error parsing attribute hash - Did not find a terminating "}"');
} else {
this.token = {
attributeHash: true,
token: 'ATTRHASH',
tokenString: this.buffer.substring(this.bufferIndex, i + 1),
matched: this.buffer.substring(this.bufferIndex, i + 1)
};
return this.advanceCharsInBuffer(i - this.bufferIndex + 1);
}
};
/*
Calculate the indent value of the current line
*/
Tokeniser.prototype.calculateCurrentIndent = function() {
var result;
this.tokenMatchers.whitespace.lastIndex = 0;
result = this.tokenMatchers.whitespace.exec(this.currentLine);
if ((result != null ? result.index : void 0) === 0) {
return this.calculateIndent(result[0]);
} else {
return 0;
}
};
/*
Calculate the indent level of the provided whitespace
*/
Tokeniser.prototype.calculateIndent = function(whitespace) {
var i, indent;
indent = 0;
i = 0;
while (i < whitespace.length) {
if (whitespace.charCodeAt(i) === 9) {
indent += 2;
} else {
indent++;
}
i++;
}
return Math.floor((indent + 1) / 2);
};
return Tokeniser;
})();
/*
Provides buffering between the generated javascript and html contents
*/
Buffer = (function() {
function Buffer(generator1) {
this.generator = generator1;
this.buffer = '';
this.outputBuffer = '';
}
Buffer.prototype.append = function(str) {
if ((this.generator != null) && this.buffer.length === 0) {
this.generator.mark();
}
if ((str != null ? str.length : void 0) > 0) {
return this.buffer += str;
}
};
Buffer.prototype.appendToOutputBuffer = function(str) {
if ((str != null ? str.length : void 0) > 0) {
this.flush();
return this.outputBuffer += str;
}
};
Buffer.prototype.flush = function() {
var ref;
if (((ref = this.buffer) != null ? ref.length : void 0) > 0) {
this.outputBuffer += this.generator.generateFlush(this.buffer);
}
return this.buffer = '';
};
Buffer.prototype.output = function() {
return this.outputBuffer;
};
Buffer.prototype.trimWhitespace = function() {
var ch, i;
if (this.buffer.length > 0) {
i = this.buffer.length - 1;
while (i > 0) {
ch = this.buffer.charAt(i);
if (this._isWhitespace(ch)) {
i--;
} else if (i > 1 && (ch === 'n' || ch === 't') && (this.buffer.charAt(i - 1) === '\\')) {
i -= 2;
} else {
break;
}
}
if (i > 0 && i < this.buffer.length - 1) {
return this.buffer = this.buffer.substring(0, i + 1);
} else if (i === 0 && this._isWhitespace(this.buffer.charAt(0))) {
return this.buffer = '';
}
}
};
Buffer.prototype._isWhitespace = function(ch) {
return ch === ' ' || ch === '\t' || ch === '\n';
};
return Buffer;
})();
/*
Common code shared across all code generators
*/
CodeGenerator = (function() {
function CodeGenerator() {}
CodeGenerator.prototype.embeddedCodeBlockMatcher = /#{([^}]*)}/g;
CodeGenerator.prototype.closeElements = function(indent, elementStack, tokeniser, generator) {
var i, results;
i = elementStack.length - 1;
results = [];
while (i >= indent) {
results.push(this.closeElement(i--, elementStack, tokeniser, generator));
}
return results;
};
CodeGenerator.prototype.closeElement = function(indent, elementStack, tokeniser, generator) {
var innerWhitespace, outerWhitespace;
if (elementStack[indent]) {
generator.setIndent(indent);
if (elementStack[indent].htmlComment) {
generator.outputBuffer.append(HamlRuntime.indentText(indent) + '-->' + elementStack[indent].eol);
} else if (elementStack[indent].htmlConditionalComment) {
generator.outputBuffer.append(HamlRuntime.indentText(indent) + '<![endif]-->' + elementStack[indent].eol);
} else if (elementStack[indent].block) {
generator.closeOffCodeBlock(tokeniser);
} else if (elementStack[indent].fnBlock) {
generator.closeOffFunctionBlock(tokeniser);
} else {
innerWhitespace = !elementStack[indent].tagOptions || elementStack[indent].tagOptions.innerWhitespace;
if (innerWhitespace) {
generator.outputBuffer.append(HamlRuntime.indentText(indent));
} else {
generator.outputBuffer.trimWhitespace();
}
generator.outputBuffer.append('</' + elementStack[indent].tag + '>');
outerWhitespace = !elementStack[indent].tagOptions || elementStack[indent].tagOptions.outerWhitespace;
if (haml._parentInnerWhitespace(elementStack, indent) && outerWhitespace) {
generator.outputBuffer.append('\n');
}
}
elementStack[indent] = null;
return generator.mark();
}
};
CodeGenerator.prototype.openElement = function(currentParsePoint, indent, identifier, id, classes, objectRef, attributeList, attributeHash, elementStack, tagOptions, generator) {
var element, parentInnerWhitespace, tagOuterWhitespace;
element = identifier.length === 0 ? "div" : identifier;
parentInnerWhitespace = haml._parentInnerWhitespace(elementStack, indent);
tagOuterWhitespace = !tagOptions || tagOptions.outerWhitespace;
if (!tagOuterWhitespace) {
generator.outputBuffer.trimWhitespace();
}
if (indent > 0 && parentInnerWhitespace && tagOuterWhitespace) {
generator.outputBuffer.append(HamlRuntime.indentText(indent));
}
generator.outputBuffer.append('<' + element);
if (attributeHash.length > 0 || objectRef.length > 0) {
generator.generateCodeForDynamicAttributes(id, classes, attributeList, attributeHash, objectRef, currentParsePoint);
} else {
generator.outputBuffer.append(HamlRuntime.generateElementAttributes(null, id, classes, null, attributeList, null, currentParsePoint.lineNumber, currentParsePoint.characterNumber, currentParsePoint.currentLine));
}
if (tagOptions.selfClosingTag) {
generator.outputBuffer.append("/>");
if (tagOptions.outerWhitespace) {
return generator.outputBuffer.append("\n");
}
} else {
generator.outputBuffer.append(">");
elementStack[indent] = {
tag: element,
tagOptions: tagOptions
};
if (tagOptions.innerWhitespace) {
return generator.outputBuffer.append("\n");
}
}
};
return CodeGenerator;
})();
/*
Code generator that generates a Javascript function body
*/
JsCodeGenerator = (function(superClass) {
extend(JsCodeGenerator, superClass);
function JsCodeGenerator(options1) {
this.options = options1;
this.outputBuffer = new haml.Buffer(this);
}
/*
Append a line with embedded javascript code
*/
JsCodeGenerator.prototype.appendEmbeddedCode = function(indentText, expression, escapeContents, perserveWhitespace, currentParsePoint) {
this.outputBuffer.flush();
this.outputBuffer.appendToOutputBuffer(indentText + 'try {\n');
this.outputBuffer.appendToOutputBuffer(indentText + ' var value = eval("' + (_.str || _).trim(expression).replace(/"/g, '\\"').replace(/\\n/g, '\\\\n') + '");\n');
this.outputBuffer.appendToOutputBuffer(indentText + ' value = value === null ? "" : value;');
if (escapeContents) {
this.outputBuffer.appendToOutputBuffer(indentText + ' html.push(haml.HamlRuntime.escapeHTML(String(value)));\n');
} else if (perserveWhitespace) {
this.outputBuffer.appendToOutputBuffer(indentText + ' html.push(haml.HamlRuntime.perserveWhitespace(String(value)));\n');
} else {
this.outputBuffer.appendToOutputBuffer(indentText + ' html.push(String(value));\n');
}
this.outputBuffer.appendToOutputBuffer(indentText + '} catch (e) {\n');
this.outputBuffer.appendToOutputBuffer(indentText + ' handleError(haml.HamlRuntime.templateError(' + currentParsePoint.lineNumber + ', ' + currentParsePoint.characterNumber + ', "' + this.escapeCode(currentParsePoint.currentLine) + '",\n');
this.outputBuffer.appendToOutputBuffer(indentText + ' "Error evaluating expression - " + e));\n');
return this.outputBuffer.appendToOutputBuffer(indentText + '}\n');
};
/*
Initilising the output buffer with any variables or code
*/
JsCodeGenerator.prototype.initOutput = function() {
var ref;
if ((ref = this.options) != null ? ref.tolerateFaults : void 0) {
this.outputBuffer.appendToOutputBuffer(' var handleError = haml.HamlRuntime._logError;');
} else {
this.outputBuffer.appendToOutputBuffer(' var handleError = haml.HamlRuntime._raiseError;');
}
return this.outputBuffer.appendToOutputBuffer('var html = [];\nvar hashFunction = null, hashObject = null, objRef = null, objRefFn = null;\nwith (context || {}) {');
};
/*
Flush and close the output buffer and return the contents
*/
JsCodeGenerator.prototype.closeAndReturnOutput = function() {
this.outputBuffer.flush();
return this.outputBuffer.output() + ' }\n return html.join("");\n';
};
/*
Append a line of code to the output buffer
*/
JsCodeGenerator.prototype.appendCodeLine = function(line, eol) {
this.outputBuffer.flush();
this.outputBuffer.appendToOutputBuffer(HamlRuntime.indentText(this.indent));
this.outputBuffer.appendToOutputBuffer(line);
return this.outputBuffer.appendToOutputBuffer(eol);
};
/*
Does the current line end with a function declaration?
*/
JsCodeGenerator.prototype.lineMatchesStartFunctionBlock = function(line) {
return line.match(/function\s*\((,?\s*\w+)*\)\s*\{\s*$/);
};
/*
Does the current line end with a starting code block
*/
JsCodeGenerator.prototype.lineMatchesStartBlock = function(line) {
return line.match(/\{\s*$/);
};
/*
Generate the code to close off a code block
*/
JsCodeGenerator.prototype.closeOffCodeBlock = function(tokeniser) {
if (!(tokeniser.token.minus && tokeniser.matchToken(/\s*\}/g))) {
this.outputBuffer.flush();
return this.outputBuffer.appendToOutputBuffer(HamlRuntime.indentText(this.indent) + '}\n');
}
};
/*
Generate the code to close off a function parameter
*/
JsCodeGenerator.prototype.closeOffFunctionBlock = function(tokeniser) {
if (!(tokeniser.token.minus && tokeniser.matchToken(/\s*\}/g))) {
this.outputBuffer.flush();
return this.outputBuffer.appendToOutputBuffer(HamlRuntime.indentText(this.indent) + '});\n');
}
};
/*
Generate the code for dynamic attributes ({} form)
*/
JsCodeGenerator.prototype.generateCodeForDynamicAttributes = function(id, classes, attributeList, attributeHash, objectRef, currentParsePoint) {
this.outputBuffer.flush();
if (attributeHash.length > 0) {
attributeHash = this.replaceReservedWordsInHash(attributeHash);
this.outputBuffer.appendToOutputBuffer(' hashFunction = function () { return eval("hashObject = ' + attributeHash.replace(/"/g, '\\"').replace(/\n/g, '\\n') + '"); };\n');
} else {
this.outputBuffer.appendToOutputBuffer(' hashFunction = null;\n');
}
if (objectRef.length > 0) {
this.outputBuffer.appendToOutputBuffer(' objRefFn = function () { return eval("objRef = ' + objectRef.replace(/"/g, '\\"') + '"); };\n');
} else {
this.outputBuffer.appendToOutputBuffer(' objRefFn = null;\n');
}
return this.outputBuffer.appendToOutputBuffer(' html.push(haml.HamlRuntime.generateElementAttributes(context, "' + id + '", ["' + classes.join('","') + '"], objRefFn, ' + JSON.stringify(attributeList) + ', hashFunction, ' + currentParsePoint.lineNumber + ', ' + currentParsePoint.characterNumber + ', "' + this.escapeCode(currentParsePoint.currentLine) + '", handleError));\n');
};
/*
Clean any reserved words in the given hash
*/
JsCodeGenerator.prototype.replaceReservedWordsInHash = function(hash) {
var j, len, ref, reservedWord, resultHash;
resultHash = hash;
ref = ['class', 'for'];
for (j = 0, len = ref.length; j < len; j++) {
reservedWord = ref[j];
resultHash = resultHash.replace(reservedWord + ':', '"' + reservedWord + '":');
}
return resultHash;
};
/*
Escape the line so it is safe to put into a javascript string
*/
JsCodeGenerator.prototype.escapeCode = function(jsStr) {
return jsStr.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
};
/*
Generate a function from the function body
*/
JsCodeGenerator.prototype.generateJsFunction = function(functionBody) {
var e;
try {
return new Function('context', functionBody);
} catch (error1) {
e = error1;
throw "Incorrect embedded code has resulted in an invalid Haml function - " + e + "\nGenerated Function:\n" + functionBody;
}
};
/*
Generate the code required to support a buffer flush
*/
JsCodeGenerator.prototype.generateFlush = function(bufferStr) {
return ' html.push("' + this.escapeCode(bufferStr) + '");\n';
};
/*
Set the current indent level
*/
JsCodeGenerator.prototype.setIndent = function(indent) {
return this.indent = indent;
};
/*
Save the current indent level if required
*/
JsCodeGenerator.prototype.mark = function() {};
/*
Append the text contents to the buffer, expanding any embedded code
*/
JsCodeGenerator.prototype.appendTextContents = function(text, shouldInterpolate, currentParsePoint, options) {
if (options == null) {
options = {};
}
if (shouldInterpolate && text.match(/#{[^}]*}/)) {
return this.interpolateString(text, currentParsePoint, options);
} else {
return this.outputBuffer.append(this.processText(text, options));
}
};
/*
Interpolate any embedded code in the text
*/
JsCodeGenerator.prototype.interpolateString = function(text, currentParsePoint, options) {
var index, precheedingChar, precheedingChar2, result;
index = 0;
result = this.embeddedCodeBlockMatcher.exec(text);
while (result) {
if (result.index > 0) {
precheedingChar = text.charAt(result.index - 1);
}
if (result.index > 1) {
precheedingChar2 = text.charAt(result.index - 2);
}
if (precheedingChar === '\\' && precheedingChar2 !== '\\') {
if (result.index !== 0) {
this.outputBuffer.append(this.processText(text.substring(index, result.index - 1), options));
}
this.outputBuffer.append(this.processText(result[0]), options);
} else {
this.outputBuffer.append(this.processText(text.substring(index, result.index)), options);
this.appendEmbeddedCode(HamlRuntime.indentText(this.indent + 1), result[1], options.escapeHTML, options.perserveWhitespace, currentParsePoint);
}
index = this.embeddedCodeBlockMatcher.lastIndex;
result = this.embeddedCodeBlockMatcher.exec(text);
}
if (index < text.length) {
return this.outputBuffer.append(this.processText(text.substring(index), options));
}
};
/*
process text based on escape and preserve flags
*/
JsCodeGenerator.prototype.processText = function(text, options) {
if (options != null ? options.escapeHTML : void 0) {
return haml.HamlRuntime.escapeHTML(text);
} else if (options != null ? options.perserveWhitespace : void 0) {
return haml.HamlRuntime.perserveWhitespace(text);
} else {
return text;
}
};
return JsCodeGenerator;
})(CodeGenerator);
/*
Code generator that generates javascript code without runtime evaluation
*/
ProductionJsCodeGenerator = (function(superClass) {
extend(ProductionJsCodeGenerator, superClass);
function ProductionJsCodeGenerator() {
return ProductionJsCodeGenerator.__super__.constructor.apply(this, arguments);
}
/*
Append a line with embedded javascript code
*/
ProductionJsCodeGenerator.prototype.appendEmbeddedCode = function(indentText, expression, escapeContents, perserveWhitespace, currentParsePoint) {
this.outputBuffer.flush();
this.outputBuffer.appendToOutputBuffer(indentText + ' value = ' + (_.str || _).trim(expression) + ';\n');
this.outputBuffer.appendToOutputBuffer(indentText + ' value = value === null ? "" : value;');
if (escapeContents) {
return this.outputBuffer.appendToOutputBuffer(indentText + ' html.push(haml.HamlRuntime.escapeHTML(String(value)));\n');
} else if (perserveWhitespace) {
return this.outputBuffer.appendToOutputBuffer(indentText + ' html.push(haml.HamlRuntime.perserveWhitespace(String(value)));\n');
} else {
return this.outputBuffer.appendToOutputBuffer(indentText + ' html.push(String(value));\n');
}
};
/*
Generate the code for dynamic attributes ({} form)
*/
ProductionJsCodeGenerator.prototype.generateCodeForDynamicAttributes = function(id, classes, attributeList, attributeHash, objectRef, currentParsePoint) {
this.outputBuffer.flush();
if (attributeHash.length > 0) {
attributeHash = this.replaceReservedWordsInHash(attributeHash);
this.outputBuffer.appendToOutputBuffer(' hashFunction = function () { return ' + attributeHash + '; };\n');
} else {
this.outputBuffer.appendToOutputBuffer(' hashFunction = null;\n');
}
if (objectRef.length > 0) {
this.outputBuffer.appendToOutputBuffer(' objRefFn = function () { return ' + objectRef + '; };\n');
} else {
this.outputBuffer.appendToOutputBuffer(' objRefFn = null;\n');
}
return this.outputBuffer.appendToOutputBuffer(' html.push(haml.HamlRuntime.generateElementAttributes(context, "' + id + '", ["' + classes.join('","') + '"], objRefFn, ' + JSON.stringify(attributeList) + ', hashFunction, ' + currentParsePoint.lineNumber + ', ' + currentParsePoint.characterNumber + ', "' + this.escapeCode(currentParsePoint.currentLine) + '"));\n');
};
/*
Initilising the output buffer with any variables or code
*/
ProductionJsCodeGenerator.prototype.initOutput = function() {
return this.outputBuffer.appendToOutputBuffer(' var html = [];\n' + ' var hashFunction = null, hashObject = null, objRef = null, objRefFn = null, value= null;\n with (context || {}) {\n');
};
return ProductionJsCodeGenerator;
})(JsCodeGenerator);
/*
Code generator that generates a coffeescript function body
*/
CoffeeCodeGenerator = (function(superClass) {
extend(CoffeeCodeGenerator, superClass);
function CoffeeCodeGenerator(options1) {
this.options = options1;
this.outputBuffer = new haml.Buffer(this);
}
CoffeeCodeGenerator.prototype.appendEmbeddedCode = function(indentText, expression, escapeContents, perserveWhitespace, currentParsePoint) {
var indent;
this.outputBuffer.flush();
indent = this.calcCodeIndent();
this.outputBuffer.appendToOutputBuffer(indent + "try\n");
this.outputBuffer.appendToOutputBuffer(indent + " exp = CoffeeScript.compile('" + expression.replace(/'/g, "\\'").replace(/\\n/g, '\\\\n') + "', bare: true)\n");
this.outputBuffer.appendToOutputBuffer(indent + " value = eval(exp)\n");
this.outputBuffer.appendToOutputBuffer(indent + " value ?= ''\n");
if (escapeContents) {
this.outputBuffer.appendToOutputBuffer(indent + " html.push(haml.HamlRuntime.escapeHTML(String(value)))\n");
} else if (perserveWhitespace) {
this.outputBuffer.appendToOutputBuffer(indent + " html.push(haml.HamlRuntime.perserveWhitespace(String(value)))\n");
} else {
this.outputBuffer.appendToOutputBuffer(indent + " html.push(String(value))\n");
}
this.outputBuffer.appendToOutputBuffer(indent + "catch e \n");
this.outputBuffer.appendToOutputBuffer(indent + " handleError new Error(haml.HamlRuntime.templateError(" + currentParsePoint.lineNumber + ", " + currentParsePoint.characterNumber + ", '" + this.escapeCode(currentParsePoint.currentLine) + "',\n");
return this.outputBuffer.appendToOutputBuffer(indent + " 'Error evaluating expression - ' + e))\n");
};
CoffeeCodeGenerator.prototype.initOutput = function() {
var ref;
if ((ref = this.options) != null ? ref.tolerateFaults : void 0) {
this.outputBuffer.appendToOutputBuffer('handleError = haml.HamlRuntime._logError\n');
} else {
this.outputBuffer.appendToOutputBuffer('handleError = haml.HamlRuntime._raiseError\n');
}
return this.outputBuffer.appendToOutputBuffer('html = []\n');
};
CoffeeCodeGenerator.prototype.closeAndReturnOutput = function() {
this.outputBuffer.flush();
return this.outputBuffer.output() + 'return html.join("")\n';
};
CoffeeCodeGenerator.prototype.appendCodeLine = function(line, eol) {
this.outputBuffer.flush();
this.outputBuffer.appendToOutputBuffer(this.calcCodeIndent());
this.outputBuffer.appendToOutputBuffer((_.str || _).trim(line));
this.outputBuffer.appendToOutputBuffer(eol);
return this.prevCodeIndent = this.indent;
};
CoffeeCodeGenerator.prototype.lineMatchesStartFunctionBlock = function(line) {
return line.match(/\) [\-=]>\s*$/);
};
CoffeeCodeGenerator.prototype.lineMatchesStartBlock = function(line) {
return true;
};
CoffeeCodeGenerator.prototype.closeOffCodeBlock = function(tokeniser) {
return this.outputBuffer.flush();
};
CoffeeCodeGenerator.prototype.closeOffFunctionBlock = function(tokeniser) {
return this.outputBuffer.flush();
};
CoffeeCodeGenerator.prototype.generateCodeForDynamicAttributes = function(id, classes, attributeList, attributeHash, objectRef, currentParsePoint) {
var indent;
this.outputBuffer.flush();
indent = this.calcCodeIndent();
if (attributeHash.length > 0) {
attributeHash = this.replaceReservedWordsInHash(attributeHash);
this.outputBuffer.appendToOutputBuffer(indent + "hashFunction = () -> s = CoffeeScript.compile('" + attributeHash.replace(/'/g, "\\'").replace(/\n/g, '\\n') + "', bare: true); eval 'hashObject = ' + s\n");
} else {
this.outputBuffer.appendToOutputBuffer(indent + "hashFunction = null\n");
}
if (objectRef.length > 0) {
this.outputBuffer.appendToOutputBuffer(indent + "objRefFn = () -> s = CoffeeScript.compile('" + objectRef.replace(/'/g, "\\'") + "', bare: true); eval 'objRef = ' + s\n");
} else {
this.outputBuffer.appendToOutputBuffer(indent + "objRefFn = null\n");
}
return this.outputBuffer.appendToOutputBuffer(indent + "html.push(haml.HamlRuntime.generateElementAttributes(this, '" + id + "', ['" + classes.join("','") + "'], objRefFn ? null, " + JSON.stringify(attributeList) + ", hashFunction ? null, " + currentParsePoint.lineNumber + ", " + currentParsePoint.characterNumber + ", '" + this.escapeCode(currentParsePoint.currentLine) + "', handleError))\n");
};
CoffeeCodeGenerator.prototype.replaceReservedWordsInHash = function(hash) {
var j, len, ref, reservedWord, resultHash;
resultHash = hash;
ref = ['class', 'for'];
for (j = 0, len = ref.length; j < len; j++) {
reservedWord = ref[j];
resultHash = resultHash.replace(reservedWord + ':', "'" + reservedWord + "':");
}
return resultHash;
};
/*
Escapes the string for insertion into the generated code. Embedded code blocks in strings must not be escaped
*/
CoffeeCodeGenerator.prototype.escapeCode = function(str) {
var index, outString, precheedingChar, precheedingChar2, result;
outString = '';
index = 0;
result = this.embeddedCodeBlockMatcher.exec(str);
while (result) {
if (result.index > 0) {
precheedingChar = str.charAt(result.index - 1);
}
if (result.index > 1) {
precheedingChar2 = str.charAt(result.index - 2);
}
if (precheedingChar === '\\' && precheedingChar2 !== '\\') {
if (result.index !== 0) {
outString += this._escapeText(str.substring(index, result.index - 1));
}
outString += this._escapeText('\\' + result[0]);
} else {
outString += this._escapeText(str.substring(index, result.index));
outString += result[0];
}
index = this.embeddedCodeBlockMatcher.lastIndex;
result = this.embeddedCodeBlockMatcher.exec(str);
}
if (index < str.length) {
outString += this._escapeText(str.substring(index));
}
return outString;
};
CoffeeCodeGenerator.prototype._escapeText = function(text) {
return text.replace(/\\/g, '\\\\').replace(/'/g, '\\\'').replace(/"/g, '\\\"').replace(/\n/g, '\\n').replace(/(^|[^\\]{2})\\\\#{/g, '$1\\#{');
};
/*
Generates the javascript function by compiling the given code with coffeescript compiler
*/
CoffeeCodeGenerator.prototype.generateJsFunction = function(functionBody) {
var e, fn;
try {
fn = CoffeeScript.compile(functionBody, {
bare: true
});
return new Function(fn);
} catch (error1) {
e = error1;
throw "Incorrect embedded code has resulted in an invalid Haml function - " + e + "\nGenerated Function:\n" + fn;
}
};
CoffeeCodeGenerator.prototype.generateFlush = function(bufferStr) {
return this.calcCodeIndent() + "html.push('" + this.escapeCode(bufferStr) + "')\n";
};
CoffeeCodeGenerator.prototype.setIndent = function(indent) {
return this.indent = indent;
};
CoffeeCodeGenerator.prototype.mark = function() {
return this.prevIndent = this.indent;
};
CoffeeCodeGenerator.prototype.calcCodeIndent = function() {
var codeIndent, i, j, ref, ref1, ref2;
codeIndent = 0;
for (i = j = 0, ref = this.indent; 0 <= ref ? j <= ref : j >= ref; i = 0 <= ref ? ++j : --j) {
if (((ref1 = this.elementStack[i]) != null ? ref1.block : void 0) || ((ref2 = this.elementStack[i]) != null ? ref2.fnBlock : void 0)) {
codeIndent += 1;
}
}
return HamlRuntime.indentText(codeIndent);
};
/*
Append the text contents to the buffer (interpolating embedded code not required for coffeescript)
*/
CoffeeCodeGenerator.prototype.appendTextContents = function(text, shouldInterpolate, currentParsePoint, options) {
var prefix, suffix;
if (shouldInterpolate && text.match(/#{[^}]*}/)) {
this.outputBuffer.flush();
prefix = suffix = '';
if (options != null ? options.escapeHTML : void 0) {
prefix = 'haml.HamlRuntime.escapeHTML(';
suffix = ')';
} else if (options != null ? options.perserveWhitespace : void 0) {
prefix = 'haml.HamlRuntime.perserveWhitespace(';
suffix = ')';
}
return this.outputBuffer.appendToOutputBuffer(this.calcCodeIndent() + 'html.push(' + prefix + '"' + this.escapeCode(text) + '"' + suffix + ')\n');
} else {
if (options != null ? options.escapeHTML : void 0) {
text = haml.HamlRuntime.escapeHTML(text);
}
if (options != null ? options.perserveWhitespace : void 0) {
text = haml.HamlRuntime.perserveWhitespace(text);
}
return this.outputBuffer.append(text);
}
};
return CoffeeCodeGenerator;
})(CodeGenerator);
if (!Array.prototype.peek) {
Array.prototype.peek = function() {
return this[this.length - 1];
};
}
/*
Code generator that generates a Javascript function body
to generate document elements.
*/
ElementGenerator = (function(superClass) {
extend(ElementGenerator, superClass);
function ElementGenerator(options1) {
this.options = options1;
this.outputBuffer = new haml.Buffer(this);
}
/*
Initilising the output buffer with any variables or code
*/
ElementGenerator.prototype.initOutput = function() {
var ref;
if ((ref = this.options) != null ? ref.tolerateFaults : void 0) {
this.outputBuffer.appendToOutputBuffer(' var handleError = haml.HamlRuntime._logError;');
} else {
this.outputBuffer.appendToOutputBuffer(' var handleError = haml.HamlRuntime._raiseError;');
}
return this.outputBuffer.appendToOutputBuffer('var hashFunction = null, hashObject = null, objRef = null, objRefFn = null, elm = null, parents = [];\nwith (context || {}) {\n');
};
/*
Flush and close the output buffer and return the contents
*/
ElementGenerator.prototype.closeAndReturnOutput = function() {
var ret;
this.outputBuffer.flush();
ret = this.outputBuffer.output() + ' }\n return elm; ';
return ret;
};
ElementGenerator.prototype._indent = function(indent) {
if (indent > 0) {
return this.outputBuffer.append(HamlRuntime.indentText(indent));
}
};
ElementGenerator.prototype.openElement = function(currentParsePoint, indent, identifier, id, classes, objectRef, attributeList, attributeHash, elementStack, tagOptions, generator) {
var element, parentInnerWhitespace, tagOuterWhitespace;
element = identifier.length === 0 ? "div" : identifier;
parentInnerWhitespace = haml._parentInnerWhitespace(elementStack, indent);
tagOuterWhitespace = !tagOptions || tagOptions.outerWhitespace;
if (!tagOuterWhitespace) {
this.outputBuffer.trimWhitespace();
}
this._indent(indent);
this.outputBuffer.append('elm = document.createElement("' + element + '");\n');
this._indent(indent);
this.outputBuffer.append('if (parents.peek()) parents.peek().appendChild(elm);\n');
this._indent(indent);
this.outputBuffer.append('parents.push(elm);\n');
if (id) {
this._indent(indent);
this.outputBuffer.append('elm.setAttribute("id", "' + id + '");\n');
}
if (classes && classes.length > 0) {
this._indent(indent);
this.outputBuffer.append('elm.setAttribute("class", "' + classes.join(' ') + '");\n');
}
if (attributeHash.length > 0) {
this._indent(indent);
this.outputBuffer.append('hashFunction = eval("(' + attributeHash.replace(/"/g, '\\"').replace(/\n/g, '\\n') + ')");');
this._indent(indent);
this.outputBuffer.append('for(var index in hashFunction) { if (hashFunction.hasOwnProperty(index)) { elm.setAttribute(index, hashFunction[index]);}}\n');
}
return elementStack[indent] = {
element: element
};
};
ElementGenerator.prototype.closeElement = function(indent, elementStack, tokeniser, generator) {
if (elementStack[indent] && elementStack[indent].element) {
this._indent(indent);
this.outputBuffer.append('elm = parents.pop();\n');
elementStack[indent] = null;
return generator.mark();
}
};
/*
Append a line with embedded javascript code
*/
ElementGenerator.prototype.appendEmbeddedCode = function(indentText, expression, escapeContents, perserveWhitespace, currentParsePoint) {
this.outputBuffer.flush();
this.outputBuffer.appendToOutputBuffer(indentText + 'try {\n');
this.outputBuffer.appendToOutputBuffer(indentText + ' var value = eval("' + (_.str || _).trim(expression).replace(/"/g, '\\"').replace(/\\n/g, '\\\\n') + '");\n');
this.outputBuffer.appendToOutputBuffer(indentText + ' elm.appendChild( (typeof value === "string") ? document.createTextNode(value) : value);\n');
if (false) {
if (escapeContents) {
this.outputBuffer.appendToOutputBuffer(indentText + ' html.push(haml.HamlRuntime.escapeHTML(String(value)));\n');
} else if (perserveWhitespace) {
this.outputBuffer.appendToOutputBuffer(indentText + ' html.push(haml.HamlRuntime.perserveWhitespace(String(value)));\n');
} else {
this.outputBuffer.appendToOutputBuffer(indentText + ' html.push(String(value));\n');
}
}
this.outputBuffer.appendToOutputBuffer(indentText + '} catch (e) {\n');
this.outputBuffer.appendToOutputBuffer(indentText + ' handleError(haml.HamlRuntime.templateError(' + currentParsePoint.lineNumber + ', ' + currentParsePoint.characterNumber + ', "' + this.escapeCode(currentParsePoint.currentLine) + '",\n');
this.outputBuffer.appendToOutputBuffer(indentText + ' "Error evaluating expression - " + e));\n');
return this.outputBuffer.appendToOutputBuffer(indentText + '}\n');
};
/*
Append a line of code to the output buffer
*/
ElementGenerator.prototype.appendCodeLine = function(line, eol) {
this.outputBuffer.flush();
this.outputBuffer.appendToOutputBuffer(HamlRuntime.indentText(this.indent));
this.outputBuffer.appendToOutputBuffer(line);
return this.outputBuffer.appendToOutputBuffer(eol);
};
/*
Does the current line end with a function declaration?
*/
ElementGenerator.prototype.lineMatchesStartFunctionBlock = function(line) {
return line.match(/function\s*\((,?\s*\w+)*\)\s*\{\s*$/);
};
/*
Does the current line end with a starting code block
*/
ElementGenerator.prototype.lineMatchesStartBlock = function(line) {
return line.match(/\{\s*$/);
};
/*
Generate the code to close off a code block
*/
ElementGenerator.prototype.closeOffCodeBlock = function(tokeniser) {
if (!(tokeniser.token.minus && tokeniser.matchToken(/\s*\}/g))) {
this.outputBuffer.flush();
return this.outputBuffer.appendToOutputBuffer(HamlRuntime.indentText(this.indent) + '}\n');
}
};
/*
Generate the code to close off a function parameter
*/
ElementGenerator.prototype.closeOffFunctionBlock = function(tokeniser) {
if (!(tokeniser.token.minus && tokeniser.matchToken(/\s*\}/g))) {
this.outputBuffer.flush();
return this.outputBuffer.appendToOutputBuffer(HamlRuntime.indentText(this.indent) + '});\n');
}
};
/*
Generate the code for dynamic attributes ({} form)
*/
ElementGenerator.prototype.generateCodeForDynamicAttributes = function(id, classes, attributeList, attributeHash, objectRef, currentParsePoint) {
this.outputBuffer.flush();
if (attributeHash.length > 0) {
attributeHash = this.replaceReservedWordsInHash(attributeHash);
this.outputBuffer.appendToOutputBuffer(' hashFunction = function () { return eval("hashObject = ' + attributeHash.replace(/"/g, '\\"').replace(/\n/g, '\\n') + '"); };\n');
} else {
this.outputBuffer.appendToOutputBuffer(' hashFunction = null;\n');
}
if (objectRef.length > 0) {
this.outputBuffer.appendToOutputBuffer(' objRefFn = function () { return eval("objRef = ' + objectRef.replace(/"/g, '\\"') + '"); };\n');
} else {
this.outputBuffer.appendToOutputBuffer(' objRefFn = null;\n');
}
return this.outputBuffer.appendToOutputBuffer(' html.push(haml.HamlRuntime.generateElementAttributes(context, "' + id + '", ["' + classes.join('","') + '"], objRefFn, ' + JSON.stringify(attributeList) + ', hashFunction, ' + currentParsePoint.lineNumber + ', ' + currentParsePoint.characterNumber + ', "' + this.escapeCode(currentParsePoint.currentLine) + '", handleError));\n');
};
/*
Clean any reserved words in the given hash
*/
ElementGenerator.prototype.replaceReservedWordsInHash = function(hash) {
var j, len, ref, reservedWord, resultHash;
resultHash = hash;
ref = ['class', 'for'];
for (j = 0, len = ref.length; j < len; j++) {
reservedWord = ref[j];
resultHash = resultHash.replace(reservedWord + ':', '"' + reservedWord + '":');
}
return resultHash;
};
/*
Escape the line so it is safe to put into a javascript string
*/
ElementGenerator.prototype.escapeCode = function(jsStr) {
return jsStr.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
};
/*
Generate a function from the function body
*/
ElementGenerator.prototype.generateJsFunction = function(functionBody) {
var e;
try {
return new Function('context', functionBody);
} catch (error1) {
e = error1;
throw "Incorrect embedded code has resulted in an invalid Haml function - " + e + "\nGenerated Function:\n" + functionBody;
}
};
/*
Generate the code required to support a buffer flush
*/
ElementGenerator.prototype.generateFlush = function(bufferStr) {
return bufferStr;
};
/*
Set the current indent level
*/
ElementGenerator.prototype.setIndent = function(indent) {
return this.indent = indent;
};
/*
Save the current indent level if required
*/
ElementGenerator.prototype.mark = function() {};
/*
Append the text contents to the buffer, expanding any embedded code
*/
ElementGenerator.prototype.appendTextContents = function(text, shouldInterpolate, currentParsePoint, options) {
if (options == null) {
options = {};
}
if (shouldInterpolate && text.match(/#{[^}]*}/)) {
return this.interpolateString(text, currentParsePoint, options);
} else {
return this.outputBuffer.append('elm.appendChild(document.createTextNode("' + this.processText(text, options) + '"));\n');
}
};
/*
Interpolate any embedded code in the text
*/
ElementGenerator.prototype.interpolateString = function(text, currentParsePoint, options) {
var index, precheedingChar, precheedingChar2, result;
index = 0;
result = this.embeddedCodeBlockMatcher.exec(text);
while (result) {
if (result.index > 0) {
precheedingChar = text.charAt(result.index - 1);
}
if (result.index > 1) {
precheedingChar2 = text.charAt(result.index - 2);
}
if (precheedingChar === '\\' && precheedingChar2 !== '\\') {
if (result.index !== 0) {
this.outputBuffer.append(this.processText(text.substring(index, result.index - 1), options));
}
this.outputBuffer.append(this.processText(result[0]), options);
} else {
this.outputBuffer.append(this.processText(text.substring(index, result.index)), options);
this.appendEmbeddedCode(HamlRuntime.indentText(this.indent + 1), result[1], options.escapeHTML, options.perserveWhitespace, currentParsePoint);
}
index = this.embeddedCodeBlockMatcher.lastIndex;
result = this.embeddedCodeBlockMatcher.exec(text);
}
if (index < text.length) {
return this.outputBuffer.append(this.processText(text.substring(index), options));
}
};
/*
process text based on escape and preserve flags
*/
ElementGenerator.prototype.processText = function(text, options) {
var t;
if (options != null ? options.escapeHTML : void 0) {
t = haml.HamlRuntime.escapeHTML(text);
} else if (options != null ? options.perserveWhitespace : void 0) {
t = haml.HamlRuntime.perserveWhitespace(text);
} else {
t = text;
}
return t;
};
return ElementGenerator;
})(CodeGenerator);
/*
HAML filters are functions that take 3 parameters
contents: The contents block for the filter an array of lines of text
generator: The current generator for the compiled function
indent: The current indent level
currentParsePoint: line and character counters for the current parse point in the input buffer
*/
filters = {
/*
Plain filter, just renders the text in the block
*/
plain: function(contents, generator, indent, currentParsePoint) {
var j, len, line;
for (j = 0, len = contents.length; j < len; j++) {
line = contents[j];
generator.appendTextContents(haml.HamlRuntime.indentText(indent - 1) + line + '\n', true, currentParsePoint);
}
return true;
},
/*
Wraps the filter block in a javascript tag
*/
javascript: function(contents, generator, indent, currentParsePoint) {
var j, len, line;
generator.outputBuffer.append(haml.HamlRuntime.indentText(indent) + "<script type=\"text/javascript\">\n");
generator.outputBuffer.append(haml.HamlRuntime.indentText(indent + 1) + "//<![CDATA[\n");
for (j = 0, len = contents.length; j < len; j++) {
line = contents[j];
generator.appendTextContents(haml.HamlRuntime.indentText(indent + 1) + line + '\n', true, currentParsePoint);
}
generator.outputBuffer.append(haml.HamlRuntime.indentText(indent + 1) + "//]]>\n");
return generator.outputBuffer.append(haml.HamlRuntime.indentText(indent) + "</script>\n");
},
/*
Wraps the filter block in a style tag
*/
css: function(contents, generator, indent, currentParsePoint) {
var j, len, line;
generator.outputBuffer.append(haml.HamlRuntime.indentText(indent) + "<style type=\"text/css\">\n");
generator.outputBuffer.append(haml.HamlRuntime.indentText(indent + 1) + "/*<![CDATA[*/\n");
for (j = 0, len = contents.length; j < len; j++) {
line = contents[j];
generator.appendTextContents(haml.HamlRuntime.indentText(indent + 1) + line + '\n', true, currentParsePoint);
}
generator.outputBuffer.append(haml.HamlRuntime.indentText(indent + 1) + "/*]]>*/\n");
return generator.outputBuffer.append(haml.HamlRuntime.indentText(indent) + "</style>\n");
},
/*
Wraps the filter block in a CDATA tag
*/
cdata: function(contents, generator, indent, currentParsePoint) {
var j, len, line;
generator.outputBuffer.append(haml.HamlRuntime.indentText(indent) + "<![CDATA[\n");
for (j = 0, len = contents.length; j < len; j++) {
line = contents[j];
generator.appendTextContents(haml.HamlRuntime.indentText(indent) + line + '\n', true, currentParsePoint);
}
return generator.outputBuffer.append(haml.HamlRuntime.indentText(indent) + "]]>\n");
},
/*
Preserve filter, preserved blocks of text aren't indented, and newlines are replaced with the HTML escape code for newlines
*/
preserve: function(contents, generator, indent, currentParsePoint) {
var line;
generator.appendTextContents(haml.HamlRuntime.indentText(indent), false, currentParsePoint);
return generator.appendTextContents(((function() {
var j, len, results;
results = [];
for (j = 0, len = contents.length; j < len; j++) {
line = contents[j];
results.push(haml.HamlRuntime.trim(line, 2));
}
return results;
})()).join('
 ') + '\n', true, currentParsePoint);
},
/*
Escape filter, renders the text in the block with html escaped
*/
escaped: function(contents, generator, indent, currentParsePoint) {
var j, len, line;
for (j = 0, len = contents.length; j < len; j++) {
line = contents[j];
generator.appendTextContents(haml.HamlRuntime.indentText(indent - 1) + line + '\n', true, currentParsePoint, {
escapeHTML: true
});
}
return true;
}
};
/*
Main haml compiler implemtation
*/
haml = {
/*
Compiles the haml provided in the parameters to a Javascipt function
Parameter:
String: Looks for a haml template in dom with this ID
Option Hash: The following options determines how haml sources and compiles the template
source - This contains the template in string form
sourceId - This contains the element ID in the dom which contains the haml source
sourceUrl - This contains the URL where the template can be fetched from
outputFormat - This determines what is returned, and has the following values:
string - The javascript source code
function - A javascript function (default)
generator - Which code generator to use
javascript (default)
coffeescript
productionjavascript
elementgenerator
tolerateErrors - switch the compiler into fault tolerant mode (defaults to false)
Returns a javascript function
*/
compileHaml: function(options) {
var codeGenerator, result, tokinser;
if (typeof options === 'string') {
return this._compileHamlTemplate(options, new haml.JsCodeGenerator());
} else {
codeGenerator = (function() {
switch (options.generator) {
case 'coffeescript':
return new haml.CoffeeCodeGenerator(options);
case 'productionjavascript':
return new haml.ProductionJsCodeGenerator(options);
case 'elementgenerator':
return new haml.ElementGenerator(options);
default:
return new haml.JsCodeGenerator(options);
}
})();
if (options.source != null) {
tokinser = new haml.Tokeniser({
template: options.source
});
} else if (options.sourceId != null) {
tokinser = new haml.Tokeniser({
templateId: options.sourceId
});
} else if (options.sourceUrl != null) {
tokinser = new haml.Tokeniser({
templateUrl: options.sourceUrl
});
} else {
throw "No template source specified for compileHaml. You need to provide a source, sourceId or sourceUrl option";
}
result = this._compileHamlToJs(tokinser, codeGenerator, options);
if (options.outputFormat !== 'string') {
return codeGenerator.generateJsFunction(result);
} else {
return "function (context) {\n" + result + "}\n";
}
}
},
/*
Compiles the haml in the script block with ID templateId using the coffeescript generator
Returns a javascript function
*/
compileCoffeeHaml: function(templateId) {
return this._compileHamlTemplate(templateId, new haml.CoffeeCodeGenerator());
},
/*
Compiles the haml in the passed in string
Returns a javascript function
*/
compileStringToJs: function(string) {
var codeGenerator, result;
codeGenerator = new haml.JsCodeGenerator();
result = this._compileHamlToJs(new haml.Tokeniser({
template: string
}), codeGenerator);
return codeGenerator.generateJsFunction(result);
},
/*
Compiles the haml in the passed in string using the coffeescript generator
Returns a javascript function
*/
compileCoffeeHamlFromString: function(string) {
var codeGenerator, result;
codeGenerator = new haml.CoffeeCodeGenerator();
result = this._compileHamlToJs(new haml.Tokeniser({
template: string
}), codeGenerator);
return codeGenerator.generateJsFunction(result);
},
/*
Compiles the haml in the passed in string
Returns the javascript function source
This is mainly used for precompiling the haml templates so they can be packaged.
*/
compileHamlToJsString: function(string) {
var result;
result = 'function (context) {\n';
result += this._compileHamlToJs(new haml.Tokeniser({
template: string
}), new haml.JsCodeGenerator());
return result += '}\n';
},
_compileHamlTemplate: function(templateId, codeGenerator) {
var fn, result;
haml.cache || (haml.cache = {});
if (haml.cache[templateId]) {
return haml.cache[templateId];
}
result = this._compileHamlToJs(new haml.Tokeniser({
templateId: templateId
}), codeGenerator);
fn = codeGenerator.generateJsFunction(result);
haml.cache[templateId] = fn;
return fn;
},
_compileHamlToJs: function(tokeniser, generator, options) {
var e, indent;
if (options == null) {
options = {};
}
generator.elementStack = [];
generator.initOutput();
tokeniser.getNextToken();
while (!tokeniser.token.eof) {
if (!tokeniser.token.eol) {
try {
indent = this._whitespace(tokeniser);
generator.setIndent(indent);
if (tokeniser.token.eol) {
generator.outputBuffer.append(HamlRuntime.indentText(indent) + tokeniser.token.matched);
tokeniser.getNextToken();
} else if (tokeniser.token.doctype) {
this._doctype(tokeniser, indent, generator);
} else if (tokeniser.token.exclamation) {
this._ignoredLine(tokeniser, indent, generator.elementStack, generator);
} else if (tokeniser.token.equal || tokeniser.token.escapeHtml || tokeniser.token.unescapeHtml || tokeniser.token.tilde) {
this._embeddedJs(tokeniser, indent, generator.elementStack, {
innerWhitespace: true
}, generator);
} else if (tokeniser.token.minus) {
this._jsLine(tokeniser, indent, generator.elementStack, generator);
} else if (tokeniser.token.comment || tokeniser.token.slash) {
this._commentLine(tokeniser, indent, generator.elementStack, generator);
} else if (tokeniser.token.amp) {
this._escapedLine(tokeniser, indent, generator.elementStack, generator);
} else if (tokeniser.token.filter) {
this._filter(tokeniser, indent, generator, options);
} else {
this._templateLine(tokeniser, generator.elementStack, indent, generator, options);
}
} catch (error1) {
e = error1;
this._handleError(options, {
skipTo: true
}, tokeniser, e);
}
} else {
generator.outputBuffer.append(tokeniser.token.matched);
tokeniser.getNextToken();
}
}
generator.closeElements(0, generator.elementStack, tokeniser, generator);
return generator.closeAndReturnOutput();
},
_doctype: function(tokeniser, indent, generator) {
var contents, params;
if (tokeniser.token.doctype) {
generator.outputBuffer.append(HamlRuntime.indentText(indent));
tokeniser.getNextToken();
if (tokeniser.token.ws) {
tokeniser.getNextToken();
}
contents = tokeniser.skipToEOLorEOF();
if (contents && contents.length > 0) {
params = contents.split(/\s+/);
switch (params[0]) {
case 'XML':
if (params.length > 1) {
generator.outputBuffer.append("<?xml version='1.0' encoding='" + params[1] + "' ?>");
} else {
generator.outputBuffer.append("<?xml version='1.0' encoding='utf-8' ?>");
}
break;
case 'Strict':
generator.outputBuffer.append('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
break;
case 'Frameset':
generator.outputBuffer.append('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">');
break;
case '5':
generator.outputBuffer.append('<!DOCTYPE html>');
break;
case '1.1':
generator.outputBuffer.append('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">');
break;
case 'Basic':
generator.outputBuffer.append('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">');
break;
case 'Mobile':
generator.outputBuffer.append('<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">');
break;
case 'RDFa':
generator.outputBuffer.append('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">');
}
} else {
generator.outputBuffer.append('<!DOCTYPE html>');
}
generator.outputBuffer.append(this._newline(tokeniser));
return tokeniser.getNextToken();
}
},
_filter: function(tokeniser, indent, generator, options) {
var filter, filterBlock, i, line;
if (tokeniser.token.filter) {
filter = tokeniser.token.tokenString;
if (!haml.filters[filter]) {
this._handleError(options, {
skipTo: indent
}, tokeniser, tokeniser.parseError("Filter '" + filter + "' not registered. Filter functions need to be added to 'haml.filters'."));
return;
}
tokeniser.skipToEOLorEOF();
tokeniser.getNextToken();
i = haml._whitespace(tokeniser);
filterBlock = [];
while (!tokeniser.token.eof && i > indent) {
tokeniser.pushBackToken();
line = tokeniser.skipToEOLorEOF();
filterBlock.push(HamlRuntime.trim(line, 2 * indent));
tokeniser.getNextToken();
i = haml._whitespace(tokeniser);
}
haml.filters[filter](filterBlock, generator, indent, tokeniser.currentParsePoint());
return tokeniser.pushBackToken();
}
},
_commentLine: function(tokeniser, indent, elementStack, generator) {
var contents, i;
if (tokeniser.token.comment) {
tokeniser.skipToEOLorEOF();
tokeniser.getNextToken();
i = this._whitespace(tokeniser);
while (!tokeniser.token.eof && i > indent) {
tokeniser.skipToEOLorEOF();
tokeniser.getNextToken();
i = this._whitespace(tokeniser);
}
if (i > 0) {
return tokeniser.pushBackToken();
}
} else if (tokeniser.token.slash) {
generator.closeElements(indent, elementStack, tokeniser, generator);
generator.outputBuffer.append(HamlRuntime.indentText(indent));
generator.outputBuffer.append("<!--");
tokeniser.getNextToken();
contents = tokeniser.skipToEOLorEOF();
if (contents && contents.length > 0) {
generator.outputBuffer.append(contents);
}
if (contents && (_.str || _).startsWith(contents, '[') && contents.match(/\]\s*$/)) {
elementStack[indent] = {
htmlConditionalComment: true,
eol: this._newline(tokeniser)
};
generator.outputBuffer.append(">");
} else {
elementStack[indent] = {
htmlComment: true,
eol: this._newline(tokeniser)
};
}
if (haml._tagHasContents(indent, tokeniser)) {
generator.outputBuffer.append("\n");
}
return tokeniser.getNextToken();
}
},
_escapedLine: function(tokeniser, indent, elementStack, generator) {
var contents;
if (tokeniser.token.amp) {
generator.closeElements(indent, elementStack, tokeniser, generator);
generator.outputBuffer.append(HamlRuntime.indentText(indent));
tokeniser.getNextToken();
contents = tokeniser.skipToEOLorEOF();
if (contents && contents.length > 0) {
generator.outputBuffer.append(haml.HamlRuntime.escapeHTML(contents));
}
generator.outputBuffer.append(this._newline(tokeniser));
return tokeniser.getNextToken();
}
},
_ignoredLine: function(tokeniser, indent, elementStack, generator) {
var contents;
if (tokeniser.token.exclamation) {
tokeniser.getNextToken();
if (tokeniser.token.ws) {
indent += haml._whitespace(tokeniser);
}
generator.closeElements(indent, elementStack, tokeniser, generator);
contents = tokeniser.skipToEOLorEOF();
return generator.outputBuffer.append(HamlRuntime.indentText(indent) + contents);
}
},
_embeddedJs: function(tokeniser, indent, elementStack, tagOptions, generator) {
var currentParsePoint, escapeHtml, expression, indentText, perserveWhitespace;
if (elementStack) {
generator.closeElements(indent, elementStack, tokeniser, generator);
}
if (tokeniser.token.equal || tokeniser.token.escapeHtml || tokeniser.token.unescapeHtml || tokeniser.token.tilde) {
escapeHtml = tokeniser.token.escapeHtml || tokeniser.token.equal;
perserveWhitespace = tokeniser.token.tilde;
currentParsePoint = tokeniser.currentParsePoint();
tokeniser.getNextToken();
expression = tokeniser.skipToEOLorEOF();
indentText = HamlRuntime.indentText(indent);
if (!tagOptions || tagOptions.innerWhitespace) {
generator.outputBuffer.append(indentText);
}
generator.appendEmbeddedCode(indentText, expression, escapeHtml, perserveWhitespace, currentParsePoint);
if (!tagOptions || tagOptions.innerWhitespace) {
generator.outputBuffer.append(this._newline(tokeniser));
if (tokeniser.token.eol) {
return tokeniser.getNextToken();
}
}
}
},
_jsLine: function(tokeniser, indent, elementStack, generator) {
var line;
if (tokeniser.token.minus) {
generator.closeElements(indent, elementStack, tokeniser, generator);
tokeniser.getNextToken();
line = tokeniser.skipToEOLorEOF();
generator.setIndent(indent);
generator.appendCodeLine(line, this._newline(tokeniser));
if (tokeniser.token.eol) {
tokeniser.getNextToken();
}
if (generator.lineMatchesStartFunctionBlock(line)) {
return elementStack[indent] = {
fnBlock: true
};
} else if (generator.lineMatchesStartBlock(line)) {
return elementStack[indent] = {
block: true
};
}
}
},
_templateLine: function(tokeniser, elementStack, indent, generator, options) {
var attrList, attributesHash, classes, contents, currentParsePoint, hasContents, id, identifier, indentText, lineHasElement, objectRef, shouldInterpolate, tagOptions;
if (!tokeniser.token.eol) {
generator.closeElements(indent, elementStack, tokeniser, generator);
}
identifier = this._element(tokeniser);
id = this._idSelector(tokeniser);
classes = this._classSelector(tokeniser);
if (!id) {
id = this._idSelector(tokeniser);
}
objectRef = this._objectReference(tokeniser);
attrList = this._attributeList(tokeniser, options);
currentParsePoint = tokeniser.currentParsePoint();
attributesHash = this._attributeHash(tokeniser);
tagOptions = {
selfClosingTag: false,
innerWhitespace: true,
outerWhitespace: true
};
lineHasElement = this._lineHasElement(identifier, id, classes);
if (tokeniser.token.slash) {
tagOptions.selfClosingTag = true;
tokeniser.getNextToken();
}
if (tokeniser.token.gt && lineHasElement) {
tagOptions.outerWhitespace = false;
tokeniser.getNextToken();
}
if (tokeniser.token.lt && lineHasElement) {
tagOptions.innerWhitespace = false;
tokeniser.getNextToken();
}
if (lineHasElement) {
if (!tagOptions.selfClosingTag) {
tagOptions.selfClosingTag = haml._isSelfClosingTag(identifier) && !haml._tagHasContents(indent, tokeniser);
}
generator.openElement(currentParsePoint, indent, identifier, id, classes, objectRef, attrList, attributesHash, elementStack, tagOptions, generator);
}
hasContents = false;
if (tokeniser.token.ws) {
tokeniser.getNextToken();
}
if (tokeniser.token.equal || tokeniser.token.escapeHtml || tokeniser.token.unescapeHtml) {
this._embeddedJs(tokeniser, indent + 1, null, tagOptions, generator);
hasContents = true;
} else {
contents = '';
shouldInterpolate = false;
if (tokeniser.token.exclamation) {
tokeniser.getNextToken();
contents = tokeniser.skipToEOLorEOF();
} else {
contents = tokeniser.skipToEOLorEOF();
if (contents.match(/^\\/)) {
contents = contents.substring(1);
}
shouldInterpolate = true;
}
hasContents = contents.length > 0;
if (hasContents) {
if (tagOptions.innerWhitespace && lineHasElement || (!lineHasElement && haml._parentInnerWhitespace(elementStack, indent))) {
indentText = HamlRuntime.indentText(identifier.length > 0 ? indent + 1 : indent);
} else {
indentText = '';
contents = (_.str || _).trim(contents);
}
generator.appendTextContents(indentText + contents, shouldInterpolate, currentParsePoint);
generator.outputBuffer.append(this._newline(tokeniser));
}
this._eolOrEof(tokeniser);
}
if (tagOptions.selfClosingTag && hasContents) {
return this._handleError(options, null, tokeniser, haml.HamlRuntime.templateError(currentParsePoint.lineNumber, currentParsePoint.characterNumber, currentParsePoint.currentLine, "A self-closing tag can not have any contents"));
}
},
_attributeHash: function(tokeniser) {
var attr;
attr = '';
if (tokeniser.token.attributeHash) {
attr = tokeniser.token.tokenString;
tokeniser.getNextToken();
}
return attr;
},
_objectReference: function(tokeniser) {
var attr;
attr = '';
if (tokeniser.token.objectReference) {
attr = tokeniser.token.tokenString;
tokeniser.getNextToken();
}
return attr;
},
_attributeList: function(tokeniser, options) {
var attr, attrList;
attrList = {};
if (tokeniser.token.openBracket) {
tokeniser.getNextToken();
while (!tokeniser.token.closeBracket) {
attr = haml._attribute(tokeniser);
if (attr) {
attrList[attr.name] = attr.value;
} else {
if (tokeniser.token.ws || tokeniser.token.eol) {
tokeniser.getNextToken();
} else if (!tokeniser.token.closeBracket && !tokeniser.token.identifier) {
this._handleError(options, null, tokeniser, tokeniser.parseError("Expecting either an attribute name to continue the attributes or a closing " + "bracket to end"));
return attrList;
}
}
}
tokeniser.getNextToken();
}
return attrList;
},
_attribute: function(tokeniser) {
var attr, name;
attr = null;
if (tokeniser.token.identifier) {
name = tokeniser.token.tokenString;
tokeniser.getNextToken();
haml._whitespace(tokeniser);
if (!tokeniser.token.equal) {
return {
name: name,
value: ''
};
}
tokeniser.getNextToken();
haml._whitespace(tokeniser);
if (!tokeniser.token.string && !tokeniser.token.identifier) {
throw tokeniser.parseError("Expected a quoted string or an identifier for the attribute value");
}
attr = {
name: name,
value: tokeniser.token.tokenString
};
tokeniser.getNextToken();
}
return attr;
},
_isSelfClosingTag: function(tag) {
return tag === 'meta' || tag === 'img' || tag === 'link' || tag === 'script' || tag === 'br' || tag === 'hr';
},
_tagHasContents: function(indent, tokeniser) {
var nextToken;
if (!tokeniser.isEolOrEof()) {
return true;
} else {
nextToken = tokeniser.lookAhead(1);
return nextToken.ws && nextToken.tokenString.length / 2 > indent;
}
},
_parentInnerWhitespace: function(elementStack, indent) {
return indent === 0 || (!elementStack[indent - 1] || !elementStack[indent - 1].tagOptions || elementStack[indent - 1].tagOptions.innerWhitespace);
},
_lineHasElement: function(identifier, id, classes) {
return identifier.length > 0 || id.length > 0 || classes.length > 0;
},
hasValue: function(value) {
return (value != null) && value !== false;
},
attrValue: function(attr, value) {
if (attr === 'selected' || attr === 'checked' || attr === 'disabled') {
return attr;
} else {
return value;
}
},
_whitespace: function(tokeniser) {
var indent;
indent = 0;
if (tokeniser.token.ws) {
indent = tokeniser.calculateIndent(tokeniser.token.tokenString);
tokeniser.getNextToken();
}
return indent;
},
_element: function(tokeniser) {
var identifier;
identifier = '';
if (tokeniser.token.element) {
identifier = tokeniser.token.tokenString;
tokeniser.getNextToken();
}
return identifier;
},
_eolOrEof: function(tokeniser) {
if (tokeniser.token.eol || tokeniser.token.continueLine) {
return tokeniser.getNextToken();
} else if (!tokeniser.token.eof) {
throw tokeniser.parseError("Expected EOL or EOF");
}
},
_idSelector: function(tokeniser) {
var id;
id = '';
if (tokeniser.token.idSelector) {
id = tokeniser.token.tokenString;
tokeniser.getNextToken();
}
return id;
},
_classSelector: function(tokeniser) {
var classes;
classes = [];
while (tokeniser.token.classSelector) {
classes.push(tokeniser.token.tokenString);
tokeniser.getNextToken();
}
return classes;
},
_newline: function(tokeniser) {
if (tokeniser.token.eol) {
return tokeniser.token.matched;
} else if (tokeniser.token.continueLine) {
return tokeniser.token.matched.substring(1);
} else {
return "\n";
}
},
_handleError: function(options, action, tokeniser, error) {
if (options != null ? options.tolerateFaults : void 0) {
console.log(error);
if (action != null ? action.skipTo : void 0) {
return this._skipToNextLineWithIndent(tokeniser, action.skipTo);
}
} else {
throw error;
}
},
_skipToNextLineWithIndent: function(tokeniser, indent) {
var lineIndent;
tokeniser.skipToEOLorEOF();
tokeniser.getNextToken();
lineIndent = this._whitespace(tokeniser);
while (lineIndent > indent) {
tokeniser.skipToEOLorEOF();
tokeniser.getNextToken();
lineIndent = this._whitespace(tokeniser);
}
return tokeniser.pushBackToken();
}
};
haml.Tokeniser = Tokeniser;
haml.Buffer = Buffer;
haml.JsCodeGenerator = JsCodeGenerator;
haml.ProductionJsCodeGenerator = ProductionJsCodeGenerator;
haml.CoffeeCodeGenerator = CoffeeCodeGenerator;
haml.ElementGenerator = ElementGenerator;
haml.HamlRuntime = HamlRuntime;
haml.filters = filters;
if ((typeof module !== "undefined" && module !== null ? module.exports : void 0) != null) {
module.exports = haml;
} else {
root.haml = haml;
}
}).call(this);
//# sourceMappingURL=haml.js.map
|
'use strict';
module.exports = function(type) {
if (type === 'removeListeners') {
window.removeEventListener('scroll', this.pauseWhenNotInViewNameSpace);
return;
}
window.addEventListener('scroll', this.pauseWhenNotInViewNameSpace);
this.pauseWhenNotInViewNameSpace();
};
|
/* automatically built from ReflectionException.php*/
PHP.VM.Class.Predefined.ReflectionException = function( ENV, $$ ) {
ENV.$Class.New( "ReflectionException", 0, {Extends: "Exception"}, function( M, $, $$ ){
M.Create()});
ENV.$Class.Get( "DateTime").prototype.Native = true;
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:e9601d8f50c26ec09e8c182fff75f8d43a09fbf5ce34bb896636df2e54729114
size 6764
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.