code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
/*
Copyright (c) 2008-2015 Pivotal Labs
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.
*/
jasmineRequire.html = function(j$) {
j$.ResultsNode = jasmineRequire.ResultsNode();
j$.HtmlReporter = jasmineRequire.HtmlReporter(j$);
j$.QueryString = jasmineRequire.QueryString();
j$.HtmlSpecFilter = jasmineRequire.HtmlSpecFilter();
};
jasmineRequire.HtmlReporter = function(j$) {
var noopTimer = {
start: function() {},
elapsed: function() { return 0; }
};
function HtmlReporter(options) {
var env = options.env || {},
getContainer = options.getContainer,
createElement = options.createElement,
createTextNode = options.createTextNode,
onRaiseExceptionsClick = options.onRaiseExceptionsClick || function() {},
onThrowExpectationsClick = options.onThrowExpectationsClick || function() {},
addToExistingQueryString = options.addToExistingQueryString || defaultQueryString,
timer = options.timer || noopTimer,
results = [],
specsExecuted = 0,
failureCount = 0,
pendingSpecCount = 0,
htmlReporterMain,
symbols,
failedSuites = [];
this.initialize = function() {
clearPrior();
htmlReporterMain = createDom('div', {className: 'jasmine_html-reporter'},
createDom('div', {className: 'banner'},
createDom('a', {className: 'title', href: 'http://jasmine.github.io/', target: '_blank'}),
createDom('span', {className: 'version'}, j$.version)
),
createDom('ul', {className: 'symbol-summary'}),
createDom('div', {className: 'alert'}),
createDom('div', {className: 'results'},
createDom('div', {className: 'failures'})
)
);
getContainer().appendChild(htmlReporterMain);
symbols = find('.symbol-summary');
};
var totalSpecsDefined;
this.jasmineStarted = function(options) {
totalSpecsDefined = options.totalSpecsDefined || 0;
timer.start();
};
var summary = createDom('div', {className: 'summary'});
var topResults = new j$.ResultsNode({}, '', null),
currentParent = topResults;
this.suiteStarted = function(result) {
currentParent.addChild(result, 'suite');
currentParent = currentParent.last();
};
this.suiteDone = function(result) {
if (result.status == 'failed') {
failedSuites.push(result);
}
if (currentParent == topResults) {
return;
}
currentParent = currentParent.parent;
};
this.specStarted = function(result) {
currentParent.addChild(result, 'spec');
};
var failures = [];
this.specDone = function(result) {
if(noExpectations(result) && typeof console !== 'undefined' && typeof console.error !== 'undefined') {
console.error('Spec \'' + result.fullName + '\' has no expectations.');
}
if (result.status != 'disabled') {
specsExecuted++;
}
symbols.appendChild(createDom('li', {
className: noExpectations(result) ? 'empty' : result.status,
id: 'spec_' + result.id,
title: result.fullName
}
));
if (result.status == 'failed') {
failureCount++;
var failure =
createDom('div', {className: 'spec-detail failed'},
createDom('div', {className: 'description'},
createDom('a', {title: result.fullName, href: specHref(result)}, result.fullName)
),
createDom('div', {className: 'messages'})
);
var messages = failure.childNodes[1];
for (var i = 0; i < result.failedExpectations.length; i++) {
var expectation = result.failedExpectations[i];
messages.appendChild(createDom('div', {className: 'result-message'}, expectation.message));
messages.appendChild(createDom('div', {className: 'stack-trace'}, expectation.stack));
}
failures.push(failure);
}
if (result.status == 'pending') {
pendingSpecCount++;
}
};
this.jasmineDone = function() {
var banner = find('.banner');
var alert = find('.alert');
alert.appendChild(createDom('span', {className: 'duration'}, 'finished in ' + timer.elapsed() / 1000 + 's'));
banner.appendChild(
createDom('div', { className: 'run-options' },
createDom('span', { className: 'trigger' }, 'Options'),
createDom('div', { className: 'payload' },
createDom('div', { className: 'exceptions' },
createDom('input', {
className: 'raise',
id: 'raise-exceptions',
type: 'checkbox'
}),
createDom('label', { className: 'label', 'for': 'raise-exceptions' }, 'raise exceptions')),
createDom('div', { className: 'throw-failures' },
createDom('input', {
className: 'throw',
id: 'throw-failures',
type: 'checkbox'
}),
createDom('label', { className: 'label', 'for': 'throw-failures' }, 'stop spec on expectation failure'))
)
));
var raiseCheckbox = find('#raise-exceptions');
raiseCheckbox.checked = !env.catchingExceptions();
raiseCheckbox.onclick = onRaiseExceptionsClick;
var throwCheckbox = find('#throw-failures');
throwCheckbox.checked = env.throwingExpectationFailures();
throwCheckbox.onclick = onThrowExpectationsClick;
var optionsMenu = find('.run-options'),
optionsTrigger = optionsMenu.querySelector('.trigger'),
optionsPayload = optionsMenu.querySelector('.payload'),
isOpen = /\bopen\b/;
optionsTrigger.onclick = function() {
if (isOpen.test(optionsPayload.className)) {
optionsPayload.className = optionsPayload.className.replace(isOpen, '');
} else {
optionsPayload.className += ' open';
}
};
if (specsExecuted < totalSpecsDefined) {
var skippedMessage = 'Ran ' + specsExecuted + ' of ' + totalSpecsDefined + ' specs - run all';
alert.appendChild(
createDom('span', {className: 'bar skipped'},
createDom('a', {href: '?', title: 'Run all specs'}, skippedMessage)
)
);
}
var statusBarMessage = '';
var statusBarClassName = 'bar ';
if (totalSpecsDefined > 0) {
statusBarMessage += pluralize('spec', specsExecuted) + ', ' + pluralize('failure', failureCount);
if (pendingSpecCount) { statusBarMessage += ', ' + pluralize('pending spec', pendingSpecCount); }
statusBarClassName += (failureCount > 0) ? 'failed' : 'passed';
} else {
statusBarClassName += 'skipped';
statusBarMessage += 'No specs found';
}
alert.appendChild(createDom('span', {className: statusBarClassName}, statusBarMessage));
for(i = 0; i < failedSuites.length; i++) {
var failedSuite = failedSuites[i];
for(var j = 0; j < failedSuite.failedExpectations.length; j++) {
var errorBarMessage = 'AfterAll ' + failedSuite.failedExpectations[j].message;
var errorBarClassName = 'bar errored';
alert.appendChild(createDom('span', {className: errorBarClassName}, errorBarMessage));
}
}
var results = find('.results');
results.appendChild(summary);
summaryList(topResults, summary);
function summaryList(resultsTree, domParent) {
var specListNode;
for (var i = 0; i < resultsTree.children.length; i++) {
var resultNode = resultsTree.children[i];
if (resultNode.type == 'suite') {
var suiteListNode = createDom('ul', {className: 'suite', id: 'suite-' + resultNode.result.id},
createDom('li', {className: 'suite-detail'},
createDom('a', {href: specHref(resultNode.result)}, resultNode.result.description)
)
);
summaryList(resultNode, suiteListNode);
domParent.appendChild(suiteListNode);
}
if (resultNode.type == 'spec') {
if (domParent.getAttribute('class') != 'specs') {
specListNode = createDom('ul', {className: 'specs'});
domParent.appendChild(specListNode);
}
var specDescription = resultNode.result.description;
if(noExpectations(resultNode.result)) {
specDescription = 'SPEC HAS NO EXPECTATIONS ' + specDescription;
}
if(resultNode.result.status === 'pending' && resultNode.result.pendingReason !== '') {
specDescription = specDescription + ' PENDING WITH MESSAGE: ' + resultNode.result.pendingReason;
}
specListNode.appendChild(
createDom('li', {
className: resultNode.result.status,
id: 'spec-' + resultNode.result.id
},
createDom('a', {href: specHref(resultNode.result)}, specDescription)
)
);
}
}
}
if (failures.length) {
alert.appendChild(
createDom('span', {className: 'menu bar spec-list'},
createDom('span', {}, 'Spec List | '),
createDom('a', {className: 'failures-menu', href: '#'}, 'Failures')));
alert.appendChild(
createDom('span', {className: 'menu bar failure-list'},
createDom('a', {className: 'spec-list-menu', href: '#'}, 'Spec List'),
createDom('span', {}, ' | Failures ')));
find('.failures-menu').onclick = function() {
setMenuModeTo('failure-list');
};
find('.spec-list-menu').onclick = function() {
setMenuModeTo('spec-list');
};
setMenuModeTo('failure-list');
var failureNode = find('.failures');
for (var i = 0; i < failures.length; i++) {
failureNode.appendChild(failures[i]);
}
}
};
return this;
function find(selector) {
return getContainer().querySelector('.jasmine_html-reporter ' + selector);
}
function clearPrior() {
// return the reporter
var oldReporter = find('');
if(oldReporter) {
getContainer().removeChild(oldReporter);
}
}
function createDom(type, attrs, childrenVarArgs) {
var el = createElement(type);
for (var i = 2; i < arguments.length; i++) {
var child = arguments[i];
if (typeof child === 'string') {
el.appendChild(createTextNode(child));
} else {
if (child) {
el.appendChild(child);
}
}
}
for (var attr in attrs) {
if (attr == 'className') {
el[attr] = attrs[attr];
} else {
el.setAttribute(attr, attrs[attr]);
}
}
return el;
}
function pluralize(singular, count) {
var word = (count == 1 ? singular : singular + 's');
return '' + count + ' ' + word;
}
function specHref(result) {
return addToExistingQueryString('spec', result.fullName);
}
function defaultQueryString(key, value) {
return '?' + key + '=' + value;
}
function setMenuModeTo(mode) {
htmlReporterMain.setAttribute('class', 'jasmine_html-reporter ' + mode);
}
function noExpectations(result) {
return (result.failedExpectations.length + result.passedExpectations.length) === 0 &&
result.status === 'passed';
}
}
return HtmlReporter;
};
jasmineRequire.HtmlSpecFilter = function() {
function HtmlSpecFilter(options) {
var filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
var filterPattern = new RegExp(filterString);
this.matches = function(specName) {
return filterPattern.test(specName);
};
}
return HtmlSpecFilter;
};
jasmineRequire.ResultsNode = function() {
function ResultsNode(result, type, parent) {
this.result = result;
this.type = type;
this.parent = parent;
this.children = [];
this.addChild = function(result, type) {
this.children.push(new ResultsNode(result, type, this));
};
this.last = function() {
return this.children[this.children.length - 1];
};
}
return ResultsNode;
};
jasmineRequire.QueryString = function() {
function QueryString(options) {
this.navigateWithNewParam = function(key, value) {
options.getWindowLocation().search = this.fullStringWithNewParam(key, value);
};
this.fullStringWithNewParam = function(key, value) {
var paramMap = queryStringToParamMap();
paramMap[key] = value;
return toQueryString(paramMap);
};
this.getParam = function(key) {
return queryStringToParamMap()[key];
};
return this;
function toQueryString(paramMap) {
var qStrPairs = [];
for (var prop in paramMap) {
qStrPairs.push(encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop]));
}
return '?' + qStrPairs.join('&');
}
function queryStringToParamMap() {
var paramStr = options.getWindowLocation().search.substring(1),
params = [],
paramMap = {};
if (paramStr.length > 0) {
params = paramStr.split('&');
for (var i = 0; i < params.length; i++) {
var p = params[i].split('=');
var value = decodeURIComponent(p[1]);
if (value === 'true' || value === 'false') {
value = JSON.parse(value);
}
paramMap[decodeURIComponent(p[0])] = value;
}
}
return paramMap;
}
}
return QueryString;
};
| adellanno/thermostat_wed | lib/jasmine-2.3.4/jasmine-html.js | JavaScript | mit | 14,724 |
'use strict';
describe('basic mark with accuracy partially', function() {
var $ctx;
beforeEach(function(done) {
loadFixtures('basic/accuracy-partially.html');
$ctx = $('.basic-accuracy-partially');
new Mark($ctx[0]).mark('lorem', {
'accuracy': 'partially',
'separateWordSearch': false,
'done': done
});
});
it('should wrap the right matches', function() {
expect($ctx.find('mark')).toHaveLength(4);
$ctx.find('mark').each(function() {
expect($(this).text()).toBe('Lorem');
});
});
});
| julmot/jquery.mark | test/specs/basic/accuracy-partially.js | JavaScript | mit | 549 |
module.exports = function ({ $lookup }) {
return {
object: function () {
return function (object, $buffer, $start) {
$buffer[$start++] = object.nudge & 0xff
$buffer[$start++] = Number(object.value & 0xffn)
$buffer[$start++] = Number(object.value >> 8n & 0xffn)
$buffer[$start++] = Number(object.value >> 16n & 0xffn)
$buffer[$start++] = Number(object.value >> 24n & 0xffn)
$buffer[$start++] = Number(object.value >> 32n & 0xffn)
$buffer[$start++] = Number(object.value >> 40n & 0xffn)
$buffer[$start++] = Number(object.value >> 48n & 0xffn)
$buffer[$start++] = Number(object.value >> 56n & 0xffn)
$buffer[$start++] = object.sentry & 0xff
return { start: $start, serialize: null }
}
} ()
}
}
| bigeasy/packet | test/generated/bigint/le/long.serializer.all.js | JavaScript | mit | 918 |
import trimTransform from '../../../validations/trim';
import { module, test } from 'qunit';
module('Unit | Transform | trim');
test('valid', function(assert) {
assert.expect(1);
const trim = trimTransform.transform;
assert.deepEqual(trim('foo '), 'foo');
});
| JKGisMe/ember-stickler | tests/unit/validations/trim-test.js | JavaScript | mit | 273 |
CodeMirror.Vim.suppressErrorLogging = true;
var code = '' +
' wOrd1 (#%\n' +
' word3] \n' +
'aopop pop 0 1 2 3 4\n' +
' (a) [b] {c} \n' +
'int getchar(void) {\n' +
' static char buf[BUFSIZ];\n' +
' static char *bufp = buf;\n' +
' if (n == 0) { /* buffer is empty */\n' +
' n = read(0, buf, sizeof buf);\n' +
' bufp = buf;\n' +
' }\n' +
'\n' +
' return (--n >= 0) ? (unsigned char) *bufp++ : EOF;\n' +
' \n' +
'}\n';
var lines = (function() {
lineText = code.split('\n');
var ret = [];
for (var i = 0; i < lineText.length; i++) {
ret[i] = {
line: i,
length: lineText[i].length,
lineText: lineText[i],
textStart: /^\s*/.exec(lineText[i])[0].length
};
}
return ret;
})();
var endOfDocument = makeCursor(lines.length - 1,
lines[lines.length - 1].length);
var wordLine = lines[0];
var bigWordLine = lines[1];
var charLine = lines[2];
var bracesLine = lines[3];
var seekBraceLine = lines[4];
var word1 = {
start: { line: wordLine.line, ch: 1 },
end: { line: wordLine.line, ch: 5 }
};
var word2 = {
start: { line: wordLine.line, ch: word1.end.ch + 2 },
end: { line: wordLine.line, ch: word1.end.ch + 4 }
};
var word3 = {
start: { line: bigWordLine.line, ch: 1 },
end: { line: bigWordLine.line, ch: 5 }
};
var bigWord1 = word1;
var bigWord2 = word2;
var bigWord3 = {
start: { line: bigWordLine.line, ch: 1 },
end: { line: bigWordLine.line, ch: 7 }
};
var bigWord4 = {
start: { line: bigWordLine.line, ch: bigWord1.end.ch + 3 },
end: { line: bigWordLine.line, ch: bigWord1.end.ch + 7 }
};
var oChars = [ { line: charLine.line, ch: 1 },
{ line: charLine.line, ch: 3 },
{ line: charLine.line, ch: 7 } ];
var pChars = [ { line: charLine.line, ch: 2 },
{ line: charLine.line, ch: 4 },
{ line: charLine.line, ch: 6 },
{ line: charLine.line, ch: 8 } ];
var numChars = [ { line: charLine.line, ch: 10 },
{ line: charLine.line, ch: 12 },
{ line: charLine.line, ch: 14 },
{ line: charLine.line, ch: 16 },
{ line: charLine.line, ch: 18 }];
var parens1 = {
start: { line: bracesLine.line, ch: 1 },
end: { line: bracesLine.line, ch: 3 }
};
var squares1 = {
start: { line: bracesLine.line, ch: 5 },
end: { line: bracesLine.line, ch: 7 }
};
var curlys1 = {
start: { line: bracesLine.line, ch: 9 },
end: { line: bracesLine.line, ch: 11 }
};
var seekOutside = {
start: { line: seekBraceLine.line, ch: 1 },
end: { line: seekBraceLine.line, ch: 16 }
};
var seekInside = {
start: { line: seekBraceLine.line, ch: 14 },
end: { line: seekBraceLine.line, ch: 11 }
};
function copyCursor(cur) {
return { ch: cur.ch, line: cur.line };
}
function forEach(arr, func) {
for (var i = 0; i < arr.length; i++) {
func(arr[i], i, arr);
}
}
function testVim(name, run, opts, expectedFail) {
var vimOpts = {
lineNumbers: true,
vimMode: true,
showCursorWhenSelecting: true,
value: code
};
for (var prop in opts) {
if (opts.hasOwnProperty(prop)) {
vimOpts[prop] = opts[prop];
}
}
return test('vim_' + name, function() {
var place = document.getElementById("testground");
var cm = CodeMirror(place, vimOpts);
var vim = CodeMirror.Vim.maybeInitVimState_(cm);
function doKeysFn(cm) {
return function(args) {
if (args instanceof Array) {
arguments = args;
}
for (var i = 0; i < arguments.length; i++) {
CodeMirror.Vim.handleKey(cm, arguments[i]);
}
}
}
function doInsertModeKeysFn(cm) {
return function(args) {
if (args instanceof Array) { arguments = args; }
function executeHandler(handler) {
if (typeof handler == 'string') {
CodeMirror.commands[handler](cm);
} else {
handler(cm);
}
return true;
}
for (var i = 0; i < arguments.length; i++) {
var key = arguments[i];
// Find key in keymap and handle.
var handled = CodeMirror.lookupKey(key, 'vim-insert', executeHandler);
// Record for insert mode.
if (handled == "handled" && cm.state.vim.insertMode && arguments[i] != 'Esc') {
var lastChange = CodeMirror.Vim.getVimGlobalState_().macroModeState.lastInsertModeChanges;
if (lastChange) {
lastChange.changes.push(new CodeMirror.Vim.InsertModeKey(key));
}
}
}
}
}
function doExFn(cm) {
return function(command) {
cm.openDialog = helpers.fakeOpenDialog(command);
helpers.doKeys(':');
}
}
function assertCursorAtFn(cm) {
return function(line, ch) {
var pos;
if (ch == null && typeof line.line == 'number') {
pos = line;
} else {
pos = makeCursor(line, ch);
}
eqPos(pos, cm.getCursor());
}
}
function fakeOpenDialog(result) {
return function(text, callback) {
return callback(result);
}
}
function fakeOpenNotification(matcher) {
return function(text) {
matcher(text);
}
}
var helpers = {
doKeys: doKeysFn(cm),
// Warning: Only emulates keymap events, not character insertions. Use
// replaceRange to simulate character insertions.
// Keys are in CodeMirror format, NOT vim format.
doInsertModeKeys: doInsertModeKeysFn(cm),
doEx: doExFn(cm),
assertCursorAt: assertCursorAtFn(cm),
fakeOpenDialog: fakeOpenDialog,
fakeOpenNotification: fakeOpenNotification,
getRegisterController: function() {
return CodeMirror.Vim.getRegisterController();
}
}
CodeMirror.Vim.resetVimGlobalState_();
var successful = false;
var savedOpenNotification = cm.openNotification;
var savedOpenDialog = cm.openDialog;
try {
run(cm, vim, helpers);
successful = true;
} finally {
cm.openNotification = savedOpenNotification;
cm.openDialog = savedOpenDialog;
if (!successful || verbose) {
place.style.visibility = "visible";
} else {
place.removeChild(cm.getWrapperElement());
}
}
}, expectedFail);
};
testVim('qq@q', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('q', 'q', 'l', 'l', 'q');
helpers.assertCursorAt(0,2);
helpers.doKeys('@', 'q');
helpers.assertCursorAt(0,4);
}, { value: ' '});
testVim('@@', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('q', 'q', 'l', 'l', 'q');
helpers.assertCursorAt(0,2);
helpers.doKeys('@', 'q');
helpers.assertCursorAt(0,4);
helpers.doKeys('@', '@');
helpers.assertCursorAt(0,6);
}, { value: ' '});
var jumplistScene = ''+
'word\n'+
'(word)\n'+
'{word\n'+
'word.\n'+
'\n'+
'word search\n'+
'}word\n'+
'word\n'+
'word\n';
function testJumplist(name, keys, endPos, startPos, dialog) {
endPos = makeCursor(endPos[0], endPos[1]);
startPos = makeCursor(startPos[0], startPos[1]);
testVim(name, function(cm, vim, helpers) {
CodeMirror.Vim.resetVimGlobalState_();
if(dialog)cm.openDialog = helpers.fakeOpenDialog('word');
cm.setCursor(startPos);
helpers.doKeys.apply(null, keys);
helpers.assertCursorAt(endPos);
}, {value: jumplistScene});
};
testJumplist('jumplist_H', ['H', '<C-o>'], [5,2], [5,2]);
testJumplist('jumplist_M', ['M', '<C-o>'], [2,2], [2,2]);
testJumplist('jumplist_L', ['L', '<C-o>'], [2,2], [2,2]);
testJumplist('jumplist_[[', ['[', '[', '<C-o>'], [5,2], [5,2]);
testJumplist('jumplist_]]', [']', ']', '<C-o>'], [2,2], [2,2]);
testJumplist('jumplist_G', ['G', '<C-o>'], [5,2], [5,2]);
testJumplist('jumplist_gg', ['g', 'g', '<C-o>'], [5,2], [5,2]);
testJumplist('jumplist_%', ['%', '<C-o>'], [1,5], [1,5]);
testJumplist('jumplist_{', ['{', '<C-o>'], [1,5], [1,5]);
testJumplist('jumplist_}', ['}', '<C-o>'], [1,5], [1,5]);
testJumplist('jumplist_\'', ['m', 'a', 'h', '\'', 'a', 'h', '<C-i>'], [1,0], [1,5]);
testJumplist('jumplist_`', ['m', 'a', 'h', '`', 'a', 'h', '<C-i>'], [1,5], [1,5]);
testJumplist('jumplist_*_cachedCursor', ['*', '<C-o>'], [1,3], [1,3]);
testJumplist('jumplist_#_cachedCursor', ['#', '<C-o>'], [1,3], [1,3]);
testJumplist('jumplist_n', ['#', 'n', '<C-o>'], [1,1], [2,3]);
testJumplist('jumplist_N', ['#', 'N', '<C-o>'], [1,1], [2,3]);
testJumplist('jumplist_repeat_<c-o>', ['*', '*', '*', '3', '<C-o>'], [2,3], [2,3]);
testJumplist('jumplist_repeat_<c-i>', ['*', '*', '*', '3', '<C-o>', '2', '<C-i>'], [5,0], [2,3]);
testJumplist('jumplist_repeated_motion', ['3', '*', '<C-o>'], [2,3], [2,3]);
testJumplist('jumplist_/', ['/', '<C-o>'], [2,3], [2,3], 'dialog');
testJumplist('jumplist_?', ['?', '<C-o>'], [2,3], [2,3], 'dialog');
testJumplist('jumplist_skip_delted_mark<c-o>',
['*', 'n', 'n', 'k', 'd', 'k', '<C-o>', '<C-o>', '<C-o>'],
[0,2], [0,2]);
testJumplist('jumplist_skip_delted_mark<c-i>',
['*', 'n', 'n', 'k', 'd', 'k', '<C-o>', '<C-i>', '<C-i>'],
[1,0], [0,2]);
/**
* @param name Name of the test
* @param keys An array of keys or a string with a single key to simulate.
* @param endPos The expected end position of the cursor.
* @param startPos The position the cursor should start at, defaults to 0, 0.
*/
function testMotion(name, keys, endPos, startPos) {
testVim(name, function(cm, vim, helpers) {
if (!startPos) {
startPos = { line: 0, ch: 0 };
}
cm.setCursor(startPos);
helpers.doKeys(keys);
helpers.assertCursorAt(endPos);
});
};
function makeCursor(line, ch) {
return { line: line, ch: ch };
};
function offsetCursor(cur, offsetLine, offsetCh) {
return { line: cur.line + offsetLine, ch: cur.ch + offsetCh };
};
// Motion tests
testMotion('|', '|', makeCursor(0, 0), makeCursor(0,4));
testMotion('|_repeat', ['3', '|'], makeCursor(0, 2), makeCursor(0,4));
testMotion('h', 'h', makeCursor(0, 0), word1.start);
testMotion('h_repeat', ['3', 'h'], offsetCursor(word1.end, 0, -3), word1.end);
testMotion('l', 'l', makeCursor(0, 1));
testMotion('l_repeat', ['2', 'l'], makeCursor(0, 2));
testMotion('j', 'j', offsetCursor(word1.end, 1, 0), word1.end);
testMotion('j_repeat', ['2', 'j'], offsetCursor(word1.end, 2, 0), word1.end);
testMotion('j_repeat_clip', ['1000', 'j'], endOfDocument);
testMotion('k', 'k', offsetCursor(word3.end, -1, 0), word3.end);
testMotion('k_repeat', ['2', 'k'], makeCursor(0, 4), makeCursor(2, 4));
testMotion('k_repeat_clip', ['1000', 'k'], makeCursor(0, 4), makeCursor(2, 4));
testMotion('w', 'w', word1.start);
testMotion('w_multiple_newlines_no_space', 'w', makeCursor(12, 2), makeCursor(11, 2));
testMotion('w_multiple_newlines_with_space', 'w', makeCursor(14, 0), makeCursor(12, 51));
testMotion('w_repeat', ['2', 'w'], word2.start);
testMotion('w_wrap', ['w'], word3.start, word2.start);
testMotion('w_endOfDocument', 'w', endOfDocument, endOfDocument);
testMotion('w_start_to_end', ['1000', 'w'], endOfDocument, makeCursor(0, 0));
testMotion('W', 'W', bigWord1.start);
testMotion('W_repeat', ['2', 'W'], bigWord3.start, bigWord1.start);
testMotion('e', 'e', word1.end);
testMotion('e_repeat', ['2', 'e'], word2.end);
testMotion('e_wrap', 'e', word3.end, word2.end);
testMotion('e_endOfDocument', 'e', endOfDocument, endOfDocument);
testMotion('e_start_to_end', ['1000', 'e'], endOfDocument, makeCursor(0, 0));
testMotion('b', 'b', word3.start, word3.end);
testMotion('b_repeat', ['2', 'b'], word2.start, word3.end);
testMotion('b_wrap', 'b', word2.start, word3.start);
testMotion('b_startOfDocument', 'b', makeCursor(0, 0), makeCursor(0, 0));
testMotion('b_end_to_start', ['1000', 'b'], makeCursor(0, 0), endOfDocument);
testMotion('ge', ['g', 'e'], word2.end, word3.end);
testMotion('ge_repeat', ['2', 'g', 'e'], word1.end, word3.start);
testMotion('ge_wrap', ['g', 'e'], word2.end, word3.start);
testMotion('ge_startOfDocument', ['g', 'e'], makeCursor(0, 0),
makeCursor(0, 0));
testMotion('ge_end_to_start', ['1000', 'g', 'e'], makeCursor(0, 0), endOfDocument);
testMotion('gg', ['g', 'g'], makeCursor(lines[0].line, lines[0].textStart),
makeCursor(3, 1));
testMotion('gg_repeat', ['3', 'g', 'g'],
makeCursor(lines[2].line, lines[2].textStart));
testMotion('G', 'G',
makeCursor(lines[lines.length - 1].line, lines[lines.length - 1].textStart),
makeCursor(3, 1));
testMotion('G_repeat', ['3', 'G'], makeCursor(lines[2].line,
lines[2].textStart));
// TODO: Make the test code long enough to test Ctrl-F and Ctrl-B.
testMotion('0', '0', makeCursor(0, 0), makeCursor(0, 8));
testMotion('^', '^', makeCursor(0, lines[0].textStart), makeCursor(0, 8));
testMotion('+', '+', makeCursor(1, lines[1].textStart), makeCursor(0, 8));
testMotion('-', '-', makeCursor(0, lines[0].textStart), makeCursor(1, 4));
testMotion('_', ['6','_'], makeCursor(5, lines[5].textStart), makeCursor(0, 8));
testMotion('$', '$', makeCursor(0, lines[0].length - 1), makeCursor(0, 1));
testMotion('$_repeat', ['2', '$'], makeCursor(1, lines[1].length - 1),
makeCursor(0, 3));
testMotion('f', ['f', 'p'], pChars[0], makeCursor(charLine.line, 0));
testMotion('f_repeat', ['2', 'f', 'p'], pChars[2], pChars[0]);
testMotion('f_num', ['f', '2'], numChars[2], makeCursor(charLine.line, 0));
testMotion('t', ['t','p'], offsetCursor(pChars[0], 0, -1),
makeCursor(charLine.line, 0));
testMotion('t_repeat', ['2', 't', 'p'], offsetCursor(pChars[2], 0, -1),
pChars[0]);
testMotion('F', ['F', 'p'], pChars[0], pChars[1]);
testMotion('F_repeat', ['2', 'F', 'p'], pChars[0], pChars[2]);
testMotion('T', ['T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[1]);
testMotion('T_repeat', ['2', 'T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[2]);
testMotion('%_parens', ['%'], parens1.end, parens1.start);
testMotion('%_squares', ['%'], squares1.end, squares1.start);
testMotion('%_braces', ['%'], curlys1.end, curlys1.start);
testMotion('%_seek_outside', ['%'], seekOutside.end, seekOutside.start);
testMotion('%_seek_inside', ['%'], seekInside.end, seekInside.start);
testVim('%_seek_skip', function(cm, vim, helpers) {
cm.setCursor(0,0);
helpers.doKeys(['%']);
helpers.assertCursorAt(0,9);
}, {value:'01234"("()'});
testVim('%_skip_string', function(cm, vim, helpers) {
cm.setCursor(0,0);
helpers.doKeys(['%']);
helpers.assertCursorAt(0,4);
cm.setCursor(0,2);
helpers.doKeys(['%']);
helpers.assertCursorAt(0,0);
}, {value:'(")")'});
testVim('%_skip_comment', function(cm, vim, helpers) {
cm.setCursor(0,0);
helpers.doKeys(['%']);
helpers.assertCursorAt(0,6);
cm.setCursor(0,3);
helpers.doKeys(['%']);
helpers.assertCursorAt(0,0);
}, {value:'(/*)*/)'});
// Make sure that moving down after going to the end of a line always leaves you
// at the end of a line, but preserves the offset in other cases
testVim('Changing lines after Eol operation', function(cm, vim, helpers) {
cm.setCursor(0,0);
helpers.doKeys(['$']);
helpers.doKeys(['j']);
// After moving to Eol and then down, we should be at Eol of line 2
helpers.assertCursorAt({ line: 1, ch: lines[1].length - 1 });
helpers.doKeys(['j']);
// After moving down, we should be at Eol of line 3
helpers.assertCursorAt({ line: 2, ch: lines[2].length - 1 });
helpers.doKeys(['h']);
helpers.doKeys(['j']);
// After moving back one space and then down, since line 4 is shorter than line 2, we should
// be at Eol of line 2 - 1
helpers.assertCursorAt({ line: 3, ch: lines[3].length - 1 });
helpers.doKeys(['j']);
helpers.doKeys(['j']);
// After moving down again, since line 3 has enough characters, we should be back to the
// same place we were at on line 1
helpers.assertCursorAt({ line: 5, ch: lines[2].length - 2 });
});
//making sure gj and gk recover from clipping
testVim('gj_gk_clipping', function(cm,vim,helpers){
cm.setCursor(0, 1);
helpers.doKeys('g','j','g','j');
helpers.assertCursorAt(2, 1);
helpers.doKeys('g','k','g','k');
helpers.assertCursorAt(0, 1);
},{value: 'line 1\n\nline 2'});
//testing a mix of j/k and gj/gk
testVim('j_k_and_gj_gk', function(cm,vim,helpers){
cm.setSize(120);
cm.setCursor(0, 0);
//go to the last character on the first line
helpers.doKeys('$');
//move up/down on the column within the wrapped line
//side-effect: cursor is not locked to eol anymore
helpers.doKeys('g','k');
var cur=cm.getCursor();
eq(cur.line,0);
is((cur.ch<176),'gk didn\'t move cursor back (1)');
helpers.doKeys('g','j');
helpers.assertCursorAt(0, 176);
//should move to character 177 on line 2 (j/k preserve character index within line)
helpers.doKeys('j');
//due to different line wrapping, the cursor can be on a different screen-x now
//gj and gk preserve screen-x on movement, much like moveV
helpers.doKeys('3','g','k');
cur=cm.getCursor();
eq(cur.line,1);
is((cur.ch<176),'gk didn\'t move cursor back (2)');
helpers.doKeys('g','j','2','g','j');
//should return to the same character-index
helpers.doKeys('k');
helpers.assertCursorAt(0, 176);
},{ lineWrapping:true, value: 'This line is intentially long to test movement of gj and gk over wrapped lines. I will start on the end of this line, then make a step up and back to set the origin for j and k.\nThis line is supposed to be even longer than the previous. I will jump here and make another wiggle with gj and gk, before I jump back to the line above. Both wiggles should not change my cursor\'s target character but both j/k and gj/gk change each other\'s reference position.'});
testVim('gj_gk', function(cm, vim, helpers) {
if (phantom) return;
cm.setSize(120);
// Test top of document edge case.
cm.setCursor(0, 4);
helpers.doKeys('g', 'j');
helpers.doKeys('10', 'g', 'k');
helpers.assertCursorAt(0, 4);
// Test moving down preserves column position.
helpers.doKeys('g', 'j');
var pos1 = cm.getCursor();
var expectedPos2 = { line: 0, ch: (pos1.ch - 4) * 2 + 4};
helpers.doKeys('g', 'j');
helpers.assertCursorAt(expectedPos2);
// Move to the last character
cm.setCursor(0, 0);
// Move left to reset HSPos
helpers.doKeys('h');
// Test bottom of document edge case.
helpers.doKeys('100', 'g', 'j');
var endingPos = cm.getCursor();
is(endingPos != 0, 'gj should not be on wrapped line 0');
var topLeftCharCoords = cm.charCoords(makeCursor(0, 0));
var endingCharCoords = cm.charCoords(endingPos);
is(topLeftCharCoords.left == endingCharCoords.left, 'gj should end up on column 0');
},{ lineNumbers: false, lineWrapping:true, value: 'Thislineisintentiallylongtotestmovementofgjandgkoverwrappedlines.' });
testVim('}', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('}');
helpers.assertCursorAt(1, 0);
cm.setCursor(0, 0);
helpers.doKeys('2', '}');
helpers.assertCursorAt(4, 0);
cm.setCursor(0, 0);
helpers.doKeys('6', '}');
helpers.assertCursorAt(5, 0);
}, { value: 'a\n\nb\nc\n\nd' });
testVim('{', function(cm, vim, helpers) {
cm.setCursor(5, 0);
helpers.doKeys('{');
helpers.assertCursorAt(4, 0);
cm.setCursor(5, 0);
helpers.doKeys('2', '{');
helpers.assertCursorAt(1, 0);
cm.setCursor(5, 0);
helpers.doKeys('6', '{');
helpers.assertCursorAt(0, 0);
}, { value: 'a\n\nb\nc\n\nd' });
testVim('paragraph_motions', function(cm, vim, helpers) {
cm.setCursor(10, 0);
helpers.doKeys('{');
helpers.assertCursorAt(4, 0);
helpers.doKeys('{');
helpers.assertCursorAt(0, 0);
helpers.doKeys('2', '}');
helpers.assertCursorAt(7, 0);
helpers.doKeys('2', '}');
helpers.assertCursorAt(16, 0);
cm.setCursor(9, 0);
helpers.doKeys('}');
helpers.assertCursorAt(14, 0);
cm.setCursor(6, 0);
helpers.doKeys('}');
helpers.assertCursorAt(7, 0);
// ip inside empty space
cm.setCursor(10, 0);
helpers.doKeys('v', 'i', 'p');
eqPos(Pos(7, 0), cm.getCursor('anchor'));
eqPos(Pos(12, 0), cm.getCursor('head'));
helpers.doKeys('i', 'p');
eqPos(Pos(7, 0), cm.getCursor('anchor'));
eqPos(Pos(13, 1), cm.getCursor('head'));
helpers.doKeys('2', 'i', 'p');
eqPos(Pos(7, 0), cm.getCursor('anchor'));
eqPos(Pos(16, 1), cm.getCursor('head'));
// should switch to visualLine mode
cm.setCursor(14, 0);
helpers.doKeys('<Esc>', 'v', 'i', 'p');
helpers.assertCursorAt(14, 0);
cm.setCursor(14, 0);
helpers.doKeys('<Esc>', 'V', 'i', 'p');
eqPos(Pos(16, 1), cm.getCursor('head'));
// ap inside empty space
cm.setCursor(10, 0);
helpers.doKeys('<Esc>', 'v', 'a', 'p');
eqPos(Pos(7, 0), cm.getCursor('anchor'));
eqPos(Pos(13, 1), cm.getCursor('head'));
helpers.doKeys('a', 'p');
eqPos(Pos(7, 0), cm.getCursor('anchor'));
eqPos(Pos(16, 1), cm.getCursor('head'));
cm.setCursor(13, 0);
helpers.doKeys('v', 'a', 'p');
eqPos(Pos(13, 0), cm.getCursor('anchor'));
eqPos(Pos(14, 0), cm.getCursor('head'));
cm.setCursor(16, 0);
helpers.doKeys('v', 'a', 'p');
eqPos(Pos(14, 0), cm.getCursor('anchor'));
eqPos(Pos(16, 1), cm.getCursor('head'));
cm.setCursor(0, 0);
helpers.doKeys('v', 'a', 'p');
eqPos(Pos(0, 0), cm.getCursor('anchor'));
eqPos(Pos(4, 0), cm.getCursor('head'));
cm.setCursor(0, 0);
helpers.doKeys('d', 'i', 'p');
var register = helpers.getRegisterController().getRegister();
eq('a\na\n', register.toString());
is(register.linewise);
helpers.doKeys('3', 'j', 'p');
helpers.doKeys('y', 'i', 'p');
is(register.linewise);
eq('b\na\na\nc\n', register.toString());
}, { value: 'a\na\n\n\n\nb\nc\n\n\n\n\n\n\nd\n\ne\nf' });
// Operator tests
testVim('dl', function(cm, vim, helpers) {
var curStart = makeCursor(0, 0);
cm.setCursor(curStart);
helpers.doKeys('d', 'l');
eq('word1 ', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq(' ', register.toString());
is(!register.linewise);
eqPos(curStart, cm.getCursor());
}, { value: ' word1 ' });
testVim('dl_eol', function(cm, vim, helpers) {
cm.setCursor(0, 6);
helpers.doKeys('d', 'l');
eq(' word1', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq(' ', register.toString());
is(!register.linewise);
helpers.assertCursorAt(0, 5);
}, { value: ' word1 ' });
testVim('dl_repeat', function(cm, vim, helpers) {
var curStart = makeCursor(0, 0);
cm.setCursor(curStart);
helpers.doKeys('2', 'd', 'l');
eq('ord1 ', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq(' w', register.toString());
is(!register.linewise);
eqPos(curStart, cm.getCursor());
}, { value: ' word1 ' });
testVim('dh', function(cm, vim, helpers) {
var curStart = makeCursor(0, 3);
cm.setCursor(curStart);
helpers.doKeys('d', 'h');
eq(' wrd1 ', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('o', register.toString());
is(!register.linewise);
eqPos(offsetCursor(curStart, 0 , -1), cm.getCursor());
}, { value: ' word1 ' });
testVim('dj', function(cm, vim, helpers) {
var curStart = makeCursor(0, 3);
cm.setCursor(curStart);
helpers.doKeys('d', 'j');
eq(' word3', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq(' word1\nword2\n', register.toString());
is(register.linewise);
helpers.assertCursorAt(0, 1);
}, { value: ' word1\nword2\n word3' });
testVim('dj_end_of_document', function(cm, vim, helpers) {
var curStart = makeCursor(0, 3);
cm.setCursor(curStart);
helpers.doKeys('d', 'j');
eq(' word1 ', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('', register.toString());
is(!register.linewise);
helpers.assertCursorAt(0, 3);
}, { value: ' word1 ' });
testVim('dk', function(cm, vim, helpers) {
var curStart = makeCursor(1, 3);
cm.setCursor(curStart);
helpers.doKeys('d', 'k');
eq(' word3', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq(' word1\nword2\n', register.toString());
is(register.linewise);
helpers.assertCursorAt(0, 1);
}, { value: ' word1\nword2\n word3' });
testVim('dk_start_of_document', function(cm, vim, helpers) {
var curStart = makeCursor(0, 3);
cm.setCursor(curStart);
helpers.doKeys('d', 'k');
eq(' word1 ', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('', register.toString());
is(!register.linewise);
helpers.assertCursorAt(0, 3);
}, { value: ' word1 ' });
testVim('dw_space', function(cm, vim, helpers) {
var curStart = makeCursor(0, 0);
cm.setCursor(curStart);
helpers.doKeys('d', 'w');
eq('word1 ', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq(' ', register.toString());
is(!register.linewise);
eqPos(curStart, cm.getCursor());
}, { value: ' word1 ' });
testVim('dw_word', function(cm, vim, helpers) {
var curStart = makeCursor(0, 1);
cm.setCursor(curStart);
helpers.doKeys('d', 'w');
eq(' word2', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('word1 ', register.toString());
is(!register.linewise);
eqPos(curStart, cm.getCursor());
}, { value: ' word1 word2' });
testVim('dw_unicode_word', function(cm, vim, helpers) {
helpers.doKeys('d', 'w');
eq(cm.getValue().length, 10);
helpers.doKeys('d', 'w');
eq(cm.getValue().length, 6);
helpers.doKeys('d', 'w');
eq(cm.getValue().length, 5);
helpers.doKeys('d', 'e');
eq(cm.getValue().length, 2);
}, { value: ' \u0562\u0561\u0580\u0587\xbbe\xb5g ' });
testVim('dw_only_word', function(cm, vim, helpers) {
// Test that if there is only 1 word left, dw deletes till the end of the
// line.
cm.setCursor(0, 1);
helpers.doKeys('d', 'w');
eq(' ', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('word1 ', register.toString());
is(!register.linewise);
helpers.assertCursorAt(0, 0);
}, { value: ' word1 ' });
testVim('dw_eol', function(cm, vim, helpers) {
// Assert that dw does not delete the newline if last word to delete is at end
// of line.
cm.setCursor(0, 1);
helpers.doKeys('d', 'w');
eq(' \nword2', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('word1', register.toString());
is(!register.linewise);
helpers.assertCursorAt(0, 0);
}, { value: ' word1\nword2' });
testVim('dw_eol_with_multiple_newlines', function(cm, vim, helpers) {
// Assert that dw does not delete the newline if last word to delete is at end
// of line and it is followed by multiple newlines.
cm.setCursor(0, 1);
helpers.doKeys('d', 'w');
eq(' \n\nword2', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('word1', register.toString());
is(!register.linewise);
helpers.assertCursorAt(0, 0);
}, { value: ' word1\n\nword2' });
testVim('dw_empty_line_followed_by_whitespace', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('d', 'w');
eq(' \nword', cm.getValue());
}, { value: '\n \nword' });
testVim('dw_empty_line_followed_by_word', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('d', 'w');
eq('word', cm.getValue());
}, { value: '\nword' });
testVim('dw_empty_line_followed_by_empty_line', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('d', 'w');
eq('\n', cm.getValue());
}, { value: '\n\n' });
testVim('dw_whitespace_followed_by_whitespace', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('d', 'w');
eq('\n \n', cm.getValue());
}, { value: ' \n \n' });
testVim('dw_whitespace_followed_by_empty_line', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('d', 'w');
eq('\n\n', cm.getValue());
}, { value: ' \n\n' });
testVim('dw_word_whitespace_word', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('d', 'w');
eq('\n \nword2', cm.getValue());
}, { value: 'word1\n \nword2'})
testVim('dw_end_of_document', function(cm, vim, helpers) {
cm.setCursor(1, 2);
helpers.doKeys('d', 'w');
eq('\nab', cm.getValue());
}, { value: '\nabc' });
testVim('dw_repeat', function(cm, vim, helpers) {
// Assert that dw does delete newline if it should go to the next line, and
// that repeat works properly.
cm.setCursor(0, 1);
helpers.doKeys('d', '2', 'w');
eq(' ', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('word1\nword2', register.toString());
is(!register.linewise);
helpers.assertCursorAt(0, 0);
}, { value: ' word1\nword2' });
testVim('de_word_start_and_empty_lines', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('d', 'e');
eq('\n\n', cm.getValue());
}, { value: 'word\n\n' });
testVim('de_word_end_and_empty_lines', function(cm, vim, helpers) {
cm.setCursor(0, 3);
helpers.doKeys('d', 'e');
eq('wor', cm.getValue());
}, { value: 'word\n\n\n' });
testVim('de_whitespace_and_empty_lines', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('d', 'e');
eq('', cm.getValue());
}, { value: ' \n\n\n' });
testVim('de_end_of_document', function(cm, vim, helpers) {
cm.setCursor(1, 2);
helpers.doKeys('d', 'e');
eq('\nab', cm.getValue());
}, { value: '\nabc' });
testVim('db_empty_lines', function(cm, vim, helpers) {
cm.setCursor(2, 0);
helpers.doKeys('d', 'b');
eq('\n\n', cm.getValue());
}, { value: '\n\n\n' });
testVim('db_word_start_and_empty_lines', function(cm, vim, helpers) {
cm.setCursor(2, 0);
helpers.doKeys('d', 'b');
eq('\nword', cm.getValue());
}, { value: '\n\nword' });
testVim('db_word_end_and_empty_lines', function(cm, vim, helpers) {
cm.setCursor(2, 3);
helpers.doKeys('d', 'b');
eq('\n\nd', cm.getValue());
}, { value: '\n\nword' });
testVim('db_whitespace_and_empty_lines', function(cm, vim, helpers) {
cm.setCursor(2, 0);
helpers.doKeys('d', 'b');
eq('', cm.getValue());
}, { value: '\n \n' });
testVim('db_start_of_document', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('d', 'b');
eq('abc\n', cm.getValue());
}, { value: 'abc\n' });
testVim('dge_empty_lines', function(cm, vim, helpers) {
cm.setCursor(1, 0);
helpers.doKeys('d', 'g', 'e');
// Note: In real VIM the result should be '', but it's not quite consistent,
// since 2 newlines are deleted. But in the similar case of word\n\n, only
// 1 newline is deleted. We'll diverge from VIM's behavior since it's much
// easier this way.
eq('\n', cm.getValue());
}, { value: '\n\n' });
testVim('dge_word_and_empty_lines', function(cm, vim, helpers) {
cm.setCursor(1, 0);
helpers.doKeys('d', 'g', 'e');
eq('wor\n', cm.getValue());
}, { value: 'word\n\n'});
testVim('dge_whitespace_and_empty_lines', function(cm, vim, helpers) {
cm.setCursor(2, 0);
helpers.doKeys('d', 'g', 'e');
eq('', cm.getValue());
}, { value: '\n \n' });
testVim('dge_start_of_document', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('d', 'g', 'e');
eq('bc\n', cm.getValue());
}, { value: 'abc\n' });
testVim('d_inclusive', function(cm, vim, helpers) {
// Assert that when inclusive is set, the character the cursor is on gets
// deleted too.
var curStart = makeCursor(0, 1);
cm.setCursor(curStart);
helpers.doKeys('d', 'e');
eq(' ', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('word1', register.toString());
is(!register.linewise);
eqPos(curStart, cm.getCursor());
}, { value: ' word1 ' });
testVim('d_reverse', function(cm, vim, helpers) {
// Test that deleting in reverse works.
cm.setCursor(1, 0);
helpers.doKeys('d', 'b');
eq(' word2 ', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('word1\n', register.toString());
is(!register.linewise);
helpers.assertCursorAt(0, 1);
}, { value: ' word1\nword2 ' });
testVim('dd', function(cm, vim, helpers) {
cm.setCursor(0, 3);
var expectedBuffer = cm.getRange({ line: 0, ch: 0 },
{ line: 1, ch: 0 });
var expectedLineCount = cm.lineCount() - 1;
helpers.doKeys('d', 'd');
eq(expectedLineCount, cm.lineCount());
var register = helpers.getRegisterController().getRegister();
eq(expectedBuffer, register.toString());
is(register.linewise);
helpers.assertCursorAt(0, lines[1].textStart);
});
testVim('dd_prefix_repeat', function(cm, vim, helpers) {
cm.setCursor(0, 3);
var expectedBuffer = cm.getRange({ line: 0, ch: 0 },
{ line: 2, ch: 0 });
var expectedLineCount = cm.lineCount() - 2;
helpers.doKeys('2', 'd', 'd');
eq(expectedLineCount, cm.lineCount());
var register = helpers.getRegisterController().getRegister();
eq(expectedBuffer, register.toString());
is(register.linewise);
helpers.assertCursorAt(0, lines[2].textStart);
});
testVim('dd_motion_repeat', function(cm, vim, helpers) {
cm.setCursor(0, 3);
var expectedBuffer = cm.getRange({ line: 0, ch: 0 },
{ line: 2, ch: 0 });
var expectedLineCount = cm.lineCount() - 2;
helpers.doKeys('d', '2', 'd');
eq(expectedLineCount, cm.lineCount());
var register = helpers.getRegisterController().getRegister();
eq(expectedBuffer, register.toString());
is(register.linewise);
helpers.assertCursorAt(0, lines[2].textStart);
});
testVim('dd_multiply_repeat', function(cm, vim, helpers) {
cm.setCursor(0, 3);
var expectedBuffer = cm.getRange({ line: 0, ch: 0 },
{ line: 6, ch: 0 });
var expectedLineCount = cm.lineCount() - 6;
helpers.doKeys('2', 'd', '3', 'd');
eq(expectedLineCount, cm.lineCount());
var register = helpers.getRegisterController().getRegister();
eq(expectedBuffer, register.toString());
is(register.linewise);
helpers.assertCursorAt(0, lines[6].textStart);
});
testVim('dd_lastline', function(cm, vim, helpers) {
cm.setCursor(cm.lineCount(), 0);
var expectedLineCount = cm.lineCount() - 1;
helpers.doKeys('d', 'd');
eq(expectedLineCount, cm.lineCount());
helpers.assertCursorAt(cm.lineCount() - 1, 0);
});
testVim('dd_only_line', function(cm, vim, helpers) {
cm.setCursor(0, 0);
var expectedRegister = cm.getValue() + "\n";
helpers.doKeys('d','d');
eq(1, cm.lineCount());
eq('', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq(expectedRegister, register.toString());
}, { value: "thisistheonlyline" });
// Yank commands should behave the exact same as d commands, expect that nothing
// gets deleted.
testVim('yw_repeat', function(cm, vim, helpers) {
// Assert that yw does yank newline if it should go to the next line, and
// that repeat works properly.
var curStart = makeCursor(0, 1);
cm.setCursor(curStart);
helpers.doKeys('y', '2', 'w');
eq(' word1\nword2', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('word1\nword2', register.toString());
is(!register.linewise);
eqPos(curStart, cm.getCursor());
}, { value: ' word1\nword2' });
testVim('yy_multiply_repeat', function(cm, vim, helpers) {
var curStart = makeCursor(0, 3);
cm.setCursor(curStart);
var expectedBuffer = cm.getRange({ line: 0, ch: 0 },
{ line: 6, ch: 0 });
var expectedLineCount = cm.lineCount();
helpers.doKeys('2', 'y', '3', 'y');
eq(expectedLineCount, cm.lineCount());
var register = helpers.getRegisterController().getRegister();
eq(expectedBuffer, register.toString());
is(register.linewise);
eqPos(curStart, cm.getCursor());
});
// Change commands behave like d commands except that it also enters insert
// mode. In addition, when the change is linewise, an additional newline is
// inserted so that insert mode starts on that line.
testVim('cw', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('c', '2', 'w');
eq(' word3', cm.getValue());
helpers.assertCursorAt(0, 0);
}, { value: 'word1 word2 word3'});
testVim('cw_repeat', function(cm, vim, helpers) {
// Assert that cw does delete newline if it should go to the next line, and
// that repeat works properly.
var curStart = makeCursor(0, 1);
cm.setCursor(curStart);
helpers.doKeys('c', '2', 'w');
eq(' ', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('word1\nword2', register.toString());
is(!register.linewise);
eqPos(curStart, cm.getCursor());
eq('vim-insert', cm.getOption('keyMap'));
}, { value: ' word1\nword2' });
testVim('cc_multiply_repeat', function(cm, vim, helpers) {
cm.setCursor(0, 3);
var expectedBuffer = cm.getRange({ line: 0, ch: 0 },
{ line: 6, ch: 0 });
var expectedLineCount = cm.lineCount() - 5;
helpers.doKeys('2', 'c', '3', 'c');
eq(expectedLineCount, cm.lineCount());
var register = helpers.getRegisterController().getRegister();
eq(expectedBuffer, register.toString());
is(register.linewise);
eq('vim-insert', cm.getOption('keyMap'));
});
testVim('ct', function(cm, vim, helpers) {
cm.setCursor(0, 9);
helpers.doKeys('c', 't', 'w');
eq(' word1 word3', cm.getValue());
helpers.doKeys('<Esc>', 'c', '|');
eq(' word3', cm.getValue());
helpers.assertCursorAt(0, 0);
helpers.doKeys('<Esc>', '2', 'u', 'w', 'h');
helpers.doKeys('c', '2', 'g', 'e');
eq(' wordword3', cm.getValue());
}, { value: ' word1 word2 word3'});
testVim('cc_should_not_append_to_document', function(cm, vim, helpers) {
var expectedLineCount = cm.lineCount();
cm.setCursor(cm.lastLine(), 0);
helpers.doKeys('c', 'c');
eq(expectedLineCount, cm.lineCount());
});
function fillArray(val, times) {
var arr = [];
for (var i = 0; i < times; i++) {
arr.push(val);
}
return arr;
}
testVim('c_visual_block', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'l', 'c');
var replacement = fillArray('hello', 3);
cm.replaceSelections(replacement);
eq('1hello\n5hello\nahellofg', cm.getValue());
helpers.doKeys('<Esc>');
cm.setCursor(2, 3);
helpers.doKeys('<C-v>', '2', 'k', 'h', 'C');
replacement = fillArray('world', 3);
cm.replaceSelections(replacement);
eq('1hworld\n5hworld\nahworld', cm.getValue());
}, {value: '1234\n5678\nabcdefg'});
testVim('c_visual_block_replay', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('<C-v>', '2', 'j', 'l', 'c');
var replacement = fillArray('fo', 3);
cm.replaceSelections(replacement);
eq('1fo4\n5fo8\nafodefg', cm.getValue());
helpers.doKeys('<Esc>');
cm.setCursor(0, 0);
helpers.doKeys('.');
eq('foo4\nfoo8\nfoodefg', cm.getValue());
}, {value: '1234\n5678\nabcdefg'});
testVim('d_visual_block', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'l', 'd');
eq('1\n5\nafg', cm.getValue());
}, {value: '1234\n5678\nabcdefg'});
testVim('D_visual_block', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('<C-v>', '2', 'j', 'l', 'D');
eq('1\n5\na', cm.getValue());
}, {value: '1234\n5678\nabcdefg'});
// Swapcase commands edit in place and do not modify registers.
testVim('g~w_repeat', function(cm, vim, helpers) {
// Assert that dw does delete newline if it should go to the next line, and
// that repeat works properly.
var curStart = makeCursor(0, 1);
cm.setCursor(curStart);
helpers.doKeys('g', '~', '2', 'w');
eq(' WORD1\nWORD2', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('', register.toString());
is(!register.linewise);
eqPos(curStart, cm.getCursor());
}, { value: ' word1\nword2' });
testVim('g~g~', function(cm, vim, helpers) {
var curStart = makeCursor(0, 3);
cm.setCursor(curStart);
var expectedLineCount = cm.lineCount();
var expectedValue = cm.getValue().toUpperCase();
helpers.doKeys('2', 'g', '~', '3', 'g', '~');
eq(expectedValue, cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('', register.toString());
is(!register.linewise);
eqPos(curStart, cm.getCursor());
}, { value: ' word1\nword2\nword3\nword4\nword5\nword6' });
testVim('gu_and_gU', function(cm, vim, helpers) {
var curStart = makeCursor(0, 7);
var value = cm.getValue();
cm.setCursor(curStart);
helpers.doKeys('2', 'g', 'U', 'w');
eq(cm.getValue(), 'wa wb xX WC wd');
eqPos(curStart, cm.getCursor());
helpers.doKeys('2', 'g', 'u', 'w');
eq(cm.getValue(), value);
helpers.doKeys('2', 'g', 'U', 'B');
eq(cm.getValue(), 'wa WB Xx wc wd');
eqPos(makeCursor(0, 3), cm.getCursor());
cm.setCursor(makeCursor(0, 4));
helpers.doKeys('g', 'u', 'i', 'w');
eq(cm.getValue(), 'wa wb Xx wc wd');
eqPos(makeCursor(0, 3), cm.getCursor());
// TODO: support gUgU guu
// eqPos(makeCursor(0, 0), cm.getCursor());
var register = helpers.getRegisterController().getRegister();
eq('', register.toString());
is(!register.linewise);
}, { value: 'wa wb xx wc wd' });
testVim('visual_block_~', function(cm, vim, helpers) {
cm.setCursor(1, 1);
helpers.doKeys('<C-v>', 'l', 'l', 'j', '~');
helpers.assertCursorAt(1, 1);
eq('hello\nwoRLd\naBCDe', cm.getValue());
cm.setCursor(2, 0);
helpers.doKeys('v', 'l', 'l', '~');
helpers.assertCursorAt(2, 0);
eq('hello\nwoRLd\nAbcDe', cm.getValue());
},{value: 'hello\nwOrld\nabcde' });
testVim('._swapCase_visualBlock', function(cm, vim, helpers) {
helpers.doKeys('<C-v>', 'j', 'j', 'l', '~');
cm.setCursor(0, 3);
helpers.doKeys('.');
eq('HelLO\nWorLd\nAbcdE', cm.getValue());
},{value: 'hEllo\nwOrlD\naBcDe' });
testVim('._delete_visualBlock', function(cm, vim, helpers) {
helpers.doKeys('<C-v>', 'j', 'x');
eq('ive\ne\nsome\nsugar', cm.getValue());
helpers.doKeys('.');
eq('ve\n\nsome\nsugar', cm.getValue());
helpers.doKeys('j', 'j', '.');
eq('ve\n\nome\nugar', cm.getValue());
helpers.doKeys('u', '<C-r>', '.');
eq('ve\n\nme\ngar', cm.getValue());
},{value: 'give\nme\nsome\nsugar' });
testVim('>{motion}', function(cm, vim, helpers) {
cm.setCursor(1, 3);
var expectedLineCount = cm.lineCount();
var expectedValue = ' word1\n word2\nword3 ';
helpers.doKeys('>', 'k');
eq(expectedValue, cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('', register.toString());
is(!register.linewise);
helpers.assertCursorAt(0, 3);
}, { value: ' word1\nword2\nword3 ', indentUnit: 2 });
testVim('>>', function(cm, vim, helpers) {
cm.setCursor(0, 3);
var expectedLineCount = cm.lineCount();
var expectedValue = ' word1\n word2\nword3 ';
helpers.doKeys('2', '>', '>');
eq(expectedValue, cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('', register.toString());
is(!register.linewise);
helpers.assertCursorAt(0, 3);
}, { value: ' word1\nword2\nword3 ', indentUnit: 2 });
testVim('<{motion}', function(cm, vim, helpers) {
cm.setCursor(1, 3);
var expectedLineCount = cm.lineCount();
var expectedValue = ' word1\nword2\nword3 ';
helpers.doKeys('<', 'k');
eq(expectedValue, cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('', register.toString());
is(!register.linewise);
helpers.assertCursorAt(0, 1);
}, { value: ' word1\n word2\nword3 ', indentUnit: 2 });
testVim('<<', function(cm, vim, helpers) {
cm.setCursor(0, 3);
var expectedLineCount = cm.lineCount();
var expectedValue = ' word1\nword2\nword3 ';
helpers.doKeys('2', '<', '<');
eq(expectedValue, cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('', register.toString());
is(!register.linewise);
helpers.assertCursorAt(0, 1);
}, { value: ' word1\n word2\nword3 ', indentUnit: 2 });
// Edit tests
function testEdit(name, before, pos, edit, after) {
return testVim(name, function(cm, vim, helpers) {
var ch = before.search(pos)
var line = before.substring(0, ch).split('\n').length - 1;
if (line) {
ch = before.substring(0, ch).split('\n').pop().length;
}
cm.setCursor(line, ch);
helpers.doKeys.apply(this, edit.split(''));
eq(after, cm.getValue());
}, {value: before});
}
// These Delete tests effectively cover word-wise Change, Visual & Yank.
// Tabs are used as differentiated whitespace to catch edge cases.
// Normal word:
testEdit('diw_mid_spc', 'foo \tbAr\t baz', /A/, 'diw', 'foo \t\t baz');
testEdit('daw_mid_spc', 'foo \tbAr\t baz', /A/, 'daw', 'foo \tbaz');
testEdit('diw_mid_punct', 'foo \tbAr.\t baz', /A/, 'diw', 'foo \t.\t baz');
testEdit('daw_mid_punct', 'foo \tbAr.\t baz', /A/, 'daw', 'foo.\t baz');
testEdit('diw_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'diw', 'foo \t,.\t baz');
testEdit('daw_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'daw', 'foo \t,.\t baz');
testEdit('diw_start_spc', 'bAr \tbaz', /A/, 'diw', ' \tbaz');
testEdit('daw_start_spc', 'bAr \tbaz', /A/, 'daw', 'baz');
testEdit('diw_start_punct', 'bAr. \tbaz', /A/, 'diw', '. \tbaz');
testEdit('daw_start_punct', 'bAr. \tbaz', /A/, 'daw', '. \tbaz');
testEdit('diw_end_spc', 'foo \tbAr', /A/, 'diw', 'foo \t');
testEdit('daw_end_spc', 'foo \tbAr', /A/, 'daw', 'foo');
testEdit('diw_end_punct', 'foo \tbAr.', /A/, 'diw', 'foo \t.');
testEdit('daw_end_punct', 'foo \tbAr.', /A/, 'daw', 'foo.');
// Big word:
testEdit('diW_mid_spc', 'foo \tbAr\t baz', /A/, 'diW', 'foo \t\t baz');
testEdit('daW_mid_spc', 'foo \tbAr\t baz', /A/, 'daW', 'foo \tbaz');
testEdit('diW_mid_punct', 'foo \tbAr.\t baz', /A/, 'diW', 'foo \t\t baz');
testEdit('daW_mid_punct', 'foo \tbAr.\t baz', /A/, 'daW', 'foo \tbaz');
testEdit('diW_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'diW', 'foo \t\t baz');
testEdit('daW_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'daW', 'foo \tbaz');
testEdit('diW_start_spc', 'bAr\t baz', /A/, 'diW', '\t baz');
testEdit('daW_start_spc', 'bAr\t baz', /A/, 'daW', 'baz');
testEdit('diW_start_punct', 'bAr.\t baz', /A/, 'diW', '\t baz');
testEdit('daW_start_punct', 'bAr.\t baz', /A/, 'daW', 'baz');
testEdit('diW_end_spc', 'foo \tbAr', /A/, 'diW', 'foo \t');
testEdit('daW_end_spc', 'foo \tbAr', /A/, 'daW', 'foo');
testEdit('diW_end_punct', 'foo \tbAr.', /A/, 'diW', 'foo \t');
testEdit('daW_end_punct', 'foo \tbAr.', /A/, 'daW', 'foo');
// Deleting text objects
// Open and close on same line
testEdit('di(_open_spc', 'foo (bAr) baz', /\(/, 'di(', 'foo () baz');
testEdit('di)_open_spc', 'foo (bAr) baz', /\(/, 'di)', 'foo () baz');
testEdit('dib_open_spc', 'foo (bAr) baz', /\(/, 'dib', 'foo () baz');
testEdit('da(_open_spc', 'foo (bAr) baz', /\(/, 'da(', 'foo baz');
testEdit('da)_open_spc', 'foo (bAr) baz', /\(/, 'da)', 'foo baz');
testEdit('di(_middle_spc', 'foo (bAr) baz', /A/, 'di(', 'foo () baz');
testEdit('di)_middle_spc', 'foo (bAr) baz', /A/, 'di)', 'foo () baz');
testEdit('da(_middle_spc', 'foo (bAr) baz', /A/, 'da(', 'foo baz');
testEdit('da)_middle_spc', 'foo (bAr) baz', /A/, 'da)', 'foo baz');
testEdit('di(_close_spc', 'foo (bAr) baz', /\)/, 'di(', 'foo () baz');
testEdit('di)_close_spc', 'foo (bAr) baz', /\)/, 'di)', 'foo () baz');
testEdit('da(_close_spc', 'foo (bAr) baz', /\)/, 'da(', 'foo baz');
testEdit('da)_close_spc', 'foo (bAr) baz', /\)/, 'da)', 'foo baz');
// delete around and inner b.
testEdit('dab_on_(_should_delete_around_()block', 'o( in(abc) )', /\(a/, 'dab', 'o( in )');
// delete around and inner B.
testEdit('daB_on_{_should_delete_around_{}block', 'o{ in{abc} }', /{a/, 'daB', 'o{ in }');
testEdit('diB_on_{_should_delete_inner_{}block', 'o{ in{abc} }', /{a/, 'diB', 'o{ in{} }');
testEdit('da{_on_{_should_delete_inner_block', 'o{ in{abc} }', /{a/, 'da{', 'o{ in }');
testEdit('di[_on_(_should_not_delete', 'foo (bAr) baz', /\(/, 'di[', 'foo (bAr) baz');
testEdit('di[_on_)_should_not_delete', 'foo (bAr) baz', /\)/, 'di[', 'foo (bAr) baz');
testEdit('da[_on_(_should_not_delete', 'foo (bAr) baz', /\(/, 'da[', 'foo (bAr) baz');
testEdit('da[_on_)_should_not_delete', 'foo (bAr) baz', /\)/, 'da[', 'foo (bAr) baz');
testMotion('di(_outside_should_stay', ['d', 'i', '('], { line: 0, ch: 0}, { line: 0, ch: 0});
// Open and close on different lines, equally indented
testEdit('di{_middle_spc', 'a{\n\tbar\n}b', /r/, 'di{', 'a{}b');
testEdit('di}_middle_spc', 'a{\n\tbar\n}b', /r/, 'di}', 'a{}b');
testEdit('da{_middle_spc', 'a{\n\tbar\n}b', /r/, 'da{', 'ab');
testEdit('da}_middle_spc', 'a{\n\tbar\n}b', /r/, 'da}', 'ab');
testEdit('daB_middle_spc', 'a{\n\tbar\n}b', /r/, 'daB', 'ab');
// open and close on diff lines, open indented less than close
testEdit('di{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'di{', 'a{}b');
testEdit('di}_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'di}', 'a{}b');
testEdit('da{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'da{', 'ab');
testEdit('da}_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'da}', 'ab');
// open and close on diff lines, open indented more than close
testEdit('di[_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'di[', 'a\t[]b');
testEdit('di]_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'di]', 'a\t[]b');
testEdit('da[_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'da[', 'a\tb');
testEdit('da]_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'da]', 'a\tb');
function testSelection(name, before, pos, keys, sel) {
return testVim(name, function(cm, vim, helpers) {
var ch = before.search(pos)
var line = before.substring(0, ch).split('\n').length - 1;
if (line) {
ch = before.substring(0, ch).split('\n').pop().length;
}
cm.setCursor(line, ch);
helpers.doKeys.apply(this, keys.split(''));
eq(sel, cm.getSelection());
}, {value: before});
}
testSelection('viw_middle_spc', 'foo \tbAr\t baz', /A/, 'viw', 'bAr');
testSelection('vaw_middle_spc', 'foo \tbAr\t baz', /A/, 'vaw', 'bAr\t ');
testSelection('viw_middle_punct', 'foo \tbAr,\t baz', /A/, 'viw', 'bAr');
testSelection('vaW_middle_punct', 'foo \tbAr,\t baz', /A/, 'vaW', 'bAr,\t ');
testSelection('viw_start_spc', 'foo \tbAr\t baz', /b/, 'viw', 'bAr');
testSelection('viw_end_spc', 'foo \tbAr\t baz', /r/, 'viw', 'bAr');
testSelection('viw_eol', 'foo \tbAr', /r/, 'viw', 'bAr');
testSelection('vi{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'vi{', '\n\tbar\n\t');
testSelection('va{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'va{', '{\n\tbar\n\t}');
testVim('mouse_select', function(cm, vim, helpers) {
cm.setSelection(Pos(0, 2), Pos(0, 4), {origin: '*mouse'});
is(cm.state.vim.visualMode);
is(!cm.state.vim.visualLine);
is(!cm.state.vim.visualBlock);
helpers.doKeys('<Esc>');
is(!cm.somethingSelected());
helpers.doKeys('g', 'v');
eq('cd', cm.getSelection());
}, {value: 'abcdef'});
// Operator-motion tests
testVim('D', function(cm, vim, helpers) {
cm.setCursor(0, 3);
helpers.doKeys('D');
eq(' wo\nword2\n word3', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('rd1', register.toString());
is(!register.linewise);
helpers.assertCursorAt(0, 2);
}, { value: ' word1\nword2\n word3' });
testVim('C', function(cm, vim, helpers) {
var curStart = makeCursor(0, 3);
cm.setCursor(curStart);
helpers.doKeys('C');
eq(' wo\nword2\n word3', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('rd1', register.toString());
is(!register.linewise);
eqPos(curStart, cm.getCursor());
eq('vim-insert', cm.getOption('keyMap'));
}, { value: ' word1\nword2\n word3' });
testVim('Y', function(cm, vim, helpers) {
var curStart = makeCursor(0, 3);
cm.setCursor(curStart);
helpers.doKeys('Y');
eq(' word1\nword2\n word3', cm.getValue());
var register = helpers.getRegisterController().getRegister();
eq('rd1', register.toString());
is(!register.linewise);
helpers.assertCursorAt(0, 3);
}, { value: ' word1\nword2\n word3' });
testVim('~', function(cm, vim, helpers) {
helpers.doKeys('3', '~');
eq('ABCdefg', cm.getValue());
helpers.assertCursorAt(0, 3);
}, { value: 'abcdefg' });
// Action tests
testVim('ctrl-a', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('<C-a>');
eq('-9', cm.getValue());
helpers.assertCursorAt(0, 1);
helpers.doKeys('2','<C-a>');
eq('-7', cm.getValue());
}, {value: '-10'});
testVim('ctrl-x', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('<C-x>');
eq('-1', cm.getValue());
helpers.assertCursorAt(0, 1);
helpers.doKeys('2','<C-x>');
eq('-3', cm.getValue());
}, {value: '0'});
testVim('<C-x>/<C-a> search forward', function(cm, vim, helpers) {
forEach(['<C-x>', '<C-a>'], function(key) {
cm.setCursor(0, 0);
helpers.doKeys(key);
helpers.assertCursorAt(0, 5);
helpers.doKeys('l');
helpers.doKeys(key);
helpers.assertCursorAt(0, 10);
cm.setCursor(0, 11);
helpers.doKeys(key);
helpers.assertCursorAt(0, 11);
});
}, {value: '__jmp1 jmp2 jmp'});
testVim('a', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('a');
helpers.assertCursorAt(0, 2);
eq('vim-insert', cm.getOption('keyMap'));
});
testVim('a_eol', function(cm, vim, helpers) {
cm.setCursor(0, lines[0].length - 1);
helpers.doKeys('a');
helpers.assertCursorAt(0, lines[0].length);
eq('vim-insert', cm.getOption('keyMap'));
});
testVim('A_endOfSelectedArea', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('v', 'j', 'l');
helpers.doKeys('A');
helpers.assertCursorAt(1, 2);
eq('vim-insert', cm.getOption('keyMap'));
}, {value: 'foo\nbar'});
testVim('i', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('i');
helpers.assertCursorAt(0, 1);
eq('vim-insert', cm.getOption('keyMap'));
});
testVim('i_repeat', function(cm, vim, helpers) {
helpers.doKeys('3', 'i');
cm.replaceRange('test', cm.getCursor());
helpers.doKeys('<Esc>');
eq('testtesttest', cm.getValue());
helpers.assertCursorAt(0, 11);
}, { value: '' });
testVim('i_repeat_delete', function(cm, vim, helpers) {
cm.setCursor(0, 4);
helpers.doKeys('2', 'i');
cm.replaceRange('z', cm.getCursor());
helpers.doInsertModeKeys('Backspace', 'Backspace');
helpers.doKeys('<Esc>');
eq('abe', cm.getValue());
helpers.assertCursorAt(0, 1);
}, { value: 'abcde' });
testVim('A', function(cm, vim, helpers) {
helpers.doKeys('A');
helpers.assertCursorAt(0, lines[0].length);
eq('vim-insert', cm.getOption('keyMap'));
});
testVim('A_visual_block', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'A');
var replacement = new Array(cm.listSelections().length+1).join('hello ').split(' ');
replacement.pop();
cm.replaceSelections(replacement);
eq('testhello\nmehello\npleahellose', cm.getValue());
helpers.doKeys('<Esc>');
cm.setCursor(0, 0);
helpers.doKeys('.');
// TODO this doesn't work yet
// eq('teshellothello\nme hello hello\nplehelloahellose', cm.getValue());
}, {value: 'test\nme\nplease'});
testVim('I', function(cm, vim, helpers) {
cm.setCursor(0, 4);
helpers.doKeys('I');
helpers.assertCursorAt(0, lines[0].textStart);
eq('vim-insert', cm.getOption('keyMap'));
});
testVim('I_repeat', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('3', 'I');
cm.replaceRange('test', cm.getCursor());
helpers.doKeys('<Esc>');
eq('testtesttestblah', cm.getValue());
helpers.assertCursorAt(0, 11);
}, { value: 'blah' });
testVim('I_visual_block', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'I');
var replacement = new Array(cm.listSelections().length+1).join('hello ').split(' ');
replacement.pop();
cm.replaceSelections(replacement);
eq('hellotest\nhellome\nhelloplease', cm.getValue());
}, {value: 'test\nme\nplease'});
testVim('o', function(cm, vim, helpers) {
cm.setCursor(0, 4);
helpers.doKeys('o');
eq('word1\n\nword2', cm.getValue());
helpers.assertCursorAt(1, 0);
eq('vim-insert', cm.getOption('keyMap'));
}, { value: 'word1\nword2' });
testVim('o_repeat', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('3', 'o');
cm.replaceRange('test', cm.getCursor());
helpers.doKeys('<Esc>');
eq('\ntest\ntest\ntest', cm.getValue());
helpers.assertCursorAt(3, 3);
}, { value: '' });
testVim('O', function(cm, vim, helpers) {
cm.setCursor(0, 4);
helpers.doKeys('O');
eq('\nword1\nword2', cm.getValue());
helpers.assertCursorAt(0, 0);
eq('vim-insert', cm.getOption('keyMap'));
}, { value: 'word1\nword2' });
testVim('J', function(cm, vim, helpers) {
cm.setCursor(0, 4);
helpers.doKeys('J');
var expectedValue = 'word1 word2\nword3\n word4';
eq(expectedValue, cm.getValue());
helpers.assertCursorAt(0, expectedValue.indexOf('word2') - 1);
}, { value: 'word1 \n word2\nword3\n word4' });
testVim('J_repeat', function(cm, vim, helpers) {
cm.setCursor(0, 4);
helpers.doKeys('3', 'J');
var expectedValue = 'word1 word2 word3\n word4';
eq(expectedValue, cm.getValue());
helpers.assertCursorAt(0, expectedValue.indexOf('word3') - 1);
}, { value: 'word1 \n word2\nword3\n word4' });
testVim('p', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.getRegisterController().pushText('"', 'yank', 'abc\ndef', false);
helpers.doKeys('p');
eq('__abc\ndef_', cm.getValue());
helpers.assertCursorAt(1, 2);
}, { value: '___' });
testVim('p_register', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.getRegisterController().getRegister('a').setText('abc\ndef', false);
helpers.doKeys('"', 'a', 'p');
eq('__abc\ndef_', cm.getValue());
helpers.assertCursorAt(1, 2);
}, { value: '___' });
testVim('p_wrong_register', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.getRegisterController().getRegister('a').setText('abc\ndef', false);
helpers.doKeys('p');
eq('___', cm.getValue());
helpers.assertCursorAt(0, 1);
}, { value: '___' });
testVim('p_line', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.getRegisterController().pushText('"', 'yank', ' a\nd\n', true);
helpers.doKeys('2', 'p');
eq('___\n a\nd\n a\nd', cm.getValue());
helpers.assertCursorAt(1, 2);
}, { value: '___' });
testVim('p_lastline', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.getRegisterController().pushText('"', 'yank', ' a\nd', true);
helpers.doKeys('2', 'p');
eq('___\n a\nd\n a\nd', cm.getValue());
helpers.assertCursorAt(1, 2);
}, { value: '___' });
testVim(']p_first_indent_is_smaller', function(cm, vim, helpers) {
helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true);
helpers.doKeys(']', 'p');
eq(' ___\n abc\n def', cm.getValue());
}, { value: ' ___' });
testVim(']p_first_indent_is_larger', function(cm, vim, helpers) {
helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true);
helpers.doKeys(']', 'p');
eq(' ___\n abc\ndef', cm.getValue());
}, { value: ' ___' });
testVim(']p_with_tab_indents', function(cm, vim, helpers) {
helpers.getRegisterController().pushText('"', 'yank', '\t\tabc\n\t\t\tdef\n', true);
helpers.doKeys(']', 'p');
eq('\t___\n\tabc\n\t\tdef', cm.getValue());
}, { value: '\t___', indentWithTabs: true});
testVim(']p_with_spaces_translated_to_tabs', function(cm, vim, helpers) {
helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true);
helpers.doKeys(']', 'p');
eq('\t___\n\tabc\n\t\tdef', cm.getValue());
}, { value: '\t___', indentWithTabs: true, tabSize: 2 });
testVim('[p', function(cm, vim, helpers) {
helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true);
helpers.doKeys('[', 'p');
eq(' abc\n def\n ___', cm.getValue());
}, { value: ' ___' });
testVim('P', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.getRegisterController().pushText('"', 'yank', 'abc\ndef', false);
helpers.doKeys('P');
eq('_abc\ndef__', cm.getValue());
helpers.assertCursorAt(1, 3);
}, { value: '___' });
testVim('P_line', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.getRegisterController().pushText('"', 'yank', ' a\nd\n', true);
helpers.doKeys('2', 'P');
eq(' a\nd\n a\nd\n___', cm.getValue());
helpers.assertCursorAt(0, 2);
}, { value: '___' });
testVim('r', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('3', 'r', 'u');
eq('wuuuet\nanother', cm.getValue(),'3r failed');
helpers.assertCursorAt(0, 3);
cm.setCursor(0, 4);
helpers.doKeys('v', 'j', 'h', 'r', '<Space>');
eq('wuuu \n her', cm.getValue(),'Replacing selection by space-characters failed');
}, { value: 'wordet\nanother' });
testVim('r_visual_block', function(cm, vim, helpers) {
cm.setCursor(2, 3);
helpers.doKeys('<C-v>', 'k', 'k', 'h', 'h', 'r', 'l');
eq('1lll\n5lll\nalllefg', cm.getValue());
helpers.doKeys('<C-v>', 'l', 'j', 'r', '<Space>');
eq('1 l\n5 l\nalllefg', cm.getValue());
cm.setCursor(2, 0);
helpers.doKeys('o');
helpers.doKeys('<Esc>');
cm.replaceRange('\t\t', cm.getCursor());
helpers.doKeys('<C-v>', 'h', 'h', 'r', 'r');
eq('1 l\n5 l\nalllefg\nrrrrrrrr', cm.getValue());
}, {value: '1234\n5678\nabcdefg'});
testVim('R', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('R');
helpers.assertCursorAt(0, 1);
eq('vim-replace', cm.getOption('keyMap'));
is(cm.state.overwrite, 'Setting overwrite state failed');
});
testVim('mark', function(cm, vim, helpers) {
cm.setCursor(2, 2);
helpers.doKeys('m', 't');
cm.setCursor(0, 0);
helpers.doKeys('`', 't');
helpers.assertCursorAt(2, 2);
cm.setCursor(2, 0);
cm.replaceRange(' h', cm.getCursor());
cm.setCursor(0, 0);
helpers.doKeys('\'', 't');
helpers.assertCursorAt(2, 3);
});
testVim('jumpToMark_next', function(cm, vim, helpers) {
cm.setCursor(2, 2);
helpers.doKeys('m', 't');
cm.setCursor(0, 0);
helpers.doKeys(']', '`');
helpers.assertCursorAt(2, 2);
cm.setCursor(0, 0);
helpers.doKeys(']', '\'');
helpers.assertCursorAt(2, 0);
});
testVim('jumpToMark_next_repeat', function(cm, vim, helpers) {
cm.setCursor(2, 2);
helpers.doKeys('m', 'a');
cm.setCursor(3, 2);
helpers.doKeys('m', 'b');
cm.setCursor(4, 2);
helpers.doKeys('m', 'c');
cm.setCursor(0, 0);
helpers.doKeys('2', ']', '`');
helpers.assertCursorAt(3, 2);
cm.setCursor(0, 0);
helpers.doKeys('2', ']', '\'');
helpers.assertCursorAt(3, 1);
});
testVim('jumpToMark_next_sameline', function(cm, vim, helpers) {
cm.setCursor(2, 0);
helpers.doKeys('m', 'a');
cm.setCursor(2, 4);
helpers.doKeys('m', 'b');
cm.setCursor(2, 2);
helpers.doKeys(']', '`');
helpers.assertCursorAt(2, 4);
});
testVim('jumpToMark_next_onlyprev', function(cm, vim, helpers) {
cm.setCursor(2, 0);
helpers.doKeys('m', 'a');
cm.setCursor(4, 0);
helpers.doKeys(']', '`');
helpers.assertCursorAt(4, 0);
});
testVim('jumpToMark_next_nomark', function(cm, vim, helpers) {
cm.setCursor(2, 2);
helpers.doKeys(']', '`');
helpers.assertCursorAt(2, 2);
helpers.doKeys(']', '\'');
helpers.assertCursorAt(2, 0);
});
testVim('jumpToMark_next_linewise_over', function(cm, vim, helpers) {
cm.setCursor(2, 2);
helpers.doKeys('m', 'a');
cm.setCursor(3, 4);
helpers.doKeys('m', 'b');
cm.setCursor(2, 1);
helpers.doKeys(']', '\'');
helpers.assertCursorAt(3, 1);
});
testVim('jumpToMark_next_action', function(cm, vim, helpers) {
cm.setCursor(2, 2);
helpers.doKeys('m', 't');
cm.setCursor(0, 0);
helpers.doKeys('d', ']', '`');
helpers.assertCursorAt(0, 0);
var actual = cm.getLine(0);
var expected = 'pop pop 0 1 2 3 4';
eq(actual, expected, "Deleting while jumping to the next mark failed.");
});
testVim('jumpToMark_next_line_action', function(cm, vim, helpers) {
cm.setCursor(2, 2);
helpers.doKeys('m', 't');
cm.setCursor(0, 0);
helpers.doKeys('d', ']', '\'');
helpers.assertCursorAt(0, 1);
var actual = cm.getLine(0);
var expected = ' (a) [b] {c} '
eq(actual, expected, "Deleting while jumping to the next mark line failed.");
});
testVim('jumpToMark_prev', function(cm, vim, helpers) {
cm.setCursor(2, 2);
helpers.doKeys('m', 't');
cm.setCursor(4, 0);
helpers.doKeys('[', '`');
helpers.assertCursorAt(2, 2);
cm.setCursor(4, 0);
helpers.doKeys('[', '\'');
helpers.assertCursorAt(2, 0);
});
testVim('jumpToMark_prev_repeat', function(cm, vim, helpers) {
cm.setCursor(2, 2);
helpers.doKeys('m', 'a');
cm.setCursor(3, 2);
helpers.doKeys('m', 'b');
cm.setCursor(4, 2);
helpers.doKeys('m', 'c');
cm.setCursor(5, 0);
helpers.doKeys('2', '[', '`');
helpers.assertCursorAt(3, 2);
cm.setCursor(5, 0);
helpers.doKeys('2', '[', '\'');
helpers.assertCursorAt(3, 1);
});
testVim('jumpToMark_prev_sameline', function(cm, vim, helpers) {
cm.setCursor(2, 0);
helpers.doKeys('m', 'a');
cm.setCursor(2, 4);
helpers.doKeys('m', 'b');
cm.setCursor(2, 2);
helpers.doKeys('[', '`');
helpers.assertCursorAt(2, 0);
});
testVim('jumpToMark_prev_onlynext', function(cm, vim, helpers) {
cm.setCursor(4, 4);
helpers.doKeys('m', 'a');
cm.setCursor(2, 0);
helpers.doKeys('[', '`');
helpers.assertCursorAt(2, 0);
});
testVim('jumpToMark_prev_nomark', function(cm, vim, helpers) {
cm.setCursor(2, 2);
helpers.doKeys('[', '`');
helpers.assertCursorAt(2, 2);
helpers.doKeys('[', '\'');
helpers.assertCursorAt(2, 0);
});
testVim('jumpToMark_prev_linewise_over', function(cm, vim, helpers) {
cm.setCursor(2, 2);
helpers.doKeys('m', 'a');
cm.setCursor(3, 4);
helpers.doKeys('m', 'b');
cm.setCursor(3, 6);
helpers.doKeys('[', '\'');
helpers.assertCursorAt(2, 0);
});
testVim('delmark_single', function(cm, vim, helpers) {
cm.setCursor(1, 2);
helpers.doKeys('m', 't');
helpers.doEx('delmarks t');
cm.setCursor(0, 0);
helpers.doKeys('`', 't');
helpers.assertCursorAt(0, 0);
});
testVim('delmark_range', function(cm, vim, helpers) {
cm.setCursor(1, 2);
helpers.doKeys('m', 'a');
cm.setCursor(2, 2);
helpers.doKeys('m', 'b');
cm.setCursor(3, 2);
helpers.doKeys('m', 'c');
cm.setCursor(4, 2);
helpers.doKeys('m', 'd');
cm.setCursor(5, 2);
helpers.doKeys('m', 'e');
helpers.doEx('delmarks b-d');
cm.setCursor(0, 0);
helpers.doKeys('`', 'a');
helpers.assertCursorAt(1, 2);
helpers.doKeys('`', 'b');
helpers.assertCursorAt(1, 2);
helpers.doKeys('`', 'c');
helpers.assertCursorAt(1, 2);
helpers.doKeys('`', 'd');
helpers.assertCursorAt(1, 2);
helpers.doKeys('`', 'e');
helpers.assertCursorAt(5, 2);
});
testVim('delmark_multi', function(cm, vim, helpers) {
cm.setCursor(1, 2);
helpers.doKeys('m', 'a');
cm.setCursor(2, 2);
helpers.doKeys('m', 'b');
cm.setCursor(3, 2);
helpers.doKeys('m', 'c');
cm.setCursor(4, 2);
helpers.doKeys('m', 'd');
cm.setCursor(5, 2);
helpers.doKeys('m', 'e');
helpers.doEx('delmarks bcd');
cm.setCursor(0, 0);
helpers.doKeys('`', 'a');
helpers.assertCursorAt(1, 2);
helpers.doKeys('`', 'b');
helpers.assertCursorAt(1, 2);
helpers.doKeys('`', 'c');
helpers.assertCursorAt(1, 2);
helpers.doKeys('`', 'd');
helpers.assertCursorAt(1, 2);
helpers.doKeys('`', 'e');
helpers.assertCursorAt(5, 2);
});
testVim('delmark_multi_space', function(cm, vim, helpers) {
cm.setCursor(1, 2);
helpers.doKeys('m', 'a');
cm.setCursor(2, 2);
helpers.doKeys('m', 'b');
cm.setCursor(3, 2);
helpers.doKeys('m', 'c');
cm.setCursor(4, 2);
helpers.doKeys('m', 'd');
cm.setCursor(5, 2);
helpers.doKeys('m', 'e');
helpers.doEx('delmarks b c d');
cm.setCursor(0, 0);
helpers.doKeys('`', 'a');
helpers.assertCursorAt(1, 2);
helpers.doKeys('`', 'b');
helpers.assertCursorAt(1, 2);
helpers.doKeys('`', 'c');
helpers.assertCursorAt(1, 2);
helpers.doKeys('`', 'd');
helpers.assertCursorAt(1, 2);
helpers.doKeys('`', 'e');
helpers.assertCursorAt(5, 2);
});
testVim('delmark_all', function(cm, vim, helpers) {
cm.setCursor(1, 2);
helpers.doKeys('m', 'a');
cm.setCursor(2, 2);
helpers.doKeys('m', 'b');
cm.setCursor(3, 2);
helpers.doKeys('m', 'c');
cm.setCursor(4, 2);
helpers.doKeys('m', 'd');
cm.setCursor(5, 2);
helpers.doKeys('m', 'e');
helpers.doEx('delmarks a b-de');
cm.setCursor(0, 0);
helpers.doKeys('`', 'a');
helpers.assertCursorAt(0, 0);
helpers.doKeys('`', 'b');
helpers.assertCursorAt(0, 0);
helpers.doKeys('`', 'c');
helpers.assertCursorAt(0, 0);
helpers.doKeys('`', 'd');
helpers.assertCursorAt(0, 0);
helpers.doKeys('`', 'e');
helpers.assertCursorAt(0, 0);
});
testVim('visual', function(cm, vim, helpers) {
helpers.doKeys('l', 'v', 'l', 'l');
helpers.assertCursorAt(0, 4);
eqPos(makeCursor(0, 1), cm.getCursor('anchor'));
helpers.doKeys('d');
eq('15', cm.getValue());
}, { value: '12345' });
testVim('visual_yank', function(cm, vim, helpers) {
helpers.doKeys('v', '3', 'l', 'y');
helpers.assertCursorAt(0, 0);
helpers.doKeys('p');
eq('aa te test for yank', cm.getValue());
}, { value: 'a test for yank' })
testVim('visual_w', function(cm, vim, helpers) {
helpers.doKeys('v', 'w');
eq(cm.getSelection(), 'motion t');
}, { value: 'motion test'});
testVim('visual_initial_selection', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('v');
cm.getSelection('n');
}, { value: 'init'});
testVim('visual_crossover_left', function(cm, vim, helpers) {
cm.setCursor(0, 2);
helpers.doKeys('v', 'l', 'h', 'h');
cm.getSelection('ro');
}, { value: 'cross'});
testVim('visual_crossover_left', function(cm, vim, helpers) {
cm.setCursor(0, 2);
helpers.doKeys('v', 'h', 'l', 'l');
cm.getSelection('os');
}, { value: 'cross'});
testVim('visual_crossover_up', function(cm, vim, helpers) {
cm.setCursor(3, 2);
helpers.doKeys('v', 'j', 'k', 'k');
eqPos(Pos(2, 2), cm.getCursor('head'));
eqPos(Pos(3, 3), cm.getCursor('anchor'));
helpers.doKeys('k');
eqPos(Pos(1, 2), cm.getCursor('head'));
eqPos(Pos(3, 3), cm.getCursor('anchor'));
}, { value: 'cross\ncross\ncross\ncross\ncross\n'});
testVim('visual_crossover_down', function(cm, vim, helpers) {
cm.setCursor(1, 2);
helpers.doKeys('v', 'k', 'j', 'j');
eqPos(Pos(2, 3), cm.getCursor('head'));
eqPos(Pos(1, 2), cm.getCursor('anchor'));
helpers.doKeys('j');
eqPos(Pos(3, 3), cm.getCursor('head'));
eqPos(Pos(1, 2), cm.getCursor('anchor'));
}, { value: 'cross\ncross\ncross\ncross\ncross\n'});
testVim('visual_exit', function(cm, vim, helpers) {
helpers.doKeys('<C-v>', 'l', 'j', 'j', '<Esc>');
eqPos(cm.getCursor('anchor'), cm.getCursor('head'));
eq(vim.visualMode, false);
}, { value: 'hello\nworld\nfoo' });
testVim('visual_line', function(cm, vim, helpers) {
helpers.doKeys('l', 'V', 'l', 'j', 'j', 'd');
eq(' 4\n 5', cm.getValue());
}, { value: ' 1\n 2\n 3\n 4\n 5' });
testVim('visual_block_move_to_eol', function(cm, vim, helpers) {
// moveToEol should move all block cursors to end of line
cm.setCursor(0, 0);
helpers.doKeys('<C-v>', 'G', '$');
var selections = cm.getSelections().join();
eq('123,45,6', selections);
// Checks that with cursor at Infinity, finding words backwards still works.
helpers.doKeys('2', 'k', 'b');
selections = cm.getSelections().join();
eq('1', selections);
}, {value: '123\n45\n6'});
testVim('visual_block_different_line_lengths', function(cm, vim, helpers) {
// test the block selection with lines of different length
// i.e. extending the selection
// till the end of the longest line.
helpers.doKeys('<C-v>', 'l', 'j', 'j', '6', 'l', 'd');
helpers.doKeys('d', 'd', 'd', 'd');
eq('', cm.getValue());
}, {value: '1234\n5678\nabcdefg'});
testVim('visual_block_truncate_on_short_line', function(cm, vim, helpers) {
// check for left side selection in case
// of moving up to a shorter line.
cm.replaceRange('', cm.getCursor());
cm.setCursor(3, 4);
helpers.doKeys('<C-v>', 'l', 'k', 'k', 'd');
eq('hello world\n{\ntis\nsa!', cm.getValue());
}, {value: 'hello world\n{\nthis is\nsparta!'});
testVim('visual_block_corners', function(cm, vim, helpers) {
cm.setCursor(1, 2);
helpers.doKeys('<C-v>', '2', 'l', 'k');
// circle around the anchor
// and check the selections
var selections = cm.getSelections();
eq('345891', selections.join(''));
helpers.doKeys('4', 'h');
selections = cm.getSelections();
eq('123678', selections.join(''));
helpers.doKeys('j', 'j');
selections = cm.getSelections();
eq('678abc', selections.join(''));
helpers.doKeys('4', 'l');
selections = cm.getSelections();
eq('891cde', selections.join(''));
}, {value: '12345\n67891\nabcde'});
testVim('visual_block_mode_switch', function(cm, vim, helpers) {
// switch between visual modes
cm.setCursor(1, 1);
// blockwise to characterwise visual
helpers.doKeys('<C-v>', 'j', 'l', 'v');
selections = cm.getSelections();
eq('7891\nabc', selections.join(''));
// characterwise to blockwise
helpers.doKeys('<C-v>');
selections = cm.getSelections();
eq('78bc', selections.join(''));
// blockwise to linewise visual
helpers.doKeys('V');
selections = cm.getSelections();
eq('67891\nabcde', selections.join(''));
}, {value: '12345\n67891\nabcde'});
testVim('visual_block_crossing_short_line', function(cm, vim, helpers) {
// visual block with long and short lines
cm.setCursor(0, 3);
helpers.doKeys('<C-v>', 'j', 'j', 'j');
var selections = cm.getSelections().join();
eq('4,,d,b', selections);
helpers.doKeys('3', 'k');
selections = cm.getSelections().join();
eq('4', selections);
helpers.doKeys('5', 'j', 'k');
selections = cm.getSelections().join("");
eq(10, selections.length);
}, {value: '123456\n78\nabcdefg\nfoobar\n}\n'});
testVim('visual_block_curPos_on_exit', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('<C-v>', '3' , 'l', '<Esc>');
eqPos(makeCursor(0, 3), cm.getCursor());
helpers.doKeys('h', '<C-v>', '2' , 'j' ,'3' , 'l');
eq(cm.getSelections().join(), "3456,,cdef");
helpers.doKeys('4' , 'h');
eq(cm.getSelections().join(), "23,8,bc");
helpers.doKeys('2' , 'l');
eq(cm.getSelections().join(), "34,,cd");
}, {value: '123456\n78\nabcdefg\nfoobar'});
testVim('visual_marks', function(cm, vim, helpers) {
helpers.doKeys('l', 'v', 'l', 'l', 'j', 'j', 'v');
// Test visual mode marks
cm.setCursor(2, 1);
helpers.doKeys('\'', '<');
helpers.assertCursorAt(0, 1);
helpers.doKeys('\'', '>');
helpers.assertCursorAt(2, 0);
});
testVim('visual_join', function(cm, vim, helpers) {
helpers.doKeys('l', 'V', 'l', 'j', 'j', 'J');
eq(' 1 2 3\n 4\n 5', cm.getValue());
is(!vim.visualMode);
}, { value: ' 1\n 2\n 3\n 4\n 5' });
testVim('visual_join_2', function(cm, vim, helpers) {
helpers.doKeys('G', 'V', 'g', 'g', 'J');
eq('1 2 3 4 5 6 ', cm.getValue());
is(!vim.visualMode);
}, { value: '1\n2\n3\n4\n5\n6\n'});
testVim('visual_blank', function(cm, vim, helpers) {
helpers.doKeys('v', 'k');
eq(vim.visualMode, true);
}, { value: '\n' });
testVim('reselect_visual', function(cm, vim, helpers) {
helpers.doKeys('l', 'v', 'l', 'l', 'l', 'y', 'g', 'v');
helpers.assertCursorAt(0, 5);
eqPos(makeCursor(0, 1), cm.getCursor('anchor'));
helpers.doKeys('v');
cm.setCursor(1, 0);
helpers.doKeys('v', 'l', 'l', 'p');
eq('123456\n2345\nbar', cm.getValue());
cm.setCursor(0, 0);
helpers.doKeys('g', 'v');
// here the fake cursor is at (1, 3)
helpers.assertCursorAt(1, 4);
eqPos(makeCursor(1, 0), cm.getCursor('anchor'));
helpers.doKeys('v');
cm.setCursor(2, 0);
helpers.doKeys('v', 'l', 'l', 'g', 'v');
helpers.assertCursorAt(1, 4);
eqPos(makeCursor(1, 0), cm.getCursor('anchor'));
helpers.doKeys('g', 'v');
helpers.assertCursorAt(2, 3);
eqPos(makeCursor(2, 0), cm.getCursor('anchor'));
eq('123456\n2345\nbar', cm.getValue());
}, { value: '123456\nfoo\nbar' });
testVim('reselect_visual_line', function(cm, vim, helpers) {
helpers.doKeys('l', 'V', 'j', 'j', 'V', 'g', 'v', 'd');
eq('foo\nand\nbar', cm.getValue());
cm.setCursor(1, 0);
helpers.doKeys('V', 'y', 'j');
helpers.doKeys('V', 'p' , 'g', 'v', 'd');
eq('foo\nand', cm.getValue());
}, { value: 'hello\nthis\nis\nfoo\nand\nbar' });
testVim('reselect_visual_block', function(cm, vim, helpers) {
cm.setCursor(1, 2);
helpers.doKeys('<C-v>', 'k', 'h', '<C-v>');
cm.setCursor(2, 1);
helpers.doKeys('v', 'l', 'g', 'v');
eqPos(Pos(1, 2), vim.sel.anchor);
eqPos(Pos(0, 1), vim.sel.head);
// Ensure selection is done with visual block mode rather than one
// continuous range.
eq(cm.getSelections().join(''), '23oo')
helpers.doKeys('g', 'v');
eqPos(Pos(2, 1), vim.sel.anchor);
eqPos(Pos(2, 2), vim.sel.head);
helpers.doKeys('<Esc>');
// Ensure selection of deleted range
cm.setCursor(1, 1);
helpers.doKeys('v', '<C-v>', 'j', 'd', 'g', 'v');
eq(cm.getSelections().join(''), 'or');
}, { value: '123456\nfoo\nbar' });
testVim('s_normal', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('s');
helpers.doKeys('<Esc>');
eq('ac', cm.getValue());
}, { value: 'abc'});
testVim('s_visual', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('v', 's');
helpers.doKeys('<Esc>');
helpers.assertCursorAt(0, 0);
eq('ac', cm.getValue());
}, { value: 'abc'});
testVim('o_visual', function(cm, vim, helpers) {
cm.setCursor(0,0);
helpers.doKeys('v','l','l','l','o');
helpers.assertCursorAt(0,0);
helpers.doKeys('v','v','j','j','j','o');
helpers.assertCursorAt(0,0);
helpers.doKeys('O');
helpers.doKeys('l','l')
helpers.assertCursorAt(3, 3);
helpers.doKeys('d');
eq('p',cm.getValue());
}, { value: 'abcd\nefgh\nijkl\nmnop'});
testVim('o_visual_block', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('<C-v>','3','j','l','l', 'o');
eqPos(Pos(3, 3), vim.sel.anchor);
eqPos(Pos(0, 1), vim.sel.head);
helpers.doKeys('O');
eqPos(Pos(3, 1), vim.sel.anchor);
eqPos(Pos(0, 3), vim.sel.head);
helpers.doKeys('o');
eqPos(Pos(0, 3), vim.sel.anchor);
eqPos(Pos(3, 1), vim.sel.head);
}, { value: 'abcd\nefgh\nijkl\nmnop'});
testVim('changeCase_visual', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('v', 'l', 'l');
helpers.doKeys('U');
helpers.assertCursorAt(0, 0);
helpers.doKeys('v', 'l', 'l');
helpers.doKeys('u');
helpers.assertCursorAt(0, 0);
helpers.doKeys('l', 'l', 'l', '.');
helpers.assertCursorAt(0, 3);
cm.setCursor(0, 0);
helpers.doKeys('q', 'a', 'v', 'j', 'U', 'q');
helpers.assertCursorAt(0, 0);
helpers.doKeys('j', '@', 'a');
helpers.assertCursorAt(1, 0);
cm.setCursor(3, 0);
helpers.doKeys('V', 'U', 'j', '.');
eq('ABCDEF\nGHIJKL\nMnopq\nSHORT LINE\nLONG LINE OF TEXT', cm.getValue());
}, { value: 'abcdef\nghijkl\nmnopq\nshort line\nlong line of text'});
testVim('changeCase_visual_block', function(cm, vim, helpers) {
cm.setCursor(2, 1);
helpers.doKeys('<C-v>', 'k', 'k', 'h', 'U');
eq('ABcdef\nGHijkl\nMNopq\nfoo', cm.getValue());
cm.setCursor(0, 2);
helpers.doKeys('.');
eq('ABCDef\nGHIJkl\nMNOPq\nfoo', cm.getValue());
// check when last line is shorter.
cm.setCursor(2, 2);
helpers.doKeys('.');
eq('ABCDef\nGHIJkl\nMNOPq\nfoO', cm.getValue());
}, { value: 'abcdef\nghijkl\nmnopq\nfoo'});
testVim('visual_paste', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('v', 'l', 'l', 'y');
helpers.assertCursorAt(0, 0);
helpers.doKeys('3', 'l', 'j', 'v', 'l', 'p');
helpers.assertCursorAt(1, 5);
eq('this is a\nunithitest for visual paste', cm.getValue());
cm.setCursor(0, 0);
// in case of pasting whole line
helpers.doKeys('y', 'y');
cm.setCursor(1, 6);
helpers.doKeys('v', 'l', 'l', 'l', 'p');
helpers.assertCursorAt(2, 0);
eq('this is a\nunithi\nthis is a\n for visual paste', cm.getValue());
}, { value: 'this is a\nunit test for visual paste'});
// This checks the contents of the register used to paste the text
testVim('v_paste_from_register', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('"', 'a', 'y', 'w');
cm.setCursor(1, 0);
helpers.doKeys('v', 'p');
cm.openDialog = helpers.fakeOpenDialog('registers');
cm.openNotification = helpers.fakeOpenNotification(function(text) {
is(/a\s+register/.test(text));
});
}, { value: 'register contents\nare not erased'});
testVim('S_normal', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('j', 'S');
helpers.doKeys('<Esc>');
helpers.assertCursorAt(1, 1);
eq('aa{\n \ncc', cm.getValue());
helpers.doKeys('j', 'S');
eq('aa{\n \n ', cm.getValue());
helpers.assertCursorAt(2, 2);
helpers.doKeys('<Esc>');
helpers.doKeys('d', 'd', 'd', 'd');
helpers.assertCursorAt(0, 0);
helpers.doKeys('S');
is(vim.insertMode);
eq('', cm.getValue());
}, { value: 'aa{\nbb\ncc'});
testVim('blockwise_paste', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('<C-v>', '3', 'j', 'l', 'y');
cm.setCursor(0, 2);
// paste one char after the current cursor position
helpers.doKeys('p');
eq('helhelo\nworwold\nfoofo\nbarba', cm.getValue());
cm.setCursor(0, 0);
helpers.doKeys('v', '4', 'l', 'y');
cm.setCursor(0, 0);
helpers.doKeys('<C-v>', '3', 'j', 'p');
eq('helheelhelo\norwold\noofo\narba', cm.getValue());
}, { value: 'hello\nworld\nfoo\nbar'});
testVim('blockwise_paste_long/short_line', function(cm, vim, helpers) {
// extend short lines in case of different line lengths.
cm.setCursor(0, 0);
helpers.doKeys('<C-v>', 'j', 'j', 'y');
cm.setCursor(0, 3);
helpers.doKeys('p');
eq('hellho\nfoo f\nbar b', cm.getValue());
}, { value: 'hello\nfoo\nbar'});
testVim('blockwise_paste_cut_paste', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('<C-v>', '2', 'j', 'x');
cm.setCursor(0, 0);
helpers.doKeys('P');
eq('cut\nand\npaste\nme', cm.getValue());
}, { value: 'cut\nand\npaste\nme'});
testVim('blockwise_paste_from_register', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('<C-v>', '2', 'j', '"', 'a', 'y');
cm.setCursor(0, 3);
helpers.doKeys('"', 'a', 'p');
eq('foobfar\nhellho\nworlwd', cm.getValue());
}, { value: 'foobar\nhello\nworld'});
testVim('blockwise_paste_last_line', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('<C-v>', '2', 'j', 'l', 'y');
cm.setCursor(3, 0);
helpers.doKeys('p');
eq('cut\nand\npaste\nmcue\n an\n pa', cm.getValue());
}, { value: 'cut\nand\npaste\nme'});
testVim('S_visual', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('v', 'j', 'S');
helpers.doKeys('<Esc>');
helpers.assertCursorAt(0, 0);
eq('\ncc', cm.getValue());
}, { value: 'aa\nbb\ncc'});
testVim('d_/', function(cm, vim, helpers) {
cm.openDialog = helpers.fakeOpenDialog('match');
helpers.doKeys('2', 'd', '/');
helpers.assertCursorAt(0, 0);
eq('match \n next', cm.getValue());
cm.openDialog = helpers.fakeOpenDialog('2');
helpers.doKeys('d', ':');
// TODO eq(' next', cm.getValue());
}, { value: 'text match match \n next' });
testVim('/ and n/N', function(cm, vim, helpers) {
cm.openDialog = helpers.fakeOpenDialog('match');
helpers.doKeys('/');
helpers.assertCursorAt(0, 11);
helpers.doKeys('n');
helpers.assertCursorAt(1, 6);
helpers.doKeys('N');
helpers.assertCursorAt(0, 11);
cm.setCursor(0, 0);
helpers.doKeys('2', '/');
helpers.assertCursorAt(1, 6);
}, { value: 'match nope match \n nope Match' });
testVim('/_case', function(cm, vim, helpers) {
cm.openDialog = helpers.fakeOpenDialog('Match');
helpers.doKeys('/');
helpers.assertCursorAt(1, 6);
}, { value: 'match nope match \n nope Match' });
testVim('/_2_pcre', function(cm, vim, helpers) {
CodeMirror.Vim.setOption('pcre', true);
cm.openDialog = helpers.fakeOpenDialog('(word){2}');
helpers.doKeys('/');
helpers.assertCursorAt(1, 9);
helpers.doKeys('n');
helpers.assertCursorAt(2, 1);
}, { value: 'word\n another wordword\n wordwordword\n' });
testVim('/_2_nopcre', function(cm, vim, helpers) {
CodeMirror.Vim.setOption('pcre', false);
cm.openDialog = helpers.fakeOpenDialog('\\(word\\)\\{2}');
helpers.doKeys('/');
helpers.assertCursorAt(1, 9);
helpers.doKeys('n');
helpers.assertCursorAt(2, 1);
}, { value: 'word\n another wordword\n wordwordword\n' });
testVim('/_nongreedy', function(cm, vim, helpers) {
cm.openDialog = helpers.fakeOpenDialog('aa');
helpers.doKeys('/');
helpers.assertCursorAt(0, 4);
helpers.doKeys('n');
helpers.assertCursorAt(1, 3);
helpers.doKeys('n');
helpers.assertCursorAt(0, 0);
}, { value: 'aaa aa \n a aa'});
testVim('?_nongreedy', function(cm, vim, helpers) {
cm.openDialog = helpers.fakeOpenDialog('aa');
helpers.doKeys('?');
helpers.assertCursorAt(1, 3);
helpers.doKeys('n');
helpers.assertCursorAt(0, 4);
helpers.doKeys('n');
helpers.assertCursorAt(0, 0);
}, { value: 'aaa aa \n a aa'});
testVim('/_greedy', function(cm, vim, helpers) {
cm.openDialog = helpers.fakeOpenDialog('a+');
helpers.doKeys('/');
helpers.assertCursorAt(0, 4);
helpers.doKeys('n');
helpers.assertCursorAt(1, 1);
helpers.doKeys('n');
helpers.assertCursorAt(1, 3);
helpers.doKeys('n');
helpers.assertCursorAt(0, 0);
}, { value: 'aaa aa \n a aa'});
testVim('?_greedy', function(cm, vim, helpers) {
cm.openDialog = helpers.fakeOpenDialog('a+');
helpers.doKeys('?');
helpers.assertCursorAt(1, 3);
helpers.doKeys('n');
helpers.assertCursorAt(1, 1);
helpers.doKeys('n');
helpers.assertCursorAt(0, 4);
helpers.doKeys('n');
helpers.assertCursorAt(0, 0);
}, { value: 'aaa aa \n a aa'});
testVim('/_greedy_0_or_more', function(cm, vim, helpers) {
cm.openDialog = helpers.fakeOpenDialog('a*');
helpers.doKeys('/');
helpers.assertCursorAt(0, 3);
helpers.doKeys('n');
helpers.assertCursorAt(0, 4);
helpers.doKeys('n');
helpers.assertCursorAt(0, 5);
helpers.doKeys('n');
helpers.assertCursorAt(1, 0);
helpers.doKeys('n');
helpers.assertCursorAt(1, 1);
helpers.doKeys('n');
helpers.assertCursorAt(0, 0);
}, { value: 'aaa aa\n aa'});
testVim('?_greedy_0_or_more', function(cm, vim, helpers) {
cm.openDialog = helpers.fakeOpenDialog('a*');
helpers.doKeys('?');
helpers.assertCursorAt(1, 1);
helpers.doKeys('n');
helpers.assertCursorAt(1, 0);
helpers.doKeys('n');
helpers.assertCursorAt(0, 5);
helpers.doKeys('n');
helpers.assertCursorAt(0, 4);
helpers.doKeys('n');
helpers.assertCursorAt(0, 3);
helpers.doKeys('n');
helpers.assertCursorAt(0, 0);
}, { value: 'aaa aa\n aa'});
testVim('? and n/N', function(cm, vim, helpers) {
cm.openDialog = helpers.fakeOpenDialog('match');
helpers.doKeys('?');
helpers.assertCursorAt(1, 6);
helpers.doKeys('n');
helpers.assertCursorAt(0, 11);
helpers.doKeys('N');
helpers.assertCursorAt(1, 6);
cm.setCursor(0, 0);
helpers.doKeys('2', '?');
helpers.assertCursorAt(0, 11);
}, { value: 'match nope match \n nope Match' });
testVim('*', function(cm, vim, helpers) {
cm.setCursor(0, 9);
helpers.doKeys('*');
helpers.assertCursorAt(0, 22);
cm.setCursor(0, 9);
helpers.doKeys('2', '*');
helpers.assertCursorAt(1, 8);
}, { value: 'nomatch match nomatch match \nnomatch Match' });
testVim('*_no_word', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('*');
helpers.assertCursorAt(0, 0);
}, { value: ' \n match \n' });
testVim('*_symbol', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('*');
helpers.assertCursorAt(1, 0);
}, { value: ' /}\n/} match \n' });
testVim('#', function(cm, vim, helpers) {
cm.setCursor(0, 9);
helpers.doKeys('#');
helpers.assertCursorAt(1, 8);
cm.setCursor(0, 9);
helpers.doKeys('2', '#');
helpers.assertCursorAt(0, 22);
}, { value: 'nomatch match nomatch match \nnomatch Match' });
testVim('*_seek', function(cm, vim, helpers) {
// Should skip over space and symbols.
cm.setCursor(0, 3);
helpers.doKeys('*');
helpers.assertCursorAt(0, 22);
}, { value: ' := match nomatch match \nnomatch Match' });
testVim('#', function(cm, vim, helpers) {
// Should skip over space and symbols.
cm.setCursor(0, 3);
helpers.doKeys('#');
helpers.assertCursorAt(1, 8);
}, { value: ' := match nomatch match \nnomatch Match' });
testVim('g*', function(cm, vim, helpers) {
cm.setCursor(0, 8);
helpers.doKeys('g', '*');
helpers.assertCursorAt(0, 18);
cm.setCursor(0, 8);
helpers.doKeys('3', 'g', '*');
helpers.assertCursorAt(1, 8);
}, { value: 'matches match alsoMatch\nmatchme matching' });
testVim('g#', function(cm, vim, helpers) {
cm.setCursor(0, 8);
helpers.doKeys('g', '#');
helpers.assertCursorAt(0, 0);
cm.setCursor(0, 8);
helpers.doKeys('3', 'g', '#');
helpers.assertCursorAt(1, 0);
}, { value: 'matches match alsoMatch\nmatchme matching' });
testVim('macro_insert', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('q', 'a', '0', 'i');
cm.replaceRange('foo', cm.getCursor());
helpers.doKeys('<Esc>');
helpers.doKeys('q', '@', 'a');
eq('foofoo', cm.getValue());
}, { value: ''});
testVim('macro_insert_repeat', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('q', 'a', '$', 'a');
cm.replaceRange('larry.', cm.getCursor());
helpers.doKeys('<Esc>');
helpers.doKeys('a');
cm.replaceRange('curly.', cm.getCursor());
helpers.doKeys('<Esc>');
helpers.doKeys('q');
helpers.doKeys('a');
cm.replaceRange('moe.', cm.getCursor());
helpers.doKeys('<Esc>');
helpers.doKeys('@', 'a');
// At this point, the most recent edit should be the 2nd insert change
// inside the macro, i.e. "curly.".
helpers.doKeys('.');
eq('larry.curly.moe.larry.curly.curly.', cm.getValue());
}, { value: ''});
testVim('macro_space', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('<Space>', '<Space>');
helpers.assertCursorAt(0, 2);
helpers.doKeys('q', 'a', '<Space>', '<Space>', 'q');
helpers.assertCursorAt(0, 4);
helpers.doKeys('@', 'a');
helpers.assertCursorAt(0, 6);
helpers.doKeys('@', 'a');
helpers.assertCursorAt(0, 8);
}, { value: 'one line of text.'});
testVim('macro_t_search', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('q', 'a', 't', 'e', 'q');
helpers.assertCursorAt(0, 1);
helpers.doKeys('l', '@', 'a');
helpers.assertCursorAt(0, 6);
helpers.doKeys('l', ';');
helpers.assertCursorAt(0, 12);
}, { value: 'one line of text.'});
testVim('macro_f_search', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('q', 'b', 'f', 'e', 'q');
helpers.assertCursorAt(0, 2);
helpers.doKeys('@', 'b');
helpers.assertCursorAt(0, 7);
helpers.doKeys(';');
helpers.assertCursorAt(0, 13);
}, { value: 'one line of text.'});
testVim('macro_slash_search', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('q', 'c');
cm.openDialog = helpers.fakeOpenDialog('e');
helpers.doKeys('/', 'q');
helpers.assertCursorAt(0, 2);
helpers.doKeys('@', 'c');
helpers.assertCursorAt(0, 7);
helpers.doKeys('n');
helpers.assertCursorAt(0, 13);
}, { value: 'one line of text.'});
testVim('macro_multislash_search', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('q', 'd');
cm.openDialog = helpers.fakeOpenDialog('e');
helpers.doKeys('/');
cm.openDialog = helpers.fakeOpenDialog('t');
helpers.doKeys('/', 'q');
helpers.assertCursorAt(0, 12);
helpers.doKeys('@', 'd');
helpers.assertCursorAt(0, 15);
}, { value: 'one line of text to rule them all.'});
testVim('macro_last_ex_command_register', function (cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doEx('s/a/b');
helpers.doKeys('2', '@', ':');
eq('bbbaa', cm.getValue());
helpers.assertCursorAt(0, 2);
}, { value: 'aaaaa'});
testVim('macro_parens', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('q', 'z', 'i');
cm.replaceRange('(', cm.getCursor());
helpers.doKeys('<Esc>');
helpers.doKeys('e', 'a');
cm.replaceRange(')', cm.getCursor());
helpers.doKeys('<Esc>');
helpers.doKeys('q');
helpers.doKeys('w', '@', 'z');
helpers.doKeys('w', '@', 'z');
eq('(see) (spot) (run)', cm.getValue());
}, { value: 'see spot run'});
testVim('macro_overwrite', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('q', 'z', '0', 'i');
cm.replaceRange('I ', cm.getCursor());
helpers.doKeys('<Esc>');
helpers.doKeys('q');
helpers.doKeys('e');
// Now replace the macro with something else.
helpers.doKeys('q', 'z', 'a');
cm.replaceRange('.', cm.getCursor());
helpers.doKeys('<Esc>');
helpers.doKeys('q');
helpers.doKeys('e', '@', 'z');
helpers.doKeys('e', '@', 'z');
eq('I see. spot. run.', cm.getValue());
}, { value: 'see spot run'});
testVim('macro_search_f', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('q', 'a', 'f', ' ');
helpers.assertCursorAt(0,3);
helpers.doKeys('q', '0');
helpers.assertCursorAt(0,0);
helpers.doKeys('@', 'a');
helpers.assertCursorAt(0,3);
}, { value: 'The quick brown fox jumped over the lazy dog.'});
testVim('macro_search_2f', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('q', 'a', '2', 'f', ' ');
helpers.assertCursorAt(0,9);
helpers.doKeys('q', '0');
helpers.assertCursorAt(0,0);
helpers.doKeys('@', 'a');
helpers.assertCursorAt(0,9);
}, { value: 'The quick brown fox jumped over the lazy dog.'});
testVim('yank_register', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('"', 'a', 'y', 'y');
helpers.doKeys('j', '"', 'b', 'y', 'y');
cm.openDialog = helpers.fakeOpenDialog('registers');
cm.openNotification = helpers.fakeOpenNotification(function(text) {
is(/a\s+foo/.test(text));
is(/b\s+bar/.test(text));
});
helpers.doKeys(':');
}, { value: 'foo\nbar'});
testVim('yank_visual_block', function(cm, vim, helpers) {
cm.setCursor(0, 1);
helpers.doKeys('<C-v>', 'l', 'j', '"', 'a', 'y');
cm.openNotification = helpers.fakeOpenNotification(function(text) {
is(/a\s+oo\nar/.test(text));
});
helpers.doKeys(':');
}, { value: 'foo\nbar'});
testVim('yank_append_line_to_line_register', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('"', 'a', 'y', 'y');
helpers.doKeys('j', '"', 'A', 'y', 'y');
cm.openDialog = helpers.fakeOpenDialog('registers');
cm.openNotification = helpers.fakeOpenNotification(function(text) {
is(/a\s+foo\nbar/.test(text));
is(/"\s+foo\nbar/.test(text));
});
helpers.doKeys(':');
}, { value: 'foo\nbar'});
testVim('yank_append_word_to_word_register', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('"', 'a', 'y', 'w');
helpers.doKeys('j', '"', 'A', 'y', 'w');
cm.openDialog = helpers.fakeOpenDialog('registers');
cm.openNotification = helpers.fakeOpenNotification(function(text) {
is(/a\s+foobar/.test(text));
is(/"\s+foobar/.test(text));
});
helpers.doKeys(':');
}, { value: 'foo\nbar'});
testVim('yank_append_line_to_word_register', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('"', 'a', 'y', 'w');
helpers.doKeys('j', '"', 'A', 'y', 'y');
cm.openDialog = helpers.fakeOpenDialog('registers');
cm.openNotification = helpers.fakeOpenNotification(function(text) {
is(/a\s+foo\nbar/.test(text));
is(/"\s+foo\nbar/.test(text));
});
helpers.doKeys(':');
}, { value: 'foo\nbar'});
testVim('yank_append_word_to_line_register', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('"', 'a', 'y', 'y');
helpers.doKeys('j', '"', 'A', 'y', 'w');
cm.openDialog = helpers.fakeOpenDialog('registers');
cm.openNotification = helpers.fakeOpenNotification(function(text) {
is(/a\s+foo\nbar/.test(text));
is(/"\s+foo\nbar/.test(text));
});
helpers.doKeys(':');
}, { value: 'foo\nbar'});
testVim('macro_register', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('q', 'a', 'i');
cm.replaceRange('gangnam', cm.getCursor());
helpers.doKeys('<Esc>');
helpers.doKeys('q');
helpers.doKeys('q', 'b', 'o');
cm.replaceRange('style', cm.getCursor());
helpers.doKeys('<Esc>');
helpers.doKeys('q');
cm.openDialog = helpers.fakeOpenDialog('registers');
cm.openNotification = helpers.fakeOpenNotification(function(text) {
is(/a\s+i/.test(text));
is(/b\s+o/.test(text));
});
helpers.doKeys(':');
}, { value: ''});
testVim('._register', function(cm,vim,helpers) {
cm.setCursor(0,0);
helpers.doKeys('i');
cm.replaceRange('foo',cm.getCursor());
helpers.doKeys('<Esc>');
cm.openDialog = helpers.fakeOpenDialog('registers');
cm.openNotification = helpers.fakeOpenNotification(function(text) {
is(/\.\s+foo/.test(text));
});
helpers.doKeys(':');
}, {value: ''});
testVim(':_register', function(cm,vim,helpers) {
helpers.doEx('bar');
cm.openDialog = helpers.fakeOpenDialog('registers');
cm.openNotification = helpers.fakeOpenNotification(function(text) {
is(/:\s+bar/.test(text));
});
helpers.doKeys(':');
}, {value: ''});
testVim('search_register_escape', function(cm, vim, helpers) {
// Check that the register is restored if the user escapes rather than confirms.
cm.openDialog = helpers.fakeOpenDialog('waldo');
helpers.doKeys('/');
var onKeyDown;
var onKeyUp;
var KEYCODES = {
f: 70,
o: 79,
Esc: 27
};
cm.openDialog = function(template, callback, options) {
onKeyDown = options.onKeyDown;
onKeyUp = options.onKeyUp;
};
var close = function() {};
helpers.doKeys('/');
// Fake some keyboard events coming in.
onKeyDown({keyCode: KEYCODES.f}, '', close);
onKeyUp({keyCode: KEYCODES.f}, '', close);
onKeyDown({keyCode: KEYCODES.o}, 'f', close);
onKeyUp({keyCode: KEYCODES.o}, 'f', close);
onKeyDown({keyCode: KEYCODES.o}, 'fo', close);
onKeyUp({keyCode: KEYCODES.o}, 'fo', close);
onKeyDown({keyCode: KEYCODES.Esc}, 'foo', close);
cm.openDialog = helpers.fakeOpenDialog('registers');
cm.openNotification = helpers.fakeOpenNotification(function(text) {
is(/waldo/.test(text));
is(!/foo/.test(text));
});
helpers.doKeys(':');
}, {value: ''});
testVim('search_register', function(cm, vim, helpers) {
cm.openDialog = helpers.fakeOpenDialog('foo');
helpers.doKeys('/');
cm.openDialog = helpers.fakeOpenDialog('registers');
cm.openNotification = helpers.fakeOpenNotification(function(text) {
is(/\/\s+foo/.test(text));
});
helpers.doKeys(':');
}, {value: ''});
testVim('search_history', function(cm, vim, helpers) {
cm.openDialog = helpers.fakeOpenDialog('this');
helpers.doKeys('/');
cm.openDialog = helpers.fakeOpenDialog('checks');
helpers.doKeys('/');
cm.openDialog = helpers.fakeOpenDialog('search');
helpers.doKeys('/');
cm.openDialog = helpers.fakeOpenDialog('history');
helpers.doKeys('/');
cm.openDialog = helpers.fakeOpenDialog('checks');
helpers.doKeys('/');
var onKeyDown;
var onKeyUp;
var query = '';
var keyCodes = {
Up: 38,
Down: 40
};
cm.openDialog = function(template, callback, options) {
onKeyUp = options.onKeyUp;
onKeyDown = options.onKeyDown;
};
var close = function(newVal) {
if (typeof newVal == 'string') query = newVal;
}
helpers.doKeys('/');
onKeyDown({keyCode: keyCodes.Up}, query, close);
onKeyUp({keyCode: keyCodes.Up}, query, close);
eq(query, 'checks');
onKeyDown({keyCode: keyCodes.Up}, query, close);
onKeyUp({keyCode: keyCodes.Up}, query, close);
eq(query, 'history');
onKeyDown({keyCode: keyCodes.Up}, query, close);
onKeyUp({keyCode: keyCodes.Up}, query, close);
eq(query, 'search');
onKeyDown({keyCode: keyCodes.Up}, query, close);
onKeyUp({keyCode: keyCodes.Up}, query, close);
eq(query, 'this');
onKeyDown({keyCode: keyCodes.Down}, query, close);
onKeyUp({keyCode: keyCodes.Down}, query, close);
eq(query, 'search');
}, {value: ''});
testVim('exCommand_history', function(cm, vim, helpers) {
cm.openDialog = helpers.fakeOpenDialog('registers');
helpers.doKeys(':');
cm.openDialog = helpers.fakeOpenDialog('sort');
helpers.doKeys(':');
cm.openDialog = helpers.fakeOpenDialog('map');
helpers.doKeys(':');
cm.openDialog = helpers.fakeOpenDialog('invalid');
helpers.doKeys(':');
var onKeyDown;
var onKeyUp;
var input = '';
var keyCodes = {
Up: 38,
Down: 40,
s: 115
};
cm.openDialog = function(template, callback, options) {
onKeyUp = options.onKeyUp;
onKeyDown = options.onKeyDown;
};
var close = function(newVal) {
if (typeof newVal == 'string') input = newVal;
}
helpers.doKeys(':');
onKeyDown({keyCode: keyCodes.Up}, input, close);
eq(input, 'invalid');
onKeyDown({keyCode: keyCodes.Up}, input, close);
eq(input, 'map');
onKeyDown({keyCode: keyCodes.Up}, input, close);
eq(input, 'sort');
onKeyDown({keyCode: keyCodes.Up}, input, close);
eq(input, 'registers');
onKeyDown({keyCode: keyCodes.s}, '', close);
input = 's';
onKeyDown({keyCode: keyCodes.Up}, input, close);
eq(input, 'sort');
}, {value: ''});
testVim('search_clear', function(cm, vim, helpers) {
var onKeyDown;
var input = '';
var keyCodes = {
Ctrl: 17,
u: 85
};
cm.openDialog = function(template, callback, options) {
onKeyDown = options.onKeyDown;
};
var close = function(newVal) {
if (typeof newVal == 'string') input = newVal;
}
helpers.doKeys('/');
input = 'foo';
onKeyDown({keyCode: keyCodes.Ctrl}, input, close);
onKeyDown({keyCode: keyCodes.u, ctrlKey: true}, input, close);
eq(input, '');
});
testVim('exCommand_clear', function(cm, vim, helpers) {
var onKeyDown;
var input = '';
var keyCodes = {
Ctrl: 17,
u: 85
};
cm.openDialog = function(template, callback, options) {
onKeyDown = options.onKeyDown;
};
var close = function(newVal) {
if (typeof newVal == 'string') input = newVal;
}
helpers.doKeys(':');
input = 'foo';
onKeyDown({keyCode: keyCodes.Ctrl}, input, close);
onKeyDown({keyCode: keyCodes.u, ctrlKey: true}, input, close);
eq(input, '');
});
testVim('.', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('2', 'd', 'w');
helpers.doKeys('.');
eq('5 6', cm.getValue());
}, { value: '1 2 3 4 5 6'});
testVim('._repeat', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('2', 'd', 'w');
helpers.doKeys('3', '.');
eq('6', cm.getValue());
}, { value: '1 2 3 4 5 6'});
testVim('._insert', function(cm, vim, helpers) {
helpers.doKeys('i');
cm.replaceRange('test', cm.getCursor());
helpers.doKeys('<Esc>');
helpers.doKeys('.');
eq('testestt', cm.getValue());
helpers.assertCursorAt(0, 6);
}, { value: ''});
testVim('._insert_repeat', function(cm, vim, helpers) {
helpers.doKeys('i');
cm.replaceRange('test', cm.getCursor());
cm.setCursor(0, 4);
helpers.doKeys('<Esc>');
helpers.doKeys('2', '.');
eq('testesttestt', cm.getValue());
helpers.assertCursorAt(0, 10);
}, { value: ''});
testVim('._repeat_insert', function(cm, vim, helpers) {
helpers.doKeys('3', 'i');
cm.replaceRange('te', cm.getCursor());
cm.setCursor(0, 2);
helpers.doKeys('<Esc>');
helpers.doKeys('.');
eq('tetettetetee', cm.getValue());
helpers.assertCursorAt(0, 10);
}, { value: ''});
testVim('._insert_o', function(cm, vim, helpers) {
helpers.doKeys('o');
cm.replaceRange('z', cm.getCursor());
cm.setCursor(1, 1);
helpers.doKeys('<Esc>');
helpers.doKeys('.');
eq('\nz\nz', cm.getValue());
helpers.assertCursorAt(2, 0);
}, { value: ''});
testVim('._insert_o_repeat', function(cm, vim, helpers) {
helpers.doKeys('o');
cm.replaceRange('z', cm.getCursor());
helpers.doKeys('<Esc>');
cm.setCursor(1, 0);
helpers.doKeys('2', '.');
eq('\nz\nz\nz', cm.getValue());
helpers.assertCursorAt(3, 0);
}, { value: ''});
testVim('._insert_o_indent', function(cm, vim, helpers) {
helpers.doKeys('o');
cm.replaceRange('z', cm.getCursor());
helpers.doKeys('<Esc>');
cm.setCursor(1, 2);
helpers.doKeys('.');
eq('{\n z\n z', cm.getValue());
helpers.assertCursorAt(2, 2);
}, { value: '{'});
testVim('._insert_cw', function(cm, vim, helpers) {
helpers.doKeys('c', 'w');
cm.replaceRange('test', cm.getCursor());
helpers.doKeys('<Esc>');
cm.setCursor(0, 3);
helpers.doKeys('2', 'l');
helpers.doKeys('.');
eq('test test word3', cm.getValue());
helpers.assertCursorAt(0, 8);
}, { value: 'word1 word2 word3' });
testVim('._insert_cw_repeat', function(cm, vim, helpers) {
// For some reason, repeat cw in desktop VIM will does not repeat insert mode
// changes. Will conform to that behavior.
helpers.doKeys('c', 'w');
cm.replaceRange('test', cm.getCursor());
helpers.doKeys('<Esc>');
cm.setCursor(0, 4);
helpers.doKeys('l');
helpers.doKeys('2', '.');
eq('test test', cm.getValue());
helpers.assertCursorAt(0, 8);
}, { value: 'word1 word2 word3' });
testVim('._delete', function(cm, vim, helpers) {
cm.setCursor(0, 5);
helpers.doKeys('i');
helpers.doInsertModeKeys('Backspace');
helpers.doKeys('<Esc>');
helpers.doKeys('.');
eq('zace', cm.getValue());
helpers.assertCursorAt(0, 1);
}, { value: 'zabcde'});
testVim('._delete_repeat', function(cm, vim, helpers) {
cm.setCursor(0, 6);
helpers.doKeys('i');
helpers.doInsertModeKeys('Backspace');
helpers.doKeys('<Esc>');
helpers.doKeys('2', '.');
eq('zzce', cm.getValue());
helpers.assertCursorAt(0, 1);
}, { value: 'zzabcde'});
testVim('._visual_>', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('V', 'j', '>');
cm.setCursor(2, 0)
helpers.doKeys('.');
eq(' 1\n 2\n 3\n 4', cm.getValue());
helpers.assertCursorAt(2, 2);
}, { value: '1\n2\n3\n4'});
testVim('f;', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('f', 'x');
helpers.doKeys(';');
helpers.doKeys('2', ';');
eq(9, cm.getCursor().ch);
}, { value: '01x3xx678x'});
testVim('F;', function(cm, vim, helpers) {
cm.setCursor(0, 8);
helpers.doKeys('F', 'x');
helpers.doKeys(';');
helpers.doKeys('2', ';');
eq(2, cm.getCursor().ch);
}, { value: '01x3xx6x8x'});
testVim('t;', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('t', 'x');
helpers.doKeys(';');
helpers.doKeys('2', ';');
eq(8, cm.getCursor().ch);
}, { value: '01x3xx678x'});
testVim('T;', function(cm, vim, helpers) {
cm.setCursor(0, 9);
helpers.doKeys('T', 'x');
helpers.doKeys(';');
helpers.doKeys('2', ';');
eq(2, cm.getCursor().ch);
}, { value: '0xx3xx678x'});
testVim('f,', function(cm, vim, helpers) {
cm.setCursor(0, 6);
helpers.doKeys('f', 'x');
helpers.doKeys(',');
helpers.doKeys('2', ',');
eq(2, cm.getCursor().ch);
}, { value: '01x3xx678x'});
testVim('F,', function(cm, vim, helpers) {
cm.setCursor(0, 3);
helpers.doKeys('F', 'x');
helpers.doKeys(',');
helpers.doKeys('2', ',');
eq(9, cm.getCursor().ch);
}, { value: '01x3xx678x'});
testVim('t,', function(cm, vim, helpers) {
cm.setCursor(0, 6);
helpers.doKeys('t', 'x');
helpers.doKeys(',');
helpers.doKeys('2', ',');
eq(3, cm.getCursor().ch);
}, { value: '01x3xx678x'});
testVim('T,', function(cm, vim, helpers) {
cm.setCursor(0, 4);
helpers.doKeys('T', 'x');
helpers.doKeys(',');
helpers.doKeys('2', ',');
eq(8, cm.getCursor().ch);
}, { value: '01x3xx67xx'});
testVim('fd,;', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('f', '4');
cm.setCursor(0, 0);
helpers.doKeys('d', ';');
eq('56789', cm.getValue());
helpers.doKeys('u');
cm.setCursor(0, 9);
helpers.doKeys('d', ',');
eq('01239', cm.getValue());
}, { value: '0123456789'});
testVim('Fd,;', function(cm, vim, helpers) {
cm.setCursor(0, 9);
helpers.doKeys('F', '4');
cm.setCursor(0, 9);
helpers.doKeys('d', ';');
eq('01239', cm.getValue());
helpers.doKeys('u');
cm.setCursor(0, 0);
helpers.doKeys('d', ',');
eq('56789', cm.getValue());
}, { value: '0123456789'});
testVim('td,;', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('t', '4');
cm.setCursor(0, 0);
helpers.doKeys('d', ';');
eq('456789', cm.getValue());
helpers.doKeys('u');
cm.setCursor(0, 9);
helpers.doKeys('d', ',');
eq('012349', cm.getValue());
}, { value: '0123456789'});
testVim('Td,;', function(cm, vim, helpers) {
cm.setCursor(0, 9);
helpers.doKeys('T', '4');
cm.setCursor(0, 9);
helpers.doKeys('d', ';');
eq('012349', cm.getValue());
helpers.doKeys('u');
cm.setCursor(0, 0);
helpers.doKeys('d', ',');
eq('456789', cm.getValue());
}, { value: '0123456789'});
testVim('fc,;', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('f', '4');
cm.setCursor(0, 0);
helpers.doKeys('c', ';', '<Esc>');
eq('56789', cm.getValue());
helpers.doKeys('u');
cm.setCursor(0, 9);
helpers.doKeys('c', ',');
eq('01239', cm.getValue());
}, { value: '0123456789'});
testVim('Fc,;', function(cm, vim, helpers) {
cm.setCursor(0, 9);
helpers.doKeys('F', '4');
cm.setCursor(0, 9);
helpers.doKeys('c', ';', '<Esc>');
eq('01239', cm.getValue());
helpers.doKeys('u');
cm.setCursor(0, 0);
helpers.doKeys('c', ',');
eq('56789', cm.getValue());
}, { value: '0123456789'});
testVim('tc,;', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('t', '4');
cm.setCursor(0, 0);
helpers.doKeys('c', ';', '<Esc>');
eq('456789', cm.getValue());
helpers.doKeys('u');
cm.setCursor(0, 9);
helpers.doKeys('c', ',');
eq('012349', cm.getValue());
}, { value: '0123456789'});
testVim('Tc,;', function(cm, vim, helpers) {
cm.setCursor(0, 9);
helpers.doKeys('T', '4');
cm.setCursor(0, 9);
helpers.doKeys('c', ';', '<Esc>');
eq('012349', cm.getValue());
helpers.doKeys('u');
cm.setCursor(0, 0);
helpers.doKeys('c', ',');
eq('456789', cm.getValue());
}, { value: '0123456789'});
testVim('fy,;', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('f', '4');
cm.setCursor(0, 0);
helpers.doKeys('y', ';', 'P');
eq('012340123456789', cm.getValue());
helpers.doKeys('u');
cm.setCursor(0, 9);
helpers.doKeys('y', ',', 'P');
eq('012345678456789', cm.getValue());
}, { value: '0123456789'});
testVim('Fy,;', function(cm, vim, helpers) {
cm.setCursor(0, 9);
helpers.doKeys('F', '4');
cm.setCursor(0, 9);
helpers.doKeys('y', ';', 'p');
eq('012345678945678', cm.getValue());
helpers.doKeys('u');
cm.setCursor(0, 0);
helpers.doKeys('y', ',', 'P');
eq('012340123456789', cm.getValue());
}, { value: '0123456789'});
testVim('ty,;', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys('t', '4');
cm.setCursor(0, 0);
helpers.doKeys('y', ';', 'P');
eq('01230123456789', cm.getValue());
helpers.doKeys('u');
cm.setCursor(0, 9);
helpers.doKeys('y', ',', 'p');
eq('01234567895678', cm.getValue());
}, { value: '0123456789'});
testVim('Ty,;', function(cm, vim, helpers) {
cm.setCursor(0, 9);
helpers.doKeys('T', '4');
cm.setCursor(0, 9);
helpers.doKeys('y', ';', 'p');
eq('01234567895678', cm.getValue());
helpers.doKeys('u');
cm.setCursor(0, 0);
helpers.doKeys('y', ',', 'P');
eq('01230123456789', cm.getValue());
}, { value: '0123456789'});
testVim('HML', function(cm, vim, helpers) {
var lines = 35;
var textHeight = cm.defaultTextHeight();
cm.setSize(600, lines*textHeight);
cm.setCursor(120, 0);
helpers.doKeys('H');
helpers.assertCursorAt(86, 2);
helpers.doKeys('L');
helpers.assertCursorAt(120, 4);
helpers.doKeys('M');
helpers.assertCursorAt(103,4);
}, { value: (function(){
var lines = new Array(100);
var upper = ' xx\n';
var lower = ' xx\n';
upper = lines.join(upper);
lower = lines.join(lower);
return upper + lower;
})()});
var zVals = [];
forEach(['zb','zz','zt','z-','z.','z<CR>'], function(e, idx){
var lineNum = 250;
var lines = 35;
testVim(e, function(cm, vim, helpers) {
var k1 = e[0];
var k2 = e.substring(1);
var textHeight = cm.defaultTextHeight();
cm.setSize(600, lines*textHeight);
cm.setCursor(lineNum, 0);
helpers.doKeys(k1, k2);
zVals[idx] = cm.getScrollInfo().top;
}, { value: (function(){
return new Array(500).join('\n');
})()});
});
testVim('zb_to_bottom', function(cm, vim, helpers){
var lineNum = 250;
cm.setSize(600, 35*cm.defaultTextHeight());
cm.setCursor(lineNum, 0);
helpers.doKeys('z', 'b');
var scrollInfo = cm.getScrollInfo();
eq(scrollInfo.top + scrollInfo.clientHeight, cm.charCoords(Pos(lineNum, 0), 'local').bottom);
}, { value: (function(){
return new Array(500).join('\n');
})()});
testVim('zt_to_top', function(cm, vim, helpers){
var lineNum = 250;
cm.setSize(600, 35*cm.defaultTextHeight());
cm.setCursor(lineNum, 0);
helpers.doKeys('z', 't');
eq(cm.getScrollInfo().top, cm.charCoords(Pos(lineNum, 0), 'local').top);
}, { value: (function(){
return new Array(500).join('\n');
})()});
testVim('zb<zz', function(cm, vim, helpers){
eq(zVals[0]<zVals[1], true);
});
testVim('zz<zt', function(cm, vim, helpers){
eq(zVals[1]<zVals[2], true);
});
testVim('zb==z-', function(cm, vim, helpers){
eq(zVals[0], zVals[3]);
});
testVim('zz==z.', function(cm, vim, helpers){
eq(zVals[1], zVals[4]);
});
testVim('zt==z<CR>', function(cm, vim, helpers){
eq(zVals[2], zVals[5]);
});
var moveTillCharacterSandbox =
'The quick brown fox \n';
testVim('moveTillCharacter', function(cm, vim, helpers){
cm.setCursor(0, 0);
// Search for the 'q'.
cm.openDialog = helpers.fakeOpenDialog('q');
helpers.doKeys('/');
eq(4, cm.getCursor().ch);
// Jump to just before the first o in the list.
helpers.doKeys('t');
helpers.doKeys('o');
eq('The quick brown fox \n', cm.getValue());
// Delete that one character.
helpers.doKeys('d');
helpers.doKeys('t');
helpers.doKeys('o');
eq('The quick bown fox \n', cm.getValue());
// Delete everything until the next 'o'.
helpers.doKeys('.');
eq('The quick box \n', cm.getValue());
// An unmatched character should have no effect.
helpers.doKeys('d');
helpers.doKeys('t');
helpers.doKeys('q');
eq('The quick box \n', cm.getValue());
// Matches should only be possible on single lines.
helpers.doKeys('d');
helpers.doKeys('t');
helpers.doKeys('z');
eq('The quick box \n', cm.getValue());
// After all that, the search for 'q' should still be active, so the 'N' command
// can run it again in reverse. Use that to delete everything back to the 'q'.
helpers.doKeys('d');
helpers.doKeys('N');
eq('The ox \n', cm.getValue());
eq(4, cm.getCursor().ch);
}, { value: moveTillCharacterSandbox});
testVim('searchForPipe', function(cm, vim, helpers){
CodeMirror.Vim.setOption('pcre', false);
cm.setCursor(0, 0);
// Search for the '|'.
cm.openDialog = helpers.fakeOpenDialog('|');
helpers.doKeys('/');
eq(4, cm.getCursor().ch);
}, { value: 'this|that'});
var scrollMotionSandbox =
'\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n';
testVim('scrollMotion', function(cm, vim, helpers){
var prevCursor, prevScrollInfo;
cm.setCursor(0, 0);
// ctrl-y at the top of the file should have no effect.
helpers.doKeys('<C-y>');
eq(0, cm.getCursor().line);
prevScrollInfo = cm.getScrollInfo();
helpers.doKeys('<C-e>');
eq(1, cm.getCursor().line);
is(prevScrollInfo.top < cm.getScrollInfo().top);
// Jump to the end of the sandbox.
cm.setCursor(1000, 0);
prevCursor = cm.getCursor();
// ctrl-e at the bottom of the file should have no effect.
helpers.doKeys('<C-e>');
eq(prevCursor.line, cm.getCursor().line);
prevScrollInfo = cm.getScrollInfo();
helpers.doKeys('<C-y>');
eq(prevCursor.line - 1, cm.getCursor().line, "Y");
is(prevScrollInfo.top > cm.getScrollInfo().top);
}, { value: scrollMotionSandbox});
var squareBracketMotionSandbox = ''+
'({\n'+//0
' ({\n'+//11
' /*comment {\n'+//2
' */(\n'+//3
'#else \n'+//4
' /* )\n'+//5
'#if }\n'+//6
' )}*/\n'+//7
')}\n'+//8
'{}\n'+//9
'#else {{\n'+//10
'{}\n'+//11
'}\n'+//12
'{\n'+//13
'#endif\n'+//14
'}\n'+//15
'}\n'+//16
'#else';//17
testVim('[[, ]]', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys(']', ']');
helpers.assertCursorAt(9,0);
helpers.doKeys('2', ']', ']');
helpers.assertCursorAt(13,0);
helpers.doKeys(']', ']');
helpers.assertCursorAt(17,0);
helpers.doKeys('[', '[');
helpers.assertCursorAt(13,0);
helpers.doKeys('2', '[', '[');
helpers.assertCursorAt(9,0);
helpers.doKeys('[', '[');
helpers.assertCursorAt(0,0);
}, { value: squareBracketMotionSandbox});
testVim('[], ][', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doKeys(']', '[');
helpers.assertCursorAt(12,0);
helpers.doKeys('2', ']', '[');
helpers.assertCursorAt(16,0);
helpers.doKeys(']', '[');
helpers.assertCursorAt(17,0);
helpers.doKeys('[', ']');
helpers.assertCursorAt(16,0);
helpers.doKeys('2', '[', ']');
helpers.assertCursorAt(12,0);
helpers.doKeys('[', ']');
helpers.assertCursorAt(0,0);
}, { value: squareBracketMotionSandbox});
testVim('[{, ]}', function(cm, vim, helpers) {
cm.setCursor(4, 10);
helpers.doKeys('[', '{');
helpers.assertCursorAt(2,12);
helpers.doKeys('2', '[', '{');
helpers.assertCursorAt(0,1);
cm.setCursor(4, 10);
helpers.doKeys(']', '}');
helpers.assertCursorAt(6,11);
helpers.doKeys('2', ']', '}');
helpers.assertCursorAt(8,1);
cm.setCursor(0,1);
helpers.doKeys(']', '}');
helpers.assertCursorAt(8,1);
helpers.doKeys('[', '{');
helpers.assertCursorAt(0,1);
}, { value: squareBracketMotionSandbox});
testVim('[(, ])', function(cm, vim, helpers) {
cm.setCursor(4, 10);
helpers.doKeys('[', '(');
helpers.assertCursorAt(3,14);
helpers.doKeys('2', '[', '(');
helpers.assertCursorAt(0,0);
cm.setCursor(4, 10);
helpers.doKeys(']', ')');
helpers.assertCursorAt(5,11);
helpers.doKeys('2', ']', ')');
helpers.assertCursorAt(8,0);
helpers.doKeys('[', '(');
helpers.assertCursorAt(0,0);
helpers.doKeys(']', ')');
helpers.assertCursorAt(8,0);
}, { value: squareBracketMotionSandbox});
testVim('[*, ]*, [/, ]/', function(cm, vim, helpers) {
forEach(['*', '/'], function(key){
cm.setCursor(7, 0);
helpers.doKeys('2', '[', key);
helpers.assertCursorAt(2,2);
helpers.doKeys('2', ']', key);
helpers.assertCursorAt(7,5);
});
}, { value: squareBracketMotionSandbox});
testVim('[#, ]#', function(cm, vim, helpers) {
cm.setCursor(10, 3);
helpers.doKeys('2', '[', '#');
helpers.assertCursorAt(4,0);
helpers.doKeys('5', ']', '#');
helpers.assertCursorAt(17,0);
cm.setCursor(10, 3);
helpers.doKeys(']', '#');
helpers.assertCursorAt(14,0);
}, { value: squareBracketMotionSandbox});
testVim('[m, ]m, [M, ]M', function(cm, vim, helpers) {
cm.setCursor(11, 0);
helpers.doKeys('[', 'm');
helpers.assertCursorAt(10,7);
helpers.doKeys('4', '[', 'm');
helpers.assertCursorAt(1,3);
helpers.doKeys('5', ']', 'm');
helpers.assertCursorAt(11,0);
helpers.doKeys('[', 'M');
helpers.assertCursorAt(9,1);
helpers.doKeys('3', ']', 'M');
helpers.assertCursorAt(15,0);
helpers.doKeys('5', '[', 'M');
helpers.assertCursorAt(7,3);
}, { value: squareBracketMotionSandbox});
// Ex mode tests
testVim('ex_go_to_line', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doEx('4');
helpers.assertCursorAt(3, 0);
}, { value: 'a\nb\nc\nd\ne\n'});
testVim('ex_write', function(cm, vim, helpers) {
var tmp = CodeMirror.commands.save;
var written;
var actualCm;
CodeMirror.commands.save = function(cm) {
written = true;
actualCm = cm;
};
// Test that w, wr, wri ... write all trigger :write.
var command = 'write';
for (var i = 1; i < command.length; i++) {
written = false;
actualCm = null;
helpers.doEx(command.substring(0, i));
eq(written, true);
eq(actualCm, cm);
}
CodeMirror.commands.save = tmp;
});
testVim('ex_sort', function(cm, vim, helpers) {
helpers.doEx('sort');
eq('Z\na\nb\nc\nd', cm.getValue());
}, { value: 'b\nZ\nd\nc\na'});
testVim('ex_sort_reverse', function(cm, vim, helpers) {
helpers.doEx('sort!');
eq('d\nc\nb\na', cm.getValue());
}, { value: 'b\nd\nc\na'});
testVim('ex_sort_range', function(cm, vim, helpers) {
helpers.doEx('2,3sort');
eq('b\nc\nd\na', cm.getValue());
}, { value: 'b\nd\nc\na'});
testVim('ex_sort_oneline', function(cm, vim, helpers) {
helpers.doEx('2sort');
// Expect no change.
eq('b\nd\nc\na', cm.getValue());
}, { value: 'b\nd\nc\na'});
testVim('ex_sort_ignoreCase', function(cm, vim, helpers) {
helpers.doEx('sort i');
eq('a\nb\nc\nd\nZ', cm.getValue());
}, { value: 'b\nZ\nd\nc\na'});
testVim('ex_sort_unique', function(cm, vim, helpers) {
helpers.doEx('sort u');
eq('Z\na\nb\nc\nd', cm.getValue());
}, { value: 'b\nZ\na\na\nd\na\nc\na'});
testVim('ex_sort_decimal', function(cm, vim, helpers) {
helpers.doEx('sort d');
eq('d3\n s5\n6\n.9', cm.getValue());
}, { value: '6\nd3\n s5\n.9'});
testVim('ex_sort_decimal_negative', function(cm, vim, helpers) {
helpers.doEx('sort d');
eq('z-9\nd3\n s5\n6\n.9', cm.getValue());
}, { value: '6\nd3\n s5\n.9\nz-9'});
testVim('ex_sort_decimal_reverse', function(cm, vim, helpers) {
helpers.doEx('sort! d');
eq('.9\n6\n s5\nd3', cm.getValue());
}, { value: '6\nd3\n s5\n.9'});
testVim('ex_sort_hex', function(cm, vim, helpers) {
helpers.doEx('sort x');
eq(' s5\n6\n.9\n&0xB\nd3', cm.getValue());
}, { value: '6\nd3\n s5\n&0xB\n.9'});
testVim('ex_sort_octal', function(cm, vim, helpers) {
helpers.doEx('sort o');
eq('.8\n.9\nd3\n s5\n6', cm.getValue());
}, { value: '6\nd3\n s5\n.9\n.8'});
testVim('ex_sort_decimal_mixed', function(cm, vim, helpers) {
helpers.doEx('sort d');
eq('y\nz\nc1\nb2\na3', cm.getValue());
}, { value: 'a3\nz\nc1\ny\nb2'});
testVim('ex_sort_decimal_mixed_reverse', function(cm, vim, helpers) {
helpers.doEx('sort! d');
eq('a3\nb2\nc1\nz\ny', cm.getValue());
}, { value: 'a3\nz\nc1\ny\nb2'});
testVim('ex_sort_patterns_not_supported', function(cm, vim, helpers) {
var notified = false;
cm.openNotification = helpers.fakeOpenNotification(function(text) {
notified = /patterns not supported/.test(text);
});
helpers.doEx('sort /abc/');
is(notified, 'No notification.');
});
// test for :global command
testVim('ex_global', function(cm, vim, helpers) {
cm.setCursor(0, 0);
helpers.doEx('g/one/s//two');
eq('two two\n two two\n two two', cm.getValue());
helpers.doEx('1,2g/two/s//one');
eq('one one\n one one\n two two', cm.getValue());
}, {value: 'one one\n one one\n one one'});
testVim('ex_global_confirm', function(cm, vim, helpers) {
cm.setCursor(0, 0);
var onKeyDown;
var openDialogSave = cm.openDialog;
var KEYCODES = {
a: 65,
n: 78,
q: 81,
y: 89
};
// Intercept the ex command, 'global'
cm.openDialog = function(template, callback, options) {
// Intercept the prompt for the embedded ex command, 'substitute'
cm.openDialog = function(template, callback, options) {
onKeyDown = options.onKeyDown;
};
callback('g/one/s//two/gc');
};
helpers.doKeys(':');
var close = function() {};
onKeyDown({keyCode: KEYCODES.n}, '', close);
onKeyDown({keyCode: KEYCODES.y}, '', close);
onKeyDown({keyCode: KEYCODES.a}, '', close);
onKeyDown({keyCode: KEYCODES.q}, '', close);
onKeyDown({keyCode: KEYCODES.y}, '', close);
eq('one two\n two two\n one one\n two one\n one one', cm.getValue());
}, {value: 'one one\n one one\n one one\n one one\n one one'});
// Basic substitute tests.
testVim('ex_substitute_same_line', function(cm, vim, helpers) {
cm.setCursor(1, 0);
helpers.doEx('s/one/two/g');
eq('one one\n two two', cm.getValue());
}, { value: 'one one\n one one'});
testVim('ex_substitute_full_file', function(cm, vim, helpers) {
cm.setCursor(1, 0);
helpers.doEx('%s/one/two/g');
eq('two two\n two two', cm.getValue());
}, { value: 'one one\n one one'});
testVim('ex_substitute_input_range', function(cm, vim, helpers) {
cm.setCursor(1, 0);
helpers.doEx('1,3s/\\d/0/g');
eq('0\n0\n0\n4', cm.getValue());
}, { value: '1\n2\n3\n4' });
testVim('ex_substitute_visual_range', function(cm, vim, helpers) {
cm.setCursor(1, 0);
// Set last visual mode selection marks '< and '> at lines 2 and 4
helpers.doKeys('V', '2', 'j', 'v');
helpers.doEx('\'<,\'>s/\\d/0/g');
eq('1\n0\n0\n0\n5', cm.getValue());
}, { value: '1\n2\n3\n4\n5' });
testVim('ex_substitute_empty_query', function(cm, vim, helpers) {
// If the query is empty, use last query.
cm.setCursor(1, 0);
cm.openDialog = helpers.fakeOpenDialog('1');
helpers.doKeys('/');
helpers.doEx('s//b/g');
eq('abb ab2 ab3', cm.getValue());
}, { value: 'a11 a12 a13' });
testVim('ex_substitute_javascript', function(cm, vim, helpers) {
CodeMirror.Vim.setOption('pcre', false);
cm.setCursor(1, 0);
// Throw all the things that javascript likes to treat as special values
// into the replace part. All should be literal (this is VIM).
helpers.doEx('s/\\(\\d+\\)/$$ $\' $` $& \\1/g')
eq('a $$ $\' $` $& 0 b', cm.getValue());
}, { value: 'a 0 b' });
testVim('ex_substitute_empty_arguments', function(cm,vim,helpers) {
cm.setCursor(0, 0);
helpers.doEx('s/a/b/g');
cm.setCursor(1, 0);
helpers.doEx('s');
eq('b b\nb a', cm.getValue());
}, {value: 'a a\na a'});
// More complex substitute tests that test both pcre and nopcre options.
function testSubstitute(name, options) {
testVim(name + '_pcre', function(cm, vim, helpers) {
cm.setCursor(1, 0);
CodeMirror.Vim.setOption('pcre', true);
helpers.doEx(options.expr);
eq(options.expectedValue, cm.getValue());
}, options);
// If no noPcreExpr is defined, assume that it's the same as the expr.
var noPcreExpr = options.noPcreExpr ? options.noPcreExpr : options.expr;
testVim(name + '_nopcre', function(cm, vim, helpers) {
cm.setCursor(1, 0);
CodeMirror.Vim.setOption('pcre', false);
helpers.doEx(noPcreExpr);
eq(options.expectedValue, cm.getValue());
}, options);
}
testSubstitute('ex_substitute_capture', {
value: 'a11 a12 a13',
expectedValue: 'a1111 a1212 a1313',
// $n is a backreference
expr: 's/(\\d+)/$1$1/g',
// \n is a backreference.
noPcreExpr: 's/\\(\\d+\\)/\\1\\1/g'});
testSubstitute('ex_substitute_capture2', {
value: 'a 0 b',
expectedValue: 'a $00 b',
expr: 's/(\\d+)/$$$1$1/g',
noPcreExpr: 's/\\(\\d+\\)/$\\1\\1/g'});
testSubstitute('ex_substitute_nocapture', {
value: 'a11 a12 a13',
expectedValue: 'a$1$1 a$1$1 a$1$1',
expr: 's/(\\d+)/$$1$$1/g',
noPcreExpr: 's/\\(\\d+\\)/$1$1/g'});
testSubstitute('ex_substitute_nocapture2', {
value: 'a 0 b',
expectedValue: 'a $10 b',
expr: 's/(\\d+)/$$1$1/g',
noPcreExpr: 's/\\(\\d+\\)/\\$1\\1/g'});
testSubstitute('ex_substitute_nocapture', {
value: 'a b c',
expectedValue: 'a $ c',
expr: 's/b/$$/',
noPcreExpr: 's/b/$/'});
testSubstitute('ex_substitute_slash_regex', {
value: 'one/two \n three/four',
expectedValue: 'one|two \n three|four',
expr: '%s/\\//|'});
testSubstitute('ex_substitute_pipe_regex', {
value: 'one|two \n three|four',
expectedValue: 'one,two \n three,four',
expr: '%s/\\|/,/',
noPcreExpr: '%s/|/,/'});
testSubstitute('ex_substitute_or_regex', {
value: 'one|two \n three|four',
expectedValue: 'ana|twa \n thraa|faar',
expr: '%s/o|e|u/a/g',
noPcreExpr: '%s/o\\|e\\|u/a/g'});
testSubstitute('ex_substitute_or_word_regex', {
value: 'one|two \n three|four',
expectedValue: 'five|five \n three|four',
expr: '%s/(one|two)/five/g',
noPcreExpr: '%s/\\(one\\|two\\)/five/g'});
testSubstitute('ex_substitute_backslashslash_regex', {
value: 'one\\two \n three\\four',
expectedValue: 'one,two \n three,four',
expr: '%s/\\\\/,'});
testSubstitute('ex_substitute_slash_replacement', {
value: 'one,two \n three,four',
expectedValue: 'one/two \n three/four',
expr: '%s/,/\\/'});
testSubstitute('ex_substitute_backslash_replacement', {
value: 'one,two \n three,four',
expectedValue: 'one\\two \n three\\four',
expr: '%s/,/\\\\/g'});
testSubstitute('ex_substitute_multibackslash_replacement', {
value: 'one,two \n three,four',
expectedValue: 'one\\\\\\\\two \n three\\\\\\\\four', // 2*8 backslashes.
expr: '%s/,/\\\\\\\\\\\\\\\\/g'}); // 16 backslashes.
testSubstitute('ex_substitute_newline_replacement', {
value: 'one,two \n three,four',
expectedValue: 'one\ntwo \n three\nfour',
expr: '%s/,/\\n/g'});
testSubstitute('ex_substitute_braces_word', {
value: 'ababab abb ab{2}',
expectedValue: 'ab abb ab{2}',
expr: '%s/(ab){2}//g',
noPcreExpr: '%s/\\(ab\\)\\{2\\}//g'});
testSubstitute('ex_substitute_braces_range', {
value: 'a aa aaa aaaa',
expectedValue: 'a a',
expr: '%s/a{2,3}//g',
noPcreExpr: '%s/a\\{2,3\\}//g'});
testSubstitute('ex_substitute_braces_literal', {
value: 'ababab abb ab{2}',
expectedValue: 'ababab abb ',
expr: '%s/ab\\{2\\}//g',
noPcreExpr: '%s/ab{2}//g'});
testSubstitute('ex_substitute_braces_char', {
value: 'ababab abb ab{2}',
expectedValue: 'ababab ab{2}',
expr: '%s/ab{2}//g',
noPcreExpr: '%s/ab\\{2\\}//g'});
testSubstitute('ex_substitute_braces_no_escape', {
value: 'ababab abb ab{2}',
expectedValue: 'ababab ab{2}',
expr: '%s/ab{2}//g',
noPcreExpr: '%s/ab\\{2}//g'});
testSubstitute('ex_substitute_count', {
value: '1\n2\n3\n4',
expectedValue: '1\n0\n0\n4',
expr: 's/\\d/0/i 2'});
testSubstitute('ex_substitute_count_with_range', {
value: '1\n2\n3\n4',
expectedValue: '1\n2\n0\n0',
expr: '1,3s/\\d/0/ 3'});
testSubstitute('ex_substitute_not_global', {
value: 'aaa\nbaa\ncaa',
expectedValue: 'xaa\nbxa\ncxa',
expr: '%s/a/x/'});
function testSubstituteConfirm(name, command, initialValue, expectedValue, keys, finalPos) {
testVim(name, function(cm, vim, helpers) {
var savedOpenDialog = cm.openDialog;
var savedKeyName = CodeMirror.keyName;
var onKeyDown;
var recordedCallback;
var closed = true; // Start out closed, set false on second openDialog.
function close() {
closed = true;
}
// First openDialog should save callback.
cm.openDialog = function(template, callback, options) {
recordedCallback = callback;
}
// Do first openDialog.
helpers.doKeys(':');
// Second openDialog should save keyDown handler.
cm.openDialog = function(template, callback, options) {
onKeyDown = options.onKeyDown;
closed = false;
};
// Return the command to Vim and trigger second openDialog.
recordedCallback(command);
// The event should really use keyCode, but here just mock it out and use
// key and replace keyName to just return key.
CodeMirror.keyName = function (e) { return e.key; }
keys = keys.toUpperCase();
for (var i = 0; i < keys.length; i++) {
is(!closed);
onKeyDown({ key: keys.charAt(i) }, '', close);
}
try {
eq(expectedValue, cm.getValue());
helpers.assertCursorAt(finalPos);
is(closed);
} catch(e) {
throw e
} finally {
// Restore overriden functions.
CodeMirror.keyName = savedKeyName;
cm.openDialog = savedOpenDialog;
}
}, { value: initialValue });
};
testSubstituteConfirm('ex_substitute_confirm_emptydoc',
'%s/x/b/c', '', '', '', makeCursor(0, 0));
testSubstituteConfirm('ex_substitute_confirm_nomatch',
'%s/x/b/c', 'ba a\nbab', 'ba a\nbab', '', makeCursor(0, 0));
testSubstituteConfirm('ex_substitute_confirm_accept',
'%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'yyy', makeCursor(1, 1));
testSubstituteConfirm('ex_substitute_confirm_random_keys',
'%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'ysdkywerty', makeCursor(1, 1));
testSubstituteConfirm('ex_substitute_confirm_some',
'%s/a/b/cg', 'ba a\nbab', 'bb a\nbbb', 'yny', makeCursor(1, 1));
testSubstituteConfirm('ex_substitute_confirm_all',
'%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'a', makeCursor(1, 1));
testSubstituteConfirm('ex_substitute_confirm_accept_then_all',
'%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'ya', makeCursor(1, 1));
testSubstituteConfirm('ex_substitute_confirm_quit',
'%s/a/b/cg', 'ba a\nbab', 'bb a\nbab', 'yq', makeCursor(0, 3));
testSubstituteConfirm('ex_substitute_confirm_last',
'%s/a/b/cg', 'ba a\nbab', 'bb b\nbab', 'yl', makeCursor(0, 3));
testSubstituteConfirm('ex_substitute_confirm_oneline',
'1s/a/b/cg', 'ba a\nbab', 'bb b\nbab', 'yl', makeCursor(0, 3));
testSubstituteConfirm('ex_substitute_confirm_range_accept',
'1,2s/a/b/cg', 'aa\na \na\na', 'bb\nb \na\na', 'yyy', makeCursor(1, 0));
testSubstituteConfirm('ex_substitute_confirm_range_some',
'1,3s/a/b/cg', 'aa\na \na\na', 'ba\nb \nb\na', 'ynyy', makeCursor(2, 0));
testSubstituteConfirm('ex_substitute_confirm_range_all',
'1,3s/a/b/cg', 'aa\na \na\na', 'bb\nb \nb\na', 'a', makeCursor(2, 0));
testSubstituteConfirm('ex_substitute_confirm_range_last',
'1,3s/a/b/cg', 'aa\na \na\na', 'bb\nb \na\na', 'yyl', makeCursor(1, 0));
//:noh should clear highlighting of search-results but allow to resume search through n
testVim('ex_noh_clearSearchHighlight', function(cm, vim, helpers) {
cm.openDialog = helpers.fakeOpenDialog('match');
helpers.doKeys('?');
helpers.doEx('noh');
eq(vim.searchState_.getOverlay(),null,'match-highlighting wasn\'t cleared');
helpers.doKeys('n');
helpers.assertCursorAt(0, 11,'can\'t resume search after clearing highlighting');
}, { value: 'match nope match \n nope Match' });
testVim('set_boolean', function(cm, vim, helpers) {
CodeMirror.Vim.defineOption('testoption', true, 'boolean');
// Test default value is set.
is(CodeMirror.Vim.getOption('testoption'));
try {
// Test fail to set to non-boolean
CodeMirror.Vim.setOption('testoption', '5');
fail();
} catch (expected) {};
// Test setOption
CodeMirror.Vim.setOption('testoption', false);
is(!CodeMirror.Vim.getOption('testoption'));
});
testVim('ex_set_boolean', function(cm, vim, helpers) {
CodeMirror.Vim.defineOption('testoption', true, 'boolean');
// Test default value is set.
is(CodeMirror.Vim.getOption('testoption'));
try {
// Test fail to set to non-boolean
helpers.doEx('set testoption=22');
fail();
} catch (expected) {};
// Test setOption
helpers.doEx('set notestoption');
is(!CodeMirror.Vim.getOption('testoption'));
});
testVim('set_string', function(cm, vim, helpers) {
CodeMirror.Vim.defineOption('testoption', 'a', 'string');
// Test default value is set.
eq('a', CodeMirror.Vim.getOption('testoption'));
try {
// Test fail to set non-string.
CodeMirror.Vim.setOption('testoption', true);
fail();
} catch (expected) {};
try {
// Test fail to set 'notestoption'
CodeMirror.Vim.setOption('notestoption', 'b');
fail();
} catch (expected) {};
// Test setOption
CodeMirror.Vim.setOption('testoption', 'c');
eq('c', CodeMirror.Vim.getOption('testoption'));
});
testVim('ex_set_string', function(cm, vim, helpers) {
CodeMirror.Vim.defineOption('testopt', 'a', 'string');
// Test default value is set.
eq('a', CodeMirror.Vim.getOption('testopt'));
try {
// Test fail to set 'notestopt'
helpers.doEx('set notestopt=b');
fail();
} catch (expected) {};
// Test setOption
helpers.doEx('set testopt=c')
eq('c', CodeMirror.Vim.getOption('testopt'));
helpers.doEx('set testopt=c')
eq('c', CodeMirror.Vim.getOption('testopt', cm)); //local || global
eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); // local
eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); // global
eq('c', CodeMirror.Vim.getOption('testopt')); // global
// Test setOption global
helpers.doEx('setg testopt=d')
eq('c', CodeMirror.Vim.getOption('testopt', cm));
eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'}));
eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'}));
eq('d', CodeMirror.Vim.getOption('testopt'));
// Test setOption local
helpers.doEx('setl testopt=e')
eq('e', CodeMirror.Vim.getOption('testopt', cm));
eq('e', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'}));
eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'}));
eq('d', CodeMirror.Vim.getOption('testopt'));
});
testVim('ex_set_callback', function(cm, vim, helpers) {
var global;
function cb(val, cm, cfg) {
if (val === undefined) {
// Getter
if (cm) {
return cm._local;
} else {
return global;
}
} else {
// Setter
if (cm) {
cm._local = val;
} else {
global = val;
}
}
}
CodeMirror.Vim.defineOption('testopt', 'a', 'string', cb);
// Test default value is set.
eq('a', CodeMirror.Vim.getOption('testopt'));
try {
// Test fail to set 'notestopt'
helpers.doEx('set notestopt=b');
fail();
} catch (expected) {};
// Test setOption (Identical to the string tests, but via callback instead)
helpers.doEx('set testopt=c')
eq('c', CodeMirror.Vim.getOption('testopt', cm)); //local || global
eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); // local
eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); // global
eq('c', CodeMirror.Vim.getOption('testopt')); // global
// Test setOption global
helpers.doEx('setg testopt=d')
eq('c', CodeMirror.Vim.getOption('testopt', cm));
eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'}));
eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'}));
eq('d', CodeMirror.Vim.getOption('testopt'));
// Test setOption local
helpers.doEx('setl testopt=e')
eq('e', CodeMirror.Vim.getOption('testopt', cm));
eq('e', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'}));
eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'}));
eq('d', CodeMirror.Vim.getOption('testopt'));
})
testVim('ex_set_filetype', function(cm, vim, helpers) {
CodeMirror.defineMode('test_mode', function() {
return {token: function(stream) {
stream.match(/^\s+|^\S+/);
}};
});
CodeMirror.defineMode('test_mode_2', function() {
return {token: function(stream) {
stream.match(/^\s+|^\S+/);
}};
});
// Test mode is set.
helpers.doEx('set filetype=test_mode');
eq('test_mode', cm.getMode().name);
// Test 'ft' alias also sets mode.
helpers.doEx('set ft=test_mode_2');
eq('test_mode_2', cm.getMode().name);
});
testVim('ex_set_filetype_null', function(cm, vim, helpers) {
CodeMirror.defineMode('test_mode', function() {
return {token: function(stream) {
stream.match(/^\s+|^\S+/);
}};
});
cm.setOption('mode', 'test_mode');
// Test mode is set to null.
helpers.doEx('set filetype=');
eq('null', cm.getMode().name);
});
// TODO: Reset key maps after each test.
testVim('ex_map_key2key', function(cm, vim, helpers) {
helpers.doEx('map a x');
helpers.doKeys('a');
helpers.assertCursorAt(0, 0);
eq('bc', cm.getValue());
}, { value: 'abc' });
testVim('ex_unmap_key2key', function(cm, vim, helpers) {
helpers.doEx('unmap a');
helpers.doKeys('a');
eq('vim-insert', cm.getOption('keyMap'));
}, { value: 'abc' });
testVim('ex_unmap_key2key_does_not_remove_default', function(cm, vim, helpers) {
try {
helpers.doEx('unmap a');
fail();
} catch (expected) {}
helpers.doKeys('a');
eq('vim-insert', cm.getOption('keyMap'));
}, { value: 'abc' });
testVim('ex_map_key2key_to_colon', function(cm, vim, helpers) {
helpers.doEx('map ; :');
var dialogOpened = false;
cm.openDialog = function() {
dialogOpened = true;
}
helpers.doKeys(';');
eq(dialogOpened, true);
});
testVim('ex_map_ex2key:', function(cm, vim, helpers) {
helpers.doEx('map :del x');
helpers.doEx('del');
helpers.assertCursorAt(0, 0);
eq('bc', cm.getValue());
}, { value: 'abc' });
testVim('ex_map_ex2ex', function(cm, vim, helpers) {
helpers.doEx('map :del :w');
var tmp = CodeMirror.commands.save;
var written = false;
var actualCm;
CodeMirror.commands.save = function(cm) {
written = true;
actualCm = cm;
};
helpers.doEx('del');
CodeMirror.commands.save = tmp;
eq(written, true);
eq(actualCm, cm);
});
testVim('ex_map_key2ex', function(cm, vim, helpers) {
helpers.doEx('map a :w');
var tmp = CodeMirror.commands.save;
var written = false;
var actualCm;
CodeMirror.commands.save = function(cm) {
written = true;
actualCm = cm;
};
helpers.doKeys('a');
CodeMirror.commands.save = tmp;
eq(written, true);
eq(actualCm, cm);
});
testVim('ex_map_key2key_visual_api', function(cm, vim, helpers) {
CodeMirror.Vim.map('b', ':w', 'visual');
var tmp = CodeMirror.commands.save;
var written = false;
var actualCm;
CodeMirror.commands.save = function(cm) {
written = true;
actualCm = cm;
};
// Mapping should not work in normal mode.
helpers.doKeys('b');
eq(written, false);
// Mapping should work in visual mode.
helpers.doKeys('v', 'b');
eq(written, true);
eq(actualCm, cm);
CodeMirror.commands.save = tmp;
});
testVim('ex_imap', function(cm, vim, helpers) {
CodeMirror.Vim.map('jk', '<Esc>', 'insert');
helpers.doKeys('i');
is(vim.insertMode);
helpers.doKeys('j', 'k');
is(!vim.insertMode);
});
testVim('ex_unmap_api', function(cm, vim, helpers) {
CodeMirror.Vim.map('<Alt-X>', 'gg', 'normal');
is(CodeMirror.Vim.handleKey(cm, "<Alt-X>", "normal"), "Alt-X key is mapped");
CodeMirror.Vim.unmap("<Alt-X>", "normal");
is(!CodeMirror.Vim.handleKey(cm, "<Alt-X>", "normal"), "Alt-X key is unmapped");
});
// Testing registration of functions as ex-commands and mapping to <Key>-keys
testVim('ex_api_test', function(cm, vim, helpers) {
var res=false;
var val='from';
CodeMirror.Vim.defineEx('extest','ext',function(cm,params){
if(params.args)val=params.args[0];
else res=true;
});
helpers.doEx(':ext to');
eq(val,'to','Defining ex-command failed');
CodeMirror.Vim.map('<C-CR><Space>',':ext');
helpers.doKeys('<C-CR>','<Space>');
is(res,'Mapping to key failed');
});
// For now, this test needs to be last because it messes up : for future tests.
testVim('ex_map_key2key_from_colon', function(cm, vim, helpers) {
helpers.doEx('map : x');
helpers.doKeys(':');
helpers.assertCursorAt(0, 0);
eq('bc', cm.getValue());
}, { value: 'abc' });
// Test event handlers
testVim('beforeSelectionChange', function(cm, vim, helpers) {
cm.setCursor(0, 100);
eqPos(cm.getCursor('head'), cm.getCursor('anchor'));
}, { value: 'abc' });
| antimatter15/CodeMirror | test/vim_test.js | JavaScript | mit | 141,174 |
// Github: https://github.com/shdwjk/Roll20API/blob/master/UsePower/UsePower.js
// By: The Aaron, Arcane Scriptomancer
// Contact: https://app.roll20.net/users/104025/the-aaron
var UsePower = UsePower || (function() {
'use strict';
var version = 0.31,
schemaVersion = 0.1,
ch = function (c) {
var entities = {
'<' : 'lt',
'>' : 'gt',
"'" : '#39',
'@' : '#64',
'{' : '#123',
'|' : '#124',
'}' : '#125',
'[' : '#91',
']' : '#93',
'"' : 'quot',
'-' : 'mdash',
' ' : 'nbsp'
};
if(_.has(entities,c) ){
return ('&'+entities[c]+';');
}
return '';
},
capitalize = function(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
},
showHelp = function() {
sendChat('',
'/w gm '
+'<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">'
+'<div style="font-weight: bold; border-bottom: 1px solid black;font-size: 130%;">'
+'UsePower v'+version
+'</div>'
+'<div style="padding-left:10px;margin-bottom:3px;">'
+'<p>UsePower provides a way to instrument and track daily and encounter powers. It is intended for D&D 4E, but could be used for any system that requires the capability to flag abilities as used and reset them. Using an instrumented ability will mark it used and remove it as a token action. (<i>Caveat: it will disappear the next time the owner deselects the token.</i>)</p>'
+'<p>Daily powers are restored to token actions after <b>!long-rest</b> is executed. Encounter abilities are restored to token actions after <b>!short-rest</b> or <b>!long-rest</b> is executed. Activating a used power will whisper to the player and GM that the power was already used.</p>'
+'</div>'
+'<b>Commands</b>'
+'<div style="padding-left:10px;">'
+'<b><span style="font-family: serif;">!add-use-power --'+ch('<')+'Character Name'+ch('>')+' [--[ encounter | daily ] '+ch('<')+'number'+ch('>')+' ['+ch('<')+'number'+ch('>')+' ...] ...]</span></b>'
+'<div style="padding-left: 10px;padding-right:20px">'
+'<p> For all character names, case is ignored and you may use partial names so long as they are unique. For example, '+ch('"')+'King Maximillian'+ch('"')+' could be called '+ch('"')+'max'+ch('"')+' as long as '+ch('"')+'max'+ch('"')+' does not appear in any other names. Exception: An exact match will trump a partial match. In the previous example, if a character named '+ch('"')+'Max'+ch('"')+' existed, it would be the only character matched for <b>--max</b>.</p>'
+'<p>Omitting any <b>--encounter</b> and <b>--daily</b> parameters will cause a list of the character'+ch("'")+'s powers with the expected index numbers (<i>Caveat: These numbers will change if you add powers to the character. You should look them up again before instrumenting if you have changed the list of powers.</i>)</p>'
+'<ul>'
+'<li style="border-top: 1px solid #ccc;border-bottom: 1px solid #ccc;">'
+'<b><span style="font-family: serif;">--'+ch('<')+'Character Name'+ch('>')+'</span></b> '+ch('-')+' This is the name of the character to list or instrument powers for.'
+'</li> '
+'<li style="border-top: 1px solid #ccc;border-bottom: 1px solid #ccc;">'
+'<b><span style="font-family: serif;">--'+ch('<')+'[ encounter | daily ]'+ch('>')+' '+ch('<')+'number'+ch('>')+' ['+ch('<')+'number'+ch('>')+' ...]</span></b> '+ch('-')+' This specifies a list of abilities to instrument as either encounter or daily powers. You can specify as many powers as you like by number after these arguments. Numbers that do not index abilities or values that are not numbers are ignored. Duplicates are ignored. If you specify the same number to both an <b>--encounter</b> and a <b>--daily</b> parameter, it will be reported as an error. Powers that are already instrumented will be changed (So, if an ability is already instrumented as an encounter power and you specify it as a daily power, it will be changed to a daily power.).'
+'</li> '
+'</ul>'
+'</div>'
+'</div>'
+'<div style="padding-left:10px;">'
+'<b><span style="font-family: serif;">!short-rest</span></b>'
+'<div style="padding-left: 10px;padding-right:20px">'
+'<p>This command restores all expended encounter powers to token macros.</p>'
+'</div>'
+'</div>'
+'<div style="padding-left:10px;">'
+'<b><span style="font-family: serif;">!long-rest</span></b>'
+'<div style="padding-left: 10px;padding-right:20px">'
+'<p>This command restores all expended encounter and daily powers to token macros.</p>'
+'</div>'
+'</div>'
+'<div style="padding-left:10px;">'
+'<b><span style="font-family: serif;">!use-power '+ch('<')+'Type'+ch('>')+' '+ch('<')+'Ability ID'+ch('>')+'</span></b>'
+'<div style="padding-left: 10px;padding-right:20px">'
+'<p>This command requires 2 parameters. It is usually added by the instrumenting code. If you copy it from one ability to another, it will be updated with the correct Ability ID on save. Duplicating an existing character will also cause the new character'+ch("'")+'s abilities to be corrected. All abilities are validated and updated on restart of the API.</p>'
+'</div>'
+'</div>'
+'</div>'
);
},
instrumentPower = function (type, power) {
var action=power.object.get('action'),
match=action.match(/!use-power\s+\S+\s+\S+/);
if( match ) {
action = action.replace(/!use-power\s+\S+\s+\S+/,'!use-power '+type+' '+power.object.id);
} else {
action='!use-power '+type+' '+power.object.id+'\n'+action;
}
power.object.set({action: action});
},
validateAndRepairAbility = function(obj) {
var action=obj.get('action'),
match=action.match(/!use-power\s+(\S+)\s+(\S+)/);
if(match && match[2] && match[2] !== obj.id) {
action = action.replace(/!use-power\s+\S+\s+\S+/,'!use-power '+match[1]+' '+obj.id);
obj.set({action: action});
}
},
handleInput = function(msg) {
var args,
who,
obj,
chars,
match,
notice,
abilities,
data,
dup,
cmds;
if (msg.type !== "api") {
return;
}
who=getObj('player',msg.playerid).get('_displayname').split(' ')[0];
args = msg.content.split(" ");
switch(args[0]) {
case '!short-rest':
if(!isGM(msg.playerid)) {
sendChat('','/w '+ who+' '
+'<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">'
+'<span style="font-weight:bold;color:#990000;">Error:</span> '
+'Only the GM can initiate a short rest.'
+'</div>'
);
} else {
_.chain(state.UsePower.usedPowers.encounter)
.uniq()
.map(function(id){
return getObj('ability',id);
})
.reject(_.isUndefined)
.each(function(a){
a.set({
istokenaction: true
});
});
state.UsePower.usedPowers.encounter=[];
}
break;
case '!long-rest':
if(!isGM(msg.playerid)) {
sendChat('','/w '+ who+' '
+'<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">'
+'<span style="font-weight:bold;color:#990000;">Error:</span> '
+'Only the GM can initiate a long rest.'
+'</div>'
);
}
else
{
_.chain(_.union(state.UsePower.usedPowers.encounter,state.UsePower.usedPowers.daily))
.uniq()
.map(function(id){
return getObj('ability',id);
})
.reject(_.isUndefined)
.each(function(a){
a.set({
istokenaction: true
});
});
state.UsePower.usedPowers.encounter=[];
state.UsePower.usedPowers.daily=[];
}
break;
case '!use-power':
if( 3 !== args.length ) {
showHelp();
return;
}
if(_.contains(['encounter','daily'],args[1])) {
obj = getObj('ability',args[2]);
if(obj) {
obj.set({
istokenaction: false
});
if(_.contains(state.UsePower.usedPowers[args[1]],args[2])) {
notice ='<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">'
+'<span style="font-weight:bold;color:#990000;">Error:</span> '
+capitalize(args[1])+' Power '+'['+obj.get('name')+'] has already been used.'
+'</div>';
if(!isGM(msg.playerid)) {
sendChat('','/w gm '+notice);
}
sendChat('','/w '+ who+' '+notice);
} else {
state.UsePower.usedPowers[args[1]].push(args[2]);
}
return;
}
} else {
sendChat('','/w '+ who+' '
+'<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">'
+'<span style="font-weight:bold;color:#990000;">Error:</span> '
+'Only durations of "encounter" and "daily" are supported. Do not know what to do with ['+args[1]+'].'
+'</div>'
);
return;
}
break;
case '!add-use-power':
if(!isGM(msg.playerid)) {
sendChat('','/w '+ who+' '
+'<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">'
+'<span style="font-weight:bold;color:#990000;">Error:</span> '
+'Only the GM can instrument abilites for user-power.'
+'</div>'
);
}
else
{
args = _.rest(msg.content.split(" --"));
if(args.length) {
chars=findObjs({type: 'character',archived: false});
match=_.chain([args[0]])
.map(function(n){
var l=_.filter(chars,function(c){
return c.get('name').toLowerCase() === n.toLowerCase();
});
return ( 1 === l.length ? l : _.filter(chars,function(c){
return -1 !== c.get('name').toLowerCase().indexOf(n.toLowerCase());
}));
})
.flatten()
.value();
if(1 !== match.length) {
if(match.length) {
sendChat('','/w '+ who+' '
+'<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">'
+'<span style="font-weight:bold;color:#990000;">Error:</span> '
+'Character [<b>'+args[0]+'</b>] is ambiguous and matches '+match.length+' names: <b><i> '
+_.map(match,function(e){
return e.get('name');
}).join(', ')
+'</i></b>'
+'</div>'
);
} else {
sendChat('','/w '+ who+' '
+'<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">'
+'<span style="font-weight:bold;color:#990000;">Error:</span> '
+'Character [<b>'+args[0]+'</b>] does not match any names.'
+'</div>'
);
}
}
else
{
match=match[0];
abilities=findObjs({type: 'ability', characterid: match.id});
data=_.chain(abilities)
.sort(function(o) {
return o.get('name').toLowerCase();
})
.map(function(o,idx) {
var action=o.get('action'),
match=action.match(/!use-power\s+(\S+)\s+\S+/);
return {
name: o.get('name'),
current: (match && match[1]),
index: ++idx,
object: o
};
},0)
.value();
if(1 === args.length) {
sendChat('','/w '+ who+' '
+'<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">'
+'<div style="border-bottom: 1px solid black;font-weight:bold;size:110%;">Available Powers:</div>'
+'<div><ol>'
+_.reduce(data,function(context, o) {
return context+'<li>'+o.name+(o.current ? ' <b>['+o.current+']</b>' : '')+'</li>';
},'')
+'</ol></div>'
+'</div>'
);
}
else
{
cmds=_.chain(args)
.rest()
.map(function(c){
var work = c.split(/\s+/),
cmd = work[0].toLowerCase(),
powers = _.chain(work)
.rest()
.map(function(p) {
return (parseInt(p,10) - 1);
})
.filter(function(v) {
return !!v && (v)<data.length;
})
.value();
return {
type: cmd,
which: powers
};
})
.filter(function(o) {
var types=['encounter','daily'];
if(_.contains(types,o.type)) {
return true;
}
sendChat('','/w '+ who+' '
+'<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">'
+'<span style="font-weight:bold;color:#990000;">Warning:</span> '
+'Ignoring instrumenting type [<b>'+o.type+'</b>]. Only supported types: <b>'+types.join(', ')+'</b>'
+'</div>'
);
return false;
})
.reduce(function(context,o) {
context[o.type]=_.uniq(_.union(context[o.type],o.which));
return context;
},{encounter:[], daily:[]})
.value();
dup=_.intersection(cmds.encounter, cmds.daily);
if(dup.length) {
sendChat('','/w '+ who+' '
+'<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">'
+'<span style="font-weight:bold;color:#990000;">Error:</span> '
+'Powers cannot be both encounter and daily. Please specify each power only for one type. Duplicates: <b>'+dup.join(', ')+'</b>'
+'</div>'
);
} else {
_.each(cmds.encounter, function(e) {
instrumentPower('encounter',data[e]);
});
_.each(cmds.daily, function(e) {
instrumentPower('daily',data[e]);
});
}
}
}
} else {
showHelp();
}
}
break;
}
},
checkInstall = function() {
if( ! _.has(state,'UsePower') || state.UsePower.version !== schemaVersion)
{
state.UsePower = {
version: schemaVersion,
usedPowers: {
encounter: [],
daily: []
}
};
}
_.each(findObjs({type:'ability'}), validateAndRepairAbility);
},
registerEventHandlers = function() {
on('chat:message', handleInput);
on('add:ability', validateAndRepairAbility);
on('change:ability:action', validateAndRepairAbility);
};
return {
RegisterEventHandlers: registerEventHandlers,
CheckInstall: checkInstall
};
}());
on("ready",function(){
'use strict';
if("undefined" !== typeof isGM && _.isFunction(isGM)) {
UsePower.CheckInstall();
UsePower.RegisterEventHandlers();
} else {
log('--------------------------------------------------------------');
log('UsePower requires the isGM module to work.');
log('isGM GIST: https://gist.github.com/shdwjk/8d5bb062abab18463625');
log('--------------------------------------------------------------');
}
});
| rbroemeling/roll20-api-scripts | UsePower/UsePower.js | JavaScript | mit | 14,540 |
///////////////////////////////////////////////////////////////////////////
// Copyright © 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([
'dojo/Evented',
'dojo/_base/declare',
'dojo/_base/lang',
'dojo/_base/html',
'dojo/on',
"./a11y/HeadBar",
//'dojo/keys',
//"dijit/a11yclick",
//'esri/SpatialReference',
'dijit/_WidgetBase',
'dijit/_TemplatedMixin',
"dijit/_WidgetsInTemplateMixin",
"dojo/text!./HeadBar.html"
//'./utils'
],
function (Evented, declare, lang, html, on, a11y,/*keys, a11yclick, SpatialReference,*/
_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, template/*, utils*/) {
var clazz = declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, Evented], {
baseClass: 'dojoDndSource dojoDndTarget dojoDndContainer',
templateString: template,
nls: null,
map: null,
bookmarksContainer: null,
//editable: false,
layout: null,
//isAddingBookmark: false,//adding and haven't cancel
//isEnableRename: false,
editingName: false,//is typing the name
//isEnableDelete: false,
initMapState: null,
postMixInProperties: function () {
this.nls = lang.mixin(this.nls, window.jimuNls.common);
},
startup: function () {
this.inherited(arguments);
this.refreshUI();
this.a11y_initEvents();
//this.own(on(this.filterInput, 'change', lang.hitch(this, this.onFilterChange)));
this.own(on(this.filterInput, 'blur', lang.hitch(this, this.onFilterChange)));
this.own(on(this.filterInput, 'keyUp', lang.hitch(this, this.onFilterChange)));
//this.own(on(this.filterBtn, 'click', lang.hitch(this, this.onFilterChange)));
//TODO ==>keep start ==>
// this.own(on(this.backToInitBtn, 'click', lang.hitch(this, function () {
// require(['esri/geometry/Extent'], lang.hitch(this, function (Extent) {
// var layerOptions = this.initMapState.layers;
// utils.layerInfosRestoreState(isUse, layerOptions);
// if (this.initMapState.extent) {
// this.map.setExtent(new Extent(this.initMapState.extent));
// }
// }));
// //html.removeClass(this.backToInitBtn, "marked");
// //this._listenExtentChangeOnce();
// this.emit("goto-init-extent");
// })));
//this._listenExtentChangeOnce();
//TODO ==>keep end ==>
},
refreshUI: function () {
if (this.editable) {
html.addClass(this.domNode, "editable");
html.removeClass(this.addBtn, "hide");
} else {
html.removeClass(this.domNode, "editable");
html.addClass(this.addBtn, "hide");
}
//runtime layout mode recorder
// var lastLayout = utils.getLastLayout();
// if ("undefined" === typeof lastLayout) {
// //no record in cache, so use defaultMode
// this._toggleLayoutBtnDisplay(this.layout.defaultMode);
// } else {
// if (true === this.layout[lastLayout]) {
// //use runtime cache first
// this._toggleLayoutBtnDisplay(lastLayout);
// } else {
// //config has changed, use new config
// if (true === this.layout.cards) {
// this._toggleLayoutBtnDisplay("cards");
// } else {
// this._toggleLayoutBtnDisplay("list");
// }
// }
// }
this._toggleLayoutBtnDisplay(this.layout.defaultMode);//use default layout in config, only
if (false === this.editable &&
!(true === this.layout.list && true === this.layout.cards)) {
html.addClass(this.domNode, "hide");
} else {
html.removeClass(this.domNode, "hide");
}
},
_toggleLayoutBtnDisplay: function (mode) {
html.addClass(this.listBtn, "hide");
html.addClass(this.cardsBtn, "hide");
if ("list" === mode) {
this.listMode();
} else {
this.cardsMode();
}
//icons ui
if (true === this.layout.list && true === this.layout.cards) {
if ("list" === mode) {
html.removeClass(this.cardsBtn, "hide");
} else {
html.removeClass(this.listBtn, "hide");
}
html.addClass(this.displayMode, "two-modes");
} else {
html.removeClass(this.displayMode, "two-modes");
}
},
cardsMode: function () {
html.removeClass(this.bookmarksContainer, "list");
html.addClass(this.bookmarksContainer, "cards");
html.addClass(this.domNode, "list");
html.removeClass(this.domNode, "cards");
this.emit("layout-cards");
},
listMode: function () {
html.removeClass(this.bookmarksContainer, "cards");
html.addClass(this.bookmarksContainer, "list");
html.addClass(this.domNode, "cards");
html.removeClass(this.domNode, "list");
this.emit("layout-list");
},
// toogleMobileDisplay: function (isMobile) {
// if (isMobile) {
// html.addClass(this.displayMode, "hide");
// } else {
// html.removeClass(this.displayMode, "hide");
// }
// },
//add
addingBookmark: function () {
//this.isAddingBookmark = true;
//html.addClass(this.domNode, "adding");
this.emit("add");
},
// cancelAddingBookmark: function () {
// this.isAddingBookmark = false;
// //html.removeClass(this.domNode, "adding");
// },
onFilterChange: function () {
var val = this.filterInput.getValue();
this.emit("filter-change", val);
},
onFilterBlur: function () {
var val = this.filterInput.getValue();
this.emit("filter-blur", val);
}
// updateInitMapState: function () {
// this.initMapState = {
// extent: this.map.extent.toJson(),
// layers: {}
// };
// this.initMapState.layers = utils.getlayerInfos();
// },
// _listenExtentChangeOnce: function () {
// this.own(on.once(this.map, 'extent-change', lang.hitch(this, function () {
// html.addClass(this.backToInitBtn, "marked");
// })));
// }
});
clazz.extend(a11y);//for a11y
return clazz;
}); | tmcgee/cmv-wab-widgets | wab/2.15/widgets/Bookmark/HeadBar.js | JavaScript | mit | 7,032 |
define("p3/widget/viewer/JobResult", [
'dojo/_base/declare', 'dijit/layout/BorderContainer', 'dojo/on',
'dojo/dom-class', 'dijit/layout/ContentPane', 'dojo/dom-construct',
'../PageGrid', '../formatter', '../../WorkspaceManager', 'dojo/_base/lang',
'dojo/dom-attr', '../WorkspaceExplorerView', 'dijit/Dialog', '../../util/encodePath'
], function (
declare, BorderContainer, on,
domClass, ContentPane, domConstruct,
Grid, formatter, WorkspaceManager, lang,
domAttr, WorkspaceExplorerView, Dialog, encodePath
) {
return declare([BorderContainer], {
baseClass: 'ExperimentViewer',
disabled: false,
query: null,
data: null,
containerType: 'job_result',
_resultType: null,
_jobOut: {
id: { label: 'Job ID' },
start_time: { label: 'Start time', format: formatter.epochDate },
end_time: { label: 'End time', format: formatter.epochDate },
elapsed_time: { label: 'Run time', format: formatter.runTime },
parameters: {
label: 'Parameters',
format: function (d) {
if (Object.prototype.hasOwnProperty.call(d, 'ustring')) {
d.ustring = JSON.parse(d.ustring);
}
return '<pre style="font-size:.8em; overflow: scroll;">' + JSON.stringify(d, null, 2) + '</pre>';
}
}
},
_jobOrder: ['id', 'start_time', 'end_time', 'elapsed_time', 'parameters'],
_appLabel: '',
_resultMetaTypes: {},
_autoLabels: {},
_setDataAttr: function (data) {
this.data = data;
// console.log("[JobResult] data: ", data);
this._hiddenPath = data.path + '.' + data.name;
// console.log("[JobResult] Output Files: ", this.data.autoMeta.output_files);
var _self = this;
// check to see if there's a hidden .folder with the actual data
WorkspaceManager.getObject(this._hiddenPath, true).otherwise(function (err) {
new Dialog({
content: "No output from this job was found in the <i>'." + _self.data.name + "'</i> folder. "
+ 'If you moved the job result file from another location, please ensure you '
+ 'have also moved the accomanying folder to this location.',
title: 'Error Loading Job Result',
style: 'width: 300px !important;'
}).show();
});
// get the contents directly from the hidden folder, since metadata may be stale after a move
WorkspaceManager.getFolderContents(this._hiddenPath, true, true)
.then(function (objs) {
_self._resultObjects = objs;
_self.setupResultType();
_self.refresh();
});
},
isSummaryView: function () {
return false;
},
setupResultType: function () {
// console.log("[JobResult] setupResultType()");
if (this.data.autoMeta.app.id) {
this._resultType = this.data.autoMeta.app.id;
// console.log("[JobResult] _resultType:",this._resultType);
}
if (this._resultType == 'GenomeAssembly') {
this._appLabel = 'Genome Assembly';
}
else {
this._appLabel = this._resultType;
}
},
getExtraMetaDataForHeader: function (job_output) {
return job_output;
},
refresh: function () {
// console.log("[JobResult] refresh()");
if (this.data) {
var jobHeader = '<div style="width:100%"><div style="width:100%;" ><h3 style="color:#888;font-size:1.3em;font-weight:normal;" class="normal-case close2x"><span style="" class="wrap">';
if (this.data.autoMeta && this.data.autoMeta.app) {
jobHeader = jobHeader + this._appLabel + ' ';
}
jobHeader += 'Job Result</span></h3>';
// this.viewer.set('content',jobHeader);
var output = [];
output.push(jobHeader + '<table style="width:90%" class="p3basic striped far2x" id="data-table"><tbody>');
var job_output = [];
// add extra metadata header lines
job_output = this.getExtraMetaDataForHeader(job_output);
this._jobOrder.forEach(function (prop) {
/* if (prop=="output_files") { return; }
if (prop=="app") { return; }
if (prop=="job_output") { return; }
if (prop=="hostname") { return; } */
if (!this.data.autoMeta[prop]) {
return;
}
if (Object.prototype.hasOwnProperty.call(this._jobOut, prop)) {
// this._jobOut[prop]["value"]=this.data.autoMeta[prop];
// var tableLabel = this._jobOut[prop].hasOwnProperty('label') ? this._jobOut[prop].label : prop;
var tableValue = Object.prototype.hasOwnProperty.call(this._jobOut[prop], 'format') ? this._jobOut[prop].format(this.data.autoMeta[prop]) : this.data.autoMeta[prop];
if (prop == 'parameters') {
job_output.push('<tr class="alt"><td class="last" colspan=2><div data-dojo-type="dijit/TitlePane" data-dojo-props="title: \'Parameters\', open:false">' + tableValue + '</div></td></tr>');
} else {
job_output.push('<tr class="alt"><th scope="row" style="width:20%"><b>' + this._jobOut[prop].label + '</b></th><td class="last">' + tableValue + '</td></tr>');
}
}
}, this);
}
output.push.apply(output, job_output);
output.push('</tbody></table></div>');
if (this.data.userMeta) {
Object.keys(this.data.userMeta).forEach(function (prop) {
output.push('<div>' + prop + ': ' + this.data.userMeta[prop] + '</div>');
}, this);
}
output.push('</div>');
this.viewHeader.set('content', output.join(''));
this.resize();
},
startup: function () {
if (this._started) {
return;
}
this.inherited(arguments);
this.viewHeader = new ContentPane({ content: 'Loading data from ' + this.data.name + ' job file.', region: 'top', style: 'width:90%;height:30%;' });
this.viewer = new WorkspaceExplorerView({ region: 'center', path: encodePath(this._hiddenPath) });
this.addChild(this.viewHeader);
this.addChild(this.viewer);
this.on('i:click', function (evt) {
var rel = domAttr.get(evt.target, 'rel');
if (rel) {
WorkspaceManager.downloadFile(rel);
} else {
console.warn('link not found: ', rel);
}
});
}
});
});
| dawenx/p3_web | public/js/release/p3/widget/viewer/JobResult.js | JavaScript | mit | 6,330 |
quail.inputCheckboxRequiresFieldset = function (quail, test, Case) {
test.get('$scope').find(':checkbox').each(function() {
var _case = Case({
element: this,
expected: $(this).closest('.quail-test').data('expected')
});
test.add(_case);
if (!$(this).parents('fieldset').length) {
_case.set({
'status': 'failed'
});
}
else {
_case.set({
'status': 'passed'
});
}
});
};
| cksource/quail | src/js/custom/inputCheckboxRequiresFieldset.js | JavaScript | mit | 452 |
'use strict';
const validator = require('./utils/validator-extras').validator;
const extendModelValidations = require('./utils/validator-extras').extendModelValidations;
const Utils = require('./utils');
const sequelizeError = require('./errors');
const Promise = require('./promise');
const DataTypes = require('./data-types');
const _ = require('lodash');
/**
* The Main Instance Validator.
*
* @param {Instance} modelInstance The model instance.
* @param {Object} options A dict with options.
* @constructor
* @private
*/
class InstanceValidator {
constructor(modelInstance, options) {
options = _.clone(options) || {};
if (options.fields && !options.skip) {
options.skip = Utils._.difference(Object.keys(modelInstance.constructor.rawAttributes), options.fields);
}
// assign defined and default options
this.options = Utils._.defaults(options, {
skip: [],
hooks: true
});
this.modelInstance = modelInstance;
/**
* Exposes a reference to validator.js. This allows you to add custom validations using `validator.extend`
* @name validator
* @private
*/
this.validator = validator;
/**
* All errors will be stored here from the validations.
*
* @type {Array} Will contain keys that correspond to attributes which will
* be Arrays of Errors.
* @private
*/
this.errors = [];
/**
* @type {boolean} Indicates if validations are in progress
* @private
*/
this.inProgress = false;
extendModelValidations(modelInstance);
}
/**
* The main entry point for the Validation module, invoke to start the dance.
*
* @return {Promise}
* @private
*/
_validate() {
if (this.inProgress) {
throw new Error('Validations already in progress.');
}
this.inProgress = true;
return Promise.all(
[this._builtinValidators(), this._customValidators()].map(promise => promise.reflect())
).then(() => {
if (this.errors.length) {
throw new sequelizeError.ValidationError(null, this.errors);
}
});
}
/**
* Invoke the Validation sequence and run validation hooks if defined
* - Before Validation Model Hooks
* - Validation
* - On validation success: After Validation Model Hooks
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
* @private
*/
validate() {
return this.options.hooks ? this._validateAndRunHooks() : this._validate();
}
/**
* Invoke the Validation sequence and run hooks
* - Before Validation Model Hooks
* - Validation
* - On validation success: After Validation Model Hooks
* - On validation failure: Validation Failed Model Hooks
*
* @return {Promise}
* @private
*/
_validateAndRunHooks() {
const runHooks = this.modelInstance.constructor.runHooks.bind(this.modelInstance.constructor);
return runHooks('beforeValidate', this.modelInstance, this.options)
.then(() =>
this._validate()
.catch(error => runHooks('validationFailed', this.modelInstance, this.options, error)
.then(newError => { throw newError || error; }))
)
.then(() => runHooks('afterValidate', this.modelInstance, this.options))
.return(this.modelInstance);
}
/**
* Will run all the built-in validators.
*
* @return {Promise(Array.<Promise.PromiseInspection>)} A promise from .reflect().
* @private
*/
_builtinValidators() {
// promisify all attribute invocations
const validators = [];
Utils._.forIn(this.modelInstance.rawAttributes, (rawAttribute, field) => {
if (this.options.skip.indexOf(field) >= 0) {
return;
}
const value = this.modelInstance.dataValues[field];
if (!rawAttribute._autoGenerated && !rawAttribute.autoIncrement) {
// perform validations based on schema
this._validateSchema(rawAttribute, field, value);
}
if (this.modelInstance.validators.hasOwnProperty(field)) {
validators.push(this._builtinAttrValidate.call(this, value, field).reflect());
}
});
return Promise.all(validators);
}
/**
* Will run all the custom validators.
*
* @return {Promise(Array.<Promise.PromiseInspection>)} A promise from .reflect().
* @private
*/
_customValidators() {
const validators = [];
Utils._.each(this.modelInstance._modelOptions.validate, (validator, validatorType) => {
if (this.options.skip.indexOf(validatorType) >= 0) {
return;
}
const valprom = this._invokeCustomValidator(validator, validatorType)
// errors are handled in settling, stub this
.catch(() => {})
.reflect();
validators.push(valprom);
});
return Promise.all(validators);
}
/**
* Validate a single attribute with all the defined built-in validators.
*
* @param {*} value Anything.
* @param {string} field The field name.
* @return {Promise} A promise, will always resolve,
* auto populates error on this.error local object.
* @private
*/
_builtinAttrValidate(value, field) {
// check if value is null (if null not allowed the Schema pass will capture it)
if (value === null || typeof value === 'undefined') {
return Promise.resolve();
}
// Promisify each validator
const validators = [];
Utils._.forIn(this.modelInstance.validators[field], (test, validatorType) => {
if (['isUrl', 'isURL', 'isEmail'].indexOf(validatorType) !== -1) {
// Preserve backwards compat. Validator.js now expects the second param to isURL and isEmail to be an object
if (typeof test === 'object' && test !== null && test.msg) {
test = {
msg: test.msg
};
} else if (test === true) {
test = {};
}
}
// Check for custom validator.
if (typeof test === 'function') {
return validators.push(this._invokeCustomValidator(test, validatorType, true, value, field).reflect());
}
const validatorPromise = this._invokeBuiltinValidator(value, test, validatorType, field);
// errors are handled in settling, stub this
validatorPromise.catch(() => {});
validators.push(validatorPromise.reflect());
});
return Promise
.all(validators)
.then(results => this._handleReflectedResult(field, value, results));
}
/**
* Prepare and invoke a custom validator.
*
* @param {Function} validator The custom validator.
* @param {string} validatorType the custom validator type (name).
* @param {boolean=} optAttrDefined Set to true if custom validator was defined
* from the Attribute
* @return {Promise} A promise.
* @private
*/
_invokeCustomValidator(validator, validatorType, optAttrDefined, optValue, optField) {
let validatorFunction = null; // the validation function to call
let isAsync = false;
const validatorArity = validator.length;
// check if validator is async and requires a callback
let asyncArity = 1;
let errorKey = validatorType;
let invokeArgs;
if (optAttrDefined) {
asyncArity = 2;
invokeArgs = optValue;
errorKey = optField;
}
if (validatorArity === asyncArity) {
isAsync = true;
}
if (isAsync) {
if (optAttrDefined) {
validatorFunction = Promise.promisify(validator.bind(this.modelInstance, invokeArgs));
} else {
validatorFunction = Promise.promisify(validator.bind(this.modelInstance));
}
return validatorFunction()
.catch(e => this._pushError(false, errorKey, e, optValue));
} else {
return Promise
.try(() => validator.call(this.modelInstance, invokeArgs))
.catch(e => this._pushError(false, errorKey, e, optValue));
}
}
/**
* Prepare and invoke a build-in validator.
*
* @param {*} value Anything.
* @param {*} test The test case.
* @param {string} validatorType One of known to Sequelize validators.
* @param {string} field The field that is being validated
* @return {Object} An object with specific keys to invoke the validator.
* @private
*/
_invokeBuiltinValidator(value, test, validatorType, field) {
return Promise.try(() => {
// Cast value as string to pass new Validator.js string requirement
const valueString = String(value);
// check if Validator knows that kind of validation test
if (typeof validator[validatorType] !== 'function') {
throw new Error('Invalid validator function: ' + validatorType);
}
const validatorArgs = this._extractValidatorArgs(test, validatorType, field);
if (!validator[validatorType].apply(validator, [valueString].concat(validatorArgs))) {
// extract the error msg
throw new Error(test.msg || `Validation ${validatorType} on ${field} failed`);
}
});
}
/**
* Will extract arguments for the validator.
*
* @param {*} test The test case.
* @param {string} validatorType One of known to Sequelize validators.
* @param {string} field The field that is being validated.
* @private
*/
_extractValidatorArgs(test, validatorType, field) {
let validatorArgs = test.args || test;
const isLocalizedValidator = typeof validatorArgs !== 'string' && (validatorType === 'isAlpha' || validatorType === 'isAlphanumeric' || validatorType === 'isMobilePhone');
if (!Array.isArray(validatorArgs)) {
if (validatorType === 'isImmutable') {
validatorArgs = [validatorArgs, field];
} else if (isLocalizedValidator || validatorType === 'isIP') {
validatorArgs = [];
} else {
validatorArgs = [validatorArgs];
}
} else {
validatorArgs = validatorArgs.slice(0);
}
return validatorArgs;
}
/**
* Will validate a single field against its schema definition (isnull).
*
* @param {Object} rawAttribute As defined in the Schema.
* @param {string} field The field name.
* @param {*} value anything.
* @private
*/
_validateSchema(rawAttribute, field, value) {
let error;
if (rawAttribute.allowNull === false && (value === null || value === undefined)) {
const validators = this.modelInstance.validators[field];
const errMsg = _.get(validators, 'notNull.msg', `${field} cannot be null`);
error = new sequelizeError.ValidationErrorItem(errMsg, 'notNull Violation', field, value);
this.errors.push(error);
}
if (rawAttribute.type === DataTypes.STRING || rawAttribute.type instanceof DataTypes.STRING || rawAttribute.type === DataTypes.TEXT || rawAttribute.type instanceof DataTypes.TEXT) {
if (Array.isArray(value) || _.isObject(value) && !(value instanceof Utils.SequelizeMethod) && !Buffer.isBuffer(value)) {
error = new sequelizeError.ValidationErrorItem(`${field} cannot be an array or an object`, 'string violation', field, value);
this.errors.push(error);
}
}
}
/**
* Handles the returned result of a Promise.reflect.
*
* If errors are found it populates this.error.
*
* @param {string} field The attribute name.
* @param {string|number} value The data value.
* @param {Array.<Promise.PromiseInspection>} Promise inspection objects.
* @private
*/
_handleReflectedResult(field, value, promiseInspections) {
for (const promiseInspection of promiseInspections) {
if (promiseInspection.isRejected()) {
const rejection = promiseInspection.error();
this._pushError(true, field, rejection, value);
}
}
}
/**
* Signs all errors retaining the original.
*
* @param {boolean} isBuiltin Determines if error is from builtin validator.
* @param {string} errorKey The error key to assign on this.errors object.
* @param {Error|string} rawError The original error.
* @param {string|number} value The data that triggered the error.
* @private
*/
_pushError(isBuiltin, errorKey, rawError, value) {
const message = rawError.message || rawError || 'Validation error';
const error = new sequelizeError.ValidationErrorItem(message, 'Validation error', errorKey, value);
error[InstanceValidator.RAW_KEY_NAME] = rawError;
this.errors.push(error);
}
}
/**
* @define {string} The error key for arguments as passed by custom validators
* @private
*/
InstanceValidator.RAW_KEY_NAME = '__raw';
module.exports = InstanceValidator;
module.exports.InstanceValidator = InstanceValidator;
module.exports.default = InstanceValidator;
| mason-smith/netboox | server/node_modules/sequelize/lib/instance-validator.js | JavaScript | mit | 12,595 |
/* globals process module */
module.exports = {
port: process.env.PORT || 3001
}; | shakuu/Exams | js-apps/solution/config/index.js | JavaScript | mit | 86 |
var Fiber = require('fibers');
var Future = require('fibers/future');
var _ = require('underscore');
var files = require('./fs/files.js');
var parseStack = require('./utils/parse-stack.js');
var fiberHelpers = require('./utils/fiber-helpers.js');
var Progress = require('./progress.js').Progress;
var debugBuild = !!process.env.METEOR_DEBUG_BUILD;
// A job is something like "building package foo". It contains the set
// of messages generated by tha job. A given build run could contain
// several jobs. Each job has an (absolute) path associated with
// it. Filenames in messages within a job are to be interpreted
// relative to that path.
//
// Jobs are used both for error handling (via buildmessage.capture) and to set
// the progress bar title (via progress.js).
//
// Job titles should begin with a lower-case letter (unless they begin with a
// proper noun), so that they look correct in error messages which say "While
// jobbing the job". The first letter will be capitalized automatically for the
// progress bar.
var Job = function (options) {
var self = this;
self.messages = [];
// Should be something like "building package 'foo'"
// Should look good in "While $title:\n[messages]"
self.title = options.title;
self.rootPath = options.rootPath;
// Array of Job (jobs created inside this job)
self.children = [];
};
_.extend(Job.prototype, {
// options may include type ("error"), message, func, file, line,
// column, stack (in the format returned by parseStack.parse())
addMessage: function (options) {
var self = this;
self.messages.push(options);
},
hasMessages: function () {
var self = this;
return self.messages.length > 0;
},
hasMessageWithTag: function (tagName) {
var self = this;
return _.any(self.messages, function (message) {
return message.tags && _.has(message.tags, tagName);
});
},
// Returns a multi-line string suitable for displaying to the user
formatMessages: function (indent) {
var self = this;
var out = "";
var already = {};
indent = new Array((indent || 0) + 1).join(' ');
_.each(self.messages, function (message) {
var stack = message.stack || [];
var line = indent;
if (message.file) {
line+= message.file;
if (message.line) {
line += ":" + message.line;
if (message.column) {
// XXX maybe exclude unless specifically requested (eg,
// for an automated tool that's parsing our output?)
line += ":" + message.column;
}
}
line += ": ";
} else {
// not sure how to display messages without a filenanme.. try this?
line += "error: ";
}
// XXX line wrapping would be nice..
line += message.message;
if (message.func && stack.length <= 1) {
line += " (at " + message.func + ")";
}
line += "\n";
if (stack.length > 1) {
_.each(stack, function (frame) {
// If a nontrivial stack trace (more than just the file and line
// we already complained about), print it.
var where = "";
if (frame.file) {
where += frame.file;
if (frame.line) {
where += ":" + frame.line;
if (frame.column) {
where += ":" + frame.column;
}
}
}
if (! frame.func && ! where)
return; // that's a pretty lame stack frame
line += " at ";
if (frame.func)
line += frame.func + " (" + where + ")\n";
else
line += where + "\n";
});
line += "\n";
}
// Deduplicate messages (only when exact duplicates, including stack)
if (! (line in already)) {
out += line;
already[line] = true;
}
});
return out;
}
});
// A MessageSet contains a set of jobs, which in turn each contain a
// set of messages.
var MessageSet = function (messageSet) {
var self = this;
self.jobs = [];
if (messageSet) {
self.jobs = _.clone(messageSet.jobs);
}
};
_.extend(MessageSet.prototype, {
formatMessages: function () {
var self = this;
var jobsWithMessages = _.filter(self.jobs, function (job) {
return job.hasMessages();
});
return _.map(jobsWithMessages, function (job) {
var out = '';
out += "While " + job.title + ":\n";
out += job.formatMessages(0);
return out;
}).join('\n'); // blank line between jobs
},
hasMessages: function () {
var self = this;
return _.any(self.jobs, function (job) {
return job.hasMessages();
});
},
hasMessageWithTag: function (tagName) {
var self = this;
return _.any(self.jobs, function (job) {
return job.hasMessageWithTag(tagName);
});
},
// Copy all of the messages in another MessageSet into this
// MessageSet. If the other MessageSet is subsequently mutated,
// results are undefined.
//
// XXX rather than this, the user should be able to create a
// MessageSet and pass it into capture(), and functions such as
// bundle() should take and mutate, rather than return, a
// MessageSet.
merge: function (messageSet) {
var self = this;
_.each(messageSet.jobs, function (j) {
self.jobs.push(j);
});
}
});
var spaces = function (n) {
return _.times(n, function() { return ' ' }).join('');
};
// XXX: This is now a little bit silly... ideas:
// Can we just have one hierarchical state?
// Can we combined job & messageSet
// Can we infer nesting level?
var currentMessageSet = new fiberHelpers.EnvironmentVariable;
var currentJob = new fiberHelpers.EnvironmentVariable;
var currentNestingLevel = new fiberHelpers.EnvironmentVariable(0);
var currentProgress = new fiberHelpers.EnvironmentVariable;
var rootProgress = new Progress();
var getRootProgress = function () {
return rootProgress;
};
var reportProgress = function (state) {
var progress = currentProgress.get();
if (progress) {
progress.reportProgress(state);
}
};
var reportProgressDone = function () {
var progress = currentProgress.get();
if (progress) {
progress.reportProgressDone();
}
};
var getCurrentProgressTracker = function () {
var progress = currentProgress.get();
return progress ? progress : rootProgress;
};
var addChildTracker = function (title) {
var options = {};
if (title !== undefined)
options.title = title;
return getCurrentProgressTracker().addChildTask(options);
};
// Create a new MessageSet, run `f` with that as the current
// MessageSet for the purpose of accumulating and recovering from
// errors (see error()), and then discard the return value of `f` and
// return the MessageSet.
//
// Note that you must also create a job (with enterJob) to actually
// begin capturing errors. Alternately you may pass `options`
// (otherwise optional) and a job will be created for you based on
// `options`.
var capture = function (options, f) {
var messageSet = new MessageSet;
var parentMessageSet = currentMessageSet.get();
var title;
if (typeof options === "object" && options.title)
title = options.title;
var progress = addChildTracker(title);
currentProgress.withValue(progress, function () {
currentMessageSet.withValue(messageSet, function () {
var job = null;
if (typeof options === "object") {
job = new Job(options);
messageSet.jobs.push(job);
} else {
f = options; // options not actually provided
}
currentJob.withValue(job, function () {
var nestingLevel = currentNestingLevel.get();
currentNestingLevel.withValue(nestingLevel + 1, function () {
var start;
if (debugBuild) {
start = Date.now();
console.log(spaces(nestingLevel * 2), "START CAPTURE", nestingLevel, options.title, "took " + (end - start));
}
try {
f();
} finally {
progress.reportProgressDone();
if (debugBuild) {
var end = Date.now();
console.log(spaces(nestingLevel * 2), "END CAPTURE", nestingLevel, options.title, "took " + (end - start));
}
}
});
});
});
});
return messageSet;
};
// Called from inside capture(), creates a new Job inside the current
// MessageSet and run `f` inside of it, so that any messages emitted
// by `f` are logged in the Job. Returns the return value of `f`. May
// be called recursively.
//
// Called not from inside capture(), does nothing (except call f).
//
// options:
// - title: a title for the job (required)
// - rootPath: the absolute path relative to which paths in messages
// in this job should be interpreted (omit if there is no way to map
// files that this job talks about back to files on disk)
var enterJob = function (options, f) {
if (typeof options === "function") {
f = options;
options = {};
}
if (typeof options === "string") {
options = {title: options};
}
var progress;
{
var progressOptions = {};
// XXX: Just pass all the options?
if (typeof options === "object") {
if (options.title) {
progressOptions.title = options.title;
}
if (options.forkJoin) {
progressOptions.forkJoin = options.forkJoin;
}
}
progress = getCurrentProgressTracker().addChildTask(progressOptions);
}
return currentProgress.withValue(progress, function () {
if (!currentMessageSet.get()) {
var nestingLevel = currentNestingLevel.get();
var start;
if (debugBuild) {
start = Date.now();
console.log(spaces(nestingLevel * 2), "START", nestingLevel, options.title);
}
try {
return currentNestingLevel.withValue(nestingLevel + 1, function () {
return f();
});
} finally {
progress.reportProgressDone();
if (debugBuild) {
var end = Date.now();
console.log(spaces(nestingLevel * 2), "DONE", nestingLevel, options.title, "took " + (end - start));
}
}
}
var job = new Job(options);
var originalJob = currentJob.get();
originalJob && originalJob.children.push(job);
currentMessageSet.get().jobs.push(job);
return currentJob.withValue(job, function () {
var nestingLevel = currentNestingLevel.get();
return currentNestingLevel.withValue(nestingLevel + 1, function () {
var start;
if (debugBuild) {
start = Date.now();
console.log(spaces(nestingLevel * 2), "START", nestingLevel, options.title);
}
try {
return f();
} finally {
progress.reportProgressDone();
if (debugBuild) {
var end = Date.now();
console.log(spaces(nestingLevel * 2), "DONE", nestingLevel, options.title, "took " + (end - start));
}
}
});
});
});
};
// If not inside a job, return false. Otherwise, return true if any
// messages (presumably errors) have been recorded for this job
// (including subjobs created inside this job), else false.
var jobHasMessages = function () {
var search = function (job) {
if (job.hasMessages())
return true;
return !! _.find(job.children, search);
};
return currentJob.get() ? search(currentJob.get()) : false;
};
// Given a function f, return a "marked" version of f. The mark
// indicates that stack traces should stop just above f. So if you
// mark a user-supplied callback function before calling it, you'll be
// able to show the user just the "user portion" of the stack trace
// (the part inside their own code, and not all of the innards of the
// code that called it).
var markBoundary = function (f) {
return parseStack.markBottom(f);
};
// Record a build error. If inside a job, add the error to the current
// job and return (caller should do its best to recover and
// continue). Otherwise, throws an exception based on the error.
//
// options may include
// - file: the file containing the error, relative to the root of the build
// (this must be agreed upon out of band)
// - line: the (1-indexed) line in the file that contains the error
// - column: the (1-indexed) column in that line where the error begins
// - func: the function containing the code that triggered the error
// - useMyCaller: true to capture information the caller (function
// name, file, and line). It captures not the information of the
// caller of error(), but that caller's caller. It saves them in
// 'file', 'line', and 'column' (overwriting any values passed in
// for those). It also captures the user portion of the stack,
// starting at and including the caller's caller.
// If this is a number instead of 'true', skips that many stack frames.
// - downcase: if true, the first character of `message` will be
// converted to lower case.
// - secondary: ignore this error if there are are already other
// errors in this job (the implication is that it's probably
// downstream of the other error, ie, a consequence of our attempt
// to continue past other errors)
// - tags: object with other error-specific data; there is a method
// on MessageSet which can search for errors with a specific named
// tag.
var error = function (message, options) {
options = options || {};
if (options.downcase)
message = message.slice(0,1).toLowerCase() + message.slice(1);
if (! currentJob.get())
throw new Error("Error: " + message);
if (options.secondary && jobHasMessages())
return; // skip it
var info = _.extend({
message: message
}, options);
if ('useMyCaller' in info) {
if (info.useMyCaller) {
info.stack = parseStack.parse(new Error()).slice(2);
if (typeof info.useMyCaller === 'number') {
info.stack = info.stack.slice(info.useMyCaller);
}
var caller = info.stack[0];
info.func = caller.func;
info.file = caller.file;
info.line = caller.line;
info.column = caller.column;
}
delete info.useMyCaller;
}
currentJob.get().addMessage(info);
};
// Record an exception. The message as well as any file and line
// information be read directly out of the exception. If not in a job,
// throws the exception instead. Also capture the user portion of the stack.
//
// There is special handling for files.FancySyntaxError exceptions. We
// will grab the file and location information where the syntax error
// actually occurred, rather than the place where the exception was
// thrown.
var exception = function (error) {
if (! currentJob.get()) {
// XXX this may be the wrong place to do this, but it makes syntax errors in
// files loaded via isopack.load have context.
if (error instanceof files.FancySyntaxError) {
error = new Error("Syntax error: " + error.message + " at " +
error.file + ":" + error.line + ":" + error.column);
}
throw error;
}
var message = error.message;
if (error instanceof files.FancySyntaxError) {
// No stack, because FancySyntaxError isn't a real Error and has no stack
// property!
currentJob.get().addMessage({
message: message,
file: error.file,
line: error.line,
column: error.column
});
} else {
var stack = parseStack.parse(error);
var locus = stack[0];
currentJob.get().addMessage({
message: message,
stack: stack,
func: locus.func,
file: locus.file,
line: locus.line,
column: locus.column
});
}
};
var assertInJob = function () {
if (! currentJob.get())
throw new Error("Expected to be in a buildmessage job");
};
var assertInCapture = function () {
if (! currentMessageSet.get())
throw new Error("Expected to be in a buildmessage capture");
};
var mergeMessagesIntoCurrentJob = function (innerMessages) {
var outerMessages = currentMessageSet.get();
if (! outerMessages)
throw new Error("Expected to be in a buildmessage capture");
var outerJob = currentJob.get();
if (! outerJob)
throw new Error("Expected to be in a buildmessage job");
_.each(innerMessages.jobs, function (j) {
outerJob.children.push(j);
});
outerMessages.merge(innerMessages);
};
// Like _.each, but runs each operation in a separate job
var forkJoin = function (options, iterable, fn) {
if (!_.isFunction(fn)) {
fn = iterable;
iterable = options;
options = {};
}
var futures = [];
var results = [];
// XXX: We could check whether the sub-jobs set estimates, and if not
// assume they each take the same amount of time and auto-report their completion
var errors = [];
var firstError = null;
options.forkJoin = true;
enterJob(options, function () {
var parallel = (options.parallel !== undefined) ? options.parallel : true;
if (parallel) {
var runOne = fiberHelpers.bindEnvironment(function (fut, fnArguments) {
try {
var result = enterJob({title: (options.title || '') + ' child'}, function () {
return fn.apply(null, fnArguments);
});
fut['return'](result);
} catch (e) {
fut['throw'](e);
}
});
_.each(iterable, function (...args) {
var fut = new Future();
Fiber(function () {
runOne(fut, args);
}).run();
futures.push(fut);
});
_.each(futures, function (future) {
try {
var result = future.wait();
results.push(result);
errors.push(null);
} catch (e) {
results.push(null);
errors.push(e);
if (firstError === null) {
firstError = e;
}
}
});
} else {
// not parallel
_.each(iterable, function (...args) {
try {
var result = fn(...args);
results.push(result);
errors.push(null);
} catch (e) {
results.push(null);
errors.push(e);
if (firstError === null) {
firstError = e;
}
}
});
}
});
if (firstError) {
throw firstError;
}
return results;
};
var buildmessage = exports;
_.extend(exports, {
capture: capture,
enterJob: enterJob,
markBoundary: markBoundary,
error: error,
exception: exception,
jobHasMessages: jobHasMessages,
assertInJob: assertInJob,
assertInCapture: assertInCapture,
mergeMessagesIntoCurrentJob: mergeMessagesIntoCurrentJob,
forkJoin: forkJoin,
getRootProgress: getRootProgress,
reportProgress: reportProgress,
reportProgressDone: reportProgressDone,
getCurrentProgressTracker: getCurrentProgressTracker,
addChildTracker: addChildTracker,
_MessageSet: MessageSet
});
| D1no/meteor | tools/buildmessage.js | JavaScript | mit | 18,780 |
version https://git-lfs.github.com/spec/v1
oid sha256:6e0fec378eb4f28a5413e72853e29d53e7f507d5d5244b079b91dfc326849a1d
size 26697
| yogeshsaroya/new-cdnjs | ajax/libs/rxjs/2.1.20/rx.coincidence.js | JavaScript | mit | 130 |
import { helper as h } from "@ember/component/helper";
export const helper = h( params => params.reduce( ( a, b ) => a - b ) );
| streamlink/streamlink-twitch-gui | src/app/ui/components/helper/math-sub.js | JavaScript | mit | 130 |
/*
---
MooTools: the javascript framework
web build:
- http://mootools.net/core/76bf47062d6c1983d66ce47ad66aa0e0
packager build:
- packager build Core/Core Core/Array Core/String Core/Number Core/Function Core/Object Core/Event Core/Browser Core/Class Core/Class.Extras Core/Slick.Parser Core/Slick.Finder Core/Element Core/Element.Style Core/Element.Event Core/Element.Delegation Core/Element.Dimensions Core/Fx Core/Fx.CSS Core/Fx.Tween Core/Fx.Morph Core/Fx.Transitions Core/Request Core/Request.HTML Core/Request.JSON Core/Cookie Core/JSON Core/DOMReady Core/Swiff
copyrights:
- [MooTools](http://mootools.net)
licenses:
- [MIT License](http://mootools.net/license.txt)
...
*/
/* More/Array.Extras More/Date More/Date.Extras More/Number.Format More/Assets */
(function(){this.MooTools={version:"1.4.5",build:"ab8ea8824dc3b24b6666867a2c4ed58ebb762cf0"};var e=this.typeOf=function(i){if(i==null){return"null";}if(i.$family!=null){return i.$family();
}if(i.nodeName){if(i.nodeType==1){return"element";}if(i.nodeType==3){return(/\S/).test(i.nodeValue)?"textnode":"whitespace";}}else{if(typeof i.length=="number"){if(i.callee){return"arguments";
}if("item" in i){return"collection";}}}return typeof i;};var u=this.instanceOf=function(w,i){if(w==null){return false;}var v=w.$constructor||w.constructor;
while(v){if(v===i){return true;}v=v.parent;}if(!w.hasOwnProperty){return false;}return w instanceof i;};var f=this.Function;var r=true;for(var q in {toString:1}){r=null;
}if(r){r=["hasOwnProperty","valueOf","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","constructor"];}f.prototype.overloadSetter=function(v){var i=this;
return function(x,w){if(x==null){return this;}if(v||typeof x!="string"){for(var y in x){i.call(this,y,x[y]);}if(r){for(var z=r.length;z--;){y=r[z];if(x.hasOwnProperty(y)){i.call(this,y,x[y]);
}}}}else{i.call(this,x,w);}return this;};};f.prototype.overloadGetter=function(v){var i=this;return function(x){var y,w;if(typeof x!="string"){y=x;}else{if(arguments.length>1){y=arguments;
}else{if(v){y=[x];}}}if(y){w={};for(var z=0;z<y.length;z++){w[y[z]]=i.call(this,y[z]);}}else{w=i.call(this,x);}return w;};};f.prototype.extend=function(i,v){this[i]=v;
}.overloadSetter();f.prototype.implement=function(i,v){this.prototype[i]=v;}.overloadSetter();var o=Array.prototype.slice;f.from=function(i){return(e(i)=="function")?i:function(){return i;
};};Array.from=function(i){if(i==null){return[];}return(k.isEnumerable(i)&&typeof i!="string")?(e(i)=="array")?i:o.call(i):[i];};Number.from=function(v){var i=parseFloat(v);
return isFinite(i)?i:null;};String.from=function(i){return i+"";};f.implement({hide:function(){this.$hidden=true;return this;},protect:function(){this.$protected=true;
return this;}});var k=this.Type=function(x,w){if(x){var v=x.toLowerCase();var i=function(y){return(e(y)==v);};k["is"+x]=i;if(w!=null){w.prototype.$family=(function(){return v;
}).hide();w.type=i;}}if(w==null){return null;}w.extend(this);w.$constructor=k;w.prototype.$constructor=w;return w;};var p=Object.prototype.toString;k.isEnumerable=function(i){return(i!=null&&typeof i.length=="number"&&p.call(i)!="[object Function]");
};var b={};var d=function(i){var v=e(i.prototype);return b[v]||(b[v]=[]);};var h=function(w,A){if(A&&A.$hidden){return;}var v=d(this);for(var x=0;x<v.length;
x++){var z=v[x];if(e(z)=="type"){h.call(z,w,A);}else{z.call(this,w,A);}}var y=this.prototype[w];if(y==null||!y.$protected){this.prototype[w]=A;}if(this[w]==null&&e(A)=="function"){t.call(this,w,function(i){return A.apply(i,o.call(arguments,1));
});}};var t=function(i,w){if(w&&w.$hidden){return;}var v=this[i];if(v==null||!v.$protected){this[i]=w;}};k.implement({implement:h.overloadSetter(),extend:t.overloadSetter(),alias:function(i,v){h.call(this,i,this.prototype[v]);
}.overloadSetter(),mirror:function(i){d(this).push(i);return this;}});new k("Type",k);var c=function(v,A,y){var x=(A!=Object),E=A.prototype;if(x){A=new k(v,A);
}for(var B=0,z=y.length;B<z;B++){var F=y[B],D=A[F],C=E[F];if(D){D.protect();}if(x&&C){A.implement(F,C.protect());}}if(x){var w=E.propertyIsEnumerable(y[0]);
A.forEachMethod=function(J){if(!w){for(var I=0,G=y.length;I<G;I++){J.call(E,E[y[I]],y[I]);}}for(var H in E){J.call(E,E[H],H);}};}return c;};c("String",String,["charAt","charCodeAt","concat","indexOf","lastIndexOf","match","quote","replace","search","slice","split","substr","substring","trim","toLowerCase","toUpperCase"])("Array",Array,["pop","push","reverse","shift","sort","splice","unshift","concat","join","slice","indexOf","lastIndexOf","filter","forEach","every","map","some","reduce","reduceRight"])("Number",Number,["toExponential","toFixed","toLocaleString","toPrecision"])("Function",f,["apply","call","bind"])("RegExp",RegExp,["exec","test"])("Object",Object,["create","defineProperty","defineProperties","keys","getPrototypeOf","getOwnPropertyDescriptor","getOwnPropertyNames","preventExtensions","isExtensible","seal","isSealed","freeze","isFrozen"])("Date",Date,["now"]);
Object.extend=t.overloadSetter();Date.extend("now",function(){return +(new Date);});new k("Boolean",Boolean);Number.prototype.$family=function(){return isFinite(this)?"number":"null";
}.hide();Number.extend("random",function(v,i){return Math.floor(Math.random()*(i-v+1)+v);});var l=Object.prototype.hasOwnProperty;Object.extend("forEach",function(i,w,x){for(var v in i){if(l.call(i,v)){w.call(x,i[v],v,i);
}}});Object.each=Object.forEach;Array.implement({forEach:function(x,y){for(var w=0,v=this.length;w<v;w++){if(w in this){x.call(y,this[w],w,this);}}},each:function(i,v){Array.forEach(this,i,v);
return this;}});var s=function(i){switch(e(i)){case"array":return i.clone();case"object":return Object.clone(i);default:return i;}};Array.implement("clone",function(){var v=this.length,w=new Array(v);
while(v--){w[v]=s(this[v]);}return w;});var a=function(v,i,w){switch(e(w)){case"object":if(e(v[i])=="object"){Object.merge(v[i],w);}else{v[i]=Object.clone(w);
}break;case"array":v[i]=w.clone();break;default:v[i]=w;}return v;};Object.extend({merge:function(C,y,x){if(e(y)=="string"){return a(C,y,x);}for(var B=1,w=arguments.length;
B<w;B++){var z=arguments[B];for(var A in z){a(C,A,z[A]);}}return C;},clone:function(i){var w={};for(var v in i){w[v]=s(i[v]);}return w;},append:function(z){for(var y=1,w=arguments.length;
y<w;y++){var v=arguments[y]||{};for(var x in v){z[x]=v[x];}}return z;}});["Object","WhiteSpace","TextNode","Collection","Arguments"].each(function(i){new k(i);
});var j=Date.now();String.extend("uniqueID",function(){return(j++).toString(36);});var g=this.Hash=new k("Hash",function(i){if(e(i)=="hash"){i=Object.clone(i.getClean());
}for(var v in i){this[v]=i[v];}return this;});g.implement({forEach:function(i,v){Object.forEach(this,i,v);},getClean:function(){var v={};for(var i in this){if(this.hasOwnProperty(i)){v[i]=this[i];
}}return v;},getLength:function(){var v=0;for(var i in this){if(this.hasOwnProperty(i)){v++;}}return v;}});g.alias("each","forEach");Object.type=k.isObject;
var n=this.Native=function(i){return new k(i.name,i.initialize);};n.type=k.type;n.implement=function(x,v){for(var w=0;w<x.length;w++){x[w].implement(v);
}return n;};var m=Array.type;Array.type=function(i){return u(i,Array)||m(i);};this.$A=function(i){return Array.from(i).slice();};this.$arguments=function(v){return function(){return arguments[v];
};};this.$chk=function(i){return !!(i||i===0);};this.$clear=function(i){clearTimeout(i);clearInterval(i);return null;};this.$defined=function(i){return(i!=null);
};this.$each=function(w,v,x){var i=e(w);((i=="arguments"||i=="collection"||i=="array"||i=="elements")?Array:Object).each(w,v,x);};this.$empty=function(){};
this.$extend=function(v,i){return Object.append(v,i);};this.$H=function(i){return new g(i);};this.$merge=function(){var i=Array.slice(arguments);i.unshift({});
return Object.merge.apply(null,i);};this.$lambda=f.from;this.$mixin=Object.merge;this.$random=Number.random;this.$splat=Array.from;this.$time=Date.now;
this.$type=function(i){var v=e(i);if(v=="elements"){return"array";}return(v=="null")?false:v;};this.$unlink=function(i){switch(e(i)){case"object":return Object.clone(i);
case"array":return Array.clone(i);case"hash":return new g(i);default:return i;}};})();Array.implement({every:function(c,d){for(var b=0,a=this.length>>>0;
b<a;b++){if((b in this)&&!c.call(d,this[b],b,this)){return false;}}return true;},filter:function(d,f){var c=[];for(var e,b=0,a=this.length>>>0;b<a;b++){if(b in this){e=this[b];
if(d.call(f,e,b,this)){c.push(e);}}}return c;},indexOf:function(c,d){var b=this.length>>>0;for(var a=(d<0)?Math.max(0,b+d):d||0;a<b;a++){if(this[a]===c){return a;
}}return -1;},map:function(c,e){var d=this.length>>>0,b=Array(d);for(var a=0;a<d;a++){if(a in this){b[a]=c.call(e,this[a],a,this);}}return b;},some:function(c,d){for(var b=0,a=this.length>>>0;
b<a;b++){if((b in this)&&c.call(d,this[b],b,this)){return true;}}return false;},clean:function(){return this.filter(function(a){return a!=null;});},invoke:function(a){var b=Array.slice(arguments,1);
return this.map(function(c){return c[a].apply(c,b);});},associate:function(c){var d={},b=Math.min(this.length,c.length);for(var a=0;a<b;a++){d[c[a]]=this[a];
}return d;},link:function(c){var a={};for(var e=0,b=this.length;e<b;e++){for(var d in c){if(c[d](this[e])){a[d]=this[e];delete c[d];break;}}}return a;},contains:function(a,b){return this.indexOf(a,b)!=-1;
},append:function(a){this.push.apply(this,a);return this;},getLast:function(){return(this.length)?this[this.length-1]:null;},getRandom:function(){return(this.length)?this[Number.random(0,this.length-1)]:null;
},include:function(a){if(!this.contains(a)){this.push(a);}return this;},combine:function(c){for(var b=0,a=c.length;b<a;b++){this.include(c[b]);}return this;
},erase:function(b){for(var a=this.length;a--;){if(this[a]===b){this.splice(a,1);}}return this;},empty:function(){this.length=0;return this;},flatten:function(){var d=[];
for(var b=0,a=this.length;b<a;b++){var c=typeOf(this[b]);if(c=="null"){continue;}d=d.concat((c=="array"||c=="collection"||c=="arguments"||instanceOf(this[b],Array))?Array.flatten(this[b]):this[b]);
}return d;},pick:function(){for(var b=0,a=this.length;b<a;b++){if(this[b]!=null){return this[b];}}return null;},hexToRgb:function(b){if(this.length!=3){return null;
}var a=this.map(function(c){if(c.length==1){c+=c;}return c.toInt(16);});return(b)?a:"rgb("+a+")";},rgbToHex:function(d){if(this.length<3){return null;}if(this.length==4&&this[3]==0&&!d){return"transparent";
}var b=[];for(var a=0;a<3;a++){var c=(this[a]-0).toString(16);b.push((c.length==1)?"0"+c:c);}return(d)?b:"#"+b.join("");}});Array.alias("extend","append");
var $pick=function(){return Array.from(arguments).pick();};String.implement({test:function(a,b){return((typeOf(a)=="regexp")?a:new RegExp(""+a,b)).test(this);
},contains:function(a,b){return(b)?(b+this+b).indexOf(b+a+b)>-1:String(this).indexOf(a)>-1;},trim:function(){return String(this).replace(/^\s+|\s+$/g,"");
},clean:function(){return String(this).replace(/\s+/g," ").trim();},camelCase:function(){return String(this).replace(/-\D/g,function(a){return a.charAt(1).toUpperCase();
});},hyphenate:function(){return String(this).replace(/[A-Z]/g,function(a){return("-"+a.charAt(0).toLowerCase());});},capitalize:function(){return String(this).replace(/\b[a-z]/g,function(a){return a.toUpperCase();
});},escapeRegExp:function(){return String(this).replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1");},toInt:function(a){return parseInt(this,a||10);},toFloat:function(){return parseFloat(this);
},hexToRgb:function(b){var a=String(this).match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);return(a)?a.slice(1).hexToRgb(b):null;},rgbToHex:function(b){var a=String(this).match(/\d{1,3}/g);
return(a)?a.rgbToHex(b):null;},substitute:function(a,b){return String(this).replace(b||(/\\?\{([^{}]+)\}/g),function(d,c){if(d.charAt(0)=="\\"){return d.slice(1);
}return(a[c]!=null)?a[c]:"";});}});Number.implement({limit:function(b,a){return Math.min(a,Math.max(b,this));},round:function(a){a=Math.pow(10,a||0).toFixed(a<0?-a:0);
return Math.round(this*a)/a;},times:function(b,c){for(var a=0;a<this;a++){b.call(c,a,this);}},toFloat:function(){return parseFloat(this);},toInt:function(a){return parseInt(this,a||10);
}});Number.alias("each","times");(function(b){var a={};b.each(function(c){if(!Number[c]){a[c]=function(){return Math[c].apply(null,[this].concat(Array.from(arguments)));
};}});Number.implement(a);})(["abs","acos","asin","atan","atan2","ceil","cos","exp","floor","log","max","min","pow","sin","sqrt","tan"]);Function.extend({attempt:function(){for(var b=0,a=arguments.length;
b<a;b++){try{return arguments[b]();}catch(c){}}return null;}});Function.implement({attempt:function(a,c){try{return this.apply(c,Array.from(a));}catch(b){}return null;
},bind:function(e){var a=this,b=arguments.length>1?Array.slice(arguments,1):null,d=function(){};var c=function(){var g=e,h=arguments.length;if(this instanceof c){d.prototype=a.prototype;
g=new d;}var f=(!b&&!h)?a.call(g):a.apply(g,b&&h?b.concat(Array.slice(arguments)):b||arguments);return g==e?f:g;};return c;},pass:function(b,c){var a=this;
if(b!=null){b=Array.from(b);}return function(){return a.apply(c,b||arguments);};},delay:function(b,c,a){return setTimeout(this.pass((a==null?[]:a),c),b);
},periodical:function(c,b,a){return setInterval(this.pass((a==null?[]:a),b),c);}});delete Function.prototype.bind;Function.implement({create:function(b){var a=this;
b=b||{};return function(d){var c=b.arguments;c=(c!=null)?Array.from(c):Array.slice(arguments,(b.event)?1:0);if(b.event){c=[d||window.event].extend(c);}var e=function(){return a.apply(b.bind||null,c);
};if(b.delay){return setTimeout(e,b.delay);}if(b.periodical){return setInterval(e,b.periodical);}if(b.attempt){return Function.attempt(e);}return e();};
},bind:function(c,b){var a=this;if(b!=null){b=Array.from(b);}return function(){return a.apply(c,b||arguments);};},bindWithEvent:function(c,b){var a=this;
if(b!=null){b=Array.from(b);}return function(d){return a.apply(c,(b==null)?arguments:[d].concat(b));};},run:function(a,b){return this.apply(b,Array.from(a));
}});if(Object.create==Function.prototype.create){Object.create=null;}var $try=Function.attempt;(function(){var a=Object.prototype.hasOwnProperty;Object.extend({subset:function(d,g){var f={};
for(var e=0,b=g.length;e<b;e++){var c=g[e];if(c in d){f[c]=d[c];}}return f;},map:function(b,e,f){var d={};for(var c in b){if(a.call(b,c)){d[c]=e.call(f,b[c],c,b);
}}return d;},filter:function(b,e,g){var d={};for(var c in b){var f=b[c];if(a.call(b,c)&&e.call(g,f,c,b)){d[c]=f;}}return d;},every:function(b,d,e){for(var c in b){if(a.call(b,c)&&!d.call(e,b[c],c)){return false;
}}return true;},some:function(b,d,e){for(var c in b){if(a.call(b,c)&&d.call(e,b[c],c)){return true;}}return false;},keys:function(b){var d=[];for(var c in b){if(a.call(b,c)){d.push(c);
}}return d;},values:function(c){var b=[];for(var d in c){if(a.call(c,d)){b.push(c[d]);}}return b;},getLength:function(b){return Object.keys(b).length;},keyOf:function(b,d){for(var c in b){if(a.call(b,c)&&b[c]===d){return c;
}}return null;},contains:function(b,c){return Object.keyOf(b,c)!=null;},toQueryString:function(b,c){var d=[];Object.each(b,function(h,g){if(c){g=c+"["+g+"]";
}var f;switch(typeOf(h)){case"object":f=Object.toQueryString(h,g);break;case"array":var e={};h.each(function(k,j){e[j]=k;});f=Object.toQueryString(e,g);
break;default:f=g+"="+encodeURIComponent(h);}if(h!=null){d.push(f);}});return d.join("&");}});})();Hash.implement({has:Object.prototype.hasOwnProperty,keyOf:function(a){return Object.keyOf(this,a);
},hasValue:function(a){return Object.contains(this,a);},extend:function(a){Hash.each(a||{},function(c,b){Hash.set(this,b,c);},this);return this;},combine:function(a){Hash.each(a||{},function(c,b){Hash.include(this,b,c);
},this);return this;},erase:function(a){if(this.hasOwnProperty(a)){delete this[a];}return this;},get:function(a){return(this.hasOwnProperty(a))?this[a]:null;
},set:function(a,b){if(!this[a]||this.hasOwnProperty(a)){this[a]=b;}return this;},empty:function(){Hash.each(this,function(b,a){delete this[a];},this);
return this;},include:function(a,b){if(this[a]==null){this[a]=b;}return this;},map:function(a,b){return new Hash(Object.map(this,a,b));},filter:function(a,b){return new Hash(Object.filter(this,a,b));
},every:function(a,b){return Object.every(this,a,b);},some:function(a,b){return Object.some(this,a,b);},getKeys:function(){return Object.keys(this);},getValues:function(){return Object.values(this);
},toQueryString:function(a){return Object.toQueryString(this,a);}});Hash.extend=Object.append;Hash.alias({indexOf:"keyOf",contains:"hasValue"});(function(){var k=this.document;
var h=k.window=this;var a=navigator.userAgent.toLowerCase(),b=navigator.platform.toLowerCase(),i=a.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/)||[null,"unknown",0],f=i[1]=="ie"&&k.documentMode;
var o=this.Browser={extend:Function.prototype.extend,name:(i[1]=="version")?i[3]:i[1],version:f||parseFloat((i[1]=="opera"&&i[4])?i[4]:i[2]),Platform:{name:a.match(/ip(?:ad|od|hone)/)?"ios":(a.match(/(?:webos|android)/)||b.match(/mac|win|linux/)||["other"])[0]},Features:{xpath:!!(k.evaluate),air:!!(h.runtime),query:!!(k.querySelector),json:!!(h.JSON)},Plugins:{}};
o[o.name]=true;o[o.name+parseInt(o.version,10)]=true;o.Platform[o.Platform.name]=true;o.Request=(function(){var q=function(){return new XMLHttpRequest();
};var p=function(){return new ActiveXObject("MSXML2.XMLHTTP");};var e=function(){return new ActiveXObject("Microsoft.XMLHTTP");};return Function.attempt(function(){q();
return q;},function(){p();return p;},function(){e();return e;});})();o.Features.xhr=!!(o.Request);var j=(Function.attempt(function(){return navigator.plugins["Shockwave Flash"].description;
},function(){return new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version");})||"0 r0").match(/\d+/g);o.Plugins.Flash={version:Number(j[0]||"0."+j[1])||0,build:Number(j[2])||0};
o.exec=function(p){if(!p){return p;}if(h.execScript){h.execScript(p);}else{var e=k.createElement("script");e.setAttribute("type","text/javascript");e.text=p;
k.head.appendChild(e);k.head.removeChild(e);}return p;};String.implement("stripScripts",function(p){var e="";var q=this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi,function(r,s){e+=s+"\n";
return"";});if(p===true){o.exec(e);}else{if(typeOf(p)=="function"){p(e,q);}}return q;});o.extend({Document:this.Document,Window:this.Window,Element:this.Element,Event:this.Event});
this.Window=this.$constructor=new Type("Window",function(){});this.$family=Function.from("window").hide();Window.mirror(function(e,p){h[e]=p;});this.Document=k.$constructor=new Type("Document",function(){});
k.$family=Function.from("document").hide();Document.mirror(function(e,p){k[e]=p;});k.html=k.documentElement;if(!k.head){k.head=k.getElementsByTagName("head")[0];
}if(k.execCommand){try{k.execCommand("BackgroundImageCache",false,true);}catch(g){}}if(this.attachEvent&&!this.addEventListener){var c=function(){this.detachEvent("onunload",c);
k.head=k.html=k.window=null;};this.attachEvent("onunload",c);}var m=Array.from;try{m(k.html.childNodes);}catch(g){Array.from=function(p){if(typeof p!="string"&&Type.isEnumerable(p)&&typeOf(p)!="array"){var e=p.length,q=new Array(e);
while(e--){q[e]=p[e];}return q;}return m(p);};var l=Array.prototype,n=l.slice;["pop","push","reverse","shift","sort","splice","unshift","concat","join","slice"].each(function(e){var p=l[e];
Array[e]=function(q){return p.apply(Array.from(q),n.call(arguments,1));};});}if(o.Platform.ios){o.Platform.ipod=true;}o.Engine={};var d=function(p,e){o.Engine.name=p;
o.Engine[p+e]=true;o.Engine.version=e;};if(o.ie){o.Engine.trident=true;switch(o.version){case 6:d("trident",4);break;case 7:d("trident",5);break;case 8:d("trident",6);
}}if(o.firefox){o.Engine.gecko=true;if(o.version>=3){d("gecko",19);}else{d("gecko",18);}}if(o.safari||o.chrome){o.Engine.webkit=true;switch(o.version){case 2:d("webkit",419);
break;case 3:d("webkit",420);break;case 4:d("webkit",525);}}if(o.opera){o.Engine.presto=true;if(o.version>=9.6){d("presto",960);}else{if(o.version>=9.5){d("presto",950);
}else{d("presto",925);}}}if(o.name=="unknown"){switch((a.match(/(?:webkit|khtml|gecko)/)||[])[0]){case"webkit":case"khtml":o.Engine.webkit=true;break;case"gecko":o.Engine.gecko=true;
}}this.$exec=o.exec;})();(function(){var b={};var a=this.DOMEvent=new Type("DOMEvent",function(c,g){if(!g){g=window;}c=c||g.event;if(c.$extended){return c;
}this.event=c;this.$extended=true;this.shift=c.shiftKey;this.control=c.ctrlKey;this.alt=c.altKey;this.meta=c.metaKey;var i=this.type=c.type;var h=c.target||c.srcElement;
while(h&&h.nodeType==3){h=h.parentNode;}this.target=document.id(h);if(i.indexOf("key")==0){var d=this.code=(c.which||c.keyCode);this.key=b[d]||Object.keyOf(Event.Keys,d);
if(i=="keydown"){if(d>111&&d<124){this.key="f"+(d-111);}else{if(d>95&&d<106){this.key=d-96;}}}if(this.key==null){this.key=String.fromCharCode(d).toLowerCase();
}}else{if(i=="click"||i=="dblclick"||i=="contextmenu"||i=="DOMMouseScroll"||i.indexOf("mouse")==0){var j=g.document;j=(!j.compatMode||j.compatMode=="CSS1Compat")?j.html:j.body;
this.page={x:(c.pageX!=null)?c.pageX:c.clientX+j.scrollLeft,y:(c.pageY!=null)?c.pageY:c.clientY+j.scrollTop};this.client={x:(c.pageX!=null)?c.pageX-g.pageXOffset:c.clientX,y:(c.pageY!=null)?c.pageY-g.pageYOffset:c.clientY};
if(i=="DOMMouseScroll"||i=="mousewheel"){this.wheel=(c.wheelDelta)?c.wheelDelta/120:-(c.detail||0)/3;}this.rightClick=(c.which==3||c.button==2);if(i=="mouseover"||i=="mouseout"){var k=c.relatedTarget||c[(i=="mouseover"?"from":"to")+"Element"];
while(k&&k.nodeType==3){k=k.parentNode;}this.relatedTarget=document.id(k);}}else{if(i.indexOf("touch")==0||i.indexOf("gesture")==0){this.rotation=c.rotation;
this.scale=c.scale;this.targetTouches=c.targetTouches;this.changedTouches=c.changedTouches;var f=this.touches=c.touches;if(f&&f[0]){var e=f[0];this.page={x:e.pageX,y:e.pageY};
this.client={x:e.clientX,y:e.clientY};}}}}if(!this.client){this.client={};}if(!this.page){this.page={};}});a.implement({stop:function(){return this.preventDefault().stopPropagation();
},stopPropagation:function(){if(this.event.stopPropagation){this.event.stopPropagation();}else{this.event.cancelBubble=true;}return this;},preventDefault:function(){if(this.event.preventDefault){this.event.preventDefault();
}else{this.event.returnValue=false;}return this;}});a.defineKey=function(d,c){b[d]=c;return this;};a.defineKeys=a.defineKey.overloadSetter(true);a.defineKeys({"38":"up","40":"down","37":"left","39":"right","27":"esc","32":"space","8":"backspace","9":"tab","46":"delete","13":"enter"});
})();var Event=DOMEvent;Event.Keys={};Event.Keys=new Hash(Event.Keys);(function(){var a=this.Class=new Type("Class",function(h){if(instanceOf(h,Function)){h={initialize:h};
}var g=function(){e(this);if(g.$prototyping){return this;}this.$caller=null;var i=(this.initialize)?this.initialize.apply(this,arguments):this;this.$caller=this.caller=null;
return i;}.extend(this).implement(h);g.$constructor=a;g.prototype.$constructor=g;g.prototype.parent=c;return g;});var c=function(){if(!this.$caller){throw new Error('The method "parent" cannot be called.');
}var g=this.$caller.$name,h=this.$caller.$owner.parent,i=(h)?h.prototype[g]:null;if(!i){throw new Error('The method "'+g+'" has no parent.');}return i.apply(this,arguments);
};var e=function(g){for(var h in g){var j=g[h];switch(typeOf(j)){case"object":var i=function(){};i.prototype=j;g[h]=e(new i);break;case"array":g[h]=j.clone();
break;}}return g;};var b=function(g,h,j){if(j.$origin){j=j.$origin;}var i=function(){if(j.$protected&&this.$caller==null){throw new Error('The method "'+h+'" cannot be called.');
}var l=this.caller,m=this.$caller;this.caller=m;this.$caller=i;var k=j.apply(this,arguments);this.$caller=m;this.caller=l;return k;}.extend({$owner:g,$origin:j,$name:h});
return i;};var f=function(h,i,g){if(a.Mutators.hasOwnProperty(h)){i=a.Mutators[h].call(this,i);if(i==null){return this;}}if(typeOf(i)=="function"){if(i.$hidden){return this;
}this.prototype[h]=(g)?i:b(this,h,i);}else{Object.merge(this.prototype,h,i);}return this;};var d=function(g){g.$prototyping=true;var h=new g;delete g.$prototyping;
return h;};a.implement("implement",f.overloadSetter());a.Mutators={Extends:function(g){this.parent=g;this.prototype=d(g);},Implements:function(g){Array.from(g).each(function(j){var h=new j;
for(var i in h){f.call(this,i,h[i],true);}},this);}};})();(function(){this.Chain=new Class({$chain:[],chain:function(){this.$chain.append(Array.flatten(arguments));
return this;},callChain:function(){return(this.$chain.length)?this.$chain.shift().apply(this,arguments):false;},clearChain:function(){this.$chain.empty();
return this;}});var a=function(b){return b.replace(/^on([A-Z])/,function(c,d){return d.toLowerCase();});};this.Events=new Class({$events:{},addEvent:function(d,c,b){d=a(d);
if(c==$empty){return this;}this.$events[d]=(this.$events[d]||[]).include(c);if(b){c.internal=true;}return this;},addEvents:function(b){for(var c in b){this.addEvent(c,b[c]);
}return this;},fireEvent:function(e,c,b){e=a(e);var d=this.$events[e];if(!d){return this;}c=Array.from(c);d.each(function(f){if(b){f.delay(b,this,c);}else{f.apply(this,c);
}},this);return this;},removeEvent:function(e,d){e=a(e);var c=this.$events[e];if(c&&!d.internal){var b=c.indexOf(d);if(b!=-1){delete c[b];}}return this;
},removeEvents:function(d){var e;if(typeOf(d)=="object"){for(e in d){this.removeEvent(e,d[e]);}return this;}if(d){d=a(d);}for(e in this.$events){if(d&&d!=e){continue;
}var c=this.$events[e];for(var b=c.length;b--;){if(b in c){this.removeEvent(e,c[b]);}}}return this;}});this.Options=new Class({setOptions:function(){var b=this.options=Object.merge.apply(null,[{},this.options].append(arguments));
if(this.addEvent){for(var c in b){if(typeOf(b[c])!="function"||!(/^on[A-Z]/).test(c)){continue;}this.addEvent(c,b[c]);delete b[c];}}return this;}});})();
(function(){var k,n,l,g,a={},c={},m=/\\/g;var e=function(q,p){if(q==null){return null;}if(q.Slick===true){return q;}q=(""+q).replace(/^\s+|\s+$/g,"");g=!!p;
var o=(g)?c:a;if(o[q]){return o[q];}k={Slick:true,expressions:[],raw:q,reverse:function(){return e(this.raw,true);}};n=-1;while(q!=(q=q.replace(j,b))){}k.length=k.expressions.length;
return o[k.raw]=(g)?h(k):k;};var i=function(o){if(o==="!"){return" ";}else{if(o===" "){return"!";}else{if((/^!/).test(o)){return o.replace(/^!/,"");}else{return"!"+o;
}}}};var h=function(u){var r=u.expressions;for(var p=0;p<r.length;p++){var t=r[p];var q={parts:[],tag:"*",combinator:i(t[0].combinator)};for(var o=0;o<t.length;
o++){var s=t[o];if(!s.reverseCombinator){s.reverseCombinator=" ";}s.combinator=s.reverseCombinator;delete s.reverseCombinator;}t.reverse().push(q);}return u;
};var f=function(o){return o.replace(/[-[\]{}()*+?.\\^$|,#\s]/g,function(p){return"\\"+p;});};var j=new RegExp("^(?:\\s*(,)\\s*|\\s*(<combinator>+)\\s*|(\\s+)|(<unicode>+|\\*)|\\#(<unicode>+)|\\.(<unicode>+)|\\[\\s*(<unicode1>+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(<unicode>+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)".replace(/<combinator>/,"["+f(">+~`!@$%^&={}\\;</")+"]").replace(/<unicode>/g,"(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])").replace(/<unicode1>/g,"(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])"));
function b(x,s,D,z,r,C,q,B,A,y,u,F,G,v,p,w){if(s||n===-1){k.expressions[++n]=[];l=-1;if(s){return"";}}if(D||z||l===-1){D=D||" ";var t=k.expressions[n];
if(g&&t[l]){t[l].reverseCombinator=i(D);}t[++l]={combinator:D,tag:"*"};}var o=k.expressions[n][l];if(r){o.tag=r.replace(m,"");}else{if(C){o.id=C.replace(m,"");
}else{if(q){q=q.replace(m,"");if(!o.classList){o.classList=[];}if(!o.classes){o.classes=[];}o.classList.push(q);o.classes.push({value:q,regexp:new RegExp("(^|\\s)"+f(q)+"(\\s|$)")});
}else{if(G){w=w||p;w=w?w.replace(m,""):null;if(!o.pseudos){o.pseudos=[];}o.pseudos.push({key:G.replace(m,""),value:w,type:F.length==1?"class":"element"});
}else{if(B){B=B.replace(m,"");u=(u||"").replace(m,"");var E,H;switch(A){case"^=":H=new RegExp("^"+f(u));break;case"$=":H=new RegExp(f(u)+"$");break;case"~=":H=new RegExp("(^|\\s)"+f(u)+"(\\s|$)");
break;case"|=":H=new RegExp("^"+f(u)+"(-|$)");break;case"=":E=function(I){return u==I;};break;case"*=":E=function(I){return I&&I.indexOf(u)>-1;};break;
case"!=":E=function(I){return u!=I;};break;default:E=function(I){return !!I;};}if(u==""&&(/^[*$^]=$/).test(A)){E=function(){return false;};}if(!E){E=function(I){return I&&H.test(I);
};}if(!o.attributes){o.attributes=[];}o.attributes.push({key:B,operator:A,value:u,test:E});}}}}}return"";}var d=(this.Slick||{});d.parse=function(o){return e(o);
};d.escapeRegExp=f;if(!this.Slick){this.Slick=d;}}).apply((typeof exports!="undefined")?exports:this);(function(){var k={},m={},d=Object.prototype.toString;
k.isNativeCode=function(c){return(/\{\s*\[native code\]\s*\}/).test(""+c);};k.isXML=function(c){return(!!c.xmlVersion)||(!!c.xml)||(d.call(c)=="[object XMLDocument]")||(c.nodeType==9&&c.documentElement.nodeName!="HTML");
};k.setDocument=function(w){var p=w.nodeType;if(p==9){}else{if(p){w=w.ownerDocument;}else{if(w.navigator){w=w.document;}else{return;}}}if(this.document===w){return;
}this.document=w;var A=w.documentElement,o=this.getUIDXML(A),s=m[o],r;if(s){for(r in s){this[r]=s[r];}return;}s=m[o]={};s.root=A;s.isXMLDocument=this.isXML(w);
s.brokenStarGEBTN=s.starSelectsClosedQSA=s.idGetsName=s.brokenMixedCaseQSA=s.brokenGEBCN=s.brokenCheckedQSA=s.brokenEmptyAttributeQSA=s.isHTMLDocument=s.nativeMatchesSelector=false;
var q,u,y,z,t;var x,v="slick_uniqueid";var c=w.createElement("div");var n=w.body||w.getElementsByTagName("body")[0]||A;n.appendChild(c);try{c.innerHTML='<a id="'+v+'"></a>';
s.isHTMLDocument=!!w.getElementById(v);}catch(C){}if(s.isHTMLDocument){c.style.display="none";c.appendChild(w.createComment(""));u=(c.getElementsByTagName("*").length>1);
try{c.innerHTML="foo</foo>";x=c.getElementsByTagName("*");q=(x&&!!x.length&&x[0].nodeName.charAt(0)=="/");}catch(C){}s.brokenStarGEBTN=u||q;try{c.innerHTML='<a name="'+v+'"></a><b id="'+v+'"></b>';
s.idGetsName=w.getElementById(v)===c.firstChild;}catch(C){}if(c.getElementsByClassName){try{c.innerHTML='<a class="f"></a><a class="b"></a>';c.getElementsByClassName("b").length;
c.firstChild.className="b";z=(c.getElementsByClassName("b").length!=2);}catch(C){}try{c.innerHTML='<a class="a"></a><a class="f b a"></a>';y=(c.getElementsByClassName("a").length!=2);
}catch(C){}s.brokenGEBCN=z||y;}if(c.querySelectorAll){try{c.innerHTML="foo</foo>";x=c.querySelectorAll("*");s.starSelectsClosedQSA=(x&&!!x.length&&x[0].nodeName.charAt(0)=="/");
}catch(C){}try{c.innerHTML='<a class="MiX"></a>';s.brokenMixedCaseQSA=!c.querySelectorAll(".MiX").length;}catch(C){}try{c.innerHTML='<select><option selected="selected">a</option></select>';
s.brokenCheckedQSA=(c.querySelectorAll(":checked").length==0);}catch(C){}try{c.innerHTML='<a class=""></a>';s.brokenEmptyAttributeQSA=(c.querySelectorAll('[class*=""]').length!=0);
}catch(C){}}try{c.innerHTML='<form action="s"><input id="action"/></form>';t=(c.firstChild.getAttribute("action")!="s");}catch(C){}s.nativeMatchesSelector=A.matchesSelector||A.mozMatchesSelector||A.webkitMatchesSelector;
if(s.nativeMatchesSelector){try{s.nativeMatchesSelector.call(A,":slick");s.nativeMatchesSelector=null;}catch(C){}}}try{A.slick_expando=1;delete A.slick_expando;
s.getUID=this.getUIDHTML;}catch(C){s.getUID=this.getUIDXML;}n.removeChild(c);c=x=n=null;s.getAttribute=(s.isHTMLDocument&&t)?function(G,E){var H=this.attributeGetters[E];
if(H){return H.call(G);}var F=G.getAttributeNode(E);return(F)?F.nodeValue:null;}:function(F,E){var G=this.attributeGetters[E];return(G)?G.call(F):F.getAttribute(E);
};s.hasAttribute=(A&&this.isNativeCode(A.hasAttribute))?function(F,E){return F.hasAttribute(E);}:function(F,E){F=F.getAttributeNode(E);return !!(F&&(F.specified||F.nodeValue));
};var D=A&&this.isNativeCode(A.contains),B=w&&this.isNativeCode(w.contains);s.contains=(D&&B)?function(E,F){return E.contains(F);}:(D&&!B)?function(E,F){return E===F||((E===w)?w.documentElement:E).contains(F);
}:(A&&A.compareDocumentPosition)?function(E,F){return E===F||!!(E.compareDocumentPosition(F)&16);}:function(E,F){if(F){do{if(F===E){return true;}}while((F=F.parentNode));
}return false;};s.documentSorter=(A.compareDocumentPosition)?function(F,E){if(!F.compareDocumentPosition||!E.compareDocumentPosition){return 0;}return F.compareDocumentPosition(E)&4?-1:F===E?0:1;
}:("sourceIndex" in A)?function(F,E){if(!F.sourceIndex||!E.sourceIndex){return 0;}return F.sourceIndex-E.sourceIndex;}:(w.createRange)?function(H,F){if(!H.ownerDocument||!F.ownerDocument){return 0;
}var G=H.ownerDocument.createRange(),E=F.ownerDocument.createRange();G.setStart(H,0);G.setEnd(H,0);E.setStart(F,0);E.setEnd(F,0);return G.compareBoundaryPoints(Range.START_TO_END,E);
}:null;A=null;for(r in s){this[r]=s[r];}};var f=/^([#.]?)((?:[\w-]+|\*))$/,h=/\[.+[*$^]=(?:""|'')?\]/,g={};k.search=function(U,z,H,s){var p=this.found=(s)?null:(H||[]);
if(!U){return p;}else{if(U.navigator){U=U.document;}else{if(!U.nodeType){return p;}}}var F,O,V=this.uniques={},I=!!(H&&H.length),y=(U.nodeType==9);if(this.document!==(y?U:U.ownerDocument)){this.setDocument(U);
}if(I){for(O=p.length;O--;){V[this.getUID(p[O])]=true;}}if(typeof z=="string"){var r=z.match(f);simpleSelectors:if(r){var u=r[1],v=r[2],A,E;if(!u){if(v=="*"&&this.brokenStarGEBTN){break simpleSelectors;
}E=U.getElementsByTagName(v);if(s){return E[0]||null;}for(O=0;A=E[O++];){if(!(I&&V[this.getUID(A)])){p.push(A);}}}else{if(u=="#"){if(!this.isHTMLDocument||!y){break simpleSelectors;
}A=U.getElementById(v);if(!A){return p;}if(this.idGetsName&&A.getAttributeNode("id").nodeValue!=v){break simpleSelectors;}if(s){return A||null;}if(!(I&&V[this.getUID(A)])){p.push(A);
}}else{if(u=="."){if(!this.isHTMLDocument||((!U.getElementsByClassName||this.brokenGEBCN)&&U.querySelectorAll)){break simpleSelectors;}if(U.getElementsByClassName&&!this.brokenGEBCN){E=U.getElementsByClassName(v);
if(s){return E[0]||null;}for(O=0;A=E[O++];){if(!(I&&V[this.getUID(A)])){p.push(A);}}}else{var T=new RegExp("(^|\\s)"+e.escapeRegExp(v)+"(\\s|$)");E=U.getElementsByTagName("*");
for(O=0;A=E[O++];){className=A.className;if(!(className&&T.test(className))){continue;}if(s){return A;}if(!(I&&V[this.getUID(A)])){p.push(A);}}}}}}if(I){this.sort(p);
}return(s)?null:p;}querySelector:if(U.querySelectorAll){if(!this.isHTMLDocument||g[z]||this.brokenMixedCaseQSA||(this.brokenCheckedQSA&&z.indexOf(":checked")>-1)||(this.brokenEmptyAttributeQSA&&h.test(z))||(!y&&z.indexOf(",")>-1)||e.disableQSA){break querySelector;
}var S=z,x=U;if(!y){var C=x.getAttribute("id"),t="slickid__";x.setAttribute("id",t);S="#"+t+" "+S;U=x.parentNode;}try{if(s){return U.querySelector(S)||null;
}else{E=U.querySelectorAll(S);}}catch(Q){g[z]=1;break querySelector;}finally{if(!y){if(C){x.setAttribute("id",C);}else{x.removeAttribute("id");}U=x;}}if(this.starSelectsClosedQSA){for(O=0;
A=E[O++];){if(A.nodeName>"@"&&!(I&&V[this.getUID(A)])){p.push(A);}}}else{for(O=0;A=E[O++];){if(!(I&&V[this.getUID(A)])){p.push(A);}}}if(I){this.sort(p);
}return p;}F=this.Slick.parse(z);if(!F.length){return p;}}else{if(z==null){return p;}else{if(z.Slick){F=z;}else{if(this.contains(U.documentElement||U,z)){(p)?p.push(z):p=z;
return p;}else{return p;}}}}this.posNTH={};this.posNTHLast={};this.posNTHType={};this.posNTHTypeLast={};this.push=(!I&&(s||(F.length==1&&F.expressions[0].length==1)))?this.pushArray:this.pushUID;
if(p==null){p=[];}var M,L,K;var B,J,D,c,q,G,W;var N,P,o,w,R=F.expressions;search:for(O=0;(P=R[O]);O++){for(M=0;(o=P[M]);M++){B="combinator:"+o.combinator;
if(!this[B]){continue search;}J=(this.isXMLDocument)?o.tag:o.tag.toUpperCase();D=o.id;c=o.classList;q=o.classes;G=o.attributes;W=o.pseudos;w=(M===(P.length-1));
this.bitUniques={};if(w){this.uniques=V;this.found=p;}else{this.uniques={};this.found=[];}if(M===0){this[B](U,J,D,q,G,W,c);if(s&&w&&p.length){break search;
}}else{if(s&&w){for(L=0,K=N.length;L<K;L++){this[B](N[L],J,D,q,G,W,c);if(p.length){break search;}}}else{for(L=0,K=N.length;L<K;L++){this[B](N[L],J,D,q,G,W,c);
}}}N=this.found;}}if(I||(F.expressions.length>1)){this.sort(p);}return(s)?(p[0]||null):p;};k.uidx=1;k.uidk="slick-uniqueid";k.getUIDXML=function(n){var c=n.getAttribute(this.uidk);
if(!c){c=this.uidx++;n.setAttribute(this.uidk,c);}return c;};k.getUIDHTML=function(c){return c.uniqueNumber||(c.uniqueNumber=this.uidx++);};k.sort=function(c){if(!this.documentSorter){return c;
}c.sort(this.documentSorter);return c;};k.cacheNTH={};k.matchNTH=/^([+-]?\d*)?([a-z]+)?([+-]\d+)?$/;k.parseNTHArgument=function(q){var o=q.match(this.matchNTH);
if(!o){return false;}var p=o[2]||false;var n=o[1]||1;if(n=="-"){n=-1;}var c=+o[3]||0;o=(p=="n")?{a:n,b:c}:(p=="odd")?{a:2,b:1}:(p=="even")?{a:2,b:0}:{a:0,b:n};
return(this.cacheNTH[q]=o);};k.createNTHPseudo=function(p,n,c,o){return function(s,q){var u=this.getUID(s);if(!this[c][u]){var A=s.parentNode;if(!A){return false;
}var r=A[p],t=1;if(o){var z=s.nodeName;do{if(r.nodeName!=z){continue;}this[c][this.getUID(r)]=t++;}while((r=r[n]));}else{do{if(r.nodeType!=1){continue;
}this[c][this.getUID(r)]=t++;}while((r=r[n]));}}q=q||"n";var v=this.cacheNTH[q]||this.parseNTHArgument(q);if(!v){return false;}var y=v.a,x=v.b,w=this[c][u];
if(y==0){return x==w;}if(y>0){if(w<x){return false;}}else{if(x<w){return false;}}return((w-x)%y)==0;};};k.pushArray=function(p,c,r,o,n,q){if(this.matchSelector(p,c,r,o,n,q)){this.found.push(p);
}};k.pushUID=function(q,c,s,p,n,r){var o=this.getUID(q);if(!this.uniques[o]&&this.matchSelector(q,c,s,p,n,r)){this.uniques[o]=true;this.found.push(q);}};
k.matchNode=function(n,o){if(this.isHTMLDocument&&this.nativeMatchesSelector){try{return this.nativeMatchesSelector.call(n,o.replace(/\[([^=]+)=\s*([^'"\]]+?)\s*\]/g,'[$1="$2"]'));
}catch(u){}}var t=this.Slick.parse(o);if(!t){return true;}var r=t.expressions,s=0,q;for(q=0;(currentExpression=r[q]);q++){if(currentExpression.length==1){var p=currentExpression[0];
if(this.matchSelector(n,(this.isXMLDocument)?p.tag:p.tag.toUpperCase(),p.id,p.classes,p.attributes,p.pseudos)){return true;}s++;}}if(s==t.length){return false;
}var c=this.search(this.document,t),v;for(q=0;v=c[q++];){if(v===n){return true;}}return false;};k.matchPseudo=function(q,c,p){var n="pseudo:"+c;if(this[n]){return this[n](q,p);
}var o=this.getAttribute(q,c);return(p)?p==o:!!o;};k.matchSelector=function(o,v,c,p,q,s){if(v){var t=(this.isXMLDocument)?o.nodeName:o.nodeName.toUpperCase();
if(v=="*"){if(t<"@"){return false;}}else{if(t!=v){return false;}}}if(c&&o.getAttribute("id")!=c){return false;}var r,n,u;if(p){for(r=p.length;r--;){u=this.getAttribute(o,"class");
if(!(u&&p[r].regexp.test(u))){return false;}}}if(q){for(r=q.length;r--;){n=q[r];if(n.operator?!n.test(this.getAttribute(o,n.key)):!this.hasAttribute(o,n.key)){return false;
}}}if(s){for(r=s.length;r--;){n=s[r];if(!this.matchPseudo(o,n.key,n.value)){return false;}}}return true;};var j={" ":function(q,w,n,r,s,u,p){var t,v,o;
if(this.isHTMLDocument){getById:if(n){v=this.document.getElementById(n);if((!v&&q.all)||(this.idGetsName&&v&&v.getAttributeNode("id").nodeValue!=n)){o=q.all[n];
if(!o){return;}if(!o[0]){o=[o];}for(t=0;v=o[t++];){var c=v.getAttributeNode("id");if(c&&c.nodeValue==n){this.push(v,w,null,r,s,u);break;}}return;}if(!v){if(this.contains(this.root,q)){return;
}else{break getById;}}else{if(this.document!==q&&!this.contains(q,v)){return;}}this.push(v,w,null,r,s,u);return;}getByClass:if(r&&q.getElementsByClassName&&!this.brokenGEBCN){o=q.getElementsByClassName(p.join(" "));
if(!(o&&o.length)){break getByClass;}for(t=0;v=o[t++];){this.push(v,w,n,null,s,u);}return;}}getByTag:{o=q.getElementsByTagName(w);if(!(o&&o.length)){break getByTag;
}if(!this.brokenStarGEBTN){w=null;}for(t=0;v=o[t++];){this.push(v,w,n,r,s,u);}}},">":function(p,c,r,o,n,q){if((p=p.firstChild)){do{if(p.nodeType==1){this.push(p,c,r,o,n,q);
}}while((p=p.nextSibling));}},"+":function(p,c,r,o,n,q){while((p=p.nextSibling)){if(p.nodeType==1){this.push(p,c,r,o,n,q);break;}}},"^":function(p,c,r,o,n,q){p=p.firstChild;
if(p){if(p.nodeType==1){this.push(p,c,r,o,n,q);}else{this["combinator:+"](p,c,r,o,n,q);}}},"~":function(q,c,s,p,n,r){while((q=q.nextSibling)){if(q.nodeType!=1){continue;
}var o=this.getUID(q);if(this.bitUniques[o]){break;}this.bitUniques[o]=true;this.push(q,c,s,p,n,r);}},"++":function(p,c,r,o,n,q){this["combinator:+"](p,c,r,o,n,q);
this["combinator:!+"](p,c,r,o,n,q);},"~~":function(p,c,r,o,n,q){this["combinator:~"](p,c,r,o,n,q);this["combinator:!~"](p,c,r,o,n,q);},"!":function(p,c,r,o,n,q){while((p=p.parentNode)){if(p!==this.document){this.push(p,c,r,o,n,q);
}}},"!>":function(p,c,r,o,n,q){p=p.parentNode;if(p!==this.document){this.push(p,c,r,o,n,q);}},"!+":function(p,c,r,o,n,q){while((p=p.previousSibling)){if(p.nodeType==1){this.push(p,c,r,o,n,q);
break;}}},"!^":function(p,c,r,o,n,q){p=p.lastChild;if(p){if(p.nodeType==1){this.push(p,c,r,o,n,q);}else{this["combinator:!+"](p,c,r,o,n,q);}}},"!~":function(q,c,s,p,n,r){while((q=q.previousSibling)){if(q.nodeType!=1){continue;
}var o=this.getUID(q);if(this.bitUniques[o]){break;}this.bitUniques[o]=true;this.push(q,c,s,p,n,r);}}};for(var i in j){k["combinator:"+i]=j[i];}var l={empty:function(c){var n=c.firstChild;
return !(n&&n.nodeType==1)&&!(c.innerText||c.textContent||"").length;},not:function(c,n){return !this.matchNode(c,n);},contains:function(c,n){return(c.innerText||c.textContent||"").indexOf(n)>-1;
},"first-child":function(c){while((c=c.previousSibling)){if(c.nodeType==1){return false;}}return true;},"last-child":function(c){while((c=c.nextSibling)){if(c.nodeType==1){return false;
}}return true;},"only-child":function(o){var n=o;while((n=n.previousSibling)){if(n.nodeType==1){return false;}}var c=o;while((c=c.nextSibling)){if(c.nodeType==1){return false;
}}return true;},"nth-child":k.createNTHPseudo("firstChild","nextSibling","posNTH"),"nth-last-child":k.createNTHPseudo("lastChild","previousSibling","posNTHLast"),"nth-of-type":k.createNTHPseudo("firstChild","nextSibling","posNTHType",true),"nth-last-of-type":k.createNTHPseudo("lastChild","previousSibling","posNTHTypeLast",true),index:function(n,c){return this["pseudo:nth-child"](n,""+(c+1));
},even:function(c){return this["pseudo:nth-child"](c,"2n");},odd:function(c){return this["pseudo:nth-child"](c,"2n+1");},"first-of-type":function(c){var n=c.nodeName;
while((c=c.previousSibling)){if(c.nodeName==n){return false;}}return true;},"last-of-type":function(c){var n=c.nodeName;while((c=c.nextSibling)){if(c.nodeName==n){return false;
}}return true;},"only-of-type":function(o){var n=o,p=o.nodeName;while((n=n.previousSibling)){if(n.nodeName==p){return false;}}var c=o;while((c=c.nextSibling)){if(c.nodeName==p){return false;
}}return true;},enabled:function(c){return !c.disabled;},disabled:function(c){return c.disabled;},checked:function(c){return c.checked||c.selected;},focus:function(c){return this.isHTMLDocument&&this.document.activeElement===c&&(c.href||c.type||this.hasAttribute(c,"tabindex"));
},root:function(c){return(c===this.root);},selected:function(c){return c.selected;}};for(var b in l){k["pseudo:"+b]=l[b];}var a=k.attributeGetters={"for":function(){return("htmlFor" in this)?this.htmlFor:this.getAttribute("for");
},href:function(){return("href" in this)?this.getAttribute("href",2):this.getAttribute("href");},style:function(){return(this.style)?this.style.cssText:this.getAttribute("style");
},tabindex:function(){var c=this.getAttributeNode("tabindex");return(c&&c.specified)?c.nodeValue:null;},type:function(){return this.getAttribute("type");
},maxlength:function(){var c=this.getAttributeNode("maxLength");return(c&&c.specified)?c.nodeValue:null;}};a.MAXLENGTH=a.maxLength=a.maxlength;var e=k.Slick=(this.Slick||{});
e.version="1.1.7";e.search=function(n,o,c){return k.search(n,o,c);};e.find=function(c,n){return k.search(c,n,null,true);};e.contains=function(c,n){k.setDocument(c);
return k.contains(c,n);};e.getAttribute=function(n,c){k.setDocument(n);return k.getAttribute(n,c);};e.hasAttribute=function(n,c){k.setDocument(n);return k.hasAttribute(n,c);
};e.match=function(n,c){if(!(n&&c)){return false;}if(!c||c===n){return true;}k.setDocument(n);return k.matchNode(n,c);};e.defineAttributeGetter=function(c,n){k.attributeGetters[c]=n;
return this;};e.lookupAttributeGetter=function(c){return k.attributeGetters[c];};e.definePseudo=function(c,n){k["pseudo:"+c]=function(p,o){return n.call(p,o);
};return this;};e.lookupPseudo=function(c){var n=k["pseudo:"+c];if(n){return function(o){return n.call(this,o);};}return null;};e.override=function(n,c){k.override(n,c);
return this;};e.isXML=k.isXML;e.uidOf=function(c){return k.getUIDHTML(c);};if(!this.Slick){this.Slick=e;}}).apply((typeof exports!="undefined")?exports:this);
var Element=function(b,g){var h=Element.Constructors[b];if(h){return h(g);}if(typeof b!="string"){return document.id(b).set(g);}if(!g){g={};}if(!(/^[\w-]+$/).test(b)){var e=Slick.parse(b).expressions[0][0];
b=(e.tag=="*")?"div":e.tag;if(e.id&&g.id==null){g.id=e.id;}var d=e.attributes;if(d){for(var a,f=0,c=d.length;f<c;f++){a=d[f];if(g[a.key]!=null){continue;
}if(a.value!=null&&a.operator=="="){g[a.key]=a.value;}else{if(!a.value&&!a.operator){g[a.key]=true;}}}}if(e.classList&&g["class"]==null){g["class"]=e.classList.join(" ");
}}return document.newElement(b,g);};if(Browser.Element){Element.prototype=Browser.Element.prototype;Element.prototype._fireEvent=(function(a){return function(b,c){return a.call(this,b,c);
};})(Element.prototype.fireEvent);}new Type("Element",Element).mirror(function(a){if(Array.prototype[a]){return;}var b={};b[a]=function(){var h=[],e=arguments,j=true;
for(var g=0,d=this.length;g<d;g++){var f=this[g],c=h[g]=f[a].apply(f,e);j=(j&&typeOf(c)=="element");}return(j)?new Elements(h):h;};Elements.implement(b);
});if(!Browser.Element){Element.parent=Object;Element.Prototype={"$constructor":Element,"$family":Function.from("element").hide()};Element.mirror(function(a,b){Element.Prototype[a]=b;
});}Element.Constructors={};Element.Constructors=new Hash;var IFrame=new Type("IFrame",function(){var e=Array.link(arguments,{properties:Type.isObject,iframe:function(f){return(f!=null);
}});var c=e.properties||{},b;if(e.iframe){b=document.id(e.iframe);}var d=c.onload||function(){};delete c.onload;c.id=c.name=[c.id,c.name,b?(b.id||b.name):"IFrame_"+String.uniqueID()].pick();
b=new Element(b||"iframe",c);var a=function(){d.call(b.contentWindow);};if(window.frames[c.id]){a();}else{b.addListener("load",a);}return b;});var Elements=this.Elements=function(a){if(a&&a.length){var e={},d;
for(var c=0;d=a[c++];){var b=Slick.uidOf(d);if(!e[b]){e[b]=true;this.push(d);}}}};Elements.prototype={length:0};Elements.parent=Array;new Type("Elements",Elements).implement({filter:function(a,b){if(!a){return this;
}return new Elements(Array.filter(this,(typeOf(a)=="string")?function(c){return c.match(a);}:a,b));}.protect(),push:function(){var d=this.length;for(var b=0,a=arguments.length;
b<a;b++){var c=document.id(arguments[b]);if(c){this[d++]=c;}}return(this.length=d);}.protect(),unshift:function(){var b=[];for(var c=0,a=arguments.length;
c<a;c++){var d=document.id(arguments[c]);if(d){b.push(d);}}return Array.prototype.unshift.apply(this,b);}.protect(),concat:function(){var b=new Elements(this);
for(var c=0,a=arguments.length;c<a;c++){var d=arguments[c];if(Type.isEnumerable(d)){b.append(d);}else{b.push(d);}}return b;}.protect(),append:function(c){for(var b=0,a=c.length;
b<a;b++){this.push(c[b]);}return this;}.protect(),empty:function(){while(this.length){delete this[--this.length];}return this;}.protect()});Elements.alias("extend","append");
(function(){var f=Array.prototype.splice,a={"0":0,"1":1,length:2};f.call(a,1,1);if(a[1]==1){Elements.implement("splice",function(){var g=this.length;var e=f.apply(this,arguments);
while(g>=this.length){delete this[g--];}return e;}.protect());}Array.forEachMethod(function(g,e){Elements.implement(e,g);});Array.mirror(Elements);var d;
try{d=(document.createElement("<input name=x>").name=="x");}catch(b){}var c=function(e){return(""+e).replace(/&/g,"&").replace(/"/g,""");};Document.implement({newElement:function(e,g){if(g&&g.checked!=null){g.defaultChecked=g.checked;
}if(d&&g){e="<"+e;if(g.name){e+=' name="'+c(g.name)+'"';}if(g.type){e+=' type="'+c(g.type)+'"';}e+=">";delete g.name;delete g.type;}return this.id(this.createElement(e)).set(g);
}});})();(function(){Slick.uidOf(window);Slick.uidOf(document);Document.implement({newTextNode:function(e){return this.createTextNode(e);},getDocument:function(){return this;
},getWindow:function(){return this.window;},id:(function(){var e={string:function(E,D,l){E=Slick.find(l,"#"+E.replace(/(\W)/g,"\\$1"));return(E)?e.element(E,D):null;
},element:function(D,E){Slick.uidOf(D);if(!E&&!D.$family&&!(/^(?:object|embed)$/i).test(D.tagName)){var l=D.fireEvent;D._fireEvent=function(F,G){return l(F,G);
};Object.append(D,Element.Prototype);}return D;},object:function(D,E,l){if(D.toElement){return e.element(D.toElement(l),E);}return null;}};e.textnode=e.whitespace=e.window=e.document=function(l){return l;
};return function(D,F,E){if(D&&D.$family&&D.uniqueNumber){return D;}var l=typeOf(D);return(e[l])?e[l](D,F,E||document):null;};})()});if(window.$==null){Window.implement("$",function(e,l){return document.id(e,l,this.document);
});}Window.implement({getDocument:function(){return this.document;},getWindow:function(){return this;}});[Document,Element].invoke("implement",{getElements:function(e){return Slick.search(this,e,new Elements);
},getElement:function(e){return document.id(Slick.find(this,e));}});var m={contains:function(e){return Slick.contains(this,e);}};if(!document.contains){Document.implement(m);
}if(!document.createElement("div").contains){Element.implement(m);}Element.implement("hasChild",function(e){return this!==e&&this.contains(e);});(function(l,E,e){this.Selectors={};
var F=this.Selectors.Pseudo=new Hash();var D=function(){for(var G in F){if(F.hasOwnProperty(G)){Slick.definePseudo(G,F[G]);delete F[G];}}};Slick.search=function(H,I,G){D();
return l.call(this,H,I,G);};Slick.find=function(G,H){D();return E.call(this,G,H);};Slick.match=function(H,G){D();return e.call(this,H,G);};})(Slick.search,Slick.find,Slick.match);
var r=function(E,D){if(!E){return D;}E=Object.clone(Slick.parse(E));var l=E.expressions;for(var e=l.length;e--;){l[e][0].combinator=D;}return E;};Object.forEach({getNext:"~",getPrevious:"!~",getParent:"!"},function(e,l){Element.implement(l,function(D){return this.getElement(r(D,e));
});});Object.forEach({getAllNext:"~",getAllPrevious:"!~",getSiblings:"~~",getChildren:">",getParents:"!"},function(e,l){Element.implement(l,function(D){return this.getElements(r(D,e));
});});Element.implement({getFirst:function(e){return document.id(Slick.search(this,r(e,">"))[0]);},getLast:function(e){return document.id(Slick.search(this,r(e,">")).getLast());
},getWindow:function(){return this.ownerDocument.window;},getDocument:function(){return this.ownerDocument;},getElementById:function(e){return document.id(Slick.find(this,"#"+(""+e).replace(/(\W)/g,"\\$1")));
},match:function(e){return !e||Slick.match(this,e);}});if(window.$$==null){Window.implement("$$",function(e){var H=new Elements;if(arguments.length==1&&typeof e=="string"){return Slick.search(this.document,e,H);
}var E=Array.flatten(arguments);for(var F=0,D=E.length;F<D;F++){var G=E[F];switch(typeOf(G)){case"element":H.push(G);break;case"string":Slick.search(this.document,G,H);
}}return H;});}if(window.$$==null){Window.implement("$$",function(e){if(arguments.length==1){if(typeof e=="string"){return Slick.search(this.document,e,new Elements);
}else{if(Type.isEnumerable(e)){return new Elements(e);}}}return new Elements(arguments);});}var w={before:function(l,e){var D=e.parentNode;if(D){D.insertBefore(l,e);
}},after:function(l,e){var D=e.parentNode;if(D){D.insertBefore(l,e.nextSibling);}},bottom:function(l,e){e.appendChild(l);},top:function(l,e){e.insertBefore(l,e.firstChild);
}};w.inside=w.bottom;Object.each(w,function(l,D){D=D.capitalize();var e={};e["inject"+D]=function(E){l(this,document.id(E,true));return this;};e["grab"+D]=function(E){l(document.id(E,true),this);
return this;};Element.implement(e);});var j={},d={};var k={};Array.forEach(["type","value","defaultValue","accessKey","cellPadding","cellSpacing","colSpan","frameBorder","rowSpan","tabIndex","useMap"],function(e){k[e.toLowerCase()]=e;
});k.html="innerHTML";k.text=(document.createElement("div").textContent==null)?"innerText":"textContent";Object.forEach(k,function(l,e){d[e]=function(D,E){D[l]=E;
};j[e]=function(D){return D[l];};});var x=["compact","nowrap","ismap","declare","noshade","checked","disabled","readOnly","multiple","selected","noresize","defer","defaultChecked","autofocus","controls","autoplay","loop"];
var h={};Array.forEach(x,function(e){var l=e.toLowerCase();h[l]=e;d[l]=function(D,E){D[e]=!!E;};j[l]=function(D){return !!D[e];};});Object.append(d,{"class":function(e,l){("className" in e)?e.className=(l||""):e.setAttribute("class",l);
},"for":function(e,l){("htmlFor" in e)?e.htmlFor=l:e.setAttribute("for",l);},style:function(e,l){(e.style)?e.style.cssText=l:e.setAttribute("style",l);
},value:function(e,l){e.value=(l!=null)?l:"";}});j["class"]=function(e){return("className" in e)?e.className||null:e.getAttribute("class");};var f=document.createElement("button");
try{f.type="button";}catch(z){}if(f.type!="button"){d.type=function(e,l){e.setAttribute("type",l);};}f=null;var p=document.createElement("input");p.value="t";
p.type="submit";if(p.value!="t"){d.type=function(l,e){var D=l.value;l.type=e;l.value=D;};}p=null;var q=(function(e){e.random="attribute";return(e.getAttribute("random")=="attribute");
})(document.createElement("div"));Element.implement({setProperty:function(l,D){var E=d[l.toLowerCase()];if(E){E(this,D);}else{if(q){var e=this.retrieve("$attributeWhiteList",{});
}if(D==null){this.removeAttribute(l);if(q){delete e[l];}}else{this.setAttribute(l,""+D);if(q){e[l]=true;}}}return this;},setProperties:function(e){for(var l in e){this.setProperty(l,e[l]);
}return this;},getProperty:function(F){var D=j[F.toLowerCase()];if(D){return D(this);}if(q){var l=this.getAttributeNode(F),E=this.retrieve("$attributeWhiteList",{});
if(!l){return null;}if(l.expando&&!E[F]){var G=this.outerHTML;if(G.substr(0,G.search(/\/?['"]?>(?![^<]*<['"])/)).indexOf(F)<0){return null;}E[F]=true;}}var e=Slick.getAttribute(this,F);
return(!e&&!Slick.hasAttribute(this,F))?null:e;},getProperties:function(){var e=Array.from(arguments);return e.map(this.getProperty,this).associate(e);
},removeProperty:function(e){return this.setProperty(e,null);},removeProperties:function(){Array.each(arguments,this.removeProperty,this);return this;},set:function(D,l){var e=Element.Properties[D];
(e&&e.set)?e.set.call(this,l):this.setProperty(D,l);}.overloadSetter(),get:function(l){var e=Element.Properties[l];return(e&&e.get)?e.get.apply(this):this.getProperty(l);
}.overloadGetter(),erase:function(l){var e=Element.Properties[l];(e&&e.erase)?e.erase.apply(this):this.removeProperty(l);return this;},hasClass:function(e){return this.className.clean().contains(e," ");
},addClass:function(e){if(!this.hasClass(e)){this.className=(this.className+" "+e).clean();}return this;},removeClass:function(e){this.className=this.className.replace(new RegExp("(^|\\s)"+e+"(?:\\s|$)"),"$1");
return this;},toggleClass:function(e,l){if(l==null){l=!this.hasClass(e);}return(l)?this.addClass(e):this.removeClass(e);},adopt:function(){var E=this,e,G=Array.flatten(arguments),F=G.length;
if(F>1){E=e=document.createDocumentFragment();}for(var D=0;D<F;D++){var l=document.id(G[D],true);if(l){E.appendChild(l);}}if(e){this.appendChild(e);}return this;
},appendText:function(l,e){return this.grab(this.getDocument().newTextNode(l),e);},grab:function(l,e){w[e||"bottom"](document.id(l,true),this);return this;
},inject:function(l,e){w[e||"bottom"](this,document.id(l,true));return this;},replaces:function(e){e=document.id(e,true);e.parentNode.replaceChild(this,e);
return this;},wraps:function(l,e){l=document.id(l,true);return this.replaces(l).grab(l,e);},getSelected:function(){this.selectedIndex;return new Elements(Array.from(this.options).filter(function(e){return e.selected;
}));},toQueryString:function(){var e=[];this.getElements("input, select, textarea").each(function(D){var l=D.type;if(!D.name||D.disabled||l=="submit"||l=="reset"||l=="file"||l=="image"){return;
}var E=(D.get("tag")=="select")?D.getSelected().map(function(F){return document.id(F).get("value");}):((l=="radio"||l=="checkbox")&&!D.checked)?null:D.get("value");
Array.from(E).each(function(F){if(typeof F!="undefined"){e.push(encodeURIComponent(D.name)+"="+encodeURIComponent(F));}});});return e.join("&");}});var i={},A={};
var B=function(e){return(A[e]||(A[e]={}));};var v=function(l){var e=l.uniqueNumber;if(l.removeEvents){l.removeEvents();}if(l.clearAttributes){l.clearAttributes();
}if(e!=null){delete i[e];delete A[e];}return l;};var C={input:"checked",option:"selected",textarea:"value"};Element.implement({destroy:function(){var e=v(this).getElementsByTagName("*");
Array.each(e,v);Element.dispose(this);return null;},empty:function(){Array.from(this.childNodes).each(Element.dispose);return this;},dispose:function(){return(this.parentNode)?this.parentNode.removeChild(this):this;
},clone:function(G,E){G=G!==false;var L=this.cloneNode(G),D=[L],F=[this],J;if(G){D.append(Array.from(L.getElementsByTagName("*")));F.append(Array.from(this.getElementsByTagName("*")));
}for(J=D.length;J--;){var H=D[J],K=F[J];if(!E){H.removeAttribute("id");}if(H.clearAttributes){H.clearAttributes();H.mergeAttributes(K);H.removeAttribute("uniqueNumber");
if(H.options){var O=H.options,e=K.options;for(var I=O.length;I--;){O[I].selected=e[I].selected;}}}var l=C[K.tagName.toLowerCase()];if(l&&K[l]){H[l]=K[l];
}}if(Browser.ie){var M=L.getElementsByTagName("object"),N=this.getElementsByTagName("object");for(J=M.length;J--;){M[J].outerHTML=N[J].outerHTML;}}return document.id(L);
}});[Element,Window,Document].invoke("implement",{addListener:function(E,D){if(E=="unload"){var e=D,l=this;D=function(){l.removeListener("unload",D);e();
};}else{i[Slick.uidOf(this)]=this;}if(this.addEventListener){this.addEventListener(E,D,!!arguments[2]);}else{this.attachEvent("on"+E,D);}return this;},removeListener:function(l,e){if(this.removeEventListener){this.removeEventListener(l,e,!!arguments[2]);
}else{this.detachEvent("on"+l,e);}return this;},retrieve:function(l,e){var E=B(Slick.uidOf(this)),D=E[l];if(e!=null&&D==null){D=E[l]=e;}return D!=null?D:null;
},store:function(l,e){var D=B(Slick.uidOf(this));D[l]=e;return this;},eliminate:function(e){var l=B(Slick.uidOf(this));delete l[e];return this;}});if(window.attachEvent&&!window.addEventListener){window.addListener("unload",function(){Object.each(i,v);
if(window.CollectGarbage){CollectGarbage();}});}Element.Properties={};Element.Properties=new Hash;Element.Properties.style={set:function(e){this.style.cssText=e;
},get:function(){return this.style.cssText;},erase:function(){this.style.cssText="";}};Element.Properties.tag={get:function(){return this.tagName.toLowerCase();
}};Element.Properties.html={set:function(e){if(e==null){e="";}else{if(typeOf(e)=="array"){e=e.join("");}}this.innerHTML=e;},erase:function(){this.innerHTML="";
}};var t=document.createElement("div");t.innerHTML="<nav></nav>";var a=(t.childNodes.length==1);if(!a){var s="abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video".split(" "),b=document.createDocumentFragment(),u=s.length;
while(u--){b.createElement(s[u]);}}t=null;var g=Function.attempt(function(){var e=document.createElement("table");e.innerHTML="<tr><td></td></tr>";return true;
});var c=document.createElement("tr"),o="<td></td>";c.innerHTML=o;var y=(c.innerHTML==o);c=null;if(!g||!y||!a){Element.Properties.html.set=(function(l){var e={table:[1,"<table>","</table>"],select:[1,"<select>","</select>"],tbody:[2,"<table><tbody>","</tbody></table>"],tr:[3,"<table><tbody><tr>","</tr></tbody></table>"]};
e.thead=e.tfoot=e.tbody;return function(D){var E=e[this.get("tag")];if(!E&&!a){E=[0,"",""];}if(!E){return l.call(this,D);}var H=E[0],G=document.createElement("div"),F=G;
if(!a){b.appendChild(G);}G.innerHTML=[E[1],D,E[2]].flatten().join("");while(H--){F=F.firstChild;}this.empty().adopt(F.childNodes);if(!a){b.removeChild(G);
}G=null;};})(Element.Properties.html.set);}var n=document.createElement("form");n.innerHTML="<select><option>s</option></select>";if(n.firstChild.value!="s"){Element.Properties.value={set:function(G){var l=this.get("tag");
if(l!="select"){return this.setProperty("value",G);}var D=this.getElements("option");for(var E=0;E<D.length;E++){var F=D[E],e=F.getAttributeNode("value"),H=(e&&e.specified)?F.value:F.get("text");
if(H==G){return F.selected=true;}}},get:function(){var D=this,l=D.get("tag");if(l!="select"&&l!="option"){return this.getProperty("value");}if(l=="select"&&!(D=D.getSelected()[0])){return"";
}var e=D.getAttributeNode("value");return(e&&e.specified)?D.value:D.get("text");}};}n=null;if(document.createElement("div").getAttributeNode("id")){Element.Properties.id={set:function(e){this.id=this.getAttributeNode("id").value=e;
},get:function(){return this.id||null;},erase:function(){this.id=this.getAttributeNode("id").value="";}};}})();(function(){var i=document.html;var d=document.createElement("div");
d.style.color="red";d.style.color=null;var c=d.style.color=="red";d=null;Element.Properties.styles={set:function(k){this.setStyles(k);}};var h=(i.style.opacity!=null),e=(i.style.filter!=null),j=/alpha\(opacity=([\d.]+)\)/i;
var a=function(l,k){l.store("$opacity",k);l.style.visibility=k>0||k==null?"visible":"hidden";};var f=(h?function(l,k){l.style.opacity=k;}:(e?function(l,k){var n=l.style;
if(!l.currentStyle||!l.currentStyle.hasLayout){n.zoom=1;}if(k==null||k==1){k="";}else{k="alpha(opacity="+(k*100).limit(0,100).round()+")";}var m=n.filter||l.getComputedStyle("filter")||"";
n.filter=j.test(m)?m.replace(j,k):m+k;if(!n.filter){n.removeAttribute("filter");}}:a));var g=(h?function(l){var k=l.style.opacity||l.getComputedStyle("opacity");
return(k=="")?1:k.toFloat();}:(e?function(l){var m=(l.style.filter||l.getComputedStyle("filter")),k;if(m){k=m.match(j);}return(k==null||m==null)?1:(k[1]/100);
}:function(l){var k=l.retrieve("$opacity");if(k==null){k=(l.style.visibility=="hidden"?0:1);}return k;}));var b=(i.style.cssFloat==null)?"styleFloat":"cssFloat";
Element.implement({getComputedStyle:function(m){if(this.currentStyle){return this.currentStyle[m.camelCase()];}var l=Element.getDocument(this).defaultView,k=l?l.getComputedStyle(this,null):null;
return(k)?k.getPropertyValue((m==b)?"float":m.hyphenate()):null;},setStyle:function(l,k){if(l=="opacity"){if(k!=null){k=parseFloat(k);}f(this,k);return this;
}l=(l=="float"?b:l).camelCase();if(typeOf(k)!="string"){var m=(Element.Styles[l]||"@").split(" ");k=Array.from(k).map(function(o,n){if(!m[n]){return"";
}return(typeOf(o)=="number")?m[n].replace("@",Math.round(o)):o;}).join(" ");}else{if(k==String(Number(k))){k=Math.round(k);}}this.style[l]=k;if((k==""||k==null)&&c&&this.style.removeAttribute){this.style.removeAttribute(l);
}return this;},getStyle:function(q){if(q=="opacity"){return g(this);}q=(q=="float"?b:q).camelCase();var k=this.style[q];if(!k||q=="zIndex"){k=[];for(var p in Element.ShortStyles){if(q!=p){continue;
}for(var o in Element.ShortStyles[p]){k.push(this.getStyle(o));}return k.join(" ");}k=this.getComputedStyle(q);}if(k){k=String(k);var m=k.match(/rgba?\([\d\s,]+\)/);
if(m){k=k.replace(m[0],m[0].rgbToHex());}}if(Browser.opera||Browser.ie){if((/^(height|width)$/).test(q)&&!(/px$/.test(k))){var l=(q=="width")?["left","right"]:["top","bottom"],n=0;
l.each(function(r){n+=this.getStyle("border-"+r+"-width").toInt()+this.getStyle("padding-"+r).toInt();},this);return this["offset"+q.capitalize()]-n+"px";
}if(Browser.ie&&(/^border(.+)Width|margin|padding/).test(q)&&isNaN(parseFloat(k))){return"0px";}}return k;},setStyles:function(l){for(var k in l){this.setStyle(k,l[k]);
}return this;},getStyles:function(){var k={};Array.flatten(arguments).each(function(l){k[l]=this.getStyle(l);},this);return k;}});Element.Styles={left:"@px",top:"@px",bottom:"@px",right:"@px",width:"@px",height:"@px",maxWidth:"@px",maxHeight:"@px",minWidth:"@px",minHeight:"@px",backgroundColor:"rgb(@, @, @)",backgroundPosition:"@px @px",color:"rgb(@, @, @)",fontSize:"@px",letterSpacing:"@px",lineHeight:"@px",clip:"rect(@px @px @px @px)",margin:"@px @px @px @px",padding:"@px @px @px @px",border:"@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)",borderWidth:"@px @px @px @px",borderStyle:"@ @ @ @",borderColor:"rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)",zIndex:"@",zoom:"@",fontWeight:"@",textIndent:"@px",opacity:"@"};
Element.implement({setOpacity:function(k){f(this,k);return this;},getOpacity:function(){return g(this);}});Element.Properties.opacity={set:function(k){f(this,k);
a(this,k);},get:function(){return g(this);}};Element.Styles=new Hash(Element.Styles);Element.ShortStyles={margin:{},padding:{},border:{},borderWidth:{},borderStyle:{},borderColor:{}};
["Top","Right","Bottom","Left"].each(function(q){var p=Element.ShortStyles;var l=Element.Styles;["margin","padding"].each(function(r){var s=r+q;p[r][s]=l[s]="@px";
});var o="border"+q;p.border[o]=l[o]="@px @ rgb(@, @, @)";var n=o+"Width",k=o+"Style",m=o+"Color";p[o]={};p.borderWidth[n]=p[o][n]=l[n]="@px";p.borderStyle[k]=p[o][k]=l[k]="@";
p.borderColor[m]=p[o][m]=l[m]="rgb(@, @, @)";});})();(function(){Element.Properties.events={set:function(b){this.addEvents(b);}};[Element,Window,Document].invoke("implement",{addEvent:function(f,h){var i=this.retrieve("events",{});
if(!i[f]){i[f]={keys:[],values:[]};}if(i[f].keys.contains(h)){return this;}i[f].keys.push(h);var g=f,b=Element.Events[f],d=h,j=this;if(b){if(b.onAdd){b.onAdd.call(this,h,f);
}if(b.condition){d=function(k){if(b.condition.call(this,k,f)){return h.call(this,k);}return true;};}if(b.base){g=Function.from(b.base).call(this,f);}}var e=function(){return h.call(j);
};var c=Element.NativeEvents[g];if(c){if(c==2){e=function(k){k=new DOMEvent(k,j.getWindow());if(d.call(j,k)===false){k.stop();}};}this.addListener(g,e,arguments[2]);
}i[f].values.push(e);return this;},removeEvent:function(e,d){var c=this.retrieve("events");if(!c||!c[e]){return this;}var h=c[e];var b=h.keys.indexOf(d);
if(b==-1){return this;}var g=h.values[b];delete h.keys[b];delete h.values[b];var f=Element.Events[e];if(f){if(f.onRemove){f.onRemove.call(this,d,e);}if(f.base){e=Function.from(f.base).call(this,e);
}}return(Element.NativeEvents[e])?this.removeListener(e,g,arguments[2]):this;},addEvents:function(b){for(var c in b){this.addEvent(c,b[c]);}return this;
},removeEvents:function(b){var d;if(typeOf(b)=="object"){for(d in b){this.removeEvent(d,b[d]);}return this;}var c=this.retrieve("events");if(!c){return this;
}if(!b){for(d in c){this.removeEvents(d);}this.eliminate("events");}else{if(c[b]){c[b].keys.each(function(e){this.removeEvent(b,e);},this);delete c[b];
}}return this;},fireEvent:function(e,c,b){var d=this.retrieve("events");if(!d||!d[e]){return this;}c=Array.from(c);d[e].keys.each(function(f){if(b){f.delay(b,this,c);
}else{f.apply(this,c);}},this);return this;},cloneEvents:function(e,d){e=document.id(e);var c=e.retrieve("events");if(!c){return this;}if(!d){for(var b in c){this.cloneEvents(e,b);
}}else{if(c[d]){c[d].keys.each(function(f){this.addEvent(d,f);},this);}}return this;}});Element.NativeEvents={click:2,dblclick:2,mouseup:2,mousedown:2,contextmenu:2,mousewheel:2,DOMMouseScroll:2,mouseover:2,mouseout:2,mousemove:2,selectstart:2,selectend:2,keydown:2,keypress:2,keyup:2,orientationchange:2,touchstart:2,touchmove:2,touchend:2,touchcancel:2,gesturestart:2,gesturechange:2,gestureend:2,focus:2,blur:2,change:2,reset:2,select:2,submit:2,paste:2,input:2,load:2,unload:1,beforeunload:2,resize:1,move:1,DOMContentLoaded:1,readystatechange:1,error:1,abort:1,scroll:1};
Element.Events={mousewheel:{base:(Browser.firefox)?"DOMMouseScroll":"mousewheel"}};if("onmouseenter" in document.documentElement){Element.NativeEvents.mouseenter=Element.NativeEvents.mouseleave=2;
}else{var a=function(b){var c=b.relatedTarget;if(c==null){return true;}if(!c){return false;}return(c!=this&&c.prefix!="xul"&&typeOf(this)!="document"&&!this.contains(c));
};Element.Events.mouseenter={base:"mouseover",condition:a};Element.Events.mouseleave={base:"mouseout",condition:a};}if(!window.addEventListener){Element.NativeEvents.propertychange=2;
Element.Events.change={base:function(){var b=this.type;return(this.get("tag")=="input"&&(b=="radio"||b=="checkbox"))?"propertychange":"change";},condition:function(b){return this.type!="radio"||(b.event.propertyName=="checked"&&this.checked);
}};}Element.Events=new Hash(Element.Events);})();(function(){var c=!!window.addEventListener;Element.NativeEvents.focusin=Element.NativeEvents.focusout=2;
var k=function(l,m,n,o,p){while(p&&p!=l){if(m(p,o)){return n.call(p,o,p);}p=document.id(p.parentNode);}};var a={mouseenter:{base:"mouseover"},mouseleave:{base:"mouseout"},focus:{base:"focus"+(c?"":"in"),capture:true},blur:{base:c?"blur":"focusout",capture:true}};
var b="$delegation:";var i=function(l){return{base:"focusin",remove:function(m,o){var p=m.retrieve(b+l+"listeners",{})[o];if(p&&p.forms){for(var n=p.forms.length;
n--;){p.forms[n].removeEvent(l,p.fns[n]);}}},listen:function(x,r,v,n,t,s){var o=(t.get("tag")=="form")?t:n.target.getParent("form");if(!o){return;}var u=x.retrieve(b+l+"listeners",{}),p=u[s]||{forms:[],fns:[]},m=p.forms,w=p.fns;
if(m.indexOf(o)!=-1){return;}m.push(o);var q=function(y){k(x,r,v,y,t);};o.addEvent(l,q);w.push(q);u[s]=p;x.store(b+l+"listeners",u);}};};var d=function(l){return{base:"focusin",listen:function(m,n,p,q,r){var o={blur:function(){this.removeEvents(o);
}};o[l]=function(s){k(m,n,p,s,r);};q.target.addEvents(o);}};};if(!c){Object.append(a,{submit:i("submit"),reset:i("reset"),change:d("change"),select:d("select")});
}var h=Element.prototype,f=h.addEvent,j=h.removeEvent;var e=function(l,m){return function(r,q,n){if(r.indexOf(":relay")==-1){return l.call(this,r,q,n);
}var o=Slick.parse(r).expressions[0][0];if(o.pseudos[0].key!="relay"){return l.call(this,r,q,n);}var p=o.tag;o.pseudos.slice(1).each(function(s){p+=":"+s.key+(s.value?"("+s.value+")":"");
});l.call(this,r,q);return m.call(this,p,o.pseudos[0].value,q);};};var g={addEvent:function(v,q,x){var t=this.retrieve("$delegates",{}),r=t[v];if(r){for(var y in r){if(r[y].fn==x&&r[y].match==q){return this;
}}}var p=v,u=q,o=x,n=a[v]||{};v=n.base||p;q=function(B){return Slick.match(B,u);};var w=Element.Events[p];if(w&&w.condition){var l=q,m=w.condition;q=function(C,B){return l(C,B)&&m.call(C,B,v);
};}var z=this,s=String.uniqueID();var A=n.listen?function(B,C){if(!C&&B&&B.target){C=B.target;}if(C){n.listen(z,q,x,B,C,s);}}:function(B,C){if(!C&&B&&B.target){C=B.target;
}if(C){k(z,q,x,B,C);}};if(!r){r={};}r[s]={match:u,fn:o,delegator:A};t[p]=r;return f.call(this,v,A,n.capture);},removeEvent:function(r,n,t,u){var q=this.retrieve("$delegates",{}),p=q[r];
if(!p){return this;}if(u){var m=r,w=p[u].delegator,l=a[r]||{};r=l.base||m;if(l.remove){l.remove(this,u);}delete p[u];q[m]=p;return j.call(this,r,w);}var o,v;
if(t){for(o in p){v=p[o];if(v.match==n&&v.fn==t){return g.removeEvent.call(this,r,n,t,o);}}}else{for(o in p){v=p[o];if(v.match==n){g.removeEvent.call(this,r,n,v.fn,o);
}}}return this;}};[Element,Window,Document].invoke("implement",{addEvent:e(f,g.addEvent),removeEvent:e(j,g.removeEvent)});})();(function(){var h=document.createElement("div"),e=document.createElement("div");
h.style.height="0";h.appendChild(e);var d=(e.offsetParent===h);h=e=null;var l=function(m){return k(m,"position")!="static"||a(m);};var i=function(m){return l(m)||(/^(?:table|td|th)$/i).test(m.tagName);
};Element.implement({scrollTo:function(m,n){if(a(this)){this.getWindow().scrollTo(m,n);}else{this.scrollLeft=m;this.scrollTop=n;}return this;},getSize:function(){if(a(this)){return this.getWindow().getSize();
}return{x:this.offsetWidth,y:this.offsetHeight};},getScrollSize:function(){if(a(this)){return this.getWindow().getScrollSize();}return{x:this.scrollWidth,y:this.scrollHeight};
},getScroll:function(){if(a(this)){return this.getWindow().getScroll();}return{x:this.scrollLeft,y:this.scrollTop};},getScrolls:function(){var n=this.parentNode,m={x:0,y:0};
while(n&&!a(n)){m.x+=n.scrollLeft;m.y+=n.scrollTop;n=n.parentNode;}return m;},getOffsetParent:d?function(){var m=this;if(a(m)||k(m,"position")=="fixed"){return null;
}var n=(k(m,"position")=="static")?i:l;while((m=m.parentNode)){if(n(m)){return m;}}return null;}:function(){var m=this;if(a(m)||k(m,"position")=="fixed"){return null;
}try{return m.offsetParent;}catch(n){}return null;},getOffsets:function(){if(this.getBoundingClientRect&&!Browser.Platform.ios){var r=this.getBoundingClientRect(),o=document.id(this.getDocument().documentElement),q=o.getScroll(),t=this.getScrolls(),s=(k(this,"position")=="fixed");
return{x:r.left.toInt()+t.x+((s)?0:q.x)-o.clientLeft,y:r.top.toInt()+t.y+((s)?0:q.y)-o.clientTop};}var n=this,m={x:0,y:0};if(a(this)){return m;}while(n&&!a(n)){m.x+=n.offsetLeft;
m.y+=n.offsetTop;if(Browser.firefox){if(!c(n)){m.x+=b(n);m.y+=g(n);}var p=n.parentNode;if(p&&k(p,"overflow")!="visible"){m.x+=b(p);m.y+=g(p);}}else{if(n!=this&&Browser.safari){m.x+=b(n);
m.y+=g(n);}}n=n.offsetParent;}if(Browser.firefox&&!c(this)){m.x-=b(this);m.y-=g(this);}return m;},getPosition:function(p){var q=this.getOffsets(),n=this.getScrolls();
var m={x:q.x-n.x,y:q.y-n.y};if(p&&(p=document.id(p))){var o=p.getPosition();return{x:m.x-o.x-b(p),y:m.y-o.y-g(p)};}return m;},getCoordinates:function(o){if(a(this)){return this.getWindow().getCoordinates();
}var m=this.getPosition(o),n=this.getSize();var p={left:m.x,top:m.y,width:n.x,height:n.y};p.right=p.left+p.width;p.bottom=p.top+p.height;return p;},computePosition:function(m){return{left:m.x-j(this,"margin-left"),top:m.y-j(this,"margin-top")};
},setPosition:function(m){return this.setStyles(this.computePosition(m));}});[Document,Window].invoke("implement",{getSize:function(){var m=f(this);return{x:m.clientWidth,y:m.clientHeight};
},getScroll:function(){var n=this.getWindow(),m=f(this);return{x:n.pageXOffset||m.scrollLeft,y:n.pageYOffset||m.scrollTop};},getScrollSize:function(){var o=f(this),n=this.getSize(),m=this.getDocument().body;
return{x:Math.max(o.scrollWidth,m.scrollWidth,n.x),y:Math.max(o.scrollHeight,m.scrollHeight,n.y)};},getPosition:function(){return{x:0,y:0};},getCoordinates:function(){var m=this.getSize();
return{top:0,left:0,bottom:m.y,right:m.x,height:m.y,width:m.x};}});var k=Element.getComputedStyle;function j(m,n){return k(m,n).toInt()||0;}function c(m){return k(m,"-moz-box-sizing")=="border-box";
}function g(m){return j(m,"border-top-width");}function b(m){return j(m,"border-left-width");}function a(m){return(/^(?:body|html)$/i).test(m.tagName);
}function f(m){var n=m.getDocument();return(!n.compatMode||n.compatMode=="CSS1Compat")?n.html:n.body;}})();Element.alias({position:"setPosition"});[Window,Document,Element].invoke("implement",{getHeight:function(){return this.getSize().y;
},getWidth:function(){return this.getSize().x;},getScrollTop:function(){return this.getScroll().y;},getScrollLeft:function(){return this.getScroll().x;
},getScrollHeight:function(){return this.getScrollSize().y;},getScrollWidth:function(){return this.getScrollSize().x;},getTop:function(){return this.getPosition().y;
},getLeft:function(){return this.getPosition().x;}});(function(){var f=this.Fx=new Class({Implements:[Chain,Events,Options],options:{fps:60,unit:false,duration:500,frames:null,frameSkip:true,link:"ignore"},initialize:function(g){this.subject=this.subject||this;
this.setOptions(g);},getTransition:function(){return function(g){return -(Math.cos(Math.PI*g)-1)/2;};},step:function(g){if(this.options.frameSkip){var h=(this.time!=null)?(g-this.time):0,i=h/this.frameInterval;
this.time=g;this.frame+=i;}else{this.frame++;}if(this.frame<this.frames){var j=this.transition(this.frame/this.frames);this.set(this.compute(this.from,this.to,j));
}else{this.frame=this.frames;this.set(this.compute(this.from,this.to,1));this.stop();}},set:function(g){return g;},compute:function(i,h,g){return f.compute(i,h,g);
},check:function(){if(!this.isRunning()){return true;}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(this.caller.pass(arguments,this));
return false;}return false;},start:function(k,j){if(!this.check(k,j)){return this;}this.from=k;this.to=j;this.frame=(this.options.frameSkip)?0:-1;this.time=null;
this.transition=this.getTransition();var i=this.options.frames,h=this.options.fps,g=this.options.duration;this.duration=f.Durations[g]||g.toInt();this.frameInterval=1000/h;
this.frames=i||Math.round(this.duration/this.frameInterval);this.fireEvent("start",this.subject);b.call(this,h);return this;},stop:function(){if(this.isRunning()){this.time=null;
d.call(this,this.options.fps);if(this.frames==this.frame){this.fireEvent("complete",this.subject);if(!this.callChain()){this.fireEvent("chainComplete",this.subject);
}}else{this.fireEvent("stop",this.subject);}}return this;},cancel:function(){if(this.isRunning()){this.time=null;d.call(this,this.options.fps);this.frame=this.frames;
this.fireEvent("cancel",this.subject).clearChain();}return this;},pause:function(){if(this.isRunning()){this.time=null;d.call(this,this.options.fps);}return this;
},resume:function(){if((this.frame<this.frames)&&!this.isRunning()){b.call(this,this.options.fps);}return this;},isRunning:function(){var g=e[this.options.fps];
return g&&g.contains(this);}});f.compute=function(i,h,g){return(h-i)*g+i;};f.Durations={"short":250,normal:500,"long":1000};var e={},c={};var a=function(){var h=Date.now();
for(var j=this.length;j--;){var g=this[j];if(g){g.step(h);}}};var b=function(h){var g=e[h]||(e[h]=[]);g.push(this);if(!c[h]){c[h]=a.periodical(Math.round(1000/h),g);
}};var d=function(h){var g=e[h];if(g){g.erase(this);if(!g.length&&c[h]){delete e[h];c[h]=clearInterval(c[h]);}}};})();Fx.CSS=new Class({Extends:Fx,prepare:function(b,e,a){a=Array.from(a);
var h=a[0],g=a[1];if(g==null){g=h;h=b.getStyle(e);var c=this.options.unit;if(c&&h.slice(-c.length)!=c&&parseFloat(h)!=0){b.setStyle(e,g+c);var d=b.getComputedStyle(e);
if(!(/px$/.test(d))){d=b.style[("pixel-"+e).camelCase()];if(d==null){var f=b.style.left;b.style.left=g+c;d=b.style.pixelLeft;b.style.left=f;}}h=(g||1)/(parseFloat(d)||1)*(parseFloat(h)||0);
b.setStyle(e,h+c);}}return{from:this.parse(h),to:this.parse(g)};},parse:function(a){a=Function.from(a)();a=(typeof a=="string")?a.split(" "):Array.from(a);
return a.map(function(c){c=String(c);var b=false;Object.each(Fx.CSS.Parsers,function(f,e){if(b){return;}var d=f.parse(c);if(d||d===0){b={value:d,parser:f};
}});b=b||{value:c,parser:Fx.CSS.Parsers.String};return b;});},compute:function(d,c,b){var a=[];(Math.min(d.length,c.length)).times(function(e){a.push({value:d[e].parser.compute(d[e].value,c[e].value,b),parser:d[e].parser});
});a.$family=Function.from("fx:css:value");return a;},serve:function(c,b){if(typeOf(c)!="fx:css:value"){c=this.parse(c);}var a=[];c.each(function(d){a=a.concat(d.parser.serve(d.value,b));
});return a;},render:function(a,d,c,b){a.setStyle(d,this.serve(c,b));},search:function(a){if(Fx.CSS.Cache[a]){return Fx.CSS.Cache[a];}var c={},b=new RegExp("^"+a.escapeRegExp()+"$");
Array.each(document.styleSheets,function(f,e){var d=f.href;if(d&&d.contains("://")&&!d.contains(document.domain)){return;}var g=f.rules||f.cssRules;Array.each(g,function(k,h){if(!k.style){return;
}var j=(k.selectorText)?k.selectorText.replace(/^\w+/,function(i){return i.toLowerCase();}):null;if(!j||!b.test(j)){return;}Object.each(Element.Styles,function(l,i){if(!k.style[i]||Element.ShortStyles[i]){return;
}l=String(k.style[i]);c[i]=((/^rgb/).test(l))?l.rgbToHex():l;});});});return Fx.CSS.Cache[a]=c;}});Fx.CSS.Cache={};Fx.CSS.Parsers={Color:{parse:function(a){if(a.match(/^#[0-9a-f]{3,6}$/i)){return a.hexToRgb(true);
}return((a=a.match(/(\d+),\s*(\d+),\s*(\d+)/)))?[a[1],a[2],a[3]]:false;},compute:function(c,b,a){return c.map(function(e,d){return Math.round(Fx.compute(c[d],b[d],a));
});},serve:function(a){return a.map(Number);}},Number:{parse:parseFloat,compute:Fx.compute,serve:function(b,a){return(a)?b+a:b;}},String:{parse:Function.from(false),compute:function(b,a){return a;
},serve:function(a){return a;}}};Fx.CSS.Parsers=new Hash(Fx.CSS.Parsers);Fx.Tween=new Class({Extends:Fx.CSS,initialize:function(b,a){this.element=this.subject=document.id(b);
this.parent(a);},set:function(b,a){if(arguments.length==1){a=b;b=this.property||this.options.property;}this.render(this.element,b,a,this.options.unit);
return this;},start:function(c,e,d){if(!this.check(c,e,d)){return this;}var b=Array.flatten(arguments);this.property=this.options.property||b.shift();var a=this.prepare(this.element,this.property,b);
return this.parent(a.from,a.to);}});Element.Properties.tween={set:function(a){this.get("tween").cancel().setOptions(a);return this;},get:function(){var a=this.retrieve("tween");
if(!a){a=new Fx.Tween(this,{link:"cancel"});this.store("tween",a);}return a;}};Element.implement({tween:function(a,c,b){this.get("tween").start(a,c,b);
return this;},fade:function(d){var e=this.get("tween"),g,c=["opacity"].append(arguments),a;if(c[1]==null){c[1]="toggle";}switch(c[1]){case"in":g="start";
c[1]=1;break;case"out":g="start";c[1]=0;break;case"show":g="set";c[1]=1;break;case"hide":g="set";c[1]=0;break;case"toggle":var b=this.retrieve("fade:flag",this.getStyle("opacity")==1);
g="start";c[1]=b?0:1;this.store("fade:flag",!b);a=true;break;default:g="start";}if(!a){this.eliminate("fade:flag");}e[g].apply(e,c);var f=c[c.length-1];
if(g=="set"||f!=0){this.setStyle("visibility",f==0?"hidden":"visible");}else{e.chain(function(){this.element.setStyle("visibility","hidden");this.callChain();
});}return this;},highlight:function(c,a){if(!a){a=this.retrieve("highlight:original",this.getStyle("background-color"));a=(a=="transparent")?"#fff":a;
}var b=this.get("tween");b.start("background-color",c||"#ffff88",a).chain(function(){this.setStyle("background-color",this.retrieve("highlight:original"));
b.callChain();}.bind(this));return this;}});Fx.Morph=new Class({Extends:Fx.CSS,initialize:function(b,a){this.element=this.subject=document.id(b);this.parent(a);
},set:function(a){if(typeof a=="string"){a=this.search(a);}for(var b in a){this.render(this.element,b,a[b],this.options.unit);}return this;},compute:function(e,d,c){var a={};
for(var b in e){a[b]=this.parent(e[b],d[b],c);}return a;},start:function(b){if(!this.check(b)){return this;}if(typeof b=="string"){b=this.search(b);}var e={},d={};
for(var c in b){var a=this.prepare(this.element,c,b[c]);e[c]=a.from;d[c]=a.to;}return this.parent(e,d);}});Element.Properties.morph={set:function(a){this.get("morph").cancel().setOptions(a);
return this;},get:function(){var a=this.retrieve("morph");if(!a){a=new Fx.Morph(this,{link:"cancel"});this.store("morph",a);}return a;}};Element.implement({morph:function(a){this.get("morph").start(a);
return this;}});Fx.implement({getTransition:function(){var a=this.options.transition||Fx.Transitions.Sine.easeInOut;if(typeof a=="string"){var b=a.split(":");
a=Fx.Transitions;a=a[b[0]]||a[b[0].capitalize()];if(b[1]){a=a["ease"+b[1].capitalize()+(b[2]?b[2].capitalize():"")];}}return a;}});Fx.Transition=function(c,b){b=Array.from(b);
var a=function(d){return c(d,b);};return Object.append(a,{easeIn:a,easeOut:function(d){return 1-c(1-d,b);},easeInOut:function(d){return(d<=0.5?c(2*d,b):(2-c(2*(1-d),b)))/2;
}});};Fx.Transitions={linear:function(a){return a;}};Fx.Transitions=new Hash(Fx.Transitions);Fx.Transitions.extend=function(a){for(var b in a){Fx.Transitions[b]=new Fx.Transition(a[b]);
}};Fx.Transitions.extend({Pow:function(b,a){return Math.pow(b,a&&a[0]||6);},Expo:function(a){return Math.pow(2,8*(a-1));},Circ:function(a){return 1-Math.sin(Math.acos(a));
},Sine:function(a){return 1-Math.cos(a*Math.PI/2);},Back:function(b,a){a=a&&a[0]||1.618;return Math.pow(b,2)*((a+1)*b-a);},Bounce:function(f){var e;for(var d=0,c=1;
1;d+=c,c/=2){if(f>=(7-4*d)/11){e=c*c-Math.pow((11-6*d-11*f)/4,2);break;}}return e;},Elastic:function(b,a){return Math.pow(2,10*--b)*Math.cos(20*b*Math.PI*(a&&a[0]||1)/3);
}});["Quad","Cubic","Quart","Quint"].each(function(b,a){Fx.Transitions[b]=new Fx.Transition(function(c){return Math.pow(c,a+2);});});(function(){var d=function(){},a=("onprogress" in new Browser.Request);
var c=this.Request=new Class({Implements:[Chain,Events,Options],options:{url:"",data:"",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/javascript, text/html, application/xml, text/xml, */*"},async:true,format:false,method:"post",link:"ignore",isSuccess:null,emulation:true,urlEncoded:true,encoding:"utf-8",evalScripts:false,evalResponse:false,timeout:0,noCache:false},initialize:function(e){this.xhr=new Browser.Request();
this.setOptions(e);this.headers=this.options.headers;},onStateChange:function(){var e=this.xhr;if(e.readyState!=4||!this.running){return;}this.running=false;
this.status=0;Function.attempt(function(){var f=e.status;this.status=(f==1223)?204:f;}.bind(this));e.onreadystatechange=d;if(a){e.onprogress=e.onloadstart=d;
}clearTimeout(this.timer);this.response={text:this.xhr.responseText||"",xml:this.xhr.responseXML};if(this.options.isSuccess.call(this,this.status)){this.success(this.response.text,this.response.xml);
}else{this.failure();}},isSuccess:function(){var e=this.status;return(e>=200&&e<300);},isRunning:function(){return !!this.running;},processScripts:function(e){if(this.options.evalResponse||(/(ecma|java)script/).test(this.getHeader("Content-type"))){return Browser.exec(e);
}return e.stripScripts(this.options.evalScripts);},success:function(f,e){this.onSuccess(this.processScripts(f),e);},onSuccess:function(){this.fireEvent("complete",arguments).fireEvent("success",arguments).callChain();
},failure:function(){this.onFailure();},onFailure:function(){this.fireEvent("complete").fireEvent("failure",this.xhr);},loadstart:function(e){this.fireEvent("loadstart",[e,this.xhr]);
},progress:function(e){this.fireEvent("progress",[e,this.xhr]);},timeout:function(){this.fireEvent("timeout",this.xhr);},setHeader:function(e,f){this.headers[e]=f;
return this;},getHeader:function(e){return Function.attempt(function(){return this.xhr.getResponseHeader(e);}.bind(this));},check:function(){if(!this.running){return true;
}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(this.caller.pass(arguments,this));return false;}return false;},send:function(o){if(!this.check(o)){return this;
}this.options.isSuccess=this.options.isSuccess||this.isSuccess;this.running=true;var l=typeOf(o);if(l=="string"||l=="element"){o={data:o};}var h=this.options;
o=Object.append({data:h.data,url:h.url,method:h.method},o);var j=o.data,f=String(o.url),e=o.method.toLowerCase();switch(typeOf(j)){case"element":j=document.id(j).toQueryString();
break;case"object":case"hash":j=Object.toQueryString(j);}if(this.options.format){var m="format="+this.options.format;j=(j)?m+"&"+j:m;}if(this.options.emulation&&!["get","post"].contains(e)){var k="_method="+e;
j=(j)?k+"&"+j:k;e="post";}if(this.options.urlEncoded&&["post","put"].contains(e)){var g=(this.options.encoding)?"; charset="+this.options.encoding:"";this.headers["Content-type"]="application/x-www-form-urlencoded"+g;
}if(!f){f=document.location.pathname;}var i=f.lastIndexOf("/");if(i>-1&&(i=f.indexOf("#"))>-1){f=f.substr(0,i);}if(this.options.noCache){f+=(f.contains("?")?"&":"?")+String.uniqueID();
}if(j&&e=="get"){f+=(f.contains("?")?"&":"?")+j;j=null;}var n=this.xhr;if(a){n.onloadstart=this.loadstart.bind(this);n.onprogress=this.progress.bind(this);
}n.open(e.toUpperCase(),f,this.options.async,this.options.user,this.options.password);if(this.options.user&&"withCredentials" in n){n.withCredentials=true;
}n.onreadystatechange=this.onStateChange.bind(this);Object.each(this.headers,function(q,p){try{n.setRequestHeader(p,q);}catch(r){this.fireEvent("exception",[p,q]);
}},this);this.fireEvent("request");n.send(j);if(!this.options.async){this.onStateChange();}else{if(this.options.timeout){this.timer=this.timeout.delay(this.options.timeout,this);
}}return this;},cancel:function(){if(!this.running){return this;}this.running=false;var e=this.xhr;e.abort();clearTimeout(this.timer);e.onreadystatechange=d;
if(a){e.onprogress=e.onloadstart=d;}this.xhr=new Browser.Request();this.fireEvent("cancel");return this;}});var b={};["get","post","put","delete","GET","POST","PUT","DELETE"].each(function(e){b[e]=function(g){var f={method:e};
if(g!=null){f.data=g;}return this.send(f);};});c.implement(b);Element.Properties.send={set:function(e){var f=this.get("send").cancel();f.setOptions(e);
return this;},get:function(){var e=this.retrieve("send");if(!e){e=new c({data:this,link:"cancel",method:this.get("method")||"post",url:this.get("action")});
this.store("send",e);}return e;}};Element.implement({send:function(e){var f=this.get("send");f.send({data:this,url:e||f.options.url});return this;}});})();
Request.HTML=new Class({Extends:Request,options:{update:false,append:false,evalScripts:true,filter:false,headers:{Accept:"text/html, application/xml, text/xml, */*"}},success:function(f){var e=this.options,c=this.response;
c.html=f.stripScripts(function(h){c.javascript=h;});var d=c.html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);if(d){c.html=d[1];}var b=new Element("div").set("html",c.html);
c.tree=b.childNodes;c.elements=b.getElements(e.filter||"*");if(e.filter){c.tree=c.elements;}if(e.update){var g=document.id(e.update).empty();if(e.filter){g.adopt(c.elements);
}else{g.set("html",c.html);}}else{if(e.append){var a=document.id(e.append);if(e.filter){c.elements.reverse().inject(a);}else{a.adopt(b.getChildren());}}}if(e.evalScripts){Browser.exec(c.javascript);
}this.onSuccess(c.tree,c.elements,c.html,c.javascript);}});Element.Properties.load={set:function(a){var b=this.get("load").cancel();b.setOptions(a);return this;
},get:function(){var a=this.retrieve("load");if(!a){a=new Request.HTML({data:this,link:"cancel",update:this,method:"get"});this.store("load",a);}return a;
}};Element.implement({load:function(){this.get("load").send(Array.link(arguments,{data:Type.isObject,url:Type.isString}));return this;}});if(typeof JSON=="undefined"){this.JSON={};
}JSON=new Hash({stringify:JSON.stringify,parse:JSON.parse});(function(){var special={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};
var escape=function(chr){return special[chr]||"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4);};JSON.validate=function(string){string=string.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"");
return(/^[\],:{}\s]*$/).test(string);};JSON.encode=JSON.stringify?function(obj){return JSON.stringify(obj);}:function(obj){if(obj&&obj.toJSON){obj=obj.toJSON();
}switch(typeOf(obj)){case"string":return'"'+obj.replace(/[\x00-\x1f\\"]/g,escape)+'"';case"array":return"["+obj.map(JSON.encode).clean()+"]";case"object":case"hash":var string=[];
Object.each(obj,function(value,key){var json=JSON.encode(value);if(json){string.push(JSON.encode(key)+":"+json);}});return"{"+string+"}";case"number":case"boolean":return""+obj;
case"null":return"null";}return null;};JSON.decode=function(string,secure){if(!string||typeOf(string)!="string"){return null;}if(secure||JSON.secure){if(JSON.parse){return JSON.parse(string);
}if(!JSON.validate(string)){throw new Error("JSON could not decode the input; security is enabled and the value is not secure.");}}return eval("("+string+")");
};})();Request.JSON=new Class({Extends:Request,options:{secure:true},initialize:function(a){this.parent(a);Object.append(this.headers,{Accept:"application/json","X-Request":"JSON"});
},success:function(c){var b;try{b=this.response.json=JSON.decode(c,this.options.secure);}catch(a){this.fireEvent("error",[c,a]);return;}if(b==null){this.onFailure();
}else{this.onSuccess(b,c);}}});var Cookie=new Class({Implements:Options,options:{path:"/",domain:false,duration:false,secure:false,document:document,encode:true},initialize:function(b,a){this.key=b;
this.setOptions(a);},write:function(b){if(this.options.encode){b=encodeURIComponent(b);}if(this.options.domain){b+="; domain="+this.options.domain;}if(this.options.path){b+="; path="+this.options.path;
}if(this.options.duration){var a=new Date();a.setTime(a.getTime()+this.options.duration*24*60*60*1000);b+="; expires="+a.toGMTString();}if(this.options.secure){b+="; secure";
}this.options.document.cookie=this.key+"="+b;return this;},read:function(){var a=this.options.document.cookie.match("(?:^|;)\\s*"+this.key.escapeRegExp()+"=([^;]*)");
return(a)?decodeURIComponent(a[1]):null;},dispose:function(){new Cookie(this.key,Object.merge({},this.options,{duration:-1})).write("");return this;}});
Cookie.write=function(b,c,a){return new Cookie(b,a).write(c);};Cookie.read=function(a){return new Cookie(a).read();};Cookie.dispose=function(b,a){return new Cookie(b,a).dispose();
};(function(i,k){var l,f,e=[],c,b,d=k.createElement("div");var g=function(){clearTimeout(b);if(l){return;}Browser.loaded=l=true;k.removeListener("DOMContentLoaded",g).removeListener("readystatechange",a);
k.fireEvent("domready");i.fireEvent("domready");};var a=function(){for(var m=e.length;m--;){if(e[m]()){g();return true;}}return false;};var j=function(){clearTimeout(b);
if(!a()){b=setTimeout(j,10);}};k.addListener("DOMContentLoaded",g);var h=function(){try{d.doScroll();return true;}catch(m){}return false;};if(d.doScroll&&!h()){e.push(h);
c=true;}if(k.readyState){e.push(function(){var m=k.readyState;return(m=="loaded"||m=="complete");});}if("onreadystatechange" in k){k.addListener("readystatechange",a);
}else{c=true;}if(c){j();}Element.Events.domready={onAdd:function(m){if(l){m.call(this);}}};Element.Events.load={base:"load",onAdd:function(m){if(f&&this==i){m.call(this);
}},condition:function(){if(this==i){g();delete Element.Events.load;}return true;}};i.addEvent("load",function(){f=true;});})(window,document);(function(){var Swiff=this.Swiff=new Class({Implements:Options,options:{id:null,height:1,width:1,container:null,properties:{},params:{quality:"high",allowScriptAccess:"always",wMode:"window",swLiveConnect:true},callBacks:{},vars:{}},toElement:function(){return this.object;
},initialize:function(path,options){this.instance="Swiff_"+String.uniqueID();this.setOptions(options);options=this.options;var id=this.id=options.id||this.instance;
var container=document.id(options.container);Swiff.CallBacks[this.instance]={};var params=options.params,vars=options.vars,callBacks=options.callBacks;
var properties=Object.append({height:options.height,width:options.width},options.properties);var self=this;for(var callBack in callBacks){Swiff.CallBacks[this.instance][callBack]=(function(option){return function(){return option.apply(self.object,arguments);
};})(callBacks[callBack]);vars[callBack]="Swiff.CallBacks."+this.instance+"."+callBack;}params.flashVars=Object.toQueryString(vars);if(Browser.ie){properties.classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
params.movie=path;}else{properties.type="application/x-shockwave-flash";}properties.data=path;var build='<object id="'+id+'"';for(var property in properties){build+=" "+property+'="'+properties[property]+'"';
}build+=">";for(var param in params){if(params[param]){build+='<param name="'+param+'" value="'+params[param]+'" />';}}build+="</object>";this.object=((container)?container.empty():new Element("div")).set("html",build).firstChild;
},replaces:function(element){element=document.id(element,true);element.parentNode.replaceChild(this.toElement(),element);return this;},inject:function(element){document.id(element,true).appendChild(this.toElement());
return this;},remote:function(){return Swiff.remote.apply(Swiff,[this.toElement()].append(arguments));}});Swiff.CallBacks={};Swiff.remote=function(obj,fn){var rs=obj.CallFunction('<invoke name="'+fn+'" returntype="javascript">'+__flash__argumentsToXML(arguments,2)+"</invoke>");
return eval(rs);};})();
/* More */
MooTools.More={version:"1.4.0.1",build:"a4244edf2aa97ac8a196fc96082dd35af1abab87"};(function(a){Array.implement({min:function(){return Math.min.apply(null,this);
},max:function(){return Math.max.apply(null,this);},average:function(){return this.length?this.sum()/this.length:0;},sum:function(){var b=0,c=this.length;
if(c){while(c--){b+=this[c];}}return b;},unique:function(){return[].combine(this);},shuffle:function(){for(var c=this.length;c&&--c;){var b=this[c],d=Math.floor(Math.random()*(c+1));
this[c]=this[d];this[d]=b;}return this;},reduce:function(d,e){for(var c=0,b=this.length;c<b;c++){if(c in this){e=e===a?this[c]:d.call(null,e,this[c],c,this);
}}return e;},reduceRight:function(c,d){var b=this.length;while(b--){if(b in this){d=d===a?this[b]:c.call(null,d,this[b],b,this);}}return d;}});})();(function(){var b=function(c){return c!=null;
};var a=Object.prototype.hasOwnProperty;Object.extend({getFromPath:function(e,f){if(typeof f=="string"){f=f.split(".");}for(var d=0,c=f.length;d<c;d++){if(a.call(e,f[d])){e=e[f[d]];
}else{return null;}}return e;},cleanValues:function(c,e){e=e||b;for(var d in c){if(!e(c[d])){delete c[d];}}return c;},erase:function(c,d){if(a.call(c,d)){delete c[d];
}return c;},run:function(d){var c=Array.slice(arguments,1);for(var e in d){if(d[e].apply){d[e].apply(d,c);}}return d;}});})();(function(){var b=null,a={},d={};
var c=function(f){if(instanceOf(f,e.Set)){return f;}else{return a[f];}};var e=this.Locale={define:function(f,j,h,i){var g;if(instanceOf(f,e.Set)){g=f.name;
if(g){a[g]=f;}}else{g=f;if(!a[g]){a[g]=new e.Set(g);}f=a[g];}if(j){f.define(j,h,i);}if(!b){b=f;}return f;},use:function(f){f=c(f);if(f){b=f;this.fireEvent("change",f);
}return this;},getCurrent:function(){return b;},get:function(g,f){return(b)?b.get(g,f):"";},inherit:function(f,g,h){f=c(f);if(f){f.inherit(g,h);}return this;
},list:function(){return Object.keys(a);}};Object.append(e,new Events);e.Set=new Class({sets:{},inherits:{locales:[],sets:{}},initialize:function(f){this.name=f||"";
},define:function(i,g,h){var f=this.sets[i];if(!f){f={};}if(g){if(typeOf(g)=="object"){f=Object.merge(f,g);}else{f[g]=h;}}this.sets[i]=f;return this;},get:function(r,j,q){var p=Object.getFromPath(this.sets,r);
if(p!=null){var m=typeOf(p);if(m=="function"){p=p.apply(null,Array.from(j));}else{if(m=="object"){p=Object.clone(p);}}return p;}var h=r.indexOf("."),o=h<0?r:r.substr(0,h),k=(this.inherits.sets[o]||[]).combine(this.inherits.locales).include("en-US");
if(!q){q=[];}for(var g=0,f=k.length;g<f;g++){if(q.contains(k[g])){continue;}q.include(k[g]);var n=a[k[g]];if(!n){continue;}p=n.get(r,j,q);if(p!=null){return p;
}}return"";},inherit:function(g,h){g=Array.from(g);if(h&&!this.inherits.sets[h]){this.inherits.sets[h]=[];}var f=g.length;while(f--){(h?this.inherits.sets[h]:this.inherits.locales).unshift(g[f]);
}return this;}});})();Locale.define("en-US","Date",{months:["January","February","March","April","May","June","July","August","September","October","November","December"],months_abbr:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],days_abbr:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dateOrder:["month","date","year"],shortDate:"%m/%d/%Y",shortTime:"%I:%M%p",AM:"AM",PM:"PM",firstDayOfWeek:0,ordinal:function(a){return(a>3&&a<21)?"th":["th","st","nd","rd","th"][Math.min(a%10,4)];
},lessThanMinuteAgo:"less than a minute ago",minuteAgo:"about a minute ago",minutesAgo:"{delta} minutes ago",hourAgo:"about an hour ago",hoursAgo:"about {delta} hours ago",dayAgo:"1 day ago",daysAgo:"{delta} days ago",weekAgo:"1 week ago",weeksAgo:"{delta} weeks ago",monthAgo:"1 month ago",monthsAgo:"{delta} months ago",yearAgo:"1 year ago",yearsAgo:"{delta} years ago",lessThanMinuteUntil:"less than a minute from now",minuteUntil:"about a minute from now",minutesUntil:"{delta} minutes from now",hourUntil:"about an hour from now",hoursUntil:"about {delta} hours from now",dayUntil:"1 day from now",daysUntil:"{delta} days from now",weekUntil:"1 week from now",weeksUntil:"{delta} weeks from now",monthUntil:"1 month from now",monthsUntil:"{delta} months from now",yearUntil:"1 year from now",yearsUntil:"{delta} years from now"});
(function(){var a=this.Date;var f=a.Methods={ms:"Milliseconds",year:"FullYear",min:"Minutes",mo:"Month",sec:"Seconds",hr:"Hours"};["Date","Day","FullYear","Hours","Milliseconds","Minutes","Month","Seconds","Time","TimezoneOffset","Week","Timezone","GMTOffset","DayOfYear","LastMonth","LastDayOfMonth","UTCDate","UTCDay","UTCFullYear","AMPM","Ordinal","UTCHours","UTCMilliseconds","UTCMinutes","UTCMonth","UTCSeconds","UTCMilliseconds"].each(function(s){a.Methods[s.toLowerCase()]=s;
});var p=function(u,t,s){if(t==1){return u;}return u<Math.pow(10,t-1)?(s||"0")+p(u,t-1,s):u;};a.implement({set:function(u,s){u=u.toLowerCase();var t=f[u]&&"set"+f[u];
if(t&&this[t]){this[t](s);}return this;}.overloadSetter(),get:function(t){t=t.toLowerCase();var s=f[t]&&"get"+f[t];if(s&&this[s]){return this[s]();}return null;
}.overloadGetter(),clone:function(){return new a(this.get("time"));},increment:function(s,u){s=s||"day";u=u!=null?u:1;switch(s){case"year":return this.increment("month",u*12);
case"month":var t=this.get("date");this.set("date",1).set("mo",this.get("mo")+u);return this.set("date",t.min(this.get("lastdayofmonth")));case"week":return this.increment("day",u*7);
case"day":return this.set("date",this.get("date")+u);}if(!a.units[s]){throw new Error(s+" is not a supported interval");}return this.set("time",this.get("time")+u*a.units[s]());
},decrement:function(s,t){return this.increment(s,-1*(t!=null?t:1));},isLeapYear:function(){return a.isLeapYear(this.get("year"));},clearTime:function(){return this.set({hr:0,min:0,sec:0,ms:0});
},diff:function(t,s){if(typeOf(t)=="string"){t=a.parse(t);}return((t-this)/a.units[s||"day"](3,3)).round();},getLastDayOfMonth:function(){return a.daysInMonth(this.get("mo"),this.get("year"));
},getDayOfYear:function(){return(a.UTC(this.get("year"),this.get("mo"),this.get("date")+1)-a.UTC(this.get("year"),0,1))/a.units.day();},setDay:function(t,s){if(s==null){s=a.getMsg("firstDayOfWeek");
if(s===""){s=1;}}t=(7+a.parseDay(t,true)-s)%7;var u=(7+this.get("day")-s)%7;return this.increment("day",t-u);},getWeek:function(v){if(v==null){v=a.getMsg("firstDayOfWeek");
if(v===""){v=1;}}var x=this,u=(7+x.get("day")-v)%7,t=0,w;if(v==1){var y=x.get("month"),s=x.get("date")-u;if(y==11&&s>28){return 1;}if(y==0&&s<-2){x=new a(x).decrement("day",u);
u=0;}w=new a(x.get("year"),0,1).get("day")||7;if(w>4){t=-7;}}else{w=new a(x.get("year"),0,1).get("day");}t+=x.get("dayofyear");t+=6-u;t+=(7+w-v)%7;return(t/7);
},getOrdinal:function(s){return a.getMsg("ordinal",s||this.get("date"));},getTimezone:function(){return this.toString().replace(/^.*? ([A-Z]{3}).[0-9]{4}.*$/,"$1").replace(/^.*?\(([A-Z])[a-z]+ ([A-Z])[a-z]+ ([A-Z])[a-z]+\)$/,"$1$2$3");
},getGMTOffset:function(){var s=this.get("timezoneOffset");return((s>0)?"-":"+")+p((s.abs()/60).floor(),2)+p(s%60,2);},setAMPM:function(s){s=s.toUpperCase();
var t=this.get("hr");if(t>11&&s=="AM"){return this.decrement("hour",12);}else{if(t<12&&s=="PM"){return this.increment("hour",12);}}return this;},getAMPM:function(){return(this.get("hr")<12)?"AM":"PM";
},parse:function(s){this.set("time",a.parse(s));return this;},isValid:function(s){if(!s){s=this;}return typeOf(s)=="date"&&!isNaN(s.valueOf());},format:function(s){if(!this.isValid()){return"invalid date";
}if(!s){s="%x %X";}if(typeof s=="string"){s=g[s.toLowerCase()]||s;}if(typeof s=="function"){return s(this);}var t=this;return s.replace(/%([a-z%])/gi,function(v,u){switch(u){case"a":return a.getMsg("days_abbr")[t.get("day")];
case"A":return a.getMsg("days")[t.get("day")];case"b":return a.getMsg("months_abbr")[t.get("month")];case"B":return a.getMsg("months")[t.get("month")];
case"c":return t.format("%a %b %d %H:%M:%S %Y");case"d":return p(t.get("date"),2);case"e":return p(t.get("date"),2," ");case"H":return p(t.get("hr"),2);
case"I":return p((t.get("hr")%12)||12,2);case"j":return p(t.get("dayofyear"),3);case"k":return p(t.get("hr"),2," ");case"l":return p((t.get("hr")%12)||12,2," ");
case"L":return p(t.get("ms"),3);case"m":return p((t.get("mo")+1),2);case"M":return p(t.get("min"),2);case"o":return t.get("ordinal");case"p":return a.getMsg(t.get("ampm"));
case"s":return Math.round(t/1000);case"S":return p(t.get("seconds"),2);case"T":return t.format("%H:%M:%S");case"U":return p(t.get("week"),2);case"w":return t.get("day");
case"x":return t.format(a.getMsg("shortDate"));case"X":return t.format(a.getMsg("shortTime"));case"y":return t.get("year").toString().substr(2);case"Y":return t.get("year");
case"z":return t.get("GMTOffset");case"Z":return t.get("Timezone");}return u;});},toISOString:function(){return this.format("iso8601");}}).alias({toJSON:"toISOString",compare:"diff",strftime:"format"});
var k=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],h=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];var g={db:"%Y-%m-%d %H:%M:%S",compact:"%Y%m%dT%H%M%S","short":"%d %b %H:%M","long":"%B %d, %Y %H:%M",rfc822:function(s){return k[s.get("day")]+s.format(", %d ")+h[s.get("month")]+s.format(" %Y %H:%M:%S %Z");
},rfc2822:function(s){return k[s.get("day")]+s.format(", %d ")+h[s.get("month")]+s.format(" %Y %H:%M:%S %z");},iso8601:function(s){return(s.getUTCFullYear()+"-"+p(s.getUTCMonth()+1,2)+"-"+p(s.getUTCDate(),2)+"T"+p(s.getUTCHours(),2)+":"+p(s.getUTCMinutes(),2)+":"+p(s.getUTCSeconds(),2)+"."+p(s.getUTCMilliseconds(),3)+"Z");
}};var c=[],n=a.parse;var r=function(v,x,u){var t=-1,w=a.getMsg(v+"s");switch(typeOf(x)){case"object":t=w[x.get(v)];break;case"number":t=w[x];if(!t){throw new Error("Invalid "+v+" index: "+x);
}break;case"string":var s=w.filter(function(y){return this.test(y);},new RegExp("^"+x,"i"));if(!s.length){throw new Error("Invalid "+v+" string");}if(s.length>1){throw new Error("Ambiguous "+v);
}t=s[0];}return(u)?w.indexOf(t):t;};var i=1900,o=70;a.extend({getMsg:function(t,s){return Locale.get("Date."+t,s);},units:{ms:Function.from(1),second:Function.from(1000),minute:Function.from(60000),hour:Function.from(3600000),day:Function.from(86400000),week:Function.from(608400000),month:function(t,s){var u=new a;
return a.daysInMonth(t!=null?t:u.get("mo"),s!=null?s:u.get("year"))*86400000;},year:function(s){s=s||new a().get("year");return a.isLeapYear(s)?31622400000:31536000000;
}},daysInMonth:function(t,s){return[31,a.isLeapYear(s)?29:28,31,30,31,30,31,31,30,31,30,31][t];},isLeapYear:function(s){return((s%4===0)&&(s%100!==0))||(s%400===0);
},parse:function(v){var u=typeOf(v);if(u=="number"){return new a(v);}if(u!="string"){return v;}v=v.clean();if(!v.length){return null;}var s;c.some(function(w){var t=w.re.exec(v);
return(t)?(s=w.handler(t)):false;});if(!(s&&s.isValid())){s=new a(n(v));if(!(s&&s.isValid())){s=new a(v.toInt());}}return s;},parseDay:function(s,t){return r("day",s,t);
},parseMonth:function(t,s){return r("month",t,s);},parseUTC:function(t){var s=new a(t);var u=a.UTC(s.get("year"),s.get("mo"),s.get("date"),s.get("hr"),s.get("min"),s.get("sec"),s.get("ms"));
return new a(u);},orderIndex:function(s){return a.getMsg("dateOrder").indexOf(s)+1;},defineFormat:function(s,t){g[s]=t;return this;},defineParser:function(s){c.push((s.re&&s.handler)?s:l(s));
return this;},defineParsers:function(){Array.flatten(arguments).each(a.defineParser);return this;},define2DigitYearStart:function(s){o=s%100;i=s-o;return this;
}}).extend({defineFormats:a.defineFormat.overloadSetter()});var d=function(s){return new RegExp("(?:"+a.getMsg(s).map(function(t){return t.substr(0,3);
}).join("|")+")[a-z]*");};var m=function(s){switch(s){case"T":return"%H:%M:%S";case"x":return((a.orderIndex("month")==1)?"%m[-./]%d":"%d[-./]%m")+"([-./]%y)?";
case"X":return"%H([.:]%M)?([.:]%S([.:]%s)?)? ?%p? ?%z?";}return null;};var j={d:/[0-2]?[0-9]|3[01]/,H:/[01]?[0-9]|2[0-3]/,I:/0?[1-9]|1[0-2]/,M:/[0-5]?\d/,s:/\d+/,o:/[a-z]*/,p:/[ap]\.?m\.?/,y:/\d{2}|\d{4}/,Y:/\d{4}/,z:/Z|[+-]\d{2}(?::?\d{2})?/};
j.m=j.I;j.S=j.M;var e;var b=function(s){e=s;j.a=j.A=d("days");j.b=j.B=d("months");c.each(function(u,t){if(u.format){c[t]=l(u.format);}});};var l=function(u){if(!e){return{format:u};
}var s=[];var t=(u.source||u).replace(/%([a-z])/gi,function(w,v){return m(v)||w;}).replace(/\((?!\?)/g,"(?:").replace(/ (?!\?|\*)/g,",? ").replace(/%([a-z%])/gi,function(w,v){var x=j[v];
if(!x){return v;}s.push(v);return"("+x.source+")";}).replace(/\[a-z\]/gi,"[a-z\\u00c0-\\uffff;&]");return{format:u,re:new RegExp("^"+t+"$","i"),handler:function(y){y=y.slice(1).associate(s);
var v=new a().clearTime(),x=y.y||y.Y;if(x!=null){q.call(v,"y",x);}if("d" in y){q.call(v,"d",1);}if("m" in y||y.b||y.B){q.call(v,"m",1);}for(var w in y){q.call(v,w,y[w]);
}return v;}};};var q=function(s,t){if(!t){return this;}switch(s){case"a":case"A":return this.set("day",a.parseDay(t,true));case"b":case"B":return this.set("mo",a.parseMonth(t,true));
case"d":return this.set("date",t);case"H":case"I":return this.set("hr",t);case"m":return this.set("mo",t-1);case"M":return this.set("min",t);case"p":return this.set("ampm",t.replace(/\./g,""));
case"S":return this.set("sec",t);case"s":return this.set("ms",("0."+t)*1000);case"w":return this.set("day",t);case"Y":return this.set("year",t);case"y":t=+t;
if(t<100){t+=i+(t<o?100:0);}return this.set("year",t);case"z":if(t=="Z"){t="+00";}var u=t.match(/([+-])(\d{2}):?(\d{2})?/);u=(u[1]+"1")*(u[2]*60+(+u[3]||0))+this.getTimezoneOffset();
return this.set("time",this-u*60000);}return this;};a.defineParsers("%Y([-./]%m([-./]%d((T| )%X)?)?)?","%Y%m%d(T%H(%M%S?)?)?","%x( %X)?","%d%o( %b( %Y)?)?( %X)?","%b( %d%o)?( %Y)?( %X)?","%Y %b( %d%o( %X)?)?","%o %b %d %X %z %Y","%T","%H:%M( ?%p)?");
Locale.addEvent("change",function(s){if(Locale.get("Date")){b(s);}}).fireEvent("change",Locale.getCurrent());})();Date.implement({timeDiffInWords:function(a){return Date.distanceOfTimeInWords(this,a||new Date);
},timeDiff:function(f,c){if(f==null){f=new Date;}var h=((f-this)/1000).floor().abs();var e=[],a=[60,60,24,365,0],d=["s","m","h","d","y"],g,b;for(var i=0;
i<a.length;i++){if(i&&!h){break;}g=h;if((b=a[i])){g=(h%b);h=(h/b).floor();}e.unshift(g+(d[i]||""));}return e.join(c||":");}}).extend({distanceOfTimeInWords:function(b,a){return Date.getTimePhrase(((a-b)/1000).toInt());
},getTimePhrase:function(f){var d=(f<0)?"Until":"Ago";if(f<0){f*=-1;}var b={minute:60,hour:60,day:24,week:7,month:52/12,year:12,eon:Infinity};var e="lessThanMinute";
for(var c in b){var a=b[c];if(f<1.5*a){if(f>0.75*a){e=c;}break;}f/=a;e=c+"s";}f=f.round();return Date.getMsg(e+d,f).substitute({delta:f});}}).defineParsers({re:/^(?:tod|tom|yes)/i,handler:function(a){var b=new Date().clearTime();
switch(a[0]){case"tom":return b.increment();case"yes":return b.decrement();default:return b;}}},{re:/^(next|last) ([a-z]+)$/i,handler:function(e){var f=new Date().clearTime();
var b=f.getDay();var c=Date.parseDay(e[2],true);var a=c-b;if(c<=b){a+=7;}if(e[1]=="last"){a-=7;}return f.set("date",f.getDate()+a);}}).alias("timeAgoInWords","timeDiffInWords");
Locale.define("en-US","Number",{decimal:".",group:",",currency:{prefix:"$ "}});Number.implement({format:function(q){var n=this;q=q?Object.clone(q):{};var a=function(i){if(q[i]!=null){return q[i];
}return Locale.get("Number."+i);};var f=n<0,h=a("decimal"),k=a("precision"),o=a("group"),c=a("decimals");if(f){var e=a("negative")||{};if(e.prefix==null&&e.suffix==null){e.prefix="-";
}["prefix","suffix"].each(function(i){if(e[i]){q[i]=a(i)+e[i];}});n=-n;}var l=a("prefix"),p=a("suffix");if(c!==""&&c>=0&&c<=20){n=n.toFixed(c);}if(k>=1&&k<=21){n=(+n).toPrecision(k);
}n+="";var m;if(a("scientific")===false&&n.indexOf("e")>-1){var j=n.split("e"),b=+j[1];n=j[0].replace(".","");if(b<0){b=-b-1;m=j[0].indexOf(".");if(m>-1){b-=m-1;
}while(b--){n="0"+n;}n="0."+n;}else{m=j[0].lastIndexOf(".");if(m>-1){b-=j[0].length-m-1;}while(b--){n+="0";}}}if(h!="."){n=n.replace(".",h);}if(o){m=n.lastIndexOf(h);
m=(m>-1)?m:n.length;var d=n.substring(m),g=m;while(g--){if((m-g-1)%3==0&&g!=(m-1)){d=o+d;}d=n.charAt(g)+d;}n=d;}if(l){n=l+n;}if(p){n+=p;}return n;},formatCurrency:function(b){var a=Locale.get("Number.currency")||{};
if(a.scientific==null){a.scientific=false;}a.decimals=b!=null?b:(a.decimals==null?2:a.decimals);return this.format(a);},formatPercentage:function(b){var a=Locale.get("Number.percentage")||{};
if(a.suffix==null){a.suffix="%";}a.decimals=b!=null?b:(a.decimals==null?2:a.decimals);return this.format(a);}});var Asset={javascript:function(d,b){if(!b){b={};
}var a=new Element("script",{src:d,type:"text/javascript"}),e=b.document||document,c=b.onload||b.onLoad;delete b.onload;delete b.onLoad;delete b.document;
if(c){if(typeof a.onreadystatechange!="undefined"){a.addEvent("readystatechange",function(){if(["loaded","complete"].contains(this.readyState)){c.call(this);
}});}else{a.addEvent("load",c);}}return a.set(b).inject(e.head);},css:function(d,a){if(!a){a={};}var b=new Element("link",{rel:"stylesheet",media:"screen",type:"text/css",href:d});
var c=a.onload||a.onLoad,e=a.document||document;delete a.onload;delete a.onLoad;delete a.document;if(c){b.addEvent("load",c);}return b.set(a).inject(e.head);
},image:function(c,b){if(!b){b={};}var d=new Image(),a=document.id(d)||new Element("img");["load","abort","error"].each(function(e){var g="on"+e,f="on"+e.capitalize(),h=b[g]||b[f]||function(){};
delete b[f];delete b[g];d[g]=function(){if(!d){return;}if(!a.parentNode){a.width=d.width;a.height=d.height;}d=d.onload=d.onabort=d.onerror=null;h.delay(1,a,a);
a.fireEvent(e,a,1);};});d.src=a.src=c;if(d&&d.complete){d.onload.delay(1);}return a.set(b);},images:function(c,b){c=Array.from(c);var d=function(){},a=0;
b=Object.merge({onComplete:d,onProgress:d,onError:d,properties:{}},b);return new Elements(c.map(function(f,e){return Asset.image(f,Object.append(b.properties,{onload:function(){a++;
b.onProgress.call(this,a,e,f);if(a==c.length){b.onComplete();}},onerror:function(){a++;b.onError.call(this,a,e,f);if(a==c.length){b.onComplete();}}}));
}));}}; | joseluisq/uslider | assets/mootools-core-1.4.5-full-compat-yc.js | JavaScript | mit | 115,127 |
version https://git-lfs.github.com/spec/v1
oid sha256:84d2ba940af161741f3e4dce70a2cfb1a542aca54abda9b1bb6166556d1fbf8d
size 12104
| yogeshsaroya/new-cdnjs | ajax/libs/codemirror/4.4.0/mode/verilog/verilog.js | JavaScript | mit | 130 |
'use strict';
var postcss = require('postcss');
var fs = require('fs');
var path = require('path');
var fontFile = fs.readFileSync(path.resolve(__dirname, '../../packages/theme-chalk/src/icon.scss'), 'utf8');
var nodes = postcss.parse(fontFile).nodes;
var classList = [];
nodes.forEach((node) => {
var selector = node.selector || '';
var reg = new RegExp(/\.el-icon-([^:]+):before/);
var arr = selector.match(reg);
if (arr && arr[1]) {
classList.push(arr[1]);
}
});
fs.writeFile(path.resolve(__dirname, '../../examples/icon.json'), JSON.stringify(classList), () => {});
| Kingwl/element | build/bin/iconInit.js | JavaScript | mit | 588 |
Vue.mixin({
methods: {
logout() {
document.getElementById('logout-form').submit()
} // logout
} // methods
}) | PrismPrince/SSG-Poll-System | resources/assets/js/mixins/_logout.js | JavaScript | mit | 133 |
/**
* @module myModule
* @summary: This module's purpose is to:
*
* @description:
*
* Author: Justin Mooser
* Created On: 2015-05-14.
* @license Apache-2.0
*/
"use strict";
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
//specs: ['tests/e2e/*.js'],
//protractor protractor.conf.js --suite mainpage
suites: {
mainpage: ['tests/e2e/*.spec.js']
},
multiCapabilities: [{
browserName: 'firefox'
}, {
browserName: 'chrome'
}],
// This can be changed via the command line as:
// --params.login.user 'ngrocks'
params: {
login: {
user: 'protractor-br',
password: '#ng123#'
}
}
// setup the size of the window before tests start:
//onPrepare: function() {
// browser.driver.manage().window().setSize(1600, 800);
//}
}; | webinverters/ng-base | test/protractor.conf.js | JavaScript | mit | 807 |
/**
* This module is responsible for drawing an image to an enabled elements canvas element
*/
(function (cornerstone) {
"use strict";
/**
* API function to draw a standard web image (PNG, JPG) to an enabledImage
*
* @param enabledElement
* @param invalidated - true if pixel data has been invaldiated and cached rendering should not be used
*/
function renderWebImage(enabledElement, invalidated) {
if(enabledElement === undefined) {
throw "drawImage: enabledElement parameter must not be undefined";
}
var image = enabledElement.image;
if(image === undefined) {
throw "drawImage: image must be loaded before it can be drawn";
}
// get the canvas context and reset the transform
var context = enabledElement.canvas.getContext('2d');
context.setTransform(1, 0, 0, 1, 0, 0);
// clear the canvas
context.fillStyle = 'black';
context.fillRect(0,0, enabledElement.canvas.width, enabledElement.canvas.height);
// turn off image smooth/interpolation if pixelReplication is set in the viewport
if(enabledElement.viewport.pixelReplication === true) {
context.imageSmoothingEnabled = false;
context.mozImageSmoothingEnabled = false; // firefox doesn't support imageSmoothingEnabled yet
}
else {
context.imageSmoothingEnabled = true;
context.mozImageSmoothingEnabled = true;
}
// save the canvas context state and apply the viewport properties
cornerstone.setToPixelCoordinateSystem(enabledElement, context);
// if the viewport ww/wc and invert all match the initial state of the image, we can draw the image
// directly. If any of those are changed, we call renderColorImage() to apply the lut
if(enabledElement.viewport.voi.windowWidth === enabledElement.image.windowWidth &&
enabledElement.viewport.voi.windowCenter === enabledElement.image.windowCenter &&
enabledElement.viewport.invert === false)
{
context.drawImage(image.getImage(), 0, 0, image.width, image.height, 0, 0, image.width, image.height);
} else {
cornerstone.renderColorImage(enabledElement, invalidated);
}
}
// Module exports
cornerstone.rendering.webImage = renderWebImage;
cornerstone.renderWebImage = renderWebImage;
}(cornerstone)); | liyocee/cornerstone | src/rendering/renderWebImage.js | JavaScript | mit | 2,477 |
import foo from "directories_lib/foo";
import directories_lib from "directories_lib";
import { foo as other } from "./another";
export default {
name: "test/test",
foo: foo,
directories_lib: directories_lib,
other: other
};
| stealjs/steal | test/npm/directories_lib/test/test.js | JavaScript | mit | 229 |
'use strict';
var React = require('react');
var mui = require('material-ui');
var SvgIcon = mui.SvgIcon;
var ImageMusicNote = React.createClass({
displayName: 'ImageMusicNote',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z' })
);
}
});
module.exports = ImageMusicNote; | jotamaggi/react-calendar-app | node_modules/react-material-icons/icons/image/music-note.js | JavaScript | mit | 456 |
var test = require("tape");
var a = require("../");
var fixture = [ 1, 2, 3 ];
test("a.contains(array, value)", function(t){
t.strictEqual(a.contains(fixture, 1), true);
t.strictEqual(a.contains(fixture, 4), false);
t.end();
});
test("a.contains(array, array)", function(t){
t.strictEqual(a.contains(fixture, [ 1, 2 ]), true);
t.strictEqual(a.contains(fixture, [ 1, 2, 3, 4 ]), false);
t.end();
});
| Essk/FreeCodeCamp-Projects | node_modules/local-web-server/node_modules/object-tools/node_modules/array-tools/test/contains.js | JavaScript | mit | 426 |
import nodeResolve from 'rollup-plugin-node-resolve';
import uglify from 'rollup-plugin-uglify';
import progress from 'rollup-plugin-progress';
import sourcemaps from 'rollup-plugin-sourcemaps';
import visualizer from 'rollup-plugin-visualizer';
var MINIFY = process.env.MINIFY;
var ROUTER = process.env.ROUTER;
var EVENTS = process.env.EVENTS;
var RESOLVE = process.env.RESOLVE;
var pkg = require('./package.json');
var banner =
`/**
* ${pkg.description}
* @version v${pkg.version}
* @link ${pkg.homepage}
* @license MIT License, http://www.opensource.org/licenses/MIT
*/`;
var uglifyOpts = { output: {} };
// retain multiline comment with @license
uglifyOpts.output.comments = (node, comment) =>
comment.type === 'comment2' && /@license/i.test(comment.value);
var plugins = [
nodeResolve({jsnext: true}),
progress({ clearLine: false }),
sourcemaps(),
];
if (MINIFY) plugins.push(uglify(uglifyOpts));
if (ROUTER && MINIFY) plugins.push(visualizer({ sourcemap: true }));
var extension = MINIFY ? ".min.js" : ".js";
const BASE_CONFIG = {
sourceMap: true,
format: 'umd',
exports: 'named',
plugins: plugins,
banner: banner,
};
const ROUTER_CONFIG = Object.assign({
moduleName: '@uirouter/angularjs',
entry: 'lib-esm/index.js',
dest: 'release/angular-ui-router' + extension,
globals: { angular: 'angular' },
external: 'angular',
}, BASE_CONFIG);
const EVENTS_CONFIG = Object.assign({}, BASE_CONFIG, {
moduleName: '@uirouter/angularjs-state-events',
entry: 'lib-esm/legacy/stateEvents.js',
dest: 'release/stateEvents' + extension,
globals: { angular: 'angular', '@uirouter/core': '@uirouter/core' },
external: ['angular', '@uirouter/core'],
});
const RESOLVE_CONFIG = Object.assign({}, BASE_CONFIG, {
moduleName: '@uirouter/angularjs-resolve-service',
entry: 'lib-esm/legacy/resolveService.js',
dest: 'release/resolveService' + extension,
globals: { angular: 'angular', '@uirouter/core': '@uirouter/core' },
external: ['angular', '@uirouter/core'],
});
const CONFIG =
RESOLVE ? RESOLVE_CONFIG :
EVENTS ? EVENTS_CONFIG :
ROUTER ? ROUTER_CONFIG : ROUTER_CONFIG;
export default CONFIG;
| firasbarakat/node-server-template | public/bower_components/angular-ui-router/rollup.config.js | JavaScript | mit | 2,153 |
// -------------------------------------------------------------
// WARNING: this file is used by both the client and the server.
// Do not use any browser or node-specific API!
// -------------------------------------------------------------
import { Syntax } from '../tools/esotope';
import { createTempVarIdentifier, createAssignmentExprStmt, createVarDeclaration } from '../node-builder';
import replaceNode from './replace-node';
// Transform:
// for(obj[prop] in src), for(obj.prop in src) -->
// for(var __set$temp in src) { obj[prop] = __set$temp; }
export default {
nodeReplacementRequireTransform: false,
nodeTypes: [Syntax.ForInStatement],
condition: node => node.left.type === Syntax.MemberExpression,
run: node => {
var tempVarAst = createTempVarIdentifier();
var varDeclaration = createVarDeclaration(tempVarAst);
var assignmentExprStmt = createAssignmentExprStmt(node.left, tempVarAst);
replaceNode(null, assignmentExprStmt, node.body, 'body');
replaceNode(node.left, varDeclaration, node, 'left');
return null;
}
};
| georgiy-abbasov/testcafe-hammerhead | src/processing/script/transformers/for-in.js | JavaScript | mit | 1,121 |
'use strict';
/** @module */
function toEpochWithoutTime (text) {
// be sure to exclude time so we get accurate text
var dateTextWithoutTime = new Date(Date.parse(text)).toDateString();
return Date.parse(dateTextWithoutTime);
}
function sameMonth (firstEpoch, secondEpoch) {
var first = new Date(firstEpoch),
second = new Date(secondEpoch);
return first.getFullYear() === second.getFullYear() && first.getMonth() === second.getMonth();
}
/**
* Translates the distance between two dates within a month of each other to human readable text
* @param {string} thenText - The start date
* @param {string} testNowText - Ignore, used for testing purposes only.
* @returns {string}
*/
function howLongAgo (thenText, testNowText) {
var nowText = testNowText ? testNowText : new Date(Date.now()).toISOString(), // testNow is just for testing purposes
then = toEpochWithoutTime(thenText),
now = toEpochWithoutTime(nowText),
millisecondsInDay = 24 * 60 * 60 * 1000,
daysAgo = Math.floor((now - then) / millisecondsInDay);
if (daysAgo === 0) {
return 'today';
}
else if (daysAgo === 1) {
return 'yesterday';
}
else if (daysAgo < 7) {
return 'this week';
}
else if (daysAgo < 14) {
return 'last week';
}
else if (sameMonth(then, now)) {
return 'this month';
}
else {
return '';
}
}
module.exports = {
howLongAgo: howLongAgo
};
| p-equis/mountebank | src/util/date.js | JavaScript | mit | 1,489 |
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*
* Version: 5.0.16 (2019-09-24)
*/
(function () {
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var global$1 = tinymce.util.Tools.resolve('tinymce.Env');
var register = function (editor) {
editor.addCommand('mcePrint', function () {
if (global$1.ie && global$1.ie <= 11) {
editor.getDoc().execCommand('print', false, null);
} else {
editor.getWin().print();
}
});
};
var Commands = { register: register };
var register$1 = function (editor) {
editor.ui.registry.addButton('print', {
icon: 'print',
tooltip: 'Print',
onAction: function () {
return editor.execCommand('mcePrint');
}
});
editor.ui.registry.addMenuItem('print', {
text: 'Print...',
icon: 'print',
onAction: function () {
return editor.execCommand('mcePrint');
}
});
};
var Buttons = { register: register$1 };
function Plugin () {
global.add('print', function (editor) {
Commands.register(editor);
Buttons.register(editor);
editor.addShortcut('Meta+P', '', 'mcePrint');
});
}
Plugin();
}());
| extend1994/cdnjs | ajax/libs/tinymce/5.0.16/plugins/print/plugin.js | JavaScript | mit | 1,493 |
/*jshint node:true, mocha:true, expr:true*/
/**
* @author kecso / https://github.com/kecso
*/
var testFixture = require('./../_globals.js');
describe('issue110 testing', function () {
'use strict';
var gmeConfig = testFixture.getGmeConfig(),
Q = testFixture.Q,
expect = testFixture.expect,
logger = testFixture.logger.fork('issue110.spec'),
storage = null,
projectName = 'issue110test',
projectId = testFixture.projectName2Id(projectName),
gmeAuth;
before(function (done) {
testFixture.clearDBAndGetGMEAuth(gmeConfig, projectName)
.then(function (gmeAuth_) {
gmeAuth = gmeAuth_;
storage = testFixture.getMemoryStorage(logger, gmeConfig, gmeAuth);
return storage.openDatabase();
})
.then(function () {
return storage.deleteProject({projectId: projectId});
})
.nodeify(done);
});
after(function (done) {
Q.allDone([
storage.closeDatabase(),
gmeAuth.unload()
])
.nodeify(done);
});
beforeEach(function (done) {
gmeAuth.authorizeByUserId(gmeConfig.authentication.guestAccount, projectId, 'create',
{
read: true,
write: true,
delete: true
}
)
.then(function () {
return storage.deleteProject({projectId: projectId});
})
.nodeify(done);
});
it('import the problematic project', function (done) {
testFixture.importProject(storage,
{
projectSeed: './test/issue/110/input.json',
projectName: projectName,
gmeConfig: gmeConfig,
logger: logger
}, function (err, result) {
if (err) {
done(err);
return;
}
expect(result).to.contain.any.keys(['rootNode']);
expect(result).to.contain.any.keys(['core']);
done();
});
});
it('checks the ownJsonMeta of node \'specialTransition\'', function (done) {
var core,
rootHash,
root;
testFixture.importProject(storage,
{
projectSeed: './test/issue/110/input.json',
projectName: projectName,
gmeConfig: gmeConfig,
logger: logger
}, function (err, result) {
if (err) {
done(err);
return;
}
core = result.core;
rootHash = result.core.getHash(result.rootNode);
core.loadRoot(rootHash, function (err, r) {
if (err) {
return done(err);
}
root = r;
core.loadByPath(root, '/1402711366/1821421774', function (err, node) {
var meta;
if (err) {
return done(err);
}
meta = core.getOwnJsonMeta(node);
meta.pointers.should.exist;
meta.pointers.src.should.exist;
meta.pointers.src.items.should.exist;
meta.pointers.src.items.should.be.instanceof(Array);
done();
});
});
});
});
it('checks the ownJsonMeta of node \'specialState\'', function (done) {
var core,
rootHash,
root;
testFixture.importProject(storage,
{
projectSeed: './test/issue/110/input.json',
projectName: projectName,
gmeConfig: gmeConfig,
logger: logger
}, function (err, result) {
if (err) {
done(err);
return;
}
core = result.core;
rootHash = result.core.getHash(result.rootNode);
core.loadRoot(rootHash, function (err, r) {
if (err) {
return done(err);
}
root = r;
core.loadByPath(root, '/1402711366/1021878489', function (err, node) {
var meta;
if (err) {
return done(err);
}
meta = core.getOwnJsonMeta(node);
meta.aspects.should.exist;
meta.aspects.asp.should.exist;
meta.aspects.asp.should.be.instanceof(Array);
done();
});
});
});
});
}); | pillforge/webgme | test/issue/110_serialization_of_aspect_meta_rule.js | JavaScript | mit | 4,964 |
var config = require('../config')
var gulp = require('gulp')
, stylus = require('gulp-stylus')
, nib = require('nib')
, rename = require('gulp-rename')
, minifyCss = require('gulp-minify-css')
gulp.task('stylus', function(){
return gulp.src(config.entryFiles.stylus)
.on('error', function(){
console.log( 'stylus error' )
this.emit('end')
})
.pipe(stylus({use: [nib()]}))
.pipe(minifyCss({compatibility: 'ie8'}))
.pipe(rename(config.files.module + '.css'))
.pipe(gulp.dest(config.files.dist))
.pipe(gulp.dest(config.files.example+'/css'))
})
| kenCode-de/react-accordion | gulp/tasks/stylus.js | JavaScript | mit | 594 |
var util = require("util");
var choreography = require("temboo/core/choreography");
/*
ChangePassword
Changes a user's password.
*/
var ChangePassword = function(session) {
/*
Create a new instance of the ChangePassword Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/Salesforce/Passwords/ChangePassword"
ChangePassword.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new ChangePasswordResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new ChangePasswordInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the ChangePassword
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var ChangePasswordInputSet = function() {
ChangePasswordInputSet.super_.call(this);
/*
Set the value of the AccessToken input for this Choreo. ((optional, string) A valid access token retrieved during the OAuth process. This is required unless you provide the ClientID, ClientSecret, and RefreshToken to generate a new access token.)
*/
this.set_AccessToken = function(value) {
this.setInput("AccessToken", value);
}
/*
Set the value of the ClientID input for this Choreo. ((conditional, string) The Client ID provided by Salesforce. Required unless providing a valid AccessToken.)
*/
this.set_ClientID = function(value) {
this.setInput("ClientID", value);
}
/*
Set the value of the ClientSecret input for this Choreo. ((conditional, string) The Client Secret provided by Salesforce. Required unless providing a valid AccessToken.)
*/
this.set_ClientSecret = function(value) {
this.setInput("ClientSecret", value);
}
/*
Set the value of the ID input for this Choreo. ((required, string) The ID of the user whose password you want to change.)
*/
this.set_ID = function(value) {
this.setInput("ID", value);
}
/*
Set the value of the InstanceName input for this Choreo. ((required, string) The server url prefix that indicates which instance your Salesforce account is on (e.g. na1, na2, na3, etc).)
*/
this.set_InstanceName = function(value) {
this.setInput("InstanceName", value);
}
/*
Set the value of the NewPassword input for this Choreo. ((required, string) The new password.)
*/
this.set_NewPassword = function(value) {
this.setInput("NewPassword", value);
}
/*
Set the value of the RefreshToken input for this Choreo. ((conditional, string) An OAuth Refresh Token used to generate a new access token when the original token is expired. Required unless providing a valid AccessToken.)
*/
this.set_RefreshToken = function(value) {
this.setInput("RefreshToken", value);
}
}
/*
A ResultSet with methods tailored to the values returned by the ChangePassword Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var ChangePasswordResultSet = function(resultStream) {
ChangePasswordResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "ResponseStatusCode" output from this Choreo execution. ((integer) The response status code returned from Salesforce. A 204 is expected for a successful request.)
*/
this.get_ResponseStatusCode = function() {
return this.getResult("ResponseStatusCode");
}
/*
Retrieve the value for the "Response" output from this Choreo execution. (The response from Salesforce.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
/*
Retrieve the value for the "NewAccessToken" output from this Choreo execution. ((string) Contains a new AccessToken when the RefreshToken is provided.)
*/
this.get_NewAccessToken = function() {
return this.getResult("NewAccessToken");
}
}
util.inherits(ChangePassword, choreography.Choreography);
util.inherits(ChangePasswordInputSet, choreography.InputSet);
util.inherits(ChangePasswordResultSet, choreography.ResultSet);
exports.ChangePassword = ChangePassword;
/*
GetPasswordInfo
Gets information on a user's password.
*/
var GetPasswordInfo = function(session) {
/*
Create a new instance of the GetPasswordInfo Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/Salesforce/Passwords/GetPasswordInfo"
GetPasswordInfo.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new GetPasswordInfoResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new GetPasswordInfoInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the GetPasswordInfo
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var GetPasswordInfoInputSet = function() {
GetPasswordInfoInputSet.super_.call(this);
/*
Set the value of the AccessToken input for this Choreo. ((optional, string) A valid access token retrieved during the OAuth process. This is required unless you provide the ClientID, ClientSecret, and RefreshToken to generate a new access token.)
*/
this.set_AccessToken = function(value) {
this.setInput("AccessToken", value);
}
/*
Set the value of the ClientID input for this Choreo. ((conditional, string) The Client ID provided by Salesforce. Required unless providing a valid AccessToken.)
*/
this.set_ClientID = function(value) {
this.setInput("ClientID", value);
}
/*
Set the value of the ClientSecret input for this Choreo. ((conditional, string) The Client Secret provided by Salesforce. Required unless providing a valid AccessToken.)
*/
this.set_ClientSecret = function(value) {
this.setInput("ClientSecret", value);
}
/*
Set the value of the ID input for this Choreo. ((required, string) The ID of the user you're getting info for.)
*/
this.set_ID = function(value) {
this.setInput("ID", value);
}
/*
Set the value of the InstanceName input for this Choreo. ((required, string) The server url prefix that indicates which instance your Salesforce account is on (e.g. na1, na2, na3, etc).)
*/
this.set_InstanceName = function(value) {
this.setInput("InstanceName", value);
}
/*
Set the value of the RefreshToken input for this Choreo. ((conditional, string) An OAuth Refresh Token used to generate a new access token when the original token is expired. Required unless providing a valid AccessToken.)
*/
this.set_RefreshToken = function(value) {
this.setInput("RefreshToken", value);
}
/*
Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are: json (the default) and xml.)
*/
this.set_ResponseFormat = function(value) {
this.setInput("ResponseFormat", value);
}
}
/*
A ResultSet with methods tailored to the values returned by the GetPasswordInfo Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var GetPasswordInfoResultSet = function(resultStream) {
GetPasswordInfoResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. (The response from Salesforce.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
/*
Retrieve the value for the "NewAccessToken" output from this Choreo execution. ((string) Contains a new AccessToken when the RefreshToken is provided.)
*/
this.get_NewAccessToken = function() {
return this.getResult("NewAccessToken");
}
}
util.inherits(GetPasswordInfo, choreography.Choreography);
util.inherits(GetPasswordInfoInputSet, choreography.InputSet);
util.inherits(GetPasswordInfoResultSet, choreography.ResultSet);
exports.GetPasswordInfo = GetPasswordInfo;
/*
ResetPassword
Resets a user's password to new randomized password.
*/
var ResetPassword = function(session) {
/*
Create a new instance of the ResetPassword Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/Salesforce/Passwords/ResetPassword"
ResetPassword.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new ResetPasswordResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new ResetPasswordInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the ResetPassword
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var ResetPasswordInputSet = function() {
ResetPasswordInputSet.super_.call(this);
/*
Set the value of the AccessToken input for this Choreo. ((optional, string) A valid access token retrieved during the OAuth process. This is required unless you provide the ClientID, ClientSecret, and RefreshToken to generate a new access token.)
*/
this.set_AccessToken = function(value) {
this.setInput("AccessToken", value);
}
/*
Set the value of the ClientID input for this Choreo. ((conditional, string) The Client ID provided by Salesforce. Required unless providing a valid AccessToken.)
*/
this.set_ClientID = function(value) {
this.setInput("ClientID", value);
}
/*
Set the value of the ClientSecret input for this Choreo. ((conditional, string) The Client Secret provided by Salesforce. Required unless providing a valid AccessToken.)
*/
this.set_ClientSecret = function(value) {
this.setInput("ClientSecret", value);
}
/*
Set the value of the ID input for this Choreo. ((required, string) The ID of the user whos password you are resetting.)
*/
this.set_ID = function(value) {
this.setInput("ID", value);
}
/*
Set the value of the InstanceName input for this Choreo. ((required, string) The server url prefix that indicates which instance your Salesforce account is on (e.g. na1, na2, na3, etc).)
*/
this.set_InstanceName = function(value) {
this.setInput("InstanceName", value);
}
/*
Set the value of the RefreshToken input for this Choreo. ((conditional, string) An OAuth Refresh Token used to generate a new access token when the original token is expired. Required unless providing a valid AccessToken.)
*/
this.set_RefreshToken = function(value) {
this.setInput("RefreshToken", value);
}
/*
Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are: json (the default) and xml.)
*/
this.set_ResponseFormat = function(value) {
this.setInput("ResponseFormat", value);
}
}
/*
A ResultSet with methods tailored to the values returned by the ResetPassword Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var ResetPasswordResultSet = function(resultStream) {
ResetPasswordResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. (The response from Salesforce.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
/*
Retrieve the value for the "NewPassword" output from this Choreo execution. ((string) New password returned from Salesforce.)
*/
this.get_NewPassword = function() {
return this.getResult("NewPassword");
}
/*
Retrieve the value for the "NewAccessToken" output from this Choreo execution. ((string) Contains a new AccessToken when the RefreshToken is provided.)
*/
this.get_NewAccessToken = function() {
return this.getResult("NewAccessToken");
}
}
util.inherits(ResetPassword, choreography.Choreography);
util.inherits(ResetPasswordInputSet, choreography.InputSet);
util.inherits(ResetPasswordResultSet, choreography.ResultSet);
exports.ResetPassword = ResetPassword;
| rwaldron/ideino-linino-dist | node_modules/temboo/Library/Salesforce/Passwords.js | JavaScript | mit | 14,598 |
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import OpenIcon from '../svg-icons/hardware/keyboard-arrow-up';
import CloseIcon from '../svg-icons/hardware/keyboard-arrow-down';
import IconButton from '../IconButton';
function getStyles() {
return {
root: {
top: 0,
bottom: 0,
right: 4,
margin: 'auto',
position: 'absolute',
},
};
}
class CardExpandable extends Component {
static propTypes = {
closeIcon: PropTypes.node,
expanded: PropTypes.bool,
onExpanding: PropTypes.func.isRequired,
openIcon: PropTypes.node,
style: PropTypes.object,
};
static contextTypes = {
muiTheme: PropTypes.object.isRequired,
};
static defaultProps = {
closeIcon: <CloseIcon />,
openIcon: <OpenIcon />,
};
render() {
const styles = getStyles(this.props, this.context);
return (
<IconButton
style={Object.assign(styles.root, this.props.style)}
onTouchTap={this.props.onExpanding}
>
{this.props.expanded ? this.props.openIcon : this.props.closeIcon}
</IconButton>
);
}
}
export default CardExpandable;
| kittyjumbalaya/material-components-web | src/Card/CardExpandable.js | JavaScript | mit | 1,159 |
/**
* @fileoverview 管道对象集合
* @authors Tony Liang <pillar0514@163.com>
*/
define('mods/model/pipelist',function(require,exports,module){
var $ = require('lib');
var $model = require('lib/mvc/model');
var $pipe = require('mods/model/pipe');
var $channel = require('mods/channel/global');
var $delay = require('lib/kit/func/delay');
var PIPE_LIST_NAME = 'PIPE_LIST_DATA';
var PipeList = $model.extend({
defaults : {
},
events : {
'change' : 'save'
},
build : function(){
this.save = $delay(this.save, 50);
},
setEvents : function(action){
this.delegate(action);
var proxy = this.proxy();
$channel[action]('load-data', proxy('load'));
},
getPipe : function(name){
return this.get(name);
},
addPipe : function(name, pipeConf){
var that = this;
pipeConf = pipeConf || {};
pipeConf.name = name;
delete pipeConf.state;
delete pipeConf.ready;
var pipe = new $pipe(pipeConf);
pipe.on('change', function(){
that.trigger('change');
});
pipe.on('destroy', function(){
that.removePipe(name);
});
this.set(name, pipe);
return pipe;
},
removePipe : function(name){
this.remove(name);
},
getConf : function(){
var configs = {};
var data = this.get();
$.each(data, function(name, obj){
var conf = obj.get();
delete conf.data;
configs[name] = conf;
});
return configs;
},
save : function(){
var storeData = this.getConf();
try{
localStorage.setItem(PIPE_LIST_NAME, JSON.stringify(storeData));
}catch(e){
console.error('Save pipelist error:', e.message);
}
},
load : function(){
var data = {};
try{
data = localStorage.getItem(PIPE_LIST_NAME);
data = JSON.parse(data);
}catch(e){
console.error('Load pipelist error:', e.message);
}
if(!data){
data = {};
}
setTimeout(function(){
$channel.trigger('load-pipes', data);
});
}
});
module.exports = window.globalPipeList = new PipeList();
});
| tony-302/log-analysis | src/js/mods/model/pipelist.js | JavaScript | mit | 2,006 |
const SecurityExtension = Jymfony.Bundle.SecurityBundle.DependencyInjection.SecurityExtension;
const ContainerBuilder = Jymfony.Component.DependencyInjection.ContainerBuilder;
const ParameterBag = Jymfony.Component.DependencyInjection.ParameterBag.ParameterBag;
const JsDumper = Jymfony.Component.DependencyInjection.Dumper.JsDumper;
const { expect } = require('chai');
describe('[SecurityBundle] SecurityExtension', function () {
beforeEach(() => {
this.container = new ContainerBuilder(new ParameterBag({
'kernel.debug': true,
'kernel.root_dir': __dirname,
'kernel.project_dir': __dirname,
'kernel.cache_dir': __dirname + '/cache',
}));
this.extension = new SecurityExtension();
});
afterEach(() => {
this.container.compile();
const dumper = new JsDumper(this.container);
dumper.dump();
});
it('should register console command', () => {
this.extension.load([
{
firewalls: {
main: { anonymous: true },
},
},
], this.container);
expect(this.container.hasDefinition('security.command.user_password_encoder')).to.be.true;
});
});
| alekitto/jymfony | src/Bundle/SecurityBundle/test/DependencyInjection/SecurityExtensionTest.js | JavaScript | mit | 1,253 |
var inspector = require('../');
var schema = {
type: 'object',
properties: {
lorem: { type: 'string', eq: 'ipsum' },
dolor: {
type: 'array',
items: { type: 'number' }
}
}
};
var candidate = {
lorem: 'not_ipsum',
dolor: [ 12, 34, 'ERROR', 45, 'INVALID' ]
};
var result = inspector.validate(schema, candidate, function (err, result) {
console.log(result);
});
// var schema = { type: 'object', properties: { lol: { someKeys: ['pouet'] } } };
// var subject = { lol: null };
// inspector.validate(schema, subject);
| Atinux/schema-inspector | misc/node-test.js | JavaScript | mit | 533 |
var Remote = require('remote');
var App = Remote.require('app');
var React = require('react');
var SearchbarContainer = require('../searchbar/container');
var DownloadManager = require('../../../modules/DownloadManager');
var KakuCore = require('../../../modules/KakuCore');
var ToolbarContainer = React.createClass({
getInitialState: function() {
return {
downloadPercent: 0,
title: ''
};
},
componentDidMount: function() {
this.setState({
title: KakuCore.title
});
KakuCore.on('titleUpdated', (title) => {
this.setState({
title: title
});
});
DownloadManager.on('download-progress', (percent) => {
this._processDownloadProgress(percent);
});
DownloadManager.on('download-finish', () => {
this._processDownloadProgress(0);
});
DownloadManager.on('download-error', () => {
this._processDownloadProgress(0);
});
},
_onCloseButtonClick: function() {
App.quit();
},
_onShrinkButtonClick: function() {
Remote.getCurrentWindow().minimize();
},
_onEnlargeButtonClick: function() {
var win = Remote.getCurrentWindow();
if (win.isMaximized()) {
win.unmaximize();
}
else {
win.maximize();
}
},
_processDownloadProgress: function(percent) {
this.setState({
downloadPercent: percent
});
},
render: function() {
var title = this.state.title;
var downloadPercent = this.state.downloadPercent;
var progressStyle = {
width: downloadPercent + '%'
};
/* jshint ignore:start */
return (
<div className="toolbar-container clearfix">
<div className="toolbar-buttons">
<span
className="button close-button"
onClick={this._onCloseButtonClick}>
<i className="fa fa-times"></i>
</span>
<span
className="button shrink-button"
onClick={this._onShrinkButtonClick}>
<i className="fa fa-minus"></i>
</span>
<span
className="button enlarge-button"
onClick={this._onEnlargeButtonClick}>
<i className="fa fa-plus"></i>
</span>
</div>
<div className="toolbar-song-information">
{title}
</div>
<div className="searchbar-slot">
<SearchbarContainer/>
</div>
<div className="toolbar-progressbar" style={progressStyle}></div>
</div>
);
/* jshint ignore:end */
}
});
module.exports = ToolbarContainer;
| uirsevla/Kaku | src/views/components/toolbar/container.js | JavaScript | mit | 2,565 |
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
// ES6 Object.is(x,y) API extension tests -- verifies the API shape and basic functionality
WScript.LoadScriptFile("..\\UnitTestFramework\\UnitTestFramework.js");
var tests = [
{
name: "Object.assign should exist and have length 2",
body: function () {
assert.isTrue(Object.hasOwnProperty('assign'), "Object should have an assign method");
assert.areEqual(2, Object.assign.length, "assign method takes two arguments");
}
},
{
name: "Object.assign(o1, ...) should call ToObject on its sources",
body: function () {
assert.areEqual({}, Object.assign(1), "Call ToObject on target");
assert.areEqual({}, Object.assign(1, 2, 3), "Call ToObject on target and sources");
assert.areEqual({}, Object.assign({}, 2, 3), "Call ToObject on sources");
}
},
{
name: "Object.assign(object, null) and Object.assign(object, undefined) are no-op",
body: function () {
assert.areEqual({ a: 1 }, Object.assign({ a: 1 }, undefined), "Passing undefined as nextSource in assign method is a no-op");
assert.areEqual({ a: 1 }, Object.assign({ a: 1 }, null), "Passing null as nextSource in assign method is a no-op");
}
},
{
name: "Object.assign(target) returns target",
body: function () {
var o = {x:10, y:20, z:30}
assert.isTrue(o === Object.assign(o), "Object.assign(target) should return the same object");
assert.isTrue(o === Object.assign(o, { a: 1 }), "Object.assign(target, source) should return the same object");
assert.isTrue(o === Object.assign(o, { b: 2 }, { c: 3 }), "Object.assign(target, source1, source2) should return the same object");
}
},
{
name: "Object.assign({}, object) clone should work",
body: function () {
assert.areEqual({ a: 1 }, Object.assign({}, { a: 1 }), "Create a clone of a object");
assert.areEqual([1], Object.assign({}, [1]), "Create a clone of a array");
assert.areEqual(new String("hello"), Object.assign({}, new String("hello")), "Create a clone of a string");
}
},
{
name: "Object.assign(o1, o2, o3) Merging objects should work",
body: function () {
assert.areEqual({ a: 1, b: 2}, Object.assign({ a: 1 }, { b: 2 }), "Merging 2 plain objects should work");
assert.areEqual({ a: 1, b: 2, c: 3 }, Object.assign({ a: 1 }, { b: 2 }, { c: 3 }), "Merging 3 plain objects should work");
assert.areEqual({ a: 1, b: 2, c: 3, d: 4 }, Object.assign({ a: 1 }, { b: 2 }, { c: 3 }, { d: 4 }), "Merging 4 plain objects should work");
}
},
{
name: "Object.assign(o1, o2, o3) overlapping property names should preference last set",
body: function () {
assert.areEqual({ a: 2 }, Object.assign({ a: 1 }, { a: 2 }), "Merging 2 plain objects with the overlapping property name should work");
assert.areEqual({ a: 1, b: 2, c: 3, z: 3 }, Object.assign({ a: 1, z: 1 }, { b: 2, z: 2 }, { c: 3, z: 3 }), "Merging 3 plain objects with overlapping property name should work");
}
},
{
name: "Object.assign(o1, o2) throw exception if GetOwnProperty for any enumerable property in o2 if enumeration fails",
body: function () {
try
{
Object.assign({}, { get x() { throw "xyz"; } });
assert.fail("Exception is not thrown when GetOwnProperty fails");
}
catch (e)
{
}
}
},
{
name: "Object.assign(o1, o2) exception if SetProperty for any enumerable property in o2 if enumeration fails",
body: function () {
try {
Object.assign({ set x(a) { throw "xyz"; } }, { x: 10 });
assert.fail("Exception is not thrown when SetProperty fails");
}
catch (e) {
}
}
},
{
name: "Object.assign(o1, o2, o2) should work on undefined values",
body: function () {
assert.areEqual({x: undefined}, Object.assign({}, {x : 40}, { x: undefined }), "Undefined values for the property keys are propagated");
}
},
{
name: "Object.assign(o1, o2, o2) ignore non-enumerable values",
body: function () {
var o2 = { y: 40 };
Object.defineProperty(o2, "x", {value: 50, enumerable:false})
assert.areEqual({y: 40}, Object.assign({}, o2), "Non enumerable values are not ignored");
}
},
{
name: "Object.assign(Object.create(Array.prototype), o2) create pattern",
body: function () {
assert.areEqual({ x: 10, y: 40 }, Object.assign(Object.create(Array.prototype), { x: 10, y: 40 }), "Object.create pattern should work ");
}
},
{
name: "Object.assign(o1, o2) works for symbols",
body: function () {
var o2 = {};
var y = Symbol("y");
o2[y] = 10;
assert.isTrue((Object.assign({}, o2))[y] === 10, "Symbols are assigned to target object ");
}
},
{
name: "Object.assign(o1, o2) works for index properties",
body: function () {
assert.areEqual([1, 2, 3], Object.assign([], [1, 2, 3]), "Indexed properties are assigned to the target object");
}
},
{
name: "Object.assign(o1, o2) exception if SetProperty fails due to preventExtentions on o1",
body: function () {
assert.throws((function() { 'use strict'; var o = Object.preventExtensions([,0]);Object.assign(o,'xo');}), TypeError, "Invalid operand to 'Object.assign': Object expected");
}
},
{
name: "OS Bug 3080673: Object.assign(o1, o2) exception if SetProperty fails due to non-writable on o1 when o1's value is a String",
body: function () {
assert.throws((function() {
var o1 = "aaa";
var o2 = "babbb";
Object.assign(o1, o2);
}), TypeError, "Exception is not thrown when SetProperty fails", "Cannot modify non-writable property '0'");
}
},
];
testRunner.runTests(tests, { verbose: WScript.Arguments[0] != "summary" });
| arunetm/ChakraCore_0114 | test/es6/object-assign.js | JavaScript | mit | 6,868 |
'use strict';
exports.BattleItems = {
abomasite: {
inherit: true,
isUnreleased: false,
},
aggronite: {
inherit: true,
isUnreleased: false,
},
aguavberry: {
inherit: true,
onUpdate: function (pokemon) {
if (pokemon.hp <= pokemon.maxhp / 2) {
pokemon.eatItem();
}
},
onEat: function (pokemon) {
this.heal(pokemon.maxhp / 8);
if (pokemon.getNature().minus === 'spd') {
pokemon.addVolatile('confusion');
}
},
desc: "Restores 1/8 max HP at 1/2 max HP or less; confuses if -SpD Nature. Single use.",
},
altarianite: {
inherit: true,
isUnreleased: false,
},
ampharosite: {
inherit: true,
isUnreleased: false,
},
banettite: {
inherit: true,
isUnreleased: false,
},
belueberry: {
inherit: true,
isUnreleased: false,
},
bigroot: {
inherit: true,
desc: "Holder gains 1.3x HP from draining moves, Aqua Ring, Ingrain, and Leech Seed.",
},
blazikenite: {
inherit: true,
isUnreleased: false,
},
cameruptite: {
inherit: true,
isUnreleased: false,
},
cornnberry: {
inherit: true,
isUnreleased: false,
},
custapberry: {
inherit: true,
isUnreleased: false,
},
diancite: {
inherit: true,
isUnreleased: false,
},
durinberry: {
inherit: true,
isUnreleased: false,
},
enigmaberry: {
inherit: true,
isUnreleased: false,
},
figyberry: {
inherit: true,
onUpdate: function (pokemon) {
if (pokemon.hp <= pokemon.maxhp / 2) {
pokemon.eatItem();
}
},
onEat: function (pokemon) {
this.heal(pokemon.maxhp / 8);
if (pokemon.getNature().minus === 'atk') {
pokemon.addVolatile('confusion');
}
},
desc: "Restores 1/8 max HP at 1/2 max HP or less; confuses if -Atk Nature. Single use.",
},
galladite: {
inherit: true,
isUnreleased: false,
},
gardevoirite: {
inherit: true,
isUnreleased: false,
},
heracronite: {
inherit: true,
isUnreleased: false,
},
houndoominite: {
inherit: true,
isUnreleased: false,
},
iapapaberry: {
inherit: true,
onUpdate: function (pokemon) {
if (pokemon.hp <= pokemon.maxhp / 2) {
pokemon.eatItem();
}
},
onEat: function (pokemon) {
this.heal(pokemon.maxhp / 8);
if (pokemon.getNature().minus === 'def') {
pokemon.addVolatile('confusion');
}
},
desc: "Restores 1/8 max HP at 1/2 max HP or less; confuses if -Def Nature. Single use.",
},
jabocaberry: {
inherit: true,
isUnreleased: false,
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.category === 'Physical') {
if (target.eatItem()) {
this.damage(source.maxhp / 8, source, target, null, true);
}
}
},
},
latiasite: {
inherit: true,
isUnreleased: false,
},
latiosite: {
inherit: true,
isUnreleased: false,
},
lightclay: {
inherit: true,
desc: "Holder's use of Light Screen or Reflect lasts 8 turns instead of 5.",
},
lopunnite: {
inherit: true,
isUnreleased: false,
},
machobrace: {
inherit: true,
isUnreleased: false,
},
magoberry: {
inherit: true,
onUpdate: function (pokemon) {
if (pokemon.hp <= pokemon.maxhp / 2) {
pokemon.eatItem();
}
},
onEat: function (pokemon) {
this.heal(pokemon.maxhp / 8);
if (pokemon.getNature().minus === 'spe') {
pokemon.addVolatile('confusion');
}
},
desc: "Restores 1/8 max HP at 1/2 max HP or less; confuses if -Spe Nature. Single use.",
},
magostberry: {
inherit: true,
isUnreleased: false,
},
manectite: {
inherit: true,
isUnreleased: false,
},
micleberry: {
inherit: true,
isUnreleased: false,
},
nanabberry: {
inherit: true,
isUnreleased: false,
},
nomelberry: {
inherit: true,
isUnreleased: false,
},
pamtreberry: {
inherit: true,
isUnreleased: false,
},
rabutaberry: {
inherit: true,
isUnreleased: false,
},
razzberry: {
inherit: true,
isUnreleased: false,
},
rockyhelmet: {
inherit: true,
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.flags['contact']) {
this.damage(source.maxhp / 6, source, target, null, true);
}
},
},
rowapberry: {
inherit: true,
isUnreleased: false,
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.category === 'Special') {
if (target.eatItem()) {
this.damage(source.maxhp / 8, source, target, null, true);
}
}
},
},
sceptilite: {
inherit: true,
isUnreleased: false,
},
spelonberry: {
inherit: true,
isUnreleased: false,
},
swampertite: {
inherit: true,
isUnreleased: false,
},
tyranitarite: {
inherit: true,
isUnreleased: false,
},
souldew: {
id: "souldew",
name: "Soul Dew",
spritenum: 459,
fling: {
basePower: 30,
},
onModifySpAPriority: 1,
onModifySpA: function (spa, pokemon) {
if (pokemon.baseTemplate.num === 380 || pokemon.baseTemplate.num === 381) {
return this.chainModify(1.5);
}
},
onModifySpDPriority: 2,
onModifySpD: function (spd, pokemon) {
if (pokemon.baseTemplate.num === 380 || pokemon.baseTemplate.num === 381) {
return this.chainModify(1.5);
}
},
num: 225,
gen: 3,
desc: "If holder is a Latias or a Latios, its Sp. Atk and Sp. Def are 1.5x.",
},
watmelberry: {
inherit: true,
isUnreleased: false,
},
wepearberry: {
inherit: true,
isUnreleased: false,
},
wikiberry: {
inherit: true,
onUpdate: function (pokemon) {
if (pokemon.hp <= pokemon.maxhp / 2) {
pokemon.eatItem();
}
},
onEat: function (pokemon) {
this.heal(pokemon.maxhp / 8);
if (pokemon.getNature().minus === 'spa') {
pokemon.addVolatile('confusion');
}
},
desc: "Restores 1/8 max HP at 1/2 max HP or less; confuses if -SpA Nature. Single use.",
},
};
| Lord-Haji/SpacialGaze | mods/gen6/items.js | JavaScript | mit | 5,746 |
'use strict';
var React = require('react');
var mui = require('material-ui');
var SvgIcon = mui.SvgIcon;
var EditorFormatBold = React.createClass({
displayName: 'EditorFormatBold',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M15.6 10.79c.97-.67 1.65-1.77 1.65-2.79 0-2.26-1.75-4-4-4H7v14h7.04c2.09 0 3.71-1.7 3.71-3.79 0-1.52-.86-2.82-2.15-3.42zM10 6.5h3c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5h-3v-3zm3.5 9H10v-3h3.5c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5z' })
);
}
});
module.exports = EditorFormatBold; | jotamaggi/react-calendar-app | node_modules/react-material-icons/icons/editor/format-bold.js | JavaScript | mit | 606 |
// @flow
import * as React from "react";
import TopBarProgressIndicator from "react-topbar-progress-indicator";
TopBarProgressIndicator.config({
barThickness: 4,
barColors: {
"0": "#fff",
"1.0": "#fff",
},
shadowBlur: 5,
});
const devicePixelRatio =
typeof window === "undefined" ? 1 : window.devicePixelRatio || 1;
const tupleToColor = (param, alpha) => `rgba(${param.join(",")}, ${alpha})`;
type Props = {|
size: number,
color: $ReadOnlyArray<number, number, number>,
|};
class ActivityIndicator extends React.Component<Props> {
static defaultProps = {
size: 24.0,
color: [200, 200, 200],
};
componentDidMount() {
this.tick();
}
componentWillUnmount() {
cancelAnimationFrame(this.frame);
}
setCanvasRef = canvas => {
if (canvas) {
this.canvasContext = canvas.getContext("2d");
}
};
draw() {
const context = this.canvasContext;
if (!context) {
return;
}
const actualSize = this.props.size * devicePixelRatio;
context.clearRect(0.0, 0.0, actualSize, actualSize);
context.translate(actualSize / 2.0, actualSize / 2.0);
context.rotate(0.172665);
context.translate(-(actualSize / 2.0), -(actualSize / 2.0));
const centeredArc = (...args) =>
context.arc(actualSize / 2.0, actualSize / 2.0, ...args);
context.beginPath();
centeredArc(actualSize * 0.5, Math.PI, 0.0, false, context);
centeredArc(actualSize * 0.3, 0.0, Math.PI, true, context);
context.fillStyle = tupleToColor(this.props.color, 1.0);
context.fill();
context.closePath();
context.beginPath();
centeredArc(actualSize * 0.5, 0.0, Math.PI, false, context);
centeredArc(actualSize * 0.3, Math.PI, 0.0, true, context);
const gradient = context.createLinearGradient(
0.0,
actualSize * 0.5,
actualSize * 0.75,
actualSize * 0.5,
);
gradient.addColorStop(0.5, tupleToColor(this.props.color, 1.0));
gradient.addColorStop(1.0, tupleToColor(this.props.color, 0.0));
context.fillStyle = gradient;
context.fill();
}
tick = () => {
this.draw();
this.frame = requestAnimationFrame(this.tick);
};
render() {
const actualSize = this.props.size * devicePixelRatio;
return (
<React.Fragment>
<TopBarProgressIndicator />
<canvas
width={actualSize}
height={actualSize}
style={{
width: this.props.size,
height: this.props.size,
alignSelf: "center",
margin: "10px 0",
}}
ref={this.setCanvasRef}
/>
</React.Fragment>
);
}
}
export default ActivityIndicator;
| MoOx/statinamic | website/components/ActivityIndicator.js | JavaScript | mit | 2,666 |
/*eslint-disable no-console */
'use strict';
var fs = require('fs-extra');
var ng = require('../helpers/ng');
var existsSync = require('exists-sync');
var expect = require('chai').expect;
var path = require('path');
var tmp = require('../helpers/tmp');
var root = process.cwd();
var conf = require('ember-cli/tests/helpers/conf');
var Promise = require('ember-cli/lib/ext/promise');
var SilentError = require('silent-error');
describe('Acceptance: ng generate pipe', function () {
before(conf.setup);
after(conf.restore);
beforeEach(function () {
return tmp.setup('./tmp').then(function () {
process.chdir('./tmp');
}).then(function () {
return ng(['new', 'foo', '--skip-npm', '--skip-bower']);
});
});
afterEach(function () {
this.timeout(10000);
return tmp.teardown('./tmp');
});
it('ng generate pipe my-pipe', function () {
return ng(['generate', 'pipe', 'my-pipe']).then(() => {
var testPath = path.join(root, 'tmp', 'foo', 'src', 'app', 'my-pipe.pipe.ts');
expect(existsSync(testPath)).to.equal(true);
});
});
it('ng generate pipe test' + path.sep + 'my-pipe', function () {
fs.mkdirsSync(path.join(root, 'tmp', 'foo', 'src', 'app', 'test'));
return ng(['generate', 'pipe', 'test' + path.sep + 'my-pipe']).then(() => {
var testPath = path.join(root, 'tmp', 'foo', 'src', 'app', 'test', 'my-pipe.pipe.ts');
expect(existsSync(testPath)).to.equal(true);
});
});
it('ng generate pipe test' + path.sep + '..' + path.sep + 'my-pipe', function () {
return ng(['generate', 'pipe', 'test' + path.sep + '..' + path.sep + 'my-pipe']).then(() => {
var testPath = path.join(root, 'tmp', 'foo', 'src', 'app', 'my-pipe.pipe.ts');
expect(existsSync(testPath)).to.equal(true);
});
});
it('ng generate pipe my-pipe from a child dir', () => {
fs.mkdirsSync(path.join(root, 'tmp', 'foo', 'src', 'app', '1'));
return new Promise(function (resolve) {
process.chdir('./src');
resolve();
})
.then(() => process.chdir('./app'))
.then(() => process.chdir('./1'))
.then(() => {
process.env.CWD = process.cwd();
return ng(['generate', 'pipe', 'my-pipe'])
})
.then(() => {
var testPath = path.join(root, 'tmp', 'foo', 'src', 'app', '1', 'my-pipe.pipe.ts');
expect(existsSync(testPath)).to.equal(true);
}, err => console.log('ERR: ', err));
});
it('ng generate pipe child-dir' + path.sep + 'my-pipe from a child dir', () => {
fs.mkdirsSync(path.join(root, 'tmp', 'foo', 'src', 'app', '1', 'child-dir'));
return new Promise(function (resolve) {
process.chdir('./src');
resolve();
})
.then(() => process.chdir('./app'))
.then(() => process.chdir('./1'))
.then(() => {
process.env.CWD = process.cwd();
return ng(['generate', 'pipe', 'child-dir' + path.sep + 'my-pipe'])
})
.then(() => {
var testPath = path.join(
root, 'tmp', 'foo', 'src', 'app', '1', 'child-dir', 'my-pipe.pipe.ts');
expect(existsSync(testPath)).to.equal(true);
}, err => console.log('ERR: ', err));
});
it('ng generate pipe child-dir' + path.sep + '..' + path.sep + 'my-pipe from a child dir', () => {
fs.mkdirsSync(path.join(root, 'tmp', 'foo', 'src', 'app', '1'));
return new Promise(function (resolve) {
process.chdir('./src');
resolve();
})
.then(() => process.chdir('./app'))
.then(() => process.chdir('./1'))
.then(() => {
process.env.CWD = process.cwd();
return ng(['generate', 'pipe', 'child-dir' + path.sep + '..' + path.sep + 'my-pipe'])
})
.then(() => {
var testPath = path.join(root, 'tmp', 'foo', 'src', 'app', '1', 'my-pipe.pipe.ts');
expect(existsSync(testPath)).to.equal(true);
}, err => console.log('ERR: ', err));
});
it('ng generate pipe ' + path.sep + 'my-pipe from a child dir, gens under ' +
path.join('src', 'app'),
() => {
fs.mkdirsSync(path.join(root, 'tmp', 'foo', 'src', 'app', '1'));
return new Promise(function (resolve) {
process.chdir('./src');
resolve();
})
.then(() => process.chdir('./app'))
.then(() => process.chdir('./1'))
.then(() => {
process.env.CWD = process.cwd();
return ng(['generate', 'pipe', path.sep + 'my-pipe'])
})
.then(() => {
var testPath = path.join(root, 'tmp', 'foo', 'src', 'app', 'my-pipe.pipe.ts');
expect(existsSync(testPath)).to.equal(true);
}, err => console.log('ERR: ', err));
});
it('ng generate pipe ..' + path.sep + 'my-pipe from root dir will fail', () => {
return ng(['generate', 'pipe', '..' + path.sep + 'my-pipe']).then(() => {
throw new SilentError(`ng generate pipe ..${path.sep}my-pipe from root dir should fail.`);
}, (err) => {
expect(err).to.equal(`Invalid path: "..${path.sep}my-pipe" cannot be above the "src${path.sep}app" directory`);
});
});
});
| cironunes/angular-cli | tests/acceptance/generate-pipe.spec.js | JavaScript | mit | 5,065 |
"use strict";
var utils = require('../../../src/packages/dom');
describe("SirTrevor.Submittable", function() {
var submittable;
var formTemplate = "<form><input type='submit' value='Go!'></form>";
beforeEach(function() {
submittable = new SirTrevor.Submittable(utils.createDocumentFragmentFromString(formTemplate));
});
describe("submitBtn", function() {
it("should be an input btn", function() {
expect(submittable.submitBtns[0].nodeName).toBe("INPUT");
});
});
describe("submitBtnTitles", function() {
it("has the initial title for the submitBtn", function() {
expect(submittable.submitBtnTitles).toContain("Go!");
});
});
describe("_disableSubmitButton", function() {
beforeEach(function(){
submittable._disableSubmitButton();
});
it("should set a disabled attribute", function() {
expect(submittable.submitBtns[0].getAttribute('disabled')).toBe('disabled');
});
it("should set a disabled class", function() {
expect(submittable.submitBtns[0].classList.contains('disabled')).toBe(true);
});
});
describe("_enableSubmitButton", function() {
beforeEach(function(){
submittable._disableSubmitButton();
submittable._enableSubmitButton();
});
it("shouldn't set a disabled attribute", function() {
expect(submittable.submitBtns[0].getAttribute('disabled')).toBe(null);
});
it("shouldn't have a disabled class", function() {
expect(submittable.submitBtns[0].classList.contains('disabled')).toBe(false);
});
});
describe("setSubmitButton", function() {
it("Adds the title provided", function() {
submittable.setSubmitButton(null, "YOLO");
expect(submittable.submitBtns[0].value).toBe('YOLO');
});
});
describe("resetSubmitButton", function() {
beforeEach(function() {
submittable.setSubmitButton(null, "YOLO");
submittable.resetSubmitButton();
});
it("should reset the title back to its previous state", function() {
expect(submittable.submitBtns[0].value).toContain("Go!");
});
});
});
| madebymany/sir-trevor-js | spec/javascripts/units/submittable.spec.js | JavaScript | mit | 2,119 |
var assert = require('assert'),
error = require('../../../lib/error/index'),
math = require('../../../index'),
approx = require('../../../tools/approx'),
pi = math.pi,
atanh = math.atanh,
tanh = math.tanh,
complex = math.complex,
matrix = math.matrix,
unit = math.unit,
bigmath = math.create({number: 'bignumber', precision: 20}),
biggermath = math.create({precision: 21}),
atanhBig = bigmath.atanh,
Big = bigmath.bignumber;
describe('atanh', function() {
it('should return the hyperbolic arctan of a boolean', function () {
assert.equal(atanh(true), Infinity);
assert.equal(atanh(false), 0);
});
it('should return the hyperbolic arctan of null', function () {
assert.equal(atanh(null), 0);
});
it('should return the hyperbolic arctan of a number', function() {
approx.deepEqual(atanh(-2), complex(-0.54930614433405485, pi / 2));
approx.deepEqual(atanh(2), complex(0.54930614433405485, -pi / 2));
//assert.ok(isNaN(atanh(-2)));
//assert.ok(isNaN(atanh(2)));
approx.equal(atanh(-1), -Infinity);
approx.equal(atanh(-0.5), -0.54930614433405484569762261846);
approx.equal(atanh(0), 0);
approx.equal(atanh(0.5), 0.54930614433405484569762261846);
approx.equal(atanh(1), Infinity);
});
it('should return the hyperbolic arctan of a bignumber', function() {
var arg1 = Big(-1);
var arg2 = Big(-0.5);
assert.deepEqual(atanhBig(arg1), Big(-Infinity));
assert.deepEqual(atanhBig(arg2), Big('-0.5493061443340548457'));
assert.deepEqual(atanhBig(Big(0)), Big(0));
assert.deepEqual(atanhBig(Big(0.5)), Big('0.5493061443340548457'));
assert.deepEqual(atanhBig(Big(1)), Big(Infinity));
//Make sure arg was not changed
assert.deepEqual(arg1, Big(-1));
assert.deepEqual(arg2, Big(-0.5));
});
it('should be the inverse function of hyperbolic tan', function() {
approx.equal(atanh(tanh(-1)), -1);
approx.equal(atanh(tanh(0)), 0);
approx.equal(atanh(tanh(0.1)), 0.1);
approx.equal(atanh(tanh(0.5)), 0.5);
});
it('should be the inverse function of bignumber tanh', function() {
assert.deepEqual(atanhBig(bigmath.tanh(Big(-0.5))), Big(-0.5));
assert.deepEqual(atanhBig(bigmath.tanh(Big(0))), Big(0));
assert.deepEqual(atanhBig(bigmath.tanh(Big(0.5))), Big(0.5));
/* Pass in more digits to pi. */
var arg = Big(-1);
assert.deepEqual(atanhBig(biggermath.tanh(arg)), Big(-1));
assert.deepEqual(atanhBig(biggermath.tanh(Big(0.1))), Big(0.1));
assert.deepEqual(arg, Big(-1));
});
it('should throw an error if the bignumber result is complex', function() {
assert.throws(function () {
atanh(Big(1.1));
}, /atanh() only has non-complex values for |x| <= 1./);
assert.throws(function () {
atanh(Big(-1.1));
}, /atanh() only has non-complex values for |x| <= 1./);
});
it('should return the arctanh of a complex number', function() {
approx.deepEqual(atanh(complex('2+3i')), complex(0.1469466662255, 1.33897252229449));
approx.deepEqual(atanh(complex('2-3i')), complex(0.1469466662255, -1.33897252229449));
approx.deepEqual(atanh(complex('-2+3i')), complex(-0.1469466662255, 1.33897252229449));
approx.deepEqual(atanh(complex('-2-3i')), complex(-0.1469466662255, -1.33897252229449));
approx.deepEqual(atanh(complex('1+i')), complex(0.402359478108525, 1.01722196789785137));
approx.deepEqual(atanh(complex('i')), complex(0, pi / 4));
approx.deepEqual(atanh(complex('2')), complex(0.54930614433405485, -pi / 2));
assert.deepEqual(atanh(complex('1')), complex(Infinity, 0));
assert.deepEqual(atanh(complex('0')), complex(0, 0));
approx.deepEqual(atanh(complex('-2')), complex(-0.54930614433405485, pi / 2));
});
it('should throw an error if called with a unit', function() {
assert.throws(function () {atanh(unit('45deg'))});
assert.throws(function () {atanh(unit('5 celsius'))});
});
it('should throw an error if called with a string', function() {
assert.throws(function () {atanh('string')});
});
it('should calculate the arctan element-wise for arrays and matrices', function() {
var atanh101 = [-Infinity, 0, Infinity];
assert.deepEqual(atanh([-1,0,1]), atanh101);
assert.deepEqual(atanh(matrix([-1,0,1])), matrix(atanh101));
});
it('should throw an error in case of invalid number of arguments', function() {
assert.throws(function () {atanh()}, error.ArgumentsError);
assert.throws(function () {atanh(1, 2)}, error.ArgumentsError);
});
});
| jeslopcru/code-refactoring-course | class6/ejercicio/mathjs-solucion/test/function/trigonometry/atanh.test.js | JavaScript | mit | 4,567 |
import {
action,
createType,
createAsyncTypes,
APP,
BOOK,
SLOT,
} from 'helpers/actions';
const type = base => createType(APP, BOOK, SLOT, base);
const asyncType = base => createAsyncTypes(type(base));
export const INIT = asyncType('INIT');
export const INVALIDATE_PARENTS = asyncType('INVALIDATE_PARENTS');
export const INVALIDATE_CHILDREN = asyncType('INVALIDATE_CHILDREN');
export const init = {
invoke: id => action(INIT.INVOKE, { id }),
success: slot => action(INIT.SUCCESS, { slot }),
failure: error => action(INIT.FAILURE, { error }),
};
export const invalidateParents = {
invoke: () => action(INVALIDATE_PARENTS.INVOKE),
success: parents => action(INVALIDATE_PARENTS.SUCCESS, { parents }),
};
export const invalidateChildren = {
invoke: () => action(INVALIDATE_CHILDREN.INVOKE),
success: children => action(INVALIDATE_CHILDREN.SUCCESS, { children }),
};
| Apozhidaev/ergonode | src/store/app/book/currentSlot/actions.js | JavaScript | mit | 895 |
// Karma configuration
// Generated on Mon Jan 20 2014 05:41:33 GMT-0500 (EST)
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '../../..',
// frameworks to use
frameworks: ['mocha'],
// list of files / patterns to load in the browser
files: [
'http://cdn.sencha.io/touch/sencha-touch-2.1.0/sencha-touch-all.js',
'build/deft-debug.js',
'test/lib/chai-1.8.1/chai.js',
'test/lib/sinon-1.7.3/sinon.js',
'test/lib/sinon-chai-2.4.0/sinon-chai.js',
'test/lib/sinon-sencha-1.0.0/sinon-sencha.js',
'test/support/browser.js',
'test/support/custom-assertions.js',
'test/lib/mocha-as-promised-2.0.0/mocha-as-promised.js',
'test/lib/chai-as-promised-4.1.0/chai-as-promised.js',
'test/js/custom-assertions.js',
'test/js/util/Function.js',
'test/js/log/Logger.js',
'test/js/ioc/Injector.js',
'test/js/mixin/Injectable.js',
'test/js/mixin/Controllable.js',
'test/js/mvc/ViewController.js',
'test/lib/promises-aplus-tests-2.0.3/promises-aplus-tests.js',
'test/js/promise/Promise.js',
'test/js/promise/Chain.js'
],
// list of files to exclude
exclude: [
],
preprocessors: {
'build/deft-debug.js': ['coverage']
},
coverageReporter: {
type: 'html',
dir: 'test/coverage/touch/2.1.0'
},
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['dots'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
browsers: ['Chrome'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
| bentrm/DeftJS | test/karma/touch/2.1.0.conf.js | JavaScript | mit | 2,465 |
(function () {
"use strict";
var config = require('./config.js');
var app =config.initApp();
var router = config.initRouter(app);
require('./rutas/index.js')(router);
app.listen(3000);
}()); | AcademiaBinaria/NodeJS | 12 mongodb/practica/req/tienda.js | JavaScript | mit | 201 |
Error.stackTraceLimit = Infinity;
var acorn = require("../src/index")
var pp = acorn.Parser.prototype
var tt = acorn.tokTypes
pp.isRelational = function (op) {
return this.type === tt.relational && this.value === op
}
pp.expectRelational = function (op) {
if (this.isRelational(op)) {
this.next()
} else {
this.unexpected()
}
}
pp.flow_parseTypeInitialiser = function (tok) {
var oldInType = this.inType
this.inType = true
this.expect(tok || tt.colon)
var type = this.flow_parseType()
this.inType = oldInType
return type;
}
pp.flow_parseDeclareClass = function (node) {
this.next()
this.flow_parseInterfaceish(node, true)
return this.finishNode(node, "DeclareClass")
}
pp.flow_parseDeclareFunction = function (node) {
this.next()
var id = node.id = this.parseIdent()
var typeNode = this.startNode()
var typeContainer = this.startNode()
if (this.isRelational("<")) {
typeNode.typeParameters = this.flow_parseTypeParameterDeclaration()
} else {
typeNode.typeParameters = null
}
this.expect(tt.parenL)
var tmp = this.flow_parseFunctionTypeParams()
typeNode.params = tmp.params
typeNode.rest = tmp.rest
this.expect(tt.parenR)
typeNode.returnType = this.flow_parseTypeInitialiser()
typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation")
id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation")
this.finishNode(id, id.type)
this.semicolon()
return this.finishNode(node, "DeclareFunction")
}
pp.flow_parseDeclare = function (node) {
if (this.type === tt._class) {
return this.flow_parseDeclareClass(node)
} else if (this.type === tt._function) {
return this.flow_parseDeclareFunction(node)
} else if (this.type === tt._var) {
return this.flow_parseDeclareVariable(node)
} else if (this.isContextual("module")) {
return this.flow_parseDeclareModule(node)
} else {
this.unexpected()
}
}
pp.flow_parseDeclareVariable = function (node) {
this.next()
node.id = this.flow_parseTypeAnnotatableIdentifier()
this.semicolon()
return this.finishNode(node, "DeclareVariable")
}
pp.flow_parseDeclareModule = function (node) {
this.next()
if (this.type === tt.string) {
node.id = this.parseExprAtom()
} else {
node.id = this.parseIdent()
}
var bodyNode = node.body = this.startNode()
var body = bodyNode.body = []
this.expect(tt.braceL)
while (this.type !== tt.braceR) {
var node2 = this.startNode()
// todo: declare check
this.next()
body.push(this.flow_parseDeclare(node2))
}
this.expect(tt.braceR)
this.finishNode(bodyNode, "BlockStatement")
return this.finishNode(node, "DeclareModule")
}
// Interfaces
pp.flow_parseInterfaceish = function (node, allowStatic) {
node.id = this.parseIdent()
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration()
} else {
node.typeParameters = null
}
node.extends = []
if (this.eat(tt._extends)) {
do {
node.extends.push(this.flow_parseInterfaceExtends())
} while(this.eat(tt.comma))
}
node.body = this.flow_parseObjectType(allowStatic)
}
pp.flow_parseInterfaceExtends = function () {
var node = this.startNode()
node.id = this.parseIdent()
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterInstantiation()
} else {
node.typeParameters = null
}
return this.finishNode(node, "InterfaceExtends")
}
pp.flow_parseInterface = function (node) {
this.flow_parseInterfaceish(node, false)
return this.finishNode(node, "InterfaceDeclaration")
}
// Type aliases
pp.flow_parseTypeAlias = function (node) {
node.id = this.parseIdent()
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration()
} else {
node.typeParameters = null
}
node.right = this.flow_parseTypeInitialiser(tt.eq)
this.semicolon()
return this.finishNode(node, "TypeAlias")
}
// Type annotations
pp.flow_parseTypeParameterDeclaration = function () {
var node = this.startNode()
node.params = []
this.expectRelational("<")
while (!this.isRelational(">")) {
node.params.push(this.flow_parseTypeAnnotatableIdentifier())
if (!this.isRelational(">")) {
this.expect(tt.comma)
}
}
this.expectRelational(">")
return this.finishNode(node, "TypeParameterDeclaration")
}
pp.flow_parseTypeParameterInstantiation = function () {
var node = this.startNode(), oldInType = this.inType
node.params = []
this.inType = true
this.expectRelational("<")
while (!this.isRelational(">")) {
node.params.push(this.flow_parseType())
if (!this.isRelational(">")) {
this.expect(tt.comma)
}
}
this.expectRelational(">")
this.inType = oldInType
return this.finishNode(node, "TypeParameterInstantiation")
}
pp.flow_parseObjectPropertyKey = function () {
return (this.type === tt.num || this.type === tt.string) ? this.parseExprAtom() : this.parseIdent(true)
}
pp.flow_parseObjectTypeIndexer = function (node, isStatic) {
node.static = isStatic
this.expect(tt.bracketL)
node.id = this.flow_parseObjectPropertyKey()
node.key = this.flow_parseTypeInitialiser()
this.expect(tt.bracketR)
node.value = this.flow_parseTypeInitialiser()
this.flow_objectTypeSemicolon()
return this.finishNode(node, "ObjectTypeIndexer")
}
pp.flow_parseObjectTypeMethodish = function (node) {
node.params = []
node.rest = null
node.typeParameters = null
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration()
}
this.expect(tt.parenL)
while (this.type === tt.name) {
node.params.push(this.flow_parseFunctionTypeParam())
if (this.type !== tt.parenR) {
this.expect(tt.comma)
}
}
if (this.eat(tt.ellipsis)) {
node.rest = this.flow_parseFunctionTypeParam()
}
this.expect(tt.parenR)
node.returnType = this.flow_parseTypeInitialiser()
return this.finishNode(node, "FunctionTypeAnnotation")
}
pp.flow_parseObjectTypeMethod = function (start, isStatic, key) {
var node = this.startNodeAt(start)
node.value = this.flow_parseObjectTypeMethodish(this.startNodeAt(start))
node.static = isStatic
node.key = key
node.optional = false
this.flow_objectTypeSemicolon()
return this.finishNode(node, "ObjectTypeProperty")
}
pp.flow_parseObjectTypeCallProperty = function (node, isStatic) {
var valueNode = this.startNode()
node.static = isStatic
node.value = this.flow_parseObjectTypeMethodish(valueNode)
this.flow_objectTypeSemicolon()
return this.finishNode(node, "ObjectTypeCallProperty")
}
pp.flow_parseObjectType = function (allowStatic) {
var nodeStart = this.startNode()
var node
var optional = false
var property
var propertyKey
var propertyTypeAnnotation
var token
var isStatic
nodeStart.callProperties = []
nodeStart.properties = []
nodeStart.indexers = []
this.expect(tt.braceL)
while (this.type !== tt.braceR) {
var start = this.markPosition()
node = this.startNode()
if (allowStatic && this.isContextual("static")) {
this.next()
isStatic = true
}
if (this.type === tt.bracketL) {
nodeStart.indexers.push(this.flow_parseObjectTypeIndexer(node, isStatic))
} else if (this.type === tt.parenL || this.isRelational("<")) {
nodeStart.callProperties.push(this.flow_parseObjectTypeCallProperty(node, allowStatic))
} else {
if (isStatic && this.type === tt.colon) {
propertyKey = this.parseIdent()
} else {
propertyKey = this.flow_parseObjectPropertyKey()
}
if (this.isRelational("<") || this.type === tt.parenL) {
// This is a method property
nodeStart.properties.push(this.flow_parseObjectTypeMethod(start, isStatic, propertyKey))
} else {
if (this.eat(tt.question)) {
optional = true
}
node.key = propertyKey
node.value = this.flow_parseTypeInitialiser()
node.optional = optional
node.static = isStatic
this.flow_objectTypeSemicolon()
nodeStart.properties.push(this.finishNode(node, "ObjectTypeProperty"))
}
}
}
this.expect(tt.braceR)
return this.finishNode(nodeStart, "ObjectTypeAnnotation")
}
pp.flow_objectTypeSemicolon = function () {
if (!this.eat(tt.semi) && !this.eat(tt.comma) && this.type !== tt.braceR) {
this.unexpected()
}
}
pp.flow_parseGenericType = function (start, id) {
var node = this.startNodeAt(start)
node.typeParameters = null
node.id = id
while (this.eat(tt.dot)) {
var node2 = this.startNodeAt(start)
node2.qualification = node.id
node2.id = this.parseIdent()
node.id = this.finishNode(node2, "QualifiedTypeIdentifier")
}
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterInstantiation()
}
return this.finishNode(node, "GenericTypeAnnotation")
}
pp.flow_parseTypeofType = function () {
var node = this.startNode()
this.expect(tt._typeof)
node.argument = this.flow_parsePrimaryType()
return this.finishNode(node, "TypeofTypeAnnotation")
}
pp.flow_parseTupleType = function () {
var node = this.startNode()
node.types = []
this.expect(tt.bracketL)
// We allow trailing commas
while (this.pos < this.input.length && this.type !== tt.bracketR) {
node.types.push(this.flow_parseType())
if (this.type === tt.bracketR) break
this.expect(tt.comma)
}
this.expect(tt.bracketR)
return this.finishNode(node, "TupleTypeAnnotation")
}
pp.flow_parseFunctionTypeParam = function () {
var optional = false
var node = this.startNode()
node.name = this.parseIdent()
if (this.eat(tt.question)) {
optional = true
}
node.optional = optional
node.typeAnnotation = this.flow_parseTypeInitialiser()
return this.finishNode(node, "FunctionTypeParam")
}
pp.flow_parseFunctionTypeParams = function () {
var ret = { params: [], rest: null }
while (this.type === tt.name) {
ret.params.push(this.flow_parseFunctionTypeParam())
if (this.type !== tt.parenR) {
this.expect(tt.comma)
}
}
if (this.eat(tt.ellipsis)) {
ret.rest = this.flow_parseFunctionTypeParam()
}
return ret
}
pp.flow_identToTypeAnnotation = function (start, node, id) {
switch (id.name) {
case "any":
return this.finishNode(node, "AnyTypeAnnotation")
case "void":
return this.finishNode(node, "VoidTypeAnnotation")
case "bool":
case "boolean":
return this.finishNode(node, "BooleanTypeAnnotation")
case "mixed":
return this.finishNode(node, "MixedTypeAnnotation")
case "number":
return this.finishNode(node, "NumberTypeAnnotation")
case "string":
return this.finishNode(node, "StringTypeAnnotation")
default:
return this.flow_parseGenericType(start, id)
}
}
// The parsing of types roughly parallels the parsing of expressions, and
// primary types are kind of like primary expressions...they're the
// primitives with which other types are constructed.
pp.flow_parsePrimaryType = function () {
var typeIdentifier = null
var params = null
var returnType = null
var start = this.markPosition()
var node = this.startNode()
var rest = null
var tmp
var typeParameters
var token
var type
var isGroupedType = false
switch (this.type) {
case tt.name:
return this.flow_identToTypeAnnotation(start, node, this.parseIdent())
case tt.braceL:
return this.flow_parseObjectType()
case tt.bracketL:
return this.flow_parseTupleType()
case tt.relational:
if (this.value === "<") {
node.typeParameters = this.flow_parseTypeParameterDeclaration()
this.expect(tt.parenL)
tmp = this.flow_parseFunctionTypeParams()
node.params = tmp.params
node.rest = tmp.rest
this.expect(tt.parenR)
this.expect(tt.arrow)
node.returnType = this.flow_parseType()
return this.finishNode(node, "FunctionTypeAnnotation")
}
case tt.parenL:
this.next()
// Check to see if this is actually a grouped type
if (this.type !== tt.parenR && this.type !== tt.ellipsis) {
if (this.type === tt.name) {
var token = this.lookahead().type
isGroupedType = token !== tt.question && token !== tt.colon
} else {
isGroupedType = true
}
}
if (isGroupedType) {
type = this.flow_parseType()
this.expect(tt.parenR)
// If we see a => next then someone was probably confused about
// function types, so we can provide a better error message
if (this.eat(tt.arrow)) {
this.raise(node,
"Unexpected token =>. It looks like " +
"you are trying to write a function type, but you ended up " +
"writing a grouped type followed by an =>, which is a syntax " +
"error. Remember, function type parameters are named so function " +
"types look like (name1: type1, name2: type2) => returnType. You " +
"probably wrote (type1) => returnType"
)
}
return type
}
tmp = this.flow_parseFunctionTypeParams()
node.params = tmp.params
node.rest = tmp.rest
this.expect(tt.parenR)
this.expect(tt.arrow)
node.returnType = this.flow_parseType()
node.typeParameters = null
return this.finishNode(node, "FunctionTypeAnnotation")
case tt.string:
node.value = this.value
node.raw = this.input.slice(this.start, this.end)
this.next()
return this.finishNode(node, "StringLiteralTypeAnnotation")
default:
if (this.type.keyword === "typeof") {
return this.flow_parseTypeofType()
}
}
this.unexpected()
}
pp.flow_parsePostfixType = function () {
var node = this.startNode()
var type = node.elementType = this.flow_parsePrimaryType()
if (this.type === tt.bracketL) {
this.expect(tt.bracketL)
this.expect(tt.bracketR)
return this.finishNode(node, "ArrayTypeAnnotation")
}
return type
}
pp.flow_parsePrefixType = function () {
var node = this.startNode()
if (this.eat(tt.question)) {
node.typeAnnotation = this.flow_parsePrefixType()
return this.finishNode(node, "NullableTypeAnnotation")
}
return this.flow_parsePostfixType()
}
pp.flow_parseIntersectionType = function () {
var node = this.startNode()
var type = this.flow_parsePrefixType()
node.types = [type]
while (this.eat(tt.bitwiseAND)) {
node.types.push(this.flow_parsePrefixType())
}
return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation")
}
pp.flow_parseUnionType = function () {
var node = this.startNode()
var type = this.flow_parseIntersectionType()
node.types = [type]
while (this.eat(tt.bitwiseOR)) {
node.types.push(this.flow_parseIntersectionType())
}
return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation")
}
pp.flow_parseType = function () {
var oldInType = this.inType
this.inType = true
var type = this.flow_parseUnionType()
this.inType = oldInType
return type
}
pp.flow_parseTypeAnnotation = function () {
var node = this.startNode()
node.typeAnnotation = this.flow_parseTypeInitialiser()
return this.finishNode(node, "TypeAnnotation")
}
pp.flow_parseTypeAnnotatableIdentifier = function (requireTypeAnnotation, canBeOptionalParam) {
var node = this.startNode()
var ident = this.parseIdent()
var isOptionalParam = false
if (canBeOptionalParam && this.eat(tt.question)) {
this.expect(tt.question)
isOptionalParam = true
}
if (requireTypeAnnotation || this.type === tt.colon) {
ident.typeAnnotation = this.flow_parseTypeAnnotation()
this.finishNode(ident, ident.type)
}
if (isOptionalParam) {
ident.optional = true
this.finishNode(ident, ident.type)
}
return ident
}
acorn.plugins.flow = function (instance) {
// function name(): string {}
instance.extend("parseFunctionBody", function (inner) {
return function (node, allowExpression) {
if (this.type === tt.colon) {
node.returnType = this.flow_parseTypeAnnotation()
}
return inner.call(this, node, allowExpression)
}
})
instance.extend("parseStatement", function (inner) {
return function(declaration, topLevel) {
// strict mode handling of `interface` since it's a reserved word
if (this.strict && this.type === tt.name && this.value === "interface") {
var node = this.startNode()
this.next()
return this.flow_parseInterface(node)
} else {
return inner.call(this, declaration, topLevel)
}
}
})
instance.extend("parseExpressionStatement", function (inner) {
return function (node, expr) {
if (expr.type === "Identifier") {
if (expr.name === "declare") {
if (this.type === tt._class || this.type === tt.name || this.type === tt._function || this.type === tt._var) {
return this.flow_parseDeclare(node)
}
} else if (this.type === tt.name) {
if (expr.name === "interface") {
return this.flow_parseInterface(node)
} else if (expr.name === "type") {
return this.flow_parseTypeAlias(node)
}
}
}
return inner.call(this, node, expr)
}
})
instance.extend("shouldParseExportDeclaration", function (inner) {
return function () {
return this.isContextual("type") || inner.call(this)
}
})
instance.extend("parseParenItem", function (inner) {
return function (node, start) {
if (this.type === tt.colon) {
var typeCastNode = this.startNodeAt(start)
typeCastNode.expression = node
typeCastNode.typeAnnotation = this.flow_parseTypeAnnotation()
return this.finishNode(typeCastNode, "TypeCastExpression")
} else {
return node
}
}
})
instance.extend("parseClassId", function (inner) {
return function (node, isStatement) {
inner.call(this, node, isStatement)
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration()
}
}
})
// don't consider `void` to be a keyword as then it'll use the void token type
// and set startExpr
instance.extend("isKeyword", function (inner) {
return function(name) {
if (this.inType && name === "void") {
return false
} else {
return inner.call(this, name)
}
}
})
instance.extend("readToken", function (inner) {
return function(code) {
if (this.inType && (code === 62 || code === 60)) {
return this.finishOp(tt.relational, 1)
} else {
return inner.call(this, code)
}
}
})
instance.extend("jsx_readToken", function (inner) {
return function () {
if (!this.inType) return inner.call(this)
}
})
instance.extend("parseParenArrowList", function (inner) {
return function (start, exprList, isAsync) {
for (var i = 0; i < exprList.length; i++) {
var listItem = exprList[i]
if (listItem.type === "TypeCastExpression") {
var expr = listItem.expression
expr.typeAnnotation = listItem.typeAnnotation
exprList[i] = expr
}
}
return inner.call(this, start, exprList, isAsync)
}
})
instance.extend("parseClassProperty", function (inner) {
return function (node) {
if (this.type === tt.colon) {
node.typeAnnotation = this.flow_parseTypeAnnotation()
}
return inner.call(this, node)
}
})
instance.extend("isClassProperty", function (inner) {
return function () {
return this.type === tt.colon || inner.call(this)
}
})
instance.extend("parseClassMethod", function (inner) {
return function (classBody, method, isGenerator, isAsync) {
var typeParameters
if (this.isRelational("<")) {
typeParameters = this.flow_parseTypeParameterDeclaration()
}
method.value = this.parseMethod(isGenerator, isAsync)
method.value.typeParameters = typeParameters
classBody.body.push(this.finishNode(method, "MethodDefinition"))
}
})
instance.extend("parseClassSuper", function (inner) {
return function (node, isStatement) {
inner.call(this, node, isStatement)
if (node.superClass && this.isRelational("<")) {
node.superTypeParameters = this.flow_parseTypeParameterInstantiation()
}
if (this.isContextual("implements")) {
this.next()
var implemented = node.implements = []
do {
var node = this.startNode()
node.id = this.parseIdent()
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterInstantiation()
} else {
node.typeParameters = null
}
implemented.push(this.finishNode(node, "ClassImplements"))
} while(this.eat(tt.comma))
}
}
})
instance.extend("parseObjPropValue", function (inner) {
return function (prop) {
var typeParameters
if (this.isRelational("<")) {
typeParameters = this.flow_parseTypeParameterDeclaration()
if (this.type !== tt.parenL) this.unexpected()
}
inner.apply(this, arguments)
prop.value.typeParameters = typeParameters
}
})
instance.extend("parseAssignableListItemTypes", function (inner) {
return function (param) {
if (this.eat(tt.question)) {
param.optional = true
}
if (this.type === tt.colon) {
param.typeAnnotation = this.flow_parseTypeAnnotation()
}
this.finishNode(param, param.type)
return param
}
})
instance.extend("parseImportSpecifiers", function (inner) {
return function (node) {
node.isType = false
if (this.isContextual("type")) {
var start = this.markPosition()
var typeId = this.parseIdent()
if ((this.type === tt.name && this.value !== "from") || this.type === tt.braceL || this.type === tt.star) {
node.isType = true
} else {
node.specifiers.push(this.parseImportSpecifierDefault(typeId, start))
if (this.isContextual("from")) return
this.eat(tt.comma)
}
}
inner.call(this, node)
}
})
// function foo<T>() {}
instance.extend("parseFunctionParams", function (inner) {
return function (node) {
if (this.isRelational("<")) {
node.typeParameters = this.flow_parseTypeParameterDeclaration()
}
inner.call(this, node)
}
})
// var foo: string = bar
instance.extend("parseVarHead", function (inner) {
return function (decl) {
inner.call(this, decl)
if (this.type === tt.colon) {
decl.id.typeAnnotation = this.flow_parseTypeAnnotation()
this.finishNode(decl.id, decl.id.type)
}
}
})
}
| samccone/babel | src/acorn/plugins/flow.js | JavaScript | mit | 22,991 |
'use strict';
/* global describe, it */
const assert = require('assert');
const app = require('../../../index');
describe('AuthController', () => {
it('should exist', () => {
assert(app.api.controllers['AuthController']);
});
});
| wbprice/okcandidate-platform | test/integration/controllers/AuthController.test.js | JavaScript | mit | 248 |
// This file is part of Indico.
// Copyright (C) 2002 - 2021 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.
import createBookingURL from 'indico-url:rb.create_booking';
import fetchEventsURL from 'indico-url:rb.events';
import searchRoomsURL from 'indico-url:rb.search_rooms';
import fetchSuggestionsURL from 'indico-url:rb.suggestions';
import fetchTimelineURL from 'indico-url:rb.timeline';
import {indicoAxios, handleAxiosError} from 'indico/utils/axios';
import {ajaxAction, submitFormAction} from 'indico/utils/redux';
import {openModal} from '../../actions';
import {validateFilters} from '../../common/filters';
import {roomSearchActionsFactory, ajaxRules as ajaxFilterRules} from '../../common/roomSearch';
import {selectors as userSelectors} from '../../common/user';
import {preProcessParameters} from '../../util';
import {ajax as ajaxRules} from './serializers';
// Booking creation
export const CREATE_BOOKING_REQUEST = 'bookRoom/CREATE_BOOKING_REQUEST';
export const CREATE_BOOKING_SUCCESS = 'bookRoom/CREATE_BOOKING_SUCCESS';
export const CREATE_BOOKING_FAILED = 'bookRoom/CREATE_BOOKING_FAILED';
// Checking availability of room
export const GET_BOOKING_AVAILABILITY_REQUEST = 'bookRoom/GET_BOOKING_AVAILABILITY_REQUEST';
export const GET_BOOKING_AVAILABILITY_SUCCESS = 'bookRoom/GET_BOOKING_AVAILABILITY_SUCCESS';
export const GET_BOOKING_AVAILABILITY_ERROR = 'bookRoom/GET_BOOKING_AVAILABILITY_ERROR';
export const RESET_BOOKING_AVAILABILITY = 'bookRoom/RESET_BOOKING_AVAILABILITY';
export const SET_BOOKING_AVAILABILITY = 'bookRoom/SET_BOOKING_AVAILABILITY';
// Timeline
export const TOGGLE_TIMELINE_VIEW = 'bookRoom/TOGGLE_TIMELINE_VIEW';
export const INIT_TIMELINE = 'bookRoom/INIT_TIMELINE';
export const ADD_TIMELINE_ROOMS = 'bookRoom/ADD_TIMELINE_ROOMS';
export const GET_TIMELINE_REQUEST = 'bookRoom/GET_TIMELINE_REQUEST';
export const GET_TIMELINE_SUCCESS = 'bookRoom/GET_TIMELINE_SUCCESS';
export const GET_TIMELINE_ERROR = 'bookRoom/GET_TIMELINE_ERROR';
export const TIMELINE_RECEIVED = 'bookRoom/TIMELINE_RECEIVED';
export const SET_TIMELINE_MODE = 'bookRoom/SET_TIMELINE_MODE';
export const SET_TIMELINE_DATE = 'bookRoom/SET_TIMELINE_DATE';
// Unavailable room list
export const GET_UNAVAILABLE_TIMELINE_REQUEST = 'bookRoom/GET_UNAVAILABLE_TIMELINE_REQUEST';
export const GET_UNAVAILABLE_TIMELINE_SUCCESS = 'bookRoom/GET_UNAVAILABLE_TIMELINE_SUCCESS';
export const GET_UNAVAILABLE_TIMELINE_ERROR = 'bookRoom/GET_UNAVAILABLE_TIMELINE_ERROR';
export const UNAVAILABLE_TIMELINE_RECEIVED = 'bookRoom/UNAVAILABLE_TIMELINE_RECEIVED';
export const SET_UNAVAILABLE_NAV_MODE = 'bookRoom/SET_UNAVAILABLE_NAV_MODE';
export const SET_UNAVAILABLE_NAV_DATE = 'bookRoom/SET_UNAVAILABLE_NAV_DATE';
export const INIT_UNAVAILABLE_TIMELINE = 'bookRoom/INIT_UNAVAILABLE_TIMELINE';
// Suggestions
export const FETCH_SUGGESTIONS_REQUEST = 'bookRoom/FETCH_SUGGESTIONS_REQUEST';
export const FETCH_SUGGESTIONS_SUCCESS = 'bookRoom/FETCH_SUGGESTIONS_SUCCESS';
export const FETCH_SUGGESTIONS_ERROR = 'bookRoom/FETCH_SUGGESTIONS_ERROR';
export const SUGGESTIONS_RECEIVED = 'bookRoom/SUGGESTIONS_RECEIVED';
export const RESET_SUGGESTIONS = 'bookRoom/RESET_SUGGESTIONS';
// Related events
export const FETCH_RELATED_EVENTS_REQUEST = 'bookRoom/FETCH_RELATED_EVENTS_REQUEST';
export const FETCH_RELATED_EVENTS_SUCCESS = 'bookRoom/FETCH_RELATED_EVENTS_SUCCESS';
export const FETCH_RELATED_EVENTS_ERROR = 'bookRoom/FETCH_RELATED_EVENTS_ERROR';
export const RELATED_EVENTS_RECEIVED = 'bookRoom/RELATED_EVENTS_RECEIVED';
export const RESET_RELATED_EVENTS = 'bookRoom/RESET_RELATED_EVENTS';
export function createBooking(args, isAdminOverrideEnabled) {
const params = preProcessParameters(args, ajaxRules);
if (isAdminOverrideEnabled) {
params.admin_override_enabled = true;
}
return submitFormAction(
() => indicoAxios.post(createBookingURL(), params),
CREATE_BOOKING_REQUEST,
CREATE_BOOKING_SUCCESS,
CREATE_BOOKING_FAILED
);
}
export function resetBookingAvailability() {
return {type: RESET_BOOKING_AVAILABILITY};
}
export function fetchBookingAvailability(room, filters) {
return async (dispatch, getStore) => {
const store = getStore();
const {dates, timeSlot, recurrence} = filters;
const params = preProcessParameters({dates, timeSlot, recurrence}, ajaxFilterRules);
if (userSelectors.isUserAdminOverrideEnabled(store)) {
params.admin_override_enabled = true;
}
return await ajaxAction(
() => indicoAxios.get(fetchTimelineURL({room_id: room.id}), {params}),
GET_BOOKING_AVAILABILITY_REQUEST,
[SET_BOOKING_AVAILABILITY, GET_BOOKING_AVAILABILITY_SUCCESS],
GET_BOOKING_AVAILABILITY_ERROR
)(dispatch);
};
}
export function fetchUnavailableRooms(filters) {
return async (dispatch, getStore) => {
dispatch({type: GET_UNAVAILABLE_TIMELINE_REQUEST});
const store = getStore();
const isAdminOverrideEnabled = userSelectors.isUserAdminOverrideEnabled(store);
const searchParams = preProcessParameters(filters, ajaxFilterRules);
searchParams.unavailable = true;
if (isAdminOverrideEnabled) {
searchParams.admin_override_enabled = true;
}
let response;
try {
response = await indicoAxios.get(searchRoomsURL(), {params: searchParams});
} catch (error) {
const message = handleAxiosError(error);
dispatch({type: GET_UNAVAILABLE_TIMELINE_ERROR, error: message});
return;
}
const roomIds = response.data.rooms;
const {dates, timeSlot, recurrence} = filters;
const timelineParams = preProcessParameters({dates, timeSlot, recurrence}, ajaxFilterRules);
if (isAdminOverrideEnabled) {
timelineParams.admin_override_enabled = true;
}
return await ajaxAction(
() => indicoAxios.post(fetchTimelineURL(), {room_ids: roomIds}, {params: timelineParams}),
null,
[UNAVAILABLE_TIMELINE_RECEIVED, GET_UNAVAILABLE_TIMELINE_SUCCESS],
GET_UNAVAILABLE_TIMELINE_ERROR
)(dispatch);
};
}
export function initTimeline(roomIds, dates, timeSlot, recurrence) {
return {
type: INIT_TIMELINE,
params: {dates, timeSlot, recurrence},
roomIds,
};
}
export function addTimelineRooms(roomIds) {
return {
type: ADD_TIMELINE_ROOMS,
roomIds,
};
}
export function fetchTimeline() {
const PER_PAGE = 20;
return async (dispatch, getStore) => {
const store = getStore();
const {
bookRoom: {
timeline: {
data: {params: stateParams, roomIds: stateRoomIds, availability: stateAvailability},
},
},
} = store;
const params = preProcessParameters(stateParams, ajaxFilterRules);
if (userSelectors.isUserAdminOverrideEnabled(store)) {
params.admin_override_enabled = true;
}
const numFetchedIds = stateAvailability.length;
const roomIds = stateRoomIds.slice(numFetchedIds, numFetchedIds + PER_PAGE);
if (!roomIds.length) {
console.warn('Tried to fetch timeline for zero rooms');
return Promise.reject();
}
return await ajaxAction(
() => indicoAxios.post(fetchTimelineURL(), {room_ids: roomIds}, {params}),
GET_TIMELINE_REQUEST,
[TIMELINE_RECEIVED, GET_TIMELINE_SUCCESS],
GET_TIMELINE_ERROR
)(dispatch);
};
}
export function toggleTimelineView(visible) {
return {type: TOGGLE_TIMELINE_VIEW, visible};
}
export function fetchRoomSuggestions() {
return async (dispatch, getStore) => {
const {
bookRoom: {filters},
} = getStore();
if (!validateFilters(filters, 'bookRoom', dispatch)) {
return;
}
const params = preProcessParameters(filters, ajaxFilterRules);
return await ajaxAction(
() => indicoAxios.get(fetchSuggestionsURL(), {params}),
FETCH_SUGGESTIONS_REQUEST,
[SUGGESTIONS_RECEIVED, FETCH_SUGGESTIONS_SUCCESS],
FETCH_SUGGESTIONS_ERROR
)(dispatch);
};
}
export function resetRoomSuggestions() {
return {type: RESET_SUGGESTIONS};
}
export const {searchRooms} = roomSearchActionsFactory('bookRoom');
export const openBookRoom = (roomId, data = null) => openModal('book-room', roomId, data);
export const openUnavailableRooms = () => openModal('unavailable-rooms');
export const openBookingForm = (roomId, data) => openModal('booking-form', roomId, data);
export function setTimelineDate(date) {
return {type: SET_TIMELINE_DATE, date};
}
export function setTimelineMode(mode) {
return {type: SET_TIMELINE_MODE, mode};
}
export function setUnavailableNavDate(date) {
return {type: SET_UNAVAILABLE_NAV_DATE, date};
}
export function setUnavailableNavMode(mode) {
return {type: SET_UNAVAILABLE_NAV_MODE, mode};
}
export function initUnavailableTimeline(selectedDate, mode) {
return {type: INIT_UNAVAILABLE_TIMELINE, selectedDate, mode};
}
export function fetchRelatedEvents(filters) {
const {dates, timeSlot, recurrence} = filters;
const params = preProcessParameters({dates, timeSlot, recurrence}, ajaxFilterRules);
return ajaxAction(
() => indicoAxios.get(fetchEventsURL(), {params}),
FETCH_RELATED_EVENTS_REQUEST,
[RELATED_EVENTS_RECEIVED, FETCH_RELATED_EVENTS_SUCCESS],
FETCH_RELATED_EVENTS_ERROR
);
}
export function resetRelatedEvents() {
return {type: RESET_RELATED_EVENTS};
}
| pferreir/indico | indico/modules/rb/client/js/modules/bookRoom/actions.js | JavaScript | mit | 9,361 |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.normalizeCoreJSOption = normalizeCoreJSOption;
exports.default = normalizeOptions;
exports.validateUseBuiltInsOption = exports.validateModulesOption = exports.validateIgnoreBrowserslistConfig = exports.validateBoolOption = exports.validateConfigPathOption = exports.checkDuplicateIncludeExcludes = exports.normalizePluginName = void 0;
var _data = _interopRequireDefault(require("core-js-compat/data"));
var _invariant = _interopRequireDefault(require("invariant"));
var _semver = require("semver");
var _corejs2BuiltIns = _interopRequireDefault(require("../data/corejs2-built-ins.json"));
var _plugins = _interopRequireDefault(require("../data/plugins.json"));
var _moduleTransformations = _interopRequireDefault(require("./module-transformations"));
var _options = require("./options");
var _getPlatformSpecificDefault = require("./polyfills/corejs2/get-platform-specific-default");
var _targetsParser = require("./targets-parser");
var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const validateTopLevelOptions = options => {
const validOptions = Object.keys(_options.TopLevelOptions);
for (const option in options) {
if (!_options.TopLevelOptions[option]) {
throw new Error(`Invalid Option: ${option} is not a valid top-level option.
Maybe you meant to use '${(0, _utils.findSuggestion)(validOptions, option)}'?`);
}
}
};
const allPluginsList = Object.keys(_plugins.default);
const modulePlugins = ["proposal-dynamic-import", ...Object.keys(_moduleTransformations.default).map(m => _moduleTransformations.default[m])];
const getValidIncludesAndExcludes = (type, corejs) => new Set([...allPluginsList, ...(type === "exclude" ? modulePlugins : []), ...(corejs ? corejs == 2 ? [...Object.keys(_corejs2BuiltIns.default), ..._getPlatformSpecificDefault.defaultWebIncludes] : Object.keys(_data.default) : [])]);
const pluginToRegExp = plugin => {
if (plugin instanceof RegExp) return plugin;
try {
return new RegExp(`^${normalizePluginName(plugin)}$`);
} catch (e) {
return null;
}
};
const selectPlugins = (regexp, type, corejs) => Array.from(getValidIncludesAndExcludes(type, corejs)).filter(item => regexp instanceof RegExp && regexp.test(item));
const flatten = array => [].concat(...array);
const expandIncludesAndExcludes = (plugins = [], type, corejs) => {
if (plugins.length === 0) return [];
const selectedPlugins = plugins.map(plugin => selectPlugins(pluginToRegExp(plugin), type, corejs));
const invalidRegExpList = plugins.filter((p, i) => selectedPlugins[i].length === 0);
(0, _invariant.default)(invalidRegExpList.length === 0, `Invalid Option: The plugins/built-ins '${invalidRegExpList.join(", ")}' passed to the '${type}' option are not
valid. Please check data/[plugin-features|built-in-features].js in babel-preset-env`);
return flatten(selectedPlugins);
};
const normalizePluginName = plugin => plugin.replace(/^(@babel\/|babel-)(plugin-)?/, "");
exports.normalizePluginName = normalizePluginName;
const checkDuplicateIncludeExcludes = (include = [], exclude = []) => {
const duplicates = include.filter(opt => exclude.indexOf(opt) >= 0);
(0, _invariant.default)(duplicates.length === 0, `Invalid Option: The plugins/built-ins '${duplicates.join(", ")}' were found in both the "include" and
"exclude" options.`);
};
exports.checkDuplicateIncludeExcludes = checkDuplicateIncludeExcludes;
const normalizeTargets = targets => {
if ((0, _targetsParser.isBrowsersQueryValid)(targets)) {
return {
browsers: targets
};
}
return Object.assign({}, targets);
};
const validateConfigPathOption = (configPath = process.cwd()) => {
(0, _invariant.default)(typeof configPath === "string", `Invalid Option: The configPath option '${configPath}' is invalid, only strings are allowed.`);
return configPath;
};
exports.validateConfigPathOption = validateConfigPathOption;
const validateBoolOption = (name, value, defaultValue) => {
if (typeof value === "undefined") {
value = defaultValue;
}
if (typeof value !== "boolean") {
throw new Error(`Preset env: '${name}' option must be a boolean.`);
}
return value;
};
exports.validateBoolOption = validateBoolOption;
const validateIgnoreBrowserslistConfig = ignoreBrowserslistConfig => validateBoolOption(_options.TopLevelOptions.ignoreBrowserslistConfig, ignoreBrowserslistConfig, false);
exports.validateIgnoreBrowserslistConfig = validateIgnoreBrowserslistConfig;
const validateModulesOption = (modulesOpt = _options.ModulesOption.auto) => {
(0, _invariant.default)(_options.ModulesOption[modulesOpt.toString()] || _options.ModulesOption[modulesOpt.toString()] === _options.ModulesOption.false, `Invalid Option: The 'modules' option must be one of \n` + ` - 'false' to indicate no module processing\n` + ` - a specific module type: 'commonjs', 'amd', 'umd', 'systemjs'` + ` - 'auto' (default) which will automatically select 'false' if the current\n` + ` process is known to support ES module syntax, or "commonjs" otherwise\n`);
return modulesOpt;
};
exports.validateModulesOption = validateModulesOption;
const validateUseBuiltInsOption = (builtInsOpt = false) => {
(0, _invariant.default)(_options.UseBuiltInsOption[builtInsOpt.toString()] || _options.UseBuiltInsOption[builtInsOpt.toString()] === _options.UseBuiltInsOption.false, `Invalid Option: The 'useBuiltIns' option must be either
'false' (default) to indicate no polyfill,
'"entry"' to indicate replacing the entry polyfill, or
'"usage"' to import only used polyfills per file`);
return builtInsOpt;
};
exports.validateUseBuiltInsOption = validateUseBuiltInsOption;
function normalizeCoreJSOption(corejs, useBuiltIns) {
let proposals = false;
let rawVersion;
if (useBuiltIns && corejs === undefined) {
rawVersion = 2;
console.warn("\nWARNING: We noticed you're using the `useBuiltIns` option without declaring a " + "core-js version. Currently, we assume version 2.x when no version " + "is passed. Since this default version will likely change in future " + "versions of Babel, we recommend explicitly setting the core-js version " + "you are using via the `corejs` option.\n" + "\nYou should also be sure that the version you pass to the `corejs` " + "option matches the version specified in your `package.json`'s " + "`dependencies` section. If it doesn't, you need to run one of the " + "following commands:\n\n" + " npm install --save core-js@2 npm install --save core-js@3\n" + " yarn add core-js@2 yarn add core-js@3\n");
} else if (typeof corejs === "object" && corejs !== null) {
rawVersion = corejs.version;
proposals = Boolean(corejs.proposals);
} else {
rawVersion = corejs;
}
const version = rawVersion ? (0, _semver.coerce)(String(rawVersion)) : false;
if (!useBuiltIns && version) {
console.log("\nThe `corejs` option only has an effect when the `useBuiltIns` option is not `false`\n");
}
if (useBuiltIns && (!version || version.major < 2 || version.major > 3)) {
throw new RangeError("Invalid Option: The version passed to `corejs` is invalid. Currently, " + "only core-js@2 and core-js@3 are supported.");
}
return {
version,
proposals
};
}
function normalizeOptions(opts) {
validateTopLevelOptions(opts);
const useBuiltIns = validateUseBuiltInsOption(opts.useBuiltIns);
const corejs = normalizeCoreJSOption(opts.corejs, useBuiltIns);
const include = expandIncludesAndExcludes(opts.include, _options.TopLevelOptions.include, !!corejs.version && corejs.version.major);
const exclude = expandIncludesAndExcludes(opts.exclude, _options.TopLevelOptions.exclude, !!corejs.version && corejs.version.major);
checkDuplicateIncludeExcludes(include, exclude);
const shippedProposals = validateBoolOption(_options.TopLevelOptions.shippedProposals, opts.shippedProposals, false) || corejs.proposals;
return {
configPath: validateConfigPathOption(opts.configPath),
corejs,
debug: validateBoolOption(_options.TopLevelOptions.debug, opts.debug, false),
include,
exclude,
forceAllTransforms: validateBoolOption(_options.TopLevelOptions.forceAllTransforms, opts.forceAllTransforms, false),
ignoreBrowserslistConfig: validateIgnoreBrowserslistConfig(opts.ignoreBrowserslistConfig),
loose: validateBoolOption(_options.TopLevelOptions.loose, opts.loose, false),
modules: validateModulesOption(opts.modules),
shippedProposals,
spec: validateBoolOption(_options.TopLevelOptions.spec, opts.spec, false),
targets: normalizeTargets(opts.targets),
useBuiltIns: useBuiltIns
};
} | gusortiz/code_challenges | node_modules/@babel/preset-env/lib/normalize-options.js | JavaScript | mit | 8,771 |
// Morris.js Charts sample data for SB Admin template
$(function() {
// Area Chart
Morris.Area({
element: 'morris-area-chart',
data: [{
estacion: '2016-04-27 15:00:00',
min: 5.0,
pro: 0.7,
max: 0.8
}, {
estacion: '2016-04-27 15:00:30',
min: 5.5,
pro: 0.4,
max: 0.7
}, {
estacion: '2016-04-27 15:01:00',
min: 5,
pro: 0.5,
max: 0.7
}, {
estacion: '2016-04-27 15:01:30',
min: 4.4,
pro: 0.7,
max: 0.9
}, {
estacion: '2016-04-27 15:02:00',
min: 3.6,
pro: 0.7,
max: 0.8
}, {
estacion: '2016-04-27 15:02:30',
min: 2.8,
pro: 0.6,
max: 0.8
}, {
estacion: '2016-04-27 15:03:00',
min: 2,
pro: 0.8,
max: 0.7
}, {
estacion: '2016-04-27 15:03:30',
min: 1.4,
pro: 0.6,
max: 0.7
}, {
estacion: '2016-04-27 15:04:00',
min: 1,
pro: 0.5,
max: 0.7
}, {
estacion: '2016-04-27 15:04:30',
min: 0.8,
pro: 0.7,
max: 0.8
}, {
estacion: '2016-04-27 15:05:00',
min: 0,
pro: 0.5,
max: 0.7
}],
xkey: 'estacion',
ykeys: ['min', 'pro', 'max'],
labels: ['Maximo', 'Promedio', 'Minimo'],
pointSize: 3,
hideHover: 'auto',
resize: true
});
});
| renenoeluv/gestion-costas | plantilla/js/plugins/morris/morris-data.js | JavaScript | mit | 1,712 |
/*!
* OOUI v0.41.3
* https://www.mediawiki.org/wiki/OOUI
*
* Copyright 2011–2021 OOUI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2021-03-12T21:47:47Z
*/
( function ( OO ) {
'use strict';
/**
* An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
* Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
* of the actions.
*
* Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
* Please see the [OOUI documentation on MediaWiki] [1] for more information
* and examples.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Action_sets
*
* @class
* @extends OO.ui.ButtonWidget
* @mixins OO.ui.mixin.PendingElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
* @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
* should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
* for more information about setting modes.
* @cfg {boolean} [framed=false] Render the action button with a frame
*/
OO.ui.ActionWidget = function OoUiActionWidget( config ) {
// Configuration initialization
config = $.extend( { framed: false }, config );
// Parent constructor
OO.ui.ActionWidget.super.call( this, config );
// Mixin constructors
OO.ui.mixin.PendingElement.call( this, config );
// Properties
this.action = config.action || '';
this.modes = config.modes || [];
this.width = 0;
this.height = 0;
// Initialization
this.$element.addClass( 'oo-ui-actionWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
/* Methods */
/**
* Check if the action is configured to be available in the specified `mode`.
*
* @param {string} mode Name of mode
* @return {boolean} The action is configured with the mode
*/
OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
return this.modes.indexOf( mode ) !== -1;
};
/**
* Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
*
* @return {string}
*/
OO.ui.ActionWidget.prototype.getAction = function () {
return this.action;
};
/**
* Get the symbolic name of the mode or modes for which the action is configured to be available.
*
* The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
* Only actions that are configured to be available in the current mode will be visible.
* All other actions are hidden.
*
* @return {string[]}
*/
OO.ui.ActionWidget.prototype.getModes = function () {
return this.modes.slice();
};
/* eslint-disable no-unused-vars */
/**
* ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that
* comprise them.
* Actions can be made available for specific contexts (modes) and circumstances
* (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
*
* ActionSets contain two types of actions:
*
* - Special: Special actions are the first visible actions with special flags, such as 'safe' and
* 'primary', the default special flags. Additional special flags can be configured in subclasses
* with the static #specialFlags property.
* - Other: Other actions include all non-special visible actions.
*
* See the [OOUI documentation on MediaWiki][1] for more information.
*
* @example
* // Example: An action set used in a process dialog
* function MyProcessDialog( config ) {
* MyProcessDialog.super.call( this, config );
* }
* OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
* MyProcessDialog.static.title = 'An action set in a process dialog';
* MyProcessDialog.static.name = 'myProcessDialog';
* // An action set that uses modes ('edit' and 'help' mode, in this example).
* MyProcessDialog.static.actions = [
* {
* action: 'continue',
* modes: 'edit',
* label: 'Continue',
* flags: [ 'primary', 'progressive' ]
* },
* { action: 'help', modes: 'edit', label: 'Help' },
* { modes: 'edit', label: 'Cancel', flags: 'safe' },
* { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
* ];
*
* MyProcessDialog.prototype.initialize = function () {
* MyProcessDialog.super.prototype.initialize.apply( this, arguments );
* this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, ' +
* 'cancel, back) configured with modes. This is edit mode. Click \'help\' to see ' +
* 'help mode.</p>' );
* this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget ' +
* 'is configured to be visible here. Click \'back\' to return to \'edit\' mode.' +
* '</p>' );
* this.stackLayout = new OO.ui.StackLayout( {
* items: [ this.panel1, this.panel2 ]
* } );
* this.$body.append( this.stackLayout.$element );
* };
* MyProcessDialog.prototype.getSetupProcess = function ( data ) {
* return MyProcessDialog.super.prototype.getSetupProcess.call( this, data )
* .next( function () {
* this.actions.setMode( 'edit' );
* }, this );
* };
* MyProcessDialog.prototype.getActionProcess = function ( action ) {
* if ( action === 'help' ) {
* this.actions.setMode( 'help' );
* this.stackLayout.setItem( this.panel2 );
* } else if ( action === 'back' ) {
* this.actions.setMode( 'edit' );
* this.stackLayout.setItem( this.panel1 );
* } else if ( action === 'continue' ) {
* var dialog = this;
* return new OO.ui.Process( function () {
* dialog.close();
* } );
* }
* return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
* };
* MyProcessDialog.prototype.getBodyHeight = function () {
* return this.panel1.$element.outerHeight( true );
* };
* var windowManager = new OO.ui.WindowManager();
* $( document.body ).append( windowManager.$element );
* var dialog = new MyProcessDialog( {
* size: 'medium'
* } );
* windowManager.addWindows( [ dialog ] );
* windowManager.openWindow( dialog );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Action_sets
*
* @abstract
* @class
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.ActionSet = function OoUiActionSet( config ) {
// Configuration initialization
config = config || {};
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.list = [];
this.categories = {
actions: 'getAction',
flags: 'getFlags',
modes: 'getModes'
};
this.categorized = {};
this.special = {};
this.others = [];
this.organized = false;
this.changing = false;
this.changed = false;
};
/* eslint-enable no-unused-vars */
/* Setup */
OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
/* Static Properties */
/**
* Symbolic name of the flags used to identify special actions. Special actions are displayed in the
* header of a {@link OO.ui.ProcessDialog process dialog}.
* See the [OOUI documentation on MediaWiki][2] for more information and examples.
*
* [2]:https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs
*
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
/* Events */
/**
* @event click
*
* A 'click' event is emitted when an action is clicked.
*
* @param {OO.ui.ActionWidget} action Action that was clicked
*/
/**
* @event add
*
* An 'add' event is emitted when actions are {@link #method-add added} to the action set.
*
* @param {OO.ui.ActionWidget[]} added Actions added
*/
/**
* @event remove
*
* A 'remove' event is emitted when actions are {@link #method-remove removed}
* or {@link #clear cleared}.
*
* @param {OO.ui.ActionWidget[]} added Actions removed
*/
/**
* @event change
*
* A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
* or {@link #method-remove removed} from the action set or when the {@link #setMode mode}
* is changed.
*
*/
/* Methods */
/**
* Handle action change events.
*
* @private
* @fires change
*/
OO.ui.ActionSet.prototype.onActionChange = function () {
this.organized = false;
if ( this.changing ) {
this.changed = true;
} else {
this.emit( 'change' );
}
};
/**
* Check if an action is one of the special actions.
*
* @param {OO.ui.ActionWidget} action Action to check
* @return {boolean} Action is special
*/
OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
var flag;
for ( flag in this.special ) {
if ( action === this.special[ flag ] ) {
return true;
}
}
return false;
};
/**
* Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
* or ‘disabled’.
*
* @param {Object} [filters] Filters to use, omit to get all actions
* @param {string|string[]} [filters.actions] Actions that action widgets must have
* @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
* @param {string|string[]} [filters.modes] Modes that action widgets must have
* @param {boolean} [filters.visible] Action widgets must be visible
* @param {boolean} [filters.disabled] Action widgets must be disabled
* @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
*/
OO.ui.ActionSet.prototype.get = function ( filters ) {
var i, len, list, category, actions, index, match, matches;
if ( filters ) {
this.organize();
// Collect category candidates
matches = [];
for ( category in this.categorized ) {
list = filters[ category ];
if ( list ) {
if ( !Array.isArray( list ) ) {
list = [ list ];
}
for ( i = 0, len = list.length; i < len; i++ ) {
actions = this.categorized[ category ][ list[ i ] ];
if ( Array.isArray( actions ) ) {
matches.push.apply( matches, actions );
}
}
}
}
// Remove by boolean filters
for ( i = 0, len = matches.length; i < len; i++ ) {
match = matches[ i ];
if (
( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
) {
matches.splice( i, 1 );
len--;
i--;
}
}
// Remove duplicates
for ( i = 0, len = matches.length; i < len; i++ ) {
match = matches[ i ];
index = matches.lastIndexOf( match );
while ( index !== i ) {
matches.splice( index, 1 );
len--;
index = matches.lastIndexOf( match );
}
}
return matches;
}
return this.list.slice();
};
/**
* Get 'special' actions.
*
* Special actions are the first visible action widgets with special flags, such as 'safe' and
* 'primary'.
* Special flags can be configured in subclasses by changing the static #specialFlags property.
*
* @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
*/
OO.ui.ActionSet.prototype.getSpecial = function () {
this.organize();
return $.extend( {}, this.special );
};
/**
* Get 'other' actions.
*
* Other actions include all non-special visible action widgets.
*
* @return {OO.ui.ActionWidget[]} 'Other' action widgets
*/
OO.ui.ActionSet.prototype.getOthers = function () {
this.organize();
return this.others.slice();
};
/**
* Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
* to be available in the specified mode will be made visible. All other actions will be hidden.
*
* @param {string} mode The mode. Only actions configured to be available in the specified
* mode will be made visible.
* @chainable
* @return {OO.ui.ActionSet} The widget, for chaining
* @fires toggle
* @fires change
*/
OO.ui.ActionSet.prototype.setMode = function ( mode ) {
var i, len, action;
this.changing = true;
for ( i = 0, len = this.list.length; i < len; i++ ) {
action = this.list[ i ];
action.toggle( action.hasMode( mode ) );
}
this.organized = false;
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Set the abilities of the specified actions.
*
* Action widgets that are configured with the specified actions will be enabled
* or disabled based on the boolean values specified in the `actions`
* parameter.
*
* @param {Object.<string,boolean>} actions A list keyed by action name with boolean
* values that indicate whether or not the action should be enabled.
* @chainable
* @return {OO.ui.ActionSet} The widget, for chaining
*/
OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
var i, len, action, item;
for ( i = 0, len = this.list.length; i < len; i++ ) {
item = this.list[ i ];
action = item.getAction();
if ( actions[ action ] !== undefined ) {
item.setDisabled( !actions[ action ] );
}
}
return this;
};
/**
* Executes a function once per action.
*
* When making changes to multiple actions, use this method instead of iterating over the actions
* manually to defer emitting a #change event until after all actions have been changed.
*
* @param {Object|null} filter Filters to use to determine which actions to iterate over; see #get
* @param {Function} callback Callback to run for each action; callback is invoked with three
* arguments: the action, the action's index, the list of actions being iterated over
* @chainable
* @return {OO.ui.ActionSet} The widget, for chaining
*/
OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
this.changed = false;
this.changing = true;
this.get( filter ).forEach( callback );
this.changing = false;
if ( this.changed ) {
this.emit( 'change' );
}
return this;
};
/**
* Add action widgets to the action set.
*
* @param {OO.ui.ActionWidget[]} actions Action widgets to add
* @chainable
* @return {OO.ui.ActionSet} The widget, for chaining
* @fires add
* @fires change
*/
OO.ui.ActionSet.prototype.add = function ( actions ) {
var i, len, action;
this.changing = true;
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
action.connect( this, {
click: [ 'emit', 'click', action ],
toggle: [ 'onActionChange' ]
} );
this.list.push( action );
}
this.organized = false;
this.emit( 'add', actions );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Remove action widgets from the set.
*
* To remove all actions, you may wish to use the #clear method instead.
*
* @param {OO.ui.ActionWidget[]} actions Action widgets to remove
* @chainable
* @return {OO.ui.ActionSet} The widget, for chaining
* @fires remove
* @fires change
*/
OO.ui.ActionSet.prototype.remove = function ( actions ) {
var i, len, index, action;
this.changing = true;
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
index = this.list.indexOf( action );
if ( index !== -1 ) {
action.disconnect( this );
this.list.splice( index, 1 );
}
}
this.organized = false;
this.emit( 'remove', actions );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Remove all action widgets from the set.
*
* To remove only specified actions, use the {@link #method-remove remove} method instead.
*
* @chainable
* @return {OO.ui.ActionSet} The widget, for chaining
* @fires remove
* @fires change
*/
OO.ui.ActionSet.prototype.clear = function () {
var i, len, action,
removed = this.list.slice();
this.changing = true;
for ( i = 0, len = this.list.length; i < len; i++ ) {
action = this.list[ i ];
action.disconnect( this );
}
this.list = [];
this.organized = false;
this.emit( 'remove', removed );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Organize actions.
*
* This is called whenever organized information is requested. It will only reorganize the actions
* if something has changed since the last time it ran.
*
* @private
* @chainable
* @return {OO.ui.ActionSet} The widget, for chaining
*/
OO.ui.ActionSet.prototype.organize = function () {
var i, iLen, j, jLen, flag, action, category, list, item, special,
specialFlags = this.constructor.static.specialFlags;
if ( !this.organized ) {
this.categorized = {};
this.special = {};
this.others = [];
for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
action = this.list[ i ];
if ( action.isVisible() ) {
// Populate categories
for ( category in this.categories ) {
if ( !this.categorized[ category ] ) {
this.categorized[ category ] = {};
}
list = action[ this.categories[ category ] ]();
if ( !Array.isArray( list ) ) {
list = [ list ];
}
for ( j = 0, jLen = list.length; j < jLen; j++ ) {
item = list[ j ];
if ( !this.categorized[ category ][ item ] ) {
this.categorized[ category ][ item ] = [];
}
this.categorized[ category ][ item ].push( action );
}
}
// Populate special/others
special = false;
for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
flag = specialFlags[ j ];
if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
this.special[ flag ] = action;
special = true;
break;
}
}
if ( !special ) {
this.others.push( action );
}
}
}
this.organized = true;
}
return this;
};
/**
* Errors contain a required message (either a string or jQuery selection) that is used to describe
* what went wrong in a {@link OO.ui.Process process}. The error's #recoverable and #warning
* configurations are used to customize the appearance and functionality of the error interface.
*
* The basic error interface contains a formatted error message as well as two buttons: 'Dismiss'
* and 'Try again' (i.e., the error is 'recoverable' by default). If the error is not recoverable,
* the 'Try again' button will not be rendered and the widget that initiated the failed process will
* be disabled.
*
* If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button,
* which will try the process again.
*
* For an example of error interfaces, please see the [OOUI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Processes_and_errors
*
* @class
*
* @constructor
* @param {string|jQuery} message Description of error
* @param {Object} [config] Configuration options
* @cfg {boolean} [recoverable=true] Error is recoverable.
* By default, errors are recoverable, and users can try the process again.
* @cfg {boolean} [warning=false] Error is a warning.
* If the error is a warning, the error interface will include a
* 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the
* warning is not triggered a second time if the user chooses to continue.
*/
OO.ui.Error = function OoUiError( message, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( message ) && config === undefined ) {
config = message;
message = config.message;
}
// Configuration initialization
config = config || {};
// Properties
this.message = message instanceof $ ? message : String( message );
this.recoverable = config.recoverable === undefined || !!config.recoverable;
this.warning = !!config.warning;
};
/* Setup */
OO.initClass( OO.ui.Error );
/* Methods */
/**
* Check if the error is recoverable.
*
* If the error is recoverable, users are able to try the process again.
*
* @return {boolean} Error is recoverable
*/
OO.ui.Error.prototype.isRecoverable = function () {
return this.recoverable;
};
/**
* Check if the error is a warning.
*
* If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
*
* @return {boolean} Error is warning
*/
OO.ui.Error.prototype.isWarning = function () {
return this.warning;
};
/**
* Get error message as DOM nodes.
*
* @return {jQuery} Error message in DOM nodes
*/
OO.ui.Error.prototype.getMessage = function () {
return this.message instanceof $ ?
this.message.clone() :
$( '<div>' ).text( this.message ).contents();
};
/**
* Get the error message text.
*
* @return {string} Error message
*/
OO.ui.Error.prototype.getMessageText = function () {
return this.message instanceof $ ? this.message.text() : this.message;
};
/**
* A Process is a list of steps that are called in sequence. The step can be a number, a
* promise (jQuery, native, or any other “thenable”), or a function:
*
* - **number**: the process will wait for the specified number of milliseconds before proceeding.
* - **promise**: the process will continue to the next step when the promise is successfully
* resolved or stop if the promise is rejected.
* - **function**: the process will execute the function. The process will stop if the function
* returns either a boolean `false` or a promise that is rejected; if the function returns a
* number, the process will wait for that number of milliseconds before proceeding.
*
* If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
* configured, users can dismiss the error and try the process again, or not. If a process is
* stopped, its remaining steps will not be performed.
*
* @class
*
* @constructor
* @param {number|jQuery.Promise|Function} step Number of milliseconds to wait before proceeding,
* promise that must be resolved before proceeding, or a function to execute. See #createStep for
* more information. See #createStep for more information.
* @param {Object} [context=null] Execution context of the function. The context is ignored if the
* step is a number or promise.
*/
OO.ui.Process = function ( step, context ) {
// Properties
this.steps = [];
// Initialization
if ( step !== undefined ) {
this.next( step, context );
}
};
/* Setup */
OO.initClass( OO.ui.Process );
/* Methods */
/**
* Start the process.
*
* @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
* If any of the steps return a promise that is rejected or a boolean false, this promise is
* rejected and any remaining steps are not performed.
*/
OO.ui.Process.prototype.execute = function () {
var i, len, promise;
/**
* Continue execution.
*
* @ignore
* @param {Array} step A function and the context it should be called in
* @return {Function} Function that continues the process
*/
function proceed( step ) {
return function () {
// Execute step in the correct context
var deferred,
result = step.callback.call( step.context );
if ( result === false ) {
// Use rejected promise for boolean false results
return $.Deferred().reject( [] ).promise();
}
if ( typeof result === 'number' ) {
if ( result < 0 ) {
throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
}
// Use a delayed promise for numbers, expecting them to be in milliseconds
deferred = $.Deferred();
setTimeout( deferred.resolve, result );
return deferred.promise();
}
if ( result instanceof OO.ui.Error ) {
// Use rejected promise for error
return $.Deferred().reject( [ result ] ).promise();
}
if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
// Use rejected promise for list of errors
return $.Deferred().reject( result ).promise();
}
// Duck-type the object to see if it can produce a promise
if ( result && typeof result.then === 'function' ) {
// Use a promise generated from the result
return $.when( result ).promise();
}
// Use resolved promise for other results
return $.Deferred().resolve().promise();
};
}
if ( this.steps.length ) {
// Generate a chain reaction of promises
promise = proceed( this.steps[ 0 ] )();
for ( i = 1, len = this.steps.length; i < len; i++ ) {
promise = promise.then( proceed( this.steps[ i ] ) );
}
} else {
promise = $.Deferred().resolve().promise();
}
return promise;
};
/**
* Create a process step.
*
* @private
* @param {number|jQuery.Promise|Function} step
*
* - Number of milliseconds to wait before proceeding
* - Promise that must be resolved before proceeding
* - Function to execute
* - If the function returns a boolean false the process will stop
* - If the function returns a promise, the process will continue to the next
* step when the promise is resolved or stop if the promise is rejected
* - If the function returns a number, the process will wait for that number of
* milliseconds before proceeding
* @param {Object} [context=null] Execution context of the function. The context is
* ignored if the step is a number or promise.
* @return {Object} Step object, with `callback` and `context` properties
*/
OO.ui.Process.prototype.createStep = function ( step, context ) {
if ( typeof step === 'number' || typeof step.then === 'function' ) {
return {
callback: function () {
return step;
},
context: null
};
}
if ( typeof step === 'function' ) {
return {
callback: step,
context: context
};
}
throw new Error( 'Cannot create process step: number, promise or function expected' );
};
/**
* Add step to the beginning of the process.
*
* @inheritdoc #createStep
* @return {OO.ui.Process} this
* @chainable
*/
OO.ui.Process.prototype.first = function ( step, context ) {
this.steps.unshift( this.createStep( step, context ) );
return this;
};
/**
* Add step to the end of the process.
*
* @inheritdoc #createStep
* @return {OO.ui.Process} this
* @chainable
*/
OO.ui.Process.prototype.next = function ( step, context ) {
this.steps.push( this.createStep( step, context ) );
return this;
};
/**
* A window instance represents the life cycle for one single opening of a window
* until its closing.
*
* While OO.ui.WindowManager will reuse OO.ui.Window objects, each time a window is
* opened, a new lifecycle starts.
*
* For more information, please see the [OOUI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows
*
* @class
*
* @constructor
*/
OO.ui.WindowInstance = function OoUiWindowInstance() {
var deferreds = {
opening: $.Deferred(),
opened: $.Deferred(),
closing: $.Deferred(),
closed: $.Deferred()
};
/**
* @private
* @property {Object}
*/
this.deferreds = deferreds;
// Set these up as chained promises so that rejecting of
// an earlier stage automatically rejects the subsequent
// would-be stages as well.
/**
* @property {jQuery.Promise}
*/
this.opening = deferreds.opening.promise();
/**
* @property {jQuery.Promise}
*/
this.opened = this.opening.then( function () {
return deferreds.opened;
} );
/**
* @property {jQuery.Promise}
*/
this.closing = this.opened.then( function () {
return deferreds.closing;
} );
/**
* @property {jQuery.Promise}
*/
this.closed = this.closing.then( function () {
return deferreds.closed;
} );
};
/* Setup */
OO.initClass( OO.ui.WindowInstance );
/**
* Check if window is opening.
*
* @return {boolean} Window is opening
*/
OO.ui.WindowInstance.prototype.isOpening = function () {
return this.deferreds.opened.state() === 'pending';
};
/**
* Check if window is opened.
*
* @return {boolean} Window is opened
*/
OO.ui.WindowInstance.prototype.isOpened = function () {
return this.deferreds.opened.state() === 'resolved' &&
this.deferreds.closing.state() === 'pending';
};
/**
* Check if window is closing.
*
* @return {boolean} Window is closing
*/
OO.ui.WindowInstance.prototype.isClosing = function () {
return this.deferreds.closing.state() === 'resolved' &&
this.deferreds.closed.state() === 'pending';
};
/**
* Check if window is closed.
*
* @return {boolean} Window is closed
*/
OO.ui.WindowInstance.prototype.isClosed = function () {
return this.deferreds.closed.state() === 'resolved';
};
/**
* Window managers are used to open and close {@link OO.ui.Window windows} and control their
* presentation. Managed windows are mutually exclusive. If a new window is opened while a current
* window is opening or is opened, the current window will be closed and any on-going
* {@link OO.ui.Process process} will be cancelled. Windows
* themselves are persistent and—rather than being torn down when closed—can be repopulated with the
* pertinent data and reused.
*
* Over the lifecycle of a window, the window manager makes available three promises: `opening`,
* `opened`, and `closing`, which represent the primary stages of the cycle:
*
* **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
* {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
*
* - an `opening` event is emitted with an `opening` promise
* - the #getSetupDelay method is called and the returned value is used to time a pause in execution
* before the window’s {@link OO.ui.Window#method-setup setup} method is called which executes
* OO.ui.Window#getSetupProcess.
* - a `setup` progress notification is emitted from the `opening` promise
* - the #getReadyDelay method is called the returned value is used to time a pause in execution
* before the window’s {@link OO.ui.Window#method-ready ready} method is called which executes
* OO.ui.Window#getReadyProcess.
* - a `ready` progress notification is emitted from the `opening` promise
* - the `opening` promise is resolved with an `opened` promise
*
* **Opened**: the window is now open.
*
* **Closing**: the closing stage begins when the window manager's #closeWindow or the
* window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
* to close the window.
*
* - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
* - the #getHoldDelay method is called and the returned value is used to time a pause in execution
* before the window's {@link OO.ui.Window#getHoldProcess getHoldProcess} method is called on the
* window and its result executed
* - a `hold` progress notification is emitted from the `closing` promise
* - the #getTeardownDelay() method is called and the returned value is used to time a pause in
* execution before the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method
* is called on the window and its result executed
* - a `teardown` progress notification is emitted from the `closing` promise
* - the `closing` promise is resolved. The window is now closed
*
* See the [OOUI documentation on MediaWiki][1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers
*
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
* Note that window classes that are instantiated with a factory must have
* a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
* @cfg {boolean} [modal=true] Prevent interaction outside the dialog
*/
OO.ui.WindowManager = function OoUiWindowManager( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.WindowManager.super.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.factory = config.factory;
this.modal = config.modal === undefined || !!config.modal;
this.windows = {};
// Deprecated placeholder promise given to compatOpening in openWindow()
// that is resolved in closeWindow().
this.compatOpened = null;
this.preparingToOpen = null;
this.preparingToClose = null;
this.currentWindow = null;
this.globalEvents = false;
this.$returnFocusTo = null;
this.$ariaHidden = null;
this.onWindowResizeTimeout = null;
this.onWindowResizeHandler = this.onWindowResize.bind( this );
this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
// Initialization
this.$element
.addClass( 'oo-ui-windowManager' )
.toggleClass( 'oo-ui-windowManager-modal', this.modal );
if ( this.modal ) {
this.$element.attr( 'aria-hidden', true );
}
};
/* Setup */
OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
/* Events */
/**
* An 'opening' event is emitted when the window begins to be opened.
*
* @event opening
* @param {OO.ui.Window} win Window that's being opened
* @param {jQuery.Promise} opened A promise resolved with a value when the window is opened
* successfully. This promise also emits `setup` and `ready` notifications. When this promise is
* resolved, the first argument of the value is an 'closed' promise, the second argument is the
* opening data.
* @param {Object} data Window opening data
*/
/**
* A 'closing' event is emitted when the window begins to be closed.
*
* @event closing
* @param {OO.ui.Window} win Window that's being closed
* @param {jQuery.Promise} closed A promise resolved with a value when the window is closed
* successfully. This promise also emits `hold` and `teardown` notifications. When this promise is
* resolved, the first argument of its value is the closing data.
* @param {Object} data Window closing data
*/
/**
* A 'resize' event is emitted when a window is resized.
*
* @event resize
* @param {OO.ui.Window} win Window that was resized
*/
/* Static Properties */
/**
* Map of the symbolic name of each window size and its CSS properties.
*
* @static
* @inheritable
* @property {Object}
*/
OO.ui.WindowManager.static.sizes = {
small: {
width: 300
},
medium: {
width: 500
},
large: {
width: 700
},
larger: {
width: 900
},
full: {
// These can be non-numeric because they are never used in calculations
width: '100%',
height: '100%'
}
};
/**
* Symbolic name of the default window size.
*
* The default size is used if the window's requested size is not recognized.
*
* @static
* @inheritable
* @property {string}
*/
OO.ui.WindowManager.static.defaultSize = 'medium';
/* Methods */
/**
* Handle window resize events.
*
* @private
* @param {jQuery.Event} e Window resize event
*/
OO.ui.WindowManager.prototype.onWindowResize = function () {
clearTimeout( this.onWindowResizeTimeout );
this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
};
/**
* Handle window resize events.
*
* @private
* @param {jQuery.Event} e Window resize event
*/
OO.ui.WindowManager.prototype.afterWindowResize = function () {
var currentFocusedElement = document.activeElement;
if ( this.currentWindow ) {
this.updateWindowSize( this.currentWindow );
// Restore focus to the original element if it has changed.
// When a layout change is made on resize inputs lose focus
// on Android (Chrome and Firefox), see T162127.
if ( currentFocusedElement !== document.activeElement ) {
currentFocusedElement.focus();
}
}
};
/**
* Check if window is opening.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is opening
*/
OO.ui.WindowManager.prototype.isOpening = function ( win ) {
return win === this.currentWindow && !!this.lifecycle &&
this.lifecycle.isOpening();
};
/**
* Check if window is closing.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is closing
*/
OO.ui.WindowManager.prototype.isClosing = function ( win ) {
return win === this.currentWindow && !!this.lifecycle &&
this.lifecycle.isClosing();
};
/**
* Check if window is opened.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is opened
*/
OO.ui.WindowManager.prototype.isOpened = function ( win ) {
return win === this.currentWindow && !!this.lifecycle &&
this.lifecycle.isOpened();
};
/**
* Check if a window is being managed.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is being managed
*/
OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
var name;
for ( name in this.windows ) {
if ( this.windows[ name ] === win ) {
return true;
}
}
return false;
};
/**
* Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
*
* @param {OO.ui.Window} win Window being opened
* @param {Object} [data] Window opening data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getSetupDelay = function () {
return 0;
};
/**
* Get the number of milliseconds to wait after setup has finished before executing the ‘ready’
* process.
*
* @param {OO.ui.Window} win Window being opened
* @param {Object} [data] Window opening data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getReadyDelay = function () {
return this.modal ? OO.ui.theme.getDialogTransitionDuration() : 0;
};
/**
* Get the number of milliseconds to wait after closing has begun before executing the 'hold'
* process.
*
* @param {OO.ui.Window} win Window being closed
* @param {Object} [data] Window closing data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getHoldDelay = function () {
return 0;
};
/**
* Get the number of milliseconds to wait after the ‘hold’ process has finished before
* executing the ‘teardown’ process.
*
* @param {OO.ui.Window} win Window being closed
* @param {Object} [data] Window closing data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getTeardownDelay = function () {
return this.modal ? OO.ui.theme.getDialogTransitionDuration() : 0;
};
/**
* Get a window by its symbolic name.
*
* If the window is not yet instantiated and its symbolic name is recognized by a factory, it will
* be instantiated and added to the window manager automatically. Please see the [OOUI documentation
* on MediaWiki][3] for more information about using factories.
* [3]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers
*
* @param {string} name Symbolic name of the window
* @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
* @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
* @throws {Error} An error is thrown if the named window is not recognized as a managed window.
*/
OO.ui.WindowManager.prototype.getWindow = function ( name ) {
var deferred = $.Deferred(),
win = this.windows[ name ];
if ( !( win instanceof OO.ui.Window ) ) {
if ( this.factory ) {
if ( !this.factory.lookup( name ) ) {
deferred.reject( new OO.ui.Error(
'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
) );
} else {
win = this.factory.create( name );
this.addWindows( [ win ] );
deferred.resolve( win );
}
} else {
deferred.reject( new OO.ui.Error(
'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
) );
}
} else {
deferred.resolve( win );
}
return deferred.promise();
};
/**
* Get current window.
*
* @return {OO.ui.Window|null} Currently opening/opened/closing window
*/
OO.ui.WindowManager.prototype.getCurrentWindow = function () {
return this.currentWindow;
};
/**
* Open a window.
*
* @param {OO.ui.Window|string} win Window object or symbolic name of window to open
* @param {Object} [data] Window opening data
* @param {jQuery|null} [data.$returnFocusTo] Element to which the window will return focus when
* closed. Defaults the current activeElement. If set to null, focus isn't changed on close.
* @param {OO.ui.WindowInstance} [lifecycle] Used internally
* @param {jQuery.Deferred} [compatOpening] Used internally
* @return {OO.ui.WindowInstance} A lifecycle object representing this particular
* opening of the window. For backwards-compatibility, then object is also a Thenable that is
* resolved when the window is done opening, with nested promise for when closing starts. This
* behaviour is deprecated and is not compatible with jQuery 3, see T163510.
* @fires opening
*/
OO.ui.WindowManager.prototype.openWindow = function ( win, data, lifecycle, compatOpening ) {
var error,
manager = this;
data = data || {};
// Internal parameter 'lifecycle' allows this method to always return
// a lifecycle even if the window still needs to be created
// asynchronously when 'win' is a string.
lifecycle = lifecycle || new OO.ui.WindowInstance();
compatOpening = compatOpening || $.Deferred();
// Turn lifecycle into a Thenable for backwards-compatibility with
// the deprecated nested-promise behaviour, see T163510.
[ 'state', 'always', 'catch', 'pipe', 'then', 'promise', 'progress', 'done', 'fail' ]
.forEach( function ( method ) {
lifecycle[ method ] = function () {
OO.ui.warnDeprecation(
'Using the return value of openWindow as a promise is deprecated. ' +
'Use .openWindow( ... ).opening.' + method + '( ... ) instead.'
);
return compatOpening[ method ].apply( this, arguments );
};
} );
// Argument handling
if ( typeof win === 'string' ) {
this.getWindow( win ).then(
function ( w ) {
manager.openWindow( w, data, lifecycle, compatOpening );
},
function ( err ) {
lifecycle.deferreds.opening.reject( err );
}
);
return lifecycle;
}
// Error handling
if ( !this.hasWindow( win ) ) {
error = 'Cannot open window: window is not attached to manager';
} else if ( this.lifecycle && this.lifecycle.isOpened() ) {
error = 'Cannot open window: another window is open';
} else if ( this.preparingToOpen || ( this.lifecycle && this.lifecycle.isOpening() ) ) {
error = 'Cannot open window: another window is opening';
}
if ( error ) {
compatOpening.reject( new OO.ui.Error( error ) );
lifecycle.deferreds.opening.reject( new OO.ui.Error( error ) );
return lifecycle;
}
// If a window is currently closing, wait for it to complete
this.preparingToOpen = $.when( this.lifecycle && this.lifecycle.closed );
// Ensure handlers get called after preparingToOpen is set
this.preparingToOpen.done( function () {
if ( manager.modal ) {
manager.toggleGlobalEvents( true );
manager.toggleAriaIsolation( true );
}
manager.$returnFocusTo = data.$returnFocusTo !== undefined ?
data.$returnFocusTo :
$( document.activeElement );
manager.currentWindow = win;
manager.lifecycle = lifecycle;
manager.preparingToOpen = null;
manager.emit( 'opening', win, compatOpening, data );
lifecycle.deferreds.opening.resolve( data );
setTimeout( function () {
manager.compatOpened = $.Deferred();
win.setup( data ).then( function () {
compatOpening.notify( { state: 'setup' } );
setTimeout( function () {
win.ready( data ).then( function () {
compatOpening.notify( { state: 'ready' } );
lifecycle.deferreds.opened.resolve( data );
compatOpening.resolve( manager.compatOpened.promise(), data );
manager.togglePreventIosScrolling( true );
}, function ( dataOrErr ) {
lifecycle.deferreds.opened.reject();
compatOpening.reject();
manager.closeWindow( win );
if ( dataOrErr instanceof Error ) {
setTimeout( function () {
throw dataOrErr;
} );
}
} );
}, manager.getReadyDelay() );
}, function ( dataOrErr ) {
lifecycle.deferreds.opened.reject();
compatOpening.reject();
manager.closeWindow( win );
if ( dataOrErr instanceof Error ) {
setTimeout( function () {
throw dataOrErr;
} );
}
} );
}, manager.getSetupDelay() );
} );
return lifecycle;
};
/**
* Close a window.
*
* @param {OO.ui.Window|string} win Window object or symbolic name of window to close
* @param {Object} [data] Window closing data
* @return {OO.ui.WindowInstance} A lifecycle object representing this particular
* opening of the window. For backwards-compatibility, the object is also a Thenable that is
* resolved when the window is done closing, see T163510.
* @fires closing
*/
OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
var error,
manager = this,
compatClosing = $.Deferred(),
lifecycle = this.lifecycle,
compatOpened;
// Argument handling
if ( typeof win === 'string' ) {
win = this.windows[ win ];
} else if ( !this.hasWindow( win ) ) {
win = null;
}
// Error handling
if ( !lifecycle ) {
error = 'Cannot close window: no window is currently open';
} else if ( !win ) {
error = 'Cannot close window: window is not attached to manager';
} else if ( win !== this.currentWindow || this.lifecycle.isClosed() ) {
error = 'Cannot close window: window already closed with different data';
} else if ( this.preparingToClose || this.lifecycle.isClosing() ) {
error = 'Cannot close window: window already closing with different data';
}
if ( error ) {
// This function was called for the wrong window and we don't want to mess with the current
// window's state.
lifecycle = new OO.ui.WindowInstance();
// Pretend the window has been opened, so that we can pretend to fail to close it.
lifecycle.deferreds.opening.resolve( {} );
lifecycle.deferreds.opened.resolve( {} );
}
// Turn lifecycle into a Thenable for backwards-compatibility with
// the deprecated nested-promise behaviour, see T163510.
[ 'state', 'always', 'catch', 'pipe', 'then', 'promise', 'progress', 'done', 'fail' ]
.forEach( function ( method ) {
lifecycle[ method ] = function () {
OO.ui.warnDeprecation(
'Using the return value of closeWindow as a promise is deprecated. ' +
'Use .closeWindow( ... ).closed.' + method + '( ... ) instead.'
);
return compatClosing[ method ].apply( this, arguments );
};
} );
if ( error ) {
compatClosing.reject( new OO.ui.Error( error ) );
lifecycle.deferreds.closing.reject( new OO.ui.Error( error ) );
return lifecycle;
}
// If the window is currently opening, close it when it's done
this.preparingToClose = $.when( this.lifecycle.opened );
// Ensure handlers get called after preparingToClose is set
this.preparingToClose.always( function () {
manager.preparingToClose = null;
manager.emit( 'closing', win, compatClosing, data );
lifecycle.deferreds.closing.resolve( data );
compatOpened = manager.compatOpened;
manager.compatOpened = null;
compatOpened.resolve( compatClosing.promise(), data );
manager.togglePreventIosScrolling( false );
setTimeout( function () {
win.hold( data ).then( function () {
compatClosing.notify( { state: 'hold' } );
setTimeout( function () {
win.teardown( data ).then( function () {
compatClosing.notify( { state: 'teardown' } );
if ( manager.modal ) {
manager.toggleGlobalEvents( false );
manager.toggleAriaIsolation( false );
}
if ( manager.$returnFocusTo && manager.$returnFocusTo.length ) {
manager.$returnFocusTo[ 0 ].focus();
}
manager.currentWindow = null;
manager.lifecycle = null;
lifecycle.deferreds.closed.resolve( data );
compatClosing.resolve( data );
} );
}, manager.getTeardownDelay() );
} );
}, manager.getHoldDelay() );
} );
return lifecycle;
};
/**
* Add windows to the window manager.
*
* Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
* See the [OOUI documentation on MediaWiki] [2] for examples.
* [2]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers
*
* This function can be called in two manners:
*
* 1. `.addWindows( [ winA, winB, ... ] )` (where `winA`, `winB` are OO.ui.Window objects)
*
* This syntax registers windows under the symbolic names defined in their `.static.name`
* properties. For example, if `windowA.constructor.static.name` is `'nameA'`, calling
* `.openWindow( 'nameA' )` afterwards will open the window `windowA`. This syntax requires the
* static name to be set, otherwise an exception will be thrown.
*
* This is the recommended way, as it allows for an easier switch to using a window factory.
*
* 2. `.addWindows( { nameA: winA, nameB: winB, ... } )`
*
* This syntax registers windows under the explicitly given symbolic names. In this example,
* calling `.openWindow( 'nameA' )` afterwards will open the window `windowA`, regardless of what
* its `.static.name` is set to. The static name is not required to be set.
*
* This should only be used if you need to override the default symbolic names.
*
* Example:
*
* var windowManager = new OO.ui.WindowManager();
* $( document.body ).append( windowManager.$element );
*
* // Add a window under the default name: see OO.ui.MessageDialog.static.name
* windowManager.addWindows( [ new OO.ui.MessageDialog() ] );
* // Add a window under an explicit name
* windowManager.addWindows( { myMessageDialog: new OO.ui.MessageDialog() } );
*
* // Open window by default name
* windowManager.openWindow( 'message' );
* // Open window by explicitly given name
* windowManager.openWindow( 'myMessageDialog' );
*
*
* @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
* by reference, symbolic name, or explicitly defined symbolic names.
* @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
* explicit nor a statically configured symbolic name.
*/
OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
var i, len, win, name, list;
if ( Array.isArray( windows ) ) {
// Convert to map of windows by looking up symbolic names from static configuration
list = {};
for ( i = 0, len = windows.length; i < len; i++ ) {
name = windows[ i ].constructor.static.name;
if ( !name ) {
throw new Error( 'Windows must have a `name` static property defined.' );
}
list[ name ] = windows[ i ];
}
} else if ( OO.isPlainObject( windows ) ) {
list = windows;
}
// Add windows
for ( name in list ) {
win = list[ name ];
this.windows[ name ] = win.toggle( false );
this.$element.append( win.$element );
win.setManager( this );
}
};
/**
* Remove the specified windows from the windows manager.
*
* Windows will be closed before they are removed. If you wish to remove all windows, you may wish
* to use the #clearWindows method instead. If you no longer need the window manager and want to
* ensure that it no longer listens to events, use the #destroy method.
*
* @param {string[]} names Symbolic names of windows to remove
* @return {jQuery.Promise} Promise resolved when window is closed and removed
* @throws {Error} An error is thrown if the named windows are not managed by the window manager.
*/
OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
var promises,
manager = this;
function cleanup( name, win ) {
delete manager.windows[ name ];
win.$element.detach();
}
promises = names.map( function ( name ) {
var cleanupWindow,
win = manager.windows[ name ];
if ( !win ) {
throw new Error( 'Cannot remove window' );
}
cleanupWindow = cleanup.bind( null, name, win );
return manager.closeWindow( name ).closed.then( cleanupWindow, cleanupWindow );
} );
return $.when.apply( $, promises );
};
/**
* Remove all windows from the window manager.
*
* Windows will be closed before they are removed. Note that the window manager, though not in use,
* will still listen to events. If the window manager will not be used again, you may wish to use
* the #destroy method instead. To remove just a subset of windows, use the #removeWindows method.
*
* @return {jQuery.Promise} Promise resolved when all windows are closed and removed
*/
OO.ui.WindowManager.prototype.clearWindows = function () {
return this.removeWindows( Object.keys( this.windows ) );
};
/**
* Set dialog size. In general, this method should not be called directly.
*
* Fullscreen mode will be used if the dialog is too wide to fit in the screen.
*
* @param {OO.ui.Window} win Window to update, should be the current window
* @chainable
* @return {OO.ui.WindowManager} The manager, for chaining
*/
OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
var isFullscreen;
// Bypass for non-current, and thus invisible, windows
if ( win !== this.currentWindow ) {
return;
}
isFullscreen = win.getSize() === 'full';
this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
win.setDimensions( win.getSizeProperties() );
this.emit( 'resize', win );
return this;
};
/**
* Prevent scrolling of the document on iOS devices that don't respect `body { overflow: hidden; }`.
*
* This function is called when the window is opened (ready), and so the background is covered up,
* and the user won't see that we're doing weird things to the scroll position.
*
* @private
* @param {boolean} on
* @chainable
* @return {OO.ui.WindowManager} The manager, for chaining
*/
OO.ui.WindowManager.prototype.togglePreventIosScrolling = function ( on ) {
var
isIos = /ipad|iphone|ipod/i.test( navigator.userAgent ),
$body = $( this.getElementDocument().body ),
scrollableRoot = OO.ui.Element.static.getRootScrollableElement( $body[ 0 ] ),
stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0;
// Only if this is the first/last WindowManager (see #toggleGlobalEvents)
if ( !isIos || stackDepth !== 1 ) {
return this;
}
if ( on ) {
// We can't apply this workaround for non-fullscreen dialogs, because the user would see the
// scroll position change. If they have content that needs scrolling, you're out of luck…
// Always remember the scroll position in case dialog is closed with different size.
this.iosOrigScrollPosition = scrollableRoot.scrollTop;
if ( this.getCurrentWindow().getSize() === 'full' ) {
$body.add( $body.parent() ).addClass( 'oo-ui-windowManager-ios-modal-ready' );
}
} else {
// Always restore ability to scroll in case dialog was opened with different size.
$body.add( $body.parent() ).removeClass( 'oo-ui-windowManager-ios-modal-ready' );
if ( this.getCurrentWindow().getSize() === 'full' ) {
scrollableRoot.scrollTop = this.iosOrigScrollPosition;
}
}
return this;
};
/**
* Bind or unbind global events for scrolling.
*
* @private
* @param {boolean} [on] Bind global events
* @chainable
* @return {OO.ui.WindowManager} The manager, for chaining
*/
OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
var scrollWidth, bodyMargin,
$body = $( this.getElementDocument().body ),
// We could have multiple window managers open so only modify
// the body css at the bottom of the stack
stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0;
on = on === undefined ? !!this.globalEvents : !!on;
if ( on ) {
if ( !this.globalEvents ) {
$( this.getElementWindow() ).on( {
// Start listening for top-level window dimension changes
'orientationchange resize': this.onWindowResizeHandler
} );
if ( stackDepth === 0 ) {
scrollWidth = window.innerWidth - document.documentElement.clientWidth;
bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
$body.addClass( 'oo-ui-windowManager-modal-active' );
$body.css( 'margin-right', bodyMargin + scrollWidth );
}
stackDepth++;
this.globalEvents = true;
}
} else if ( this.globalEvents ) {
$( this.getElementWindow() ).off( {
// Stop listening for top-level window dimension changes
'orientationchange resize': this.onWindowResizeHandler
} );
stackDepth--;
if ( stackDepth === 0 ) {
$body.removeClass( 'oo-ui-windowManager-modal-active' );
$body.css( 'margin-right', '' );
}
this.globalEvents = false;
}
$body.data( 'windowManagerGlobalEvents', stackDepth );
return this;
};
/**
* Toggle screen reader visibility of content other than the window manager.
*
* @private
* @param {boolean} [isolate] Make only the window manager visible to screen readers
* @chainable
* @return {OO.ui.WindowManager} The manager, for chaining
*/
OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
var $topLevelElement;
isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
if ( isolate ) {
if ( !this.$ariaHidden ) {
// Find the top level element containing the window manager or the
// window manager's element itself in case its a direct child of body
$topLevelElement = this.$element.parentsUntil( 'body' ).last();
$topLevelElement = $topLevelElement.length === 0 ? this.$element : $topLevelElement;
// In case previously set by another window manager
this.$element.removeAttr( 'aria-hidden' );
// Hide everything other than the window manager from screen readers
this.$ariaHidden = $( document.body )
.children()
.not( 'script' )
.not( $topLevelElement )
.attr( 'aria-hidden', true );
}
} else if ( this.$ariaHidden ) {
// Restore screen reader visibility
this.$ariaHidden.removeAttr( 'aria-hidden' );
this.$ariaHidden = null;
// and hide the window manager
this.$element.attr( 'aria-hidden', true );
}
return this;
};
/**
* Destroy the window manager.
*
* Destroying the window manager ensures that it will no longer listen to events. If you would like
* to continue using the window manager, but wish to remove all windows from it, use the
* #clearWindows method instead.
*/
OO.ui.WindowManager.prototype.destroy = function () {
this.toggleGlobalEvents( false );
this.toggleAriaIsolation( false );
this.clearWindows();
this.$element.remove();
};
/**
* A window is a container for elements that are in a child frame. They are used with
* a window manager (OO.ui.WindowManager), which is used to open and close the window and control
* its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’,
* ‘medium’, ‘large’), which is interpreted by the window manager. If the requested size is not
* recognized, the window manager will choose a sensible fallback.
*
* The lifecycle of a window has three primary stages (opening, opened, and closing) in which
* different processes are executed:
*
* **opening**: The opening stage begins when the window manager's
* {@link OO.ui.WindowManager#openWindow openWindow} or the window's {@link #open open} methods are
* used, and the window manager begins to open the window.
*
* - {@link #getSetupProcess} method is called and its result executed
* - {@link #getReadyProcess} method is called and its result executed
*
* **opened**: The window is now open
*
* **closing**: The closing stage begins when the window manager's
* {@link OO.ui.WindowManager#closeWindow closeWindow}
* or the window's {@link #close} methods are used, and the window manager begins to close the
* window.
*
* - {@link #getHoldProcess} method is called and its result executed
* - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
*
* Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
* by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and
* #getTeardownProcess methods. Note that each {@link OO.ui.Process process} is executed in series,
* so asynchronous processing can complete. Always assume window processes are executed
* asynchronously.
*
* For more information, please see the [OOUI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows
*
* @abstract
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
* `full`. If omitted, the value of the {@link #static-size static size} property will be used.
*/
OO.ui.Window = function OoUiWindow( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.Window.super.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.manager = null;
this.size = config.size || this.constructor.static.size;
this.$frame = $( '<div>' );
/**
* Overlay element to use for the `$overlay` configuration option of widgets that support it.
* Things put inside it are overlaid on top of the window and are not bound to its dimensions.
* See <https://www.mediawiki.org/wiki/OOUI/Concepts#Overlays>.
*
* MyDialog.prototype.initialize = function () {
* ...
* var popupButton = new OO.ui.PopupButtonWidget( {
* $overlay: this.$overlay,
* label: 'Popup button',
* popup: {
* $content: $( '<p>Popup content.</p><p>More content.</p><p>Yet more content.</p>' ),
* padded: true
* }
* } );
* ...
* };
*
* @property {jQuery}
*/
this.$overlay = $( '<div>' );
this.$content = $( '<div>' );
this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
// Initialization
this.$overlay.addClass( 'oo-ui-window-overlay' );
this.$content
.addClass( 'oo-ui-window-content' )
.attr( 'tabindex', -1 );
this.$frame
.addClass( 'oo-ui-window-frame' )
.append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
this.$element
.addClass( 'oo-ui-window' )
.append( this.$frame, this.$overlay );
// Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
// that reference properties not initialized at that time of parent class construction
// TODO: Find a better way to handle post-constructor setup
this.visible = false;
this.$element.addClass( 'oo-ui-element-hidden' );
};
/* Setup */
OO.inheritClass( OO.ui.Window, OO.ui.Element );
OO.mixinClass( OO.ui.Window, OO.EventEmitter );
/* Static Properties */
/**
* Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
*
* The static size is used if no #size is configured during construction.
*
* @static
* @inheritable
* @property {string}
*/
OO.ui.Window.static.size = 'medium';
/* Methods */
/**
* Handle mouse down events.
*
* @private
* @param {jQuery.Event} e Mouse down event
* @return {OO.ui.Window} The window, for chaining
*/
OO.ui.Window.prototype.onMouseDown = function ( e ) {
// Prevent clicking on the click-block from stealing focus
if ( e.target === this.$element[ 0 ] ) {
return false;
}
};
/**
* Check if the window has been initialized.
*
* Initialization occurs when a window is added to a manager.
*
* @return {boolean} Window has been initialized
*/
OO.ui.Window.prototype.isInitialized = function () {
return !!this.manager;
};
/**
* Check if the window is visible.
*
* @return {boolean} Window is visible
*/
OO.ui.Window.prototype.isVisible = function () {
return this.visible;
};
/**
* Check if the window is opening.
*
* This method is a wrapper around the window manager's
* {@link OO.ui.WindowManager#isOpening isOpening} method.
*
* @return {boolean} Window is opening
*/
OO.ui.Window.prototype.isOpening = function () {
return this.manager.isOpening( this );
};
/**
* Check if the window is closing.
*
* This method is a wrapper around the window manager's
* {@link OO.ui.WindowManager#isClosing isClosing} method.
*
* @return {boolean} Window is closing
*/
OO.ui.Window.prototype.isClosing = function () {
return this.manager.isClosing( this );
};
/**
* Check if the window is opened.
*
* This method is a wrapper around the window manager's
* {@link OO.ui.WindowManager#isOpened isOpened} method.
*
* @return {boolean} Window is opened
*/
OO.ui.Window.prototype.isOpened = function () {
return this.manager.isOpened( this );
};
/**
* Get the window manager.
*
* All windows must be attached to a window manager, which is used to open
* and close the window and control its presentation.
*
* @return {OO.ui.WindowManager} Manager of window
*/
OO.ui.Window.prototype.getManager = function () {
return this.manager;
};
/**
* Get the symbolic name of the window size (e.g., `small` or `medium`).
*
* @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
*/
OO.ui.Window.prototype.getSize = function () {
var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
sizes = this.manager.constructor.static.sizes,
size = this.size;
if ( !sizes[ size ] ) {
size = this.manager.constructor.static.defaultSize;
}
if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
size = 'full';
}
return size;
};
/**
* Get the size properties associated with the current window size
*
* @return {Object} Size properties
*/
OO.ui.Window.prototype.getSizeProperties = function () {
return this.manager.constructor.static.sizes[ this.getSize() ];
};
/**
* Disable transitions on window's frame for the duration of the callback function, then enable them
* back.
*
* @private
* @param {Function} callback Function to call while transitions are disabled
*/
OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
// Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
// Disable transitions first, otherwise we'll get values from when the window was animating.
// We need to build the transition CSS properties using these specific properties since
// Firefox doesn't return anything useful when asked just for 'transition'.
var oldTransition = this.$frame.css( 'transition-property' ) + ' ' +
this.$frame.css( 'transition-duration' ) + ' ' +
this.$frame.css( 'transition-timing-function' ) + ' ' +
this.$frame.css( 'transition-delay' );
this.$frame.css( 'transition', 'none' );
callback();
// Force reflow to make sure the style changes done inside callback
// really are not transitioned
this.$frame.height();
this.$frame.css( 'transition', oldTransition );
};
/**
* Get the height of the full window contents (i.e., the window head, body and foot together).
*
* What constitutes the head, body, and foot varies depending on the window type.
* A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
* and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
* and special actions in the head, and dialog content in the body.
*
* To get just the height of the dialog body, use the #getBodyHeight method.
*
* @return {number} The height of the window contents (the dialog head, body and foot) in pixels
*/
OO.ui.Window.prototype.getContentHeight = function () {
var bodyHeight,
win = this,
bodyStyleObj = this.$body[ 0 ].style,
frameStyleObj = this.$frame[ 0 ].style;
// Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
// Disable transitions first, otherwise we'll get values from when the window was animating.
this.withoutSizeTransitions( function () {
var oldHeight = frameStyleObj.height,
oldPosition = bodyStyleObj.position;
frameStyleObj.height = '1px';
// Force body to resize to new width
bodyStyleObj.position = 'relative';
bodyHeight = win.getBodyHeight();
frameStyleObj.height = oldHeight;
bodyStyleObj.position = oldPosition;
} );
return (
// Add buffer for border
( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
// Use combined heights of children
( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
);
};
/**
* Get the height of the window body.
*
* To get the height of the full window contents (the window body, head, and foot together),
* use #getContentHeight.
*
* When this function is called, the window will temporarily have been resized
* to height=1px, so .scrollHeight measurements can be taken accurately.
*
* @return {number} Height of the window body in pixels
*/
OO.ui.Window.prototype.getBodyHeight = function () {
return this.$body[ 0 ].scrollHeight;
};
/**
* Get the directionality of the frame (right-to-left or left-to-right).
*
* @return {string} Directionality: `'ltr'` or `'rtl'`
*/
OO.ui.Window.prototype.getDir = function () {
return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
};
/**
* Get the 'setup' process.
*
* The setup process is used to set up a window for use in a particular context, based on the `data`
* argument. This method is called during the opening phase of the window’s lifecycle (before the
* opening animation). You can add elements to the window in this process or set their default
* values.
*
* Override this method to add additional steps to the ‘setup’ process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* To add window content that persists between openings, you may wish to use the #initialize method
* instead.
*
* @param {Object} [data] Window opening data
* @return {OO.ui.Process} Setup process
*/
OO.ui.Window.prototype.getSetupProcess = function () {
return new OO.ui.Process();
};
/**
* Get the ‘ready’ process.
*
* The ready process is used to ready a window for use in a particular context, based on the `data`
* argument. This method is called during the opening phase of the window’s lifecycle, after the
* window has been {@link #getSetupProcess setup} (after the opening animation). You can focus
* elements in the window in this process, or open their dropdowns.
*
* Override this method to add additional steps to the ‘ready’ process the parent method
* provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
* methods of OO.ui.Process.
*
* @param {Object} [data] Window opening data
* @return {OO.ui.Process} Ready process
*/
OO.ui.Window.prototype.getReadyProcess = function () {
return new OO.ui.Process();
};
/**
* Get the 'hold' process.
*
* The hold process is used to keep a window from being used in a particular context, based on the
* `data` argument. This method is called during the closing phase of the window’s lifecycle (before
* the closing animation). You can close dropdowns of elements in the window in this process, if
* they do not get closed automatically.
*
* Override this method to add additional steps to the 'hold' process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* @param {Object} [data] Window closing data
* @return {OO.ui.Process} Hold process
*/
OO.ui.Window.prototype.getHoldProcess = function () {
return new OO.ui.Process();
};
/**
* Get the ‘teardown’ process.
*
* The teardown process is used to teardown a window after use. During teardown, user interactions
* within the window are conveyed and the window is closed, based on the `data` argument. This
* method is called during the closing phase of the window’s lifecycle (after the closing
* animation). You can remove elements in the window in this process or clear their values.
*
* Override this method to add additional steps to the ‘teardown’ process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* @param {Object} [data] Window closing data
* @return {OO.ui.Process} Teardown process
*/
OO.ui.Window.prototype.getTeardownProcess = function () {
return new OO.ui.Process();
};
/**
* Set the window manager.
*
* This will cause the window to initialize. Calling it more than once will cause an error.
*
* @param {OO.ui.WindowManager} manager Manager for this window
* @throws {Error} An error is thrown if the method is called more than once
* @chainable
* @return {OO.ui.Window} The window, for chaining
*/
OO.ui.Window.prototype.setManager = function ( manager ) {
if ( this.manager ) {
throw new Error( 'Cannot set window manager, window already has a manager' );
}
this.manager = manager;
this.initialize();
return this;
};
/**
* Set the window size by symbolic name (e.g., 'small' or 'medium')
*
* @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
* `full`
* @chainable
* @return {OO.ui.Window} The window, for chaining
*/
OO.ui.Window.prototype.setSize = function ( size ) {
this.size = size;
this.updateSize();
return this;
};
/**
* Update the window size.
*
* @throws {Error} An error is thrown if the window is not attached to a window manager
* @chainable
* @return {OO.ui.Window} The window, for chaining
*/
OO.ui.Window.prototype.updateSize = function () {
if ( !this.manager ) {
throw new Error( 'Cannot update window size, must be attached to a manager' );
}
this.manager.updateWindowSize( this );
return this;
};
/**
* Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
* when the window is opening. In general, setDimensions should not be called directly.
*
* To set the size of the window, use the #setSize method.
*
* @param {Object} dim CSS dimension properties
* @param {string|number} [dim.width] Width
* @param {string|number} [dim.minWidth] Minimum width
* @param {string|number} [dim.maxWidth] Maximum width
* @param {string|number} [dim.height] Height, omit to set based on height of contents
* @param {string|number} [dim.minHeight] Minimum height
* @param {string|number} [dim.maxHeight] Maximum height
* @chainable
* @return {OO.ui.Window} The window, for chaining
*/
OO.ui.Window.prototype.setDimensions = function ( dim ) {
var height,
win = this,
styleObj = this.$frame[ 0 ].style;
// Calculate the height we need to set using the correct width
if ( dim.height === undefined ) {
this.withoutSizeTransitions( function () {
var oldWidth = styleObj.width;
win.$frame.css( 'width', dim.width || '' );
height = win.getContentHeight();
styleObj.width = oldWidth;
} );
} else {
height = dim.height;
}
this.$frame.css( {
width: dim.width || '',
minWidth: dim.minWidth || '',
maxWidth: dim.maxWidth || '',
height: height || '',
minHeight: dim.minHeight || '',
maxHeight: dim.maxHeight || ''
} );
return this;
};
/**
* Initialize window contents.
*
* Before the window is opened for the first time, #initialize is called so that content that
* persists between openings can be added to the window.
*
* To set up a window with new content each time the window opens, use #getSetupProcess.
*
* @throws {Error} An error is thrown if the window is not attached to a window manager
* @chainable
* @return {OO.ui.Window} The window, for chaining
*/
OO.ui.Window.prototype.initialize = function () {
if ( !this.manager ) {
throw new Error( 'Cannot initialize window, must be attached to a manager' );
}
// Properties
this.$head = $( '<div>' );
this.$body = $( '<div>' );
this.$foot = $( '<div>' );
this.$document = $( this.getElementDocument() );
// Events
this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
// Initialization
this.$head.addClass( 'oo-ui-window-head' );
this.$body.addClass( 'oo-ui-window-body' );
this.$foot.addClass( 'oo-ui-window-foot' );
this.$content.append( this.$head, this.$body, this.$foot );
return this;
};
/**
* Called when someone tries to focus the hidden element at the end of the dialog.
* Sends focus back to the start of the dialog.
*
* @param {jQuery.Event} event Focus event
*/
OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
var backwards = this.$focusTrapBefore.is( event.target ),
element = OO.ui.findFocusable( this.$content, backwards );
if ( element ) {
// There's a focusable element inside the content, at the front or
// back depending on which focus trap we hit; select it.
element.focus();
} else {
// There's nothing focusable inside the content. As a fallback,
// this.$content is focusable, and focusing it will keep our focus
// properly trapped. It's not a *meaningful* focus, since it's just
// the content-div for the Window, but it's better than letting focus
// escape into the page.
this.$content.trigger( 'focus' );
}
};
/**
* Open the window.
*
* This method is a wrapper around a call to the window
* manager’s {@link OO.ui.WindowManager#openWindow openWindow} method.
*
* To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
*
* @param {Object} [data] Window opening data
* @return {OO.ui.WindowInstance} See OO.ui.WindowManager#openWindow
* @throws {Error} An error is thrown if the window is not attached to a window manager
*/
OO.ui.Window.prototype.open = function ( data ) {
if ( !this.manager ) {
throw new Error( 'Cannot open window, must be attached to a manager' );
}
return this.manager.openWindow( this, data );
};
/**
* Close the window.
*
* This method is a wrapper around a call to the window
* manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method.
*
* The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
* phase of the window’s lifecycle and can be used to specify closing behavior each time
* the window closes.
*
* @param {Object} [data] Window closing data
* @return {OO.ui.WindowInstance} See OO.ui.WindowManager#closeWindow
* @throws {Error} An error is thrown if the window is not attached to a window manager
*/
OO.ui.Window.prototype.close = function ( data ) {
if ( !this.manager ) {
throw new Error( 'Cannot close window, must be attached to a manager' );
}
return this.manager.closeWindow( this, data );
};
/**
* Setup window.
*
* This is called by OO.ui.WindowManager during window opening (before the animation), and should
* not be called directly by other systems.
*
* @param {Object} [data] Window opening data
* @return {jQuery.Promise} Promise resolved when window is setup
*/
OO.ui.Window.prototype.setup = function ( data ) {
var win = this;
this.toggle( true );
this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
this.$focusTraps.on( 'focus', this.focusTrapHandler );
return this.getSetupProcess( data ).execute().then( function () {
win.updateSize();
// Force redraw by asking the browser to measure the elements' widths
win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
win.$content.addClass( 'oo-ui-window-content-setup' ).width();
} );
};
/**
* Ready window.
*
* This is called by OO.ui.WindowManager during window opening (after the animation), and should not
* be called directly by other systems.
*
* @param {Object} [data] Window opening data
* @return {jQuery.Promise} Promise resolved when window is ready
*/
OO.ui.Window.prototype.ready = function ( data ) {
var win = this;
this.$content.trigger( 'focus' );
return this.getReadyProcess( data ).execute().then( function () {
// Force redraw by asking the browser to measure the elements' widths
win.$element.addClass( 'oo-ui-window-ready' ).width();
win.$content.addClass( 'oo-ui-window-content-ready' ).width();
} );
};
/**
* Hold window.
*
* This is called by OO.ui.WindowManager during window closing (before the animation), and should
* not be called directly by other systems.
*
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} Promise resolved when window is held
*/
OO.ui.Window.prototype.hold = function ( data ) {
var win = this;
return this.getHoldProcess( data ).execute().then( function () {
// Get the focused element within the window's content
var $focus = win.$content.find(
OO.ui.Element.static.getDocument( win.$content ).activeElement
);
// Blur the focused element
if ( $focus.length ) {
$focus[ 0 ].blur();
}
// Force redraw by asking the browser to measure the elements' widths
win.$element.removeClass( 'oo-ui-window-ready oo-ui-window-setup' ).width();
win.$content.removeClass( 'oo-ui-window-content-ready oo-ui-window-content-setup' ).width();
} );
};
/**
* Teardown window.
*
* This is called by OO.ui.WindowManager during window closing (after the animation), and should not
* be called directly by other systems.
*
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} Promise resolved when window is torn down
*/
OO.ui.Window.prototype.teardown = function ( data ) {
var win = this;
return this.getTeardownProcess( data ).execute().then( function () {
// Force redraw by asking the browser to measure the elements' widths
win.$element.removeClass( 'oo-ui-window-active' ).width();
win.$focusTraps.off( 'focus', win.focusTrapHandler );
win.toggle( false );
} );
};
/**
* The Dialog class serves as the base class for the other types of dialogs.
* Unless extended to include controls, the rendered dialog box is a simple window
* that users can close by hitting the Escape key. Dialog windows are used with OO.ui.WindowManager,
* which opens, closes, and controls the presentation of the window. See the
* [OOUI documentation on MediaWiki] [1] for more information.
*
* @example
* // A simple dialog window.
* function MyDialog( config ) {
* MyDialog.super.call( this, config );
* }
* OO.inheritClass( MyDialog, OO.ui.Dialog );
* MyDialog.static.name = 'myDialog';
* MyDialog.prototype.initialize = function () {
* MyDialog.super.prototype.initialize.call( this );
* this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.content.$element.append( '<p>A simple dialog window. Press Escape key to ' +
* 'close.</p>' );
* this.$body.append( this.content.$element );
* };
* MyDialog.prototype.getBodyHeight = function () {
* return this.content.$element.outerHeight( true );
* };
* var myDialog = new MyDialog( {
* size: 'medium'
* } );
* // Create and append a window manager, which opens and closes the window.
* var windowManager = new OO.ui.WindowManager();
* $( document.body ).append( windowManager.$element );
* windowManager.addWindows( [ myDialog ] );
* // Open the window!
* windowManager.openWindow( myDialog );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Dialogs
*
* @abstract
* @class
* @extends OO.ui.Window
* @mixins OO.ui.mixin.PendingElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.Dialog = function OoUiDialog( config ) {
// Parent constructor
OO.ui.Dialog.super.call( this, config );
// Mixin constructors
OO.ui.mixin.PendingElement.call( this );
// Properties
this.actions = new OO.ui.ActionSet();
this.attachedActions = [];
this.currentAction = null;
this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
// Events
this.actions.connect( this, {
click: 'onActionClick',
change: 'onActionsChange'
} );
// Initialization
this.$element
.addClass( 'oo-ui-dialog' )
.attr( 'role', 'dialog' );
};
/* Setup */
OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
/* Static Properties */
/**
* Symbolic name of dialog.
*
* The dialog class must have a symbolic name in order to be registered with OO.Factory.
* Please see the [OOUI documentation on MediaWiki] [3] for more information.
*
* [3]: https://www.mediawiki.org/wiki/OOUI/Windows/Window_managers
*
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.Dialog.static.name = '';
/**
* The dialog title.
*
* The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node,
* or a function that will produce a Label node or string. The title can also be specified with data
* passed to the constructor (see #getSetupProcess). In this case, the static value will be
* overridden.
*
* @abstract
* @static
* @inheritable
* @property {jQuery|string|Function}
*/
OO.ui.Dialog.static.title = '';
/**
* An array of configured {@link OO.ui.ActionWidget action widgets}.
*
* Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this
* case, the static value will be overridden.
*
* [2]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs#Action_sets
*
* @static
* @inheritable
* @property {Object[]}
*/
OO.ui.Dialog.static.actions = [];
/**
* Close the dialog when the Escape key is pressed.
*
* @static
* @abstract
* @inheritable
* @property {boolean}
*/
OO.ui.Dialog.static.escapable = true;
/* Methods */
/**
* Handle frame document key down events.
*
* @private
* @param {jQuery.Event} e Key down event
*/
OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
var actions;
if ( e.which === OO.ui.Keys.ESCAPE && this.constructor.static.escapable ) {
this.executeAction( '' );
e.preventDefault();
e.stopPropagation();
} else if ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) {
actions = this.actions.get( { flags: 'primary', visible: true, disabled: false } );
if ( actions.length > 0 ) {
this.executeAction( actions[ 0 ].getAction() );
e.preventDefault();
e.stopPropagation();
}
}
};
/**
* Handle action click events.
*
* @private
* @param {OO.ui.ActionWidget} action Action that was clicked
*/
OO.ui.Dialog.prototype.onActionClick = function ( action ) {
if ( !this.isPending() ) {
this.executeAction( action.getAction() );
}
};
/**
* Handle actions change event.
*
* @private
*/
OO.ui.Dialog.prototype.onActionsChange = function () {
this.detachActions();
if ( !this.isClosing() ) {
this.attachActions();
if ( !this.isOpening() ) {
// If the dialog is currently opening, this will be called automatically soon.
this.updateSize();
}
}
};
/**
* Get the set of actions used by the dialog.
*
* @return {OO.ui.ActionSet}
*/
OO.ui.Dialog.prototype.getActions = function () {
return this.actions;
};
/**
* Get a process for taking action.
*
* When you override this method, you can create a new OO.ui.Process and return it, or add
* additional accept steps to the process the parent method provides using the
* {@link OO.ui.Process#first 'first'} and {@link OO.ui.Process#next 'next'} methods of
* OO.ui.Process.
*
* @param {string} [action] Symbolic name of action
* @return {OO.ui.Process} Action process
*/
OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
return new OO.ui.Process()
.next( function () {
if ( !action ) {
// An empty action always closes the dialog without data, which should always be
// safe and make no changes
this.close();
}
}, this );
};
/**
* @inheritdoc
*
* @param {Object} [data] Dialog opening data
* @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
* the {@link #static-title static title}
* @param {Object[]} [data.actions] List of configuration options for each
* {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
*/
OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
.next( function () {
var config = this.constructor.static,
actions = data.actions !== undefined ? data.actions : config.actions,
title = data.title !== undefined ? data.title : config.title;
this.title.setLabel( title ).setTitle( title );
this.actions.add( this.getActionWidgets( actions ) );
this.$element.on( 'keydown', this.onDialogKeyDownHandler );
}, this );
};
/**
* @inheritdoc
*/
OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
// Parent method
return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
.first( function () {
this.$element.off( 'keydown', this.onDialogKeyDownHandler );
this.actions.clear();
this.currentAction = null;
}, this );
};
/**
* @inheritdoc
*/
OO.ui.Dialog.prototype.initialize = function () {
// Parent method
OO.ui.Dialog.super.prototype.initialize.call( this );
// Properties
this.title = new OO.ui.LabelWidget();
// Initialization
this.$content.addClass( 'oo-ui-dialog-content' );
this.$element.attr( 'aria-labelledby', this.title.getElementId() );
this.setPendingElement( this.$head );
};
/**
* Get action widgets from a list of configs
*
* @param {Object[]} actions Action widget configs
* @return {OO.ui.ActionWidget[]} Action widgets
*/
OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
var i, len, widgets = [];
for ( i = 0, len = actions.length; i < len; i++ ) {
widgets.push( this.getActionWidget( actions[ i ] ) );
}
return widgets;
};
/**
* Get action widget from config
*
* Override this method to change the action widget class used.
*
* @param {Object} config Action widget config
* @return {OO.ui.ActionWidget} Action widget
*/
OO.ui.Dialog.prototype.getActionWidget = function ( config ) {
return new OO.ui.ActionWidget( this.getActionWidgetConfig( config ) );
};
/**
* Get action widget config
*
* Override this method to modify the action widget config
*
* @param {Object} config Initial action widget config
* @return {Object} Action widget config
*/
OO.ui.Dialog.prototype.getActionWidgetConfig = function ( config ) {
return config;
};
/**
* Attach action actions.
*
* @protected
*/
OO.ui.Dialog.prototype.attachActions = function () {
// Remember the list of potentially attached actions
this.attachedActions = this.actions.get();
};
/**
* Detach action actions.
*
* @protected
* @chainable
* @return {OO.ui.Dialog} The dialog, for chaining
*/
OO.ui.Dialog.prototype.detachActions = function () {
var i, len;
// Detach all actions that may have been previously attached
for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
this.attachedActions[ i ].$element.detach();
}
this.attachedActions = [];
return this;
};
/**
* Execute an action.
*
* @param {string} action Symbolic name of action to execute
* @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
*/
OO.ui.Dialog.prototype.executeAction = function ( action ) {
this.pushPending();
this.currentAction = action;
return this.getActionProcess( action ).execute()
.always( this.popPending.bind( this ) );
};
/**
* MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
* consists of a header that contains the dialog title, a body with the message, and a footer that
* contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
* of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
*
* There are two basic types of message dialogs, confirmation and alert:
*
* - **confirmation**: the dialog title describes what a progressive action will do and the message
* provides more details about the consequences.
* - **alert**: the dialog title describes which event occurred and the message provides more
* information about why the event occurred.
*
* The MessageDialog class specifies two actions: ‘accept’, the primary
* action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
* passing along the selected action.
*
* For more information and examples, please see the [OOUI documentation on MediaWiki][1].
*
* @example
* // Example: Creating and opening a message dialog window.
* var messageDialog = new OO.ui.MessageDialog();
*
* // Create and append a window manager.
* var windowManager = new OO.ui.WindowManager();
* $( document.body ).append( windowManager.$element );
* windowManager.addWindows( [ messageDialog ] );
* // Open the window.
* windowManager.openWindow( messageDialog, {
* title: 'Basic message dialog',
* message: 'This is the message'
* } );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Message_Dialogs
*
* @class
* @extends OO.ui.Dialog
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
// Parent constructor
OO.ui.MessageDialog.super.call( this, config );
// Properties
this.verticalActionLayout = null;
// Initialization
this.$element.addClass( 'oo-ui-messageDialog' );
};
/* Setup */
OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.name = 'message';
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.size = 'small';
/**
* Dialog title.
*
* The title of a confirmation dialog describes what a progressive action will do. The
* title of an alert dialog describes which event occurred.
*
* @static
* @inheritable
* @property {jQuery|string|Function|null}
*/
OO.ui.MessageDialog.static.title = null;
/**
* The message displayed in the dialog body.
*
* A confirmation message describes the consequences of a progressive action. An alert
* message describes why an event occurred.
*
* @static
* @inheritable
* @property {jQuery|string|Function|null}
*/
OO.ui.MessageDialog.static.message = null;
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.actions = [
// Note that OO.ui.alert() and OO.ui.confirm() rely on these.
{ action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
{ action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
];
/* Methods */
/**
* Toggle action layout between vertical and horizontal.
*
* @private
* @param {boolean} [value] Layout actions vertically, omit to toggle
* @chainable
* @return {OO.ui.MessageDialog} The dialog, for chaining
*/
OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
value = value === undefined ? !this.verticalActionLayout : !!value;
if ( value !== this.verticalActionLayout ) {
this.verticalActionLayout = value;
this.$actions
.toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
.toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
}
return this;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
if ( action ) {
return new OO.ui.Process( function () {
this.close( { action: action } );
}, this );
}
return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
};
/**
* @inheritdoc
*
* @param {Object} [data] Dialog opening data
* @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
* @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
* @param {string} [data.size] Symbolic name of the dialog size, see OO.ui.Window
* @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
* action item
*/
OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
.next( function () {
this.title.setLabel(
data.title !== undefined ? data.title : this.constructor.static.title
);
this.message.setLabel(
data.message !== undefined ? data.message : this.constructor.static.message
);
this.size = data.size !== undefined ? data.size : this.constructor.static.size;
}, this );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.MessageDialog.super.prototype.getReadyProcess.call( this, data )
.next( function () {
// Focus the primary action button
var actions = this.actions.get();
actions = actions.filter( function ( action ) {
return action.getFlags().indexOf( 'primary' ) > -1;
} );
if ( actions.length > 0 ) {
actions[ 0 ].focus();
}
}, this );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getBodyHeight = function () {
var bodyHeight, oldOverflow,
$scrollable = this.container.$element;
oldOverflow = $scrollable[ 0 ].style.overflow;
$scrollable[ 0 ].style.overflow = 'hidden';
OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
bodyHeight = this.text.$element.outerHeight( true );
$scrollable[ 0 ].style.overflow = oldOverflow;
return bodyHeight;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
var
dialog = this,
$scrollable = this.container.$element;
OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim );
// Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
// Need to do it after transition completes (250ms), add 50ms just in case.
setTimeout( function () {
var oldOverflow = $scrollable[ 0 ].style.overflow,
activeElement = document.activeElement;
$scrollable[ 0 ].style.overflow = 'hidden';
OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
// Check reconsiderScrollbars didn't destroy our focus, as we
// are doing this after the ready process.
if ( activeElement && activeElement !== document.activeElement && activeElement.focus ) {
activeElement.focus();
}
$scrollable[ 0 ].style.overflow = oldOverflow;
}, 300 );
dialog.fitActions();
// Wait for CSS transition to finish and do it again :(
setTimeout( function () {
dialog.fitActions();
}, 300 );
return this;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.initialize = function () {
// Parent method
OO.ui.MessageDialog.super.prototype.initialize.call( this );
// Properties
this.$actions = $( '<div>' );
this.container = new OO.ui.PanelLayout( {
scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
} );
this.text = new OO.ui.PanelLayout( {
padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
} );
this.message = new OO.ui.LabelWidget( {
classes: [ 'oo-ui-messageDialog-message' ]
} );
// Initialization
this.title.$element.addClass( 'oo-ui-messageDialog-title' );
this.$content.addClass( 'oo-ui-messageDialog-content' );
this.container.$element.append( this.text.$element );
this.text.$element.append( this.title.$element, this.message.$element );
this.$body.append( this.container.$element );
this.$actions.addClass( 'oo-ui-messageDialog-actions' );
this.$foot.append( this.$actions );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getActionWidgetConfig = function ( config ) {
// Force unframed
return $.extend( {}, config, { framed: false } );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.attachActions = function () {
var i, len, special, others;
// Parent method
OO.ui.MessageDialog.super.prototype.attachActions.call( this );
special = this.actions.getSpecial();
others = this.actions.getOthers();
if ( special.safe ) {
this.$actions.append( special.safe.$element );
special.safe.toggleFramed( true );
}
for ( i = 0, len = others.length; i < len; i++ ) {
this.$actions.append( others[ i ].$element );
others[ i ].toggleFramed( true );
}
if ( special.primary ) {
this.$actions.append( special.primary.$element );
special.primary.toggleFramed( true );
}
};
/**
* Fit action actions into columns or rows.
*
* Columns will be used if all labels can fit without overflow, otherwise rows will be used.
*
* @private
*/
OO.ui.MessageDialog.prototype.fitActions = function () {
var i, len, action,
previous = this.verticalActionLayout,
actions = this.actions.get();
// Detect clipping
this.toggleVerticalActionLayout( false );
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
if ( action.$element[ 0 ].scrollWidth > action.$element[ 0 ].clientWidth ) {
this.toggleVerticalActionLayout( true );
break;
}
}
// Move the body out of the way of the foot
this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
if ( this.verticalActionLayout !== previous ) {
// We changed the layout, window height might need to be updated.
this.updateSize();
}
};
/**
* ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
* to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
* interface} alerts users to the trouble, permitting the user to dismiss the error and try again
* when relevant. The ProcessDialog class is always extended and customized with the actions and
* content required for each process.
*
* The process dialog box consists of a header that visually represents the ‘working’ state of long
* processes with an animation. The header contains the dialog title as well as
* two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
* a ‘primary’ action on the right (e.g., ‘Done’).
*
* Like other windows, the process dialog is managed by a
* {@link OO.ui.WindowManager window manager}.
* Please see the [OOUI documentation on MediaWiki][1] for more information and examples.
*
* @example
* // Example: Creating and opening a process dialog window.
* function MyProcessDialog( config ) {
* MyProcessDialog.super.call( this, config );
* }
* OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
*
* MyProcessDialog.static.name = 'myProcessDialog';
* MyProcessDialog.static.title = 'Process dialog';
* MyProcessDialog.static.actions = [
* { action: 'save', label: 'Done', flags: 'primary' },
* { label: 'Cancel', flags: 'safe' }
* ];
*
* MyProcessDialog.prototype.initialize = function () {
* MyProcessDialog.super.prototype.initialize.apply( this, arguments );
* this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.content.$element.append( '<p>This is a process dialog window. The header ' +
* 'contains the title and two buttons: \'Cancel\' (a safe action) on the left and ' +
* '\'Done\' (a primary action) on the right.</p>' );
* this.$body.append( this.content.$element );
* };
* MyProcessDialog.prototype.getActionProcess = function ( action ) {
* var dialog = this;
* if ( action ) {
* return new OO.ui.Process( function () {
* dialog.close( { action: action } );
* } );
* }
* return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
* };
*
* var windowManager = new OO.ui.WindowManager();
* $( document.body ).append( windowManager.$element );
*
* var dialog = new MyProcessDialog();
* windowManager.addWindows( [ dialog ] );
* windowManager.openWindow( dialog );
*
* [1]: https://www.mediawiki.org/wiki/OOUI/Windows/Process_Dialogs
*
* @abstract
* @class
* @extends OO.ui.Dialog
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
// Parent constructor
OO.ui.ProcessDialog.super.call( this, config );
// Properties
this.fitOnOpen = false;
// Initialization
this.$element.addClass( 'oo-ui-processDialog' );
if ( OO.ui.isMobile() ) {
this.$element.addClass( 'oo-ui-isMobile' );
}
};
/* Setup */
OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
/* Methods */
/**
* Handle dismiss button click events.
*
* Hides errors.
*
* @private
*/
OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
this.hideErrors();
};
/**
* Handle retry button click events.
*
* Hides errors and then tries again.
*
* @private
*/
OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
this.hideErrors();
this.executeAction( this.currentAction );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.initialize = function () {
// Parent method
OO.ui.ProcessDialog.super.prototype.initialize.call( this );
// Properties
this.$navigation = $( '<div>' );
this.$location = $( '<div>' );
this.$safeActions = $( '<div>' );
this.$primaryActions = $( '<div>' );
this.$otherActions = $( '<div>' );
this.dismissButton = new OO.ui.ButtonWidget( {
label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
} );
this.retryButton = new OO.ui.ButtonWidget();
this.$errors = $( '<div>' );
this.$errorsTitle = $( '<div>' );
// Events
this.dismissButton.connect( this, {
click: 'onDismissErrorButtonClick'
} );
this.retryButton.connect( this, {
click: 'onRetryButtonClick'
} );
this.title.connect( this, {
labelChange: 'fitLabel'
} );
// Initialization
this.title.$element.addClass( 'oo-ui-processDialog-title' );
this.$location
.append( this.title.$element )
.addClass( 'oo-ui-processDialog-location' );
this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
this.$errorsTitle
.addClass( 'oo-ui-processDialog-errors-title' )
.text( OO.ui.msg( 'ooui-dialog-process-error' ) );
this.$errors
.addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
.append(
this.$errorsTitle,
$( '<div>' ).addClass( 'oo-ui-processDialog-errors-actions' ).append(
this.dismissButton.$element, this.retryButton.$element
)
);
this.$content
.addClass( 'oo-ui-processDialog-content' )
.append( this.$errors );
this.$navigation
.addClass( 'oo-ui-processDialog-navigation' )
// Note: Order of appends below is important. These are in the order
// we want tab to go through them. Display-order is handled entirely
// by CSS absolute-positioning. As such, primary actions like "done"
// should go first.
.append( this.$primaryActions, this.$location, this.$safeActions );
this.$head.append( this.$navigation );
this.$foot.append( this.$otherActions );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.getActionWidgetConfig = function ( config ) {
function checkFlag( flag ) {
return config.flags === flag ||
( Array.isArray( config.flags ) && config.flags.indexOf( flag ) !== -1 );
}
config = $.extend( { framed: true }, config );
if ( checkFlag( 'close' ) ) {
// Change close buttons to icon only.
$.extend( config, {
icon: 'close',
invisibleLabel: true
} );
} else if ( checkFlag( 'back' ) ) {
// Change back buttons to icon only.
$.extend( config, {
icon: 'previous',
invisibleLabel: true
} );
}
return config;
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.attachActions = function () {
var i, len, other, special, others;
// Parent method
OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
special = this.actions.getSpecial();
others = this.actions.getOthers();
if ( special.primary ) {
this.$primaryActions.append( special.primary.$element );
}
for ( i = 0, len = others.length; i < len; i++ ) {
other = others[ i ];
this.$otherActions.append( other.$element );
}
if ( special.safe ) {
this.$safeActions.append( special.safe.$element );
}
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
var dialog = this;
return OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
.fail( function ( errors ) {
dialog.showErrors( errors || [] );
} );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.setDimensions = function () {
var dialog = this;
// Parent method
OO.ui.ProcessDialog.super.prototype.setDimensions.apply( this, arguments );
this.fitLabel();
// If there are many actions, they might be shown on multiple lines. Their layout can change
// when resizing the dialog and when changing the actions. Adjust the height of the footer to
// fit them.
dialog.$body.css( 'bottom', dialog.$foot.outerHeight( true ) );
// Wait for CSS transition to finish and do it again :(
setTimeout( function () {
dialog.$body.css( 'bottom', dialog.$foot.outerHeight( true ) );
}, 300 );
};
/**
* Fit label between actions.
*
* @private
* @chainable
* @return {OO.ui.MessageDialog} The dialog, for chaining
*/
OO.ui.ProcessDialog.prototype.fitLabel = function () {
var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
size = this.getSizeProperties();
if ( typeof size.width !== 'number' ) {
if ( this.isOpened() ) {
navigationWidth = this.$head.width() - 20;
} else if ( this.isOpening() ) {
if ( !this.fitOnOpen ) {
// Size is relative and the dialog isn't open yet, so wait.
// FIXME: This should ideally be handled by setup somehow.
this.manager.lifecycle.opened.done( this.fitLabel.bind( this ) );
this.fitOnOpen = true;
}
return;
} else {
return;
}
} else {
navigationWidth = size.width - 20;
}
safeWidth = this.$safeActions.width();
primaryWidth = this.$primaryActions.width();
biggerWidth = Math.max( safeWidth, primaryWidth );
labelWidth = this.title.$element.width();
if ( !OO.ui.isMobile() && 2 * biggerWidth + labelWidth < navigationWidth ) {
// We have enough space to center the label
leftWidth = rightWidth = biggerWidth;
} else {
// Let's hope we at least have enough space not to overlap, because we can't wrap
// the label.
if ( this.getDir() === 'ltr' ) {
leftWidth = safeWidth;
rightWidth = primaryWidth;
} else {
leftWidth = primaryWidth;
rightWidth = safeWidth;
}
}
this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
return this;
};
/**
* Handle errors that occurred during accept or reject processes.
*
* @private
* @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
*/
OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
var i, len, actions,
items = [],
abilities = {},
recoverable = true,
warning = false;
if ( errors instanceof OO.ui.Error ) {
errors = [ errors ];
}
for ( i = 0, len = errors.length; i < len; i++ ) {
if ( !errors[ i ].isRecoverable() ) {
recoverable = false;
}
if ( errors[ i ].isWarning() ) {
warning = true;
}
items.push( new OO.ui.MessageWidget( {
type: 'error',
label: errors[ i ].getMessage()
} ).$element[ 0 ] );
}
this.$errorItems = $( items );
if ( recoverable ) {
abilities[ this.currentAction ] = true;
// Copy the flags from the first matching action.
actions = this.actions.get( { actions: this.currentAction } );
if ( actions.length ) {
this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
}
} else {
abilities[ this.currentAction ] = false;
this.actions.setAbilities( abilities );
}
if ( warning ) {
this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
} else {
this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
}
this.retryButton.toggle( recoverable );
this.$errorsTitle.after( this.$errorItems );
this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
};
/**
* Hide errors.
*
* @private
*/
OO.ui.ProcessDialog.prototype.hideErrors = function () {
this.$errors.addClass( 'oo-ui-element-hidden' );
if ( this.$errorItems ) {
this.$errorItems.remove();
this.$errorItems = null;
}
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
// Parent method
return OO.ui.ProcessDialog.super.prototype.getTeardownProcess.call( this, data )
.first( function () {
// Make sure to hide errors.
this.hideErrors();
this.fitOnOpen = false;
}, this );
};
/**
* @class OO.ui
*/
/**
* Lazy-initialize and return a global OO.ui.WindowManager instance, used by OO.ui.alert and
* OO.ui.confirm.
*
* @private
* @return {OO.ui.WindowManager}
*/
OO.ui.getWindowManager = function () {
if ( !OO.ui.windowManager ) {
OO.ui.windowManager = new OO.ui.WindowManager();
$( document.body ).append( OO.ui.windowManager.$element );
OO.ui.windowManager.addWindows( [ new OO.ui.MessageDialog() ] );
}
return OO.ui.windowManager;
};
/**
* Display a quick modal alert dialog, using a OO.ui.MessageDialog. While the dialog is open, the
* rest of the page will be dimmed out and the user won't be able to interact with it. The dialog
* has only one action button, labelled "OK", clicking it will simply close the dialog.
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.alert( 'Something happened!' ).done( function () {
* console.log( 'User closed the dialog.' );
* } );
*
* OO.ui.alert( 'Something larger happened!', { size: 'large' } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @return {jQuery.Promise} Promise resolved when the user closes the dialog
*/
OO.ui.alert = function ( text, options ) {
return OO.ui.getWindowManager().openWindow( 'message', $.extend( {
message: text,
actions: [ OO.ui.MessageDialog.static.actions[ 0 ] ]
}, options ) ).closed.then( function () {
return undefined;
} );
};
/**
* Display a quick modal confirmation dialog, using a OO.ui.MessageDialog. While the dialog is open,
* the rest of the page will be dimmed out and the user won't be able to interact with it. The
* dialog has two action buttons, one to confirm an operation (labelled "OK") and one to cancel it
* (labelled "Cancel").
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.confirm( 'Are you sure?' ).done( function ( confirmed ) {
* if ( confirmed ) {
* console.log( 'User clicked "OK"!' );
* } else {
* console.log( 'User clicked "Cancel" or closed the dialog.' );
* }
* } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
* confirm, the promise will resolve to boolean `true`; otherwise, it will resolve to boolean
* `false`.
*/
OO.ui.confirm = function ( text, options ) {
return OO.ui.getWindowManager().openWindow( 'message', $.extend( {
message: text
}, options ) ).closed.then( function ( data ) {
return !!( data && data.action === 'accept' );
} );
};
/**
* Display a quick modal prompt dialog, using a OO.ui.MessageDialog. While the dialog is open,
* the rest of the page will be dimmed out and the user won't be able to interact with it. The
* dialog has a text input widget and two action buttons, one to confirm an operation
* (labelled "OK") and one to cancel it (labelled "Cancel").
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.prompt( 'Choose a line to go to', {
* textInput: { placeholder: 'Line number' }
* } ).done( function ( result ) {
* if ( result !== null ) {
* console.log( 'User typed "' + result + '" then clicked "OK".' );
* } else {
* console.log( 'User clicked "Cancel" or closed the dialog.' );
* }
* } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @param {Object} [options.textInput] Additional options for text input widget,
* see OO.ui.TextInputWidget
* @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
* confirm, the promise will resolve with the value of the text input widget; otherwise, it will
* resolve to `null`.
*/
OO.ui.prompt = function ( text, options ) {
var instance,
manager = OO.ui.getWindowManager(),
textInput = new OO.ui.TextInputWidget( ( options && options.textInput ) || {} ),
textField = new OO.ui.FieldLayout( textInput, {
align: 'top',
label: text
} );
instance = manager.openWindow( 'message', $.extend( {
message: textField.$element
}, options ) );
// TODO: This is a little hacky, and could be done by extending MessageDialog instead.
instance.opened.then( function () {
textInput.on( 'enter', function () {
manager.getCurrentWindow().close( { action: 'accept' } );
} );
textInput.focus();
} );
return instance.closed.then( function ( data ) {
return data && data.action === 'accept' ? textInput.getValue() : null;
} );
};
}( OO ) );
//# sourceMappingURL=oojs-ui-windows.js.map.json | cdnjs/cdnjs | ajax/libs/oojs-ui/0.41.3/oojs-ui-windows.js | JavaScript | mit | 117,418 |
/* home: http://getbootstrap.com */
/* version: 3.1.1 */
/*!
* Bootstrap v3.1.1 (http://getbootstrap.com)
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') }
/* ========================================================================
* Bootstrap: transition.js v3.1.1
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd otransitionend',
'transition' : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false, $el = this
$(this).one($.support.transition.end, function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
})
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.1.1
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.hasClass('alert') ? $this : $this.parent()
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
$parent.trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one($.support.transition.end, removeElement)
.emulateTransitionEnd(150) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
var old = $.fn.alert
$.fn.alert = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.1.1
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state = state + 'Text'
if (!data.resetText) $el.data('resetText', $el[val]())
$el[val](data[state] || this.options[state])
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
}
if (changed) this.$element.toggleClass('active')
}
// BUTTON PLUGIN DEFINITION
// ========================
var old = $.fn.button
$.fn.button = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document).on('click.bs.button.data-api', '[data-toggle^=button]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
$btn.button('toggle')
e.preventDefault()
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.1.1
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused =
this.sliding =
this.interval =
this.$active =
this.$items = null
this.options.pause == 'hover' && this.$element
.on('mouseenter', $.proxy(this.pause, this))
.on('mouseleave', $.proxy(this.cycle, this))
}
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getActiveIndex = function () {
this.$active = this.$element.find('.item.active')
this.$items = this.$active.parent().children()
return this.$items.index(this.$active)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getActiveIndex()
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) })
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos]))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || $active[type]()
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var fallback = type == 'next' ? 'first' : 'last'
var that = this
if (!$next.length) {
if (!this.options.wrap) return
$next = this.$element.find('.item')[fallback]()
}
if ($next.hasClass('active')) return this.sliding = false
var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction })
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
this.$element.one('slid.bs.carousel', function () {
var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()])
$nextIndicator && $nextIndicator.addClass('active')
})
}
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one($.support.transition.end, function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () { that.$element.trigger('slid.bs.carousel') }, 0)
})
.emulateTransitionEnd($active.css('transition-duration').slice(0, -1) * 1000)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger('slid.bs.carousel')
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
var old = $.fn.carousel
$.fn.carousel = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
$(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
var $this = $(this), href
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
$target.carousel(options)
if (slideIndex = $this.attr('data-slide-to')) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
})
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
$carousel.carousel($carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.1.1
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.transitioning = null
if (this.options.parent) this.$parent = $(this.options.parent)
if (this.options.toggle) this.toggle()
}
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var actives = this.$parent && this.$parent.find('> .panel > .in')
if (actives && actives.length) {
var hasData = actives.data('bs.collapse')
if (hasData && hasData.transitioning) return
actives.collapse('hide')
hasData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')
[dimension](0)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')
[dimension]('auto')
this.transitioning = 0
this.$element.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one($.support.transition.end, $.proxy(complete, this))
.emulateTransitionEnd(350)
[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element
[dimension](this.$element[dimension]())
[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse')
.removeClass('in')
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.trigger('hidden.bs.collapse')
.removeClass('collapsing')
.addClass('collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one($.support.transition.end, $.proxy(complete, this))
.emulateTransitionEnd(350)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
var old = $.fn.collapse
$.fn.collapse = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && option == 'show') option = !option
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) {
var $this = $(this), href
var target = $this.attr('data-target')
|| e.preventDefault()
|| (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
var $target = $(target)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
var parent = $this.attr('data-parent')
var $parent = parent && $(parent)
if (!data || !data.transitioning) {
if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed')
$this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
}
$target.collapse(option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.1.1
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle=dropdown]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$parent
.toggleClass('open')
.trigger('shown.bs.dropdown', relatedTarget)
$this.focus()
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27)/.test(e.keyCode)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive || (isActive && e.keyCode == 27)) {
if (e.which == 27) $parent.find(toggle).focus()
return $this.click()
}
var desc = ' li:not(.divider):visible a'
var $items = $parent.find('[role=menu]' + desc + ', [role=listbox]' + desc)
if (!$items.length) return
var index = $items.index($items.filter(':focus'))
if (e.keyCode == 38 && index > 0) index-- // up
if (e.keyCode == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).focus()
}
function clearMenus(e) {
$(backdrop).remove()
$(toggle).each(function () {
var $parent = getParent($(this))
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
})
}
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
var old = $.fn.dropdown
$.fn.dropdown = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle + ', [role=menu], [role=listbox]', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.1.1
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$element = $(element)
this.$backdrop =
this.isShown = null
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this[!this.isShown ? 'show' : 'hide'](_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.escape()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(document.body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$element.find('.modal-dialog') // wait for modal to slide in
.one($.support.transition.end, function () {
that.$element.focus().trigger(e)
})
.emulateTransitionEnd(300) :
that.$element.focus().trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
.off('click.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one($.support.transition.end, $.proxy(this.hideModal, this))
.emulateTransitionEnd(300) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.focus()
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.removeBackdrop()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.appendTo(document.body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus.call(this.$element[0])
: this.hide.call(this)
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one($.support.transition.end, callback)
.emulateTransitionEnd(150) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one($.support.transition.end, callback)
.emulateTransitionEnd(150) :
callback()
} else if (callback) {
callback()
}
}
// MODAL PLUGIN DEFINITION
// =======================
var old = $.fn.modal
$.fn.modal = function (option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target
.modal(option, this)
.one('hide', function () {
$this.is(':visible') && $this.focus()
})
})
$(document)
.on('show.bs.modal', '.modal', function () { $(document.body).addClass('modal-open') })
.on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open') })
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.1.1
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type =
this.options =
this.enabled =
this.timeout =
this.hoverState =
this.$element = null
this.init('tooltip', element, options)
}
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
var that = this;
var $tip = this.tip()
this.setContent()
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var $parent = this.$element.parent()
var orgPlacement = placement
var docScroll = document.documentElement.scrollTop || document.body.scrollTop
var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth()
var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight()
var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left
placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' :
placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' :
placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' :
placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
this.hoverState = null
var complete = function() {
that.$element.trigger('shown.bs.' + that.type)
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one($.support.transition.end, complete)
.emulateTransitionEnd(150) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var replace
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top = offset.top + marginTop
offset.left = offset.left + marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
replace = true
offset.top = offset.top + height - actualHeight
}
if (/bottom|top/.test(placement)) {
var delta = 0
if (offset.left < 0) {
delta = offset.left * -2
offset.left = 0
$tip.offset(offset)
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
}
this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
} else {
this.replaceArrow(actualHeight - height, actualHeight, 'top')
}
if (replace) $tip.offset(offset)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, position) {
this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + '%') : '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function () {
var that = this
var $tip = this.tip()
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element.trigger('hidden.bs.' + that.type)
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one($.support.transition.end, complete)
.emulateTransitionEnd(150) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function () {
var el = this.$element[0]
return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
width: el.offsetWidth,
height: el.offsetHeight
}, this.$element.offset())
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.tip = function () {
return this.$tip = this.$tip || $(this.options.template)
}
Tooltip.prototype.arrow = function () {
return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')
}
Tooltip.prototype.validate = function () {
if (!this.$element[0].parentNode) {
this.hide()
this.$element = null
this.options = null
}
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
Tooltip.prototype.destroy = function () {
clearTimeout(this.timeout)
this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
}
// TOOLTIP PLUGIN DEFINITION
// =========================
var old = $.fn.tooltip
$.fn.tooltip = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.1.1
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content')[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return this.$arrow = this.$arrow || this.tip().find('.arrow')
}
Popover.prototype.tip = function () {
if (!this.$tip) this.$tip = $(this.options.template)
return this.$tip
}
// POPOVER PLUGIN DEFINITION
// =========================
var old = $.fn.popover
$.fn.popover = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.1.1
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
var href
var process = $.proxy(this.process, this)
this.$element = $(element).is('body') ? $(window) : $(element)
this.$body = $('body')
this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target
|| ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
|| '') + ' .nav li > a'
this.offsets = $([])
this.targets = $([])
this.activeTarget = null
this.refresh()
this.process()
}
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.refresh = function () {
var offsetMethod = this.$element[0] == window ? 'offset' : 'position'
this.offsets = $([])
this.targets = $([])
var self = this
var $targets = this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[ $href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
var maxScroll = scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets.last()[0]) && this.activate(i)
}
if (activeTarget && scrollTop <= offsets[0]) {
return activeTarget != (i = targets[0]) && this.activate(i)
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate( targets[i] )
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
var old = $.fn.scrollspy
$.fn.scrollspy = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
$spy.scrollspy($spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.1.1
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
this.element = $(element)
}
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var previous = $ul.find('.active:last a')[0]
var e = $.Event('show.bs.tab', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.parent('li'), $ul)
this.activate($target, $target.parent(), function () {
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: previous
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& $active.hasClass('fade')
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
transition ?
$active
.one($.support.transition.end, next)
.emulateTransitionEnd(150) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
var old = $.fn.tab
$.fn.tab = function ( option ) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
$(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
e.preventDefault()
$(this).tab('show')
})
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.1.1
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$window = $(window)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed =
this.unpin =
this.pinnedOffset = null
this.checkPosition()
}
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$window.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var scrollHeight = $(document).height()
var scrollTop = this.$window.scrollTop()
var position = this.$element.offset()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
if (this.affixed == 'top') position.top += scrollTop
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false :
offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' :
offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false
if (this.affixed === affix) return
if (this.unpin) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger($.Event(affixType.replace('affix', 'affixed')))
if (affix == 'bottom') {
this.$element.offset({ top: scrollHeight - offsetBottom - this.$element.height() })
}
}
// AFFIX PLUGIN DEFINITION
// =======================
var old = $.fn.affix
$.fn.affix = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom) data.offset.bottom = data.offsetBottom
if (data.offsetTop) data.offset.top = data.offsetTop
$spy.affix(data)
})
})
}(jQuery);
| gsitgithub/java-spring-code | webapp-template/src/main/webapp/resources/javascripts/bootstrap.js | JavaScript | gpl-2.0 | 55,315 |
/**
* @file
* @author Bob Hutchinson http://drupal.org/user/52366
* @copyright GNU GPL
*
* Javascript functions for getlocations polylines support
* jquery stuff
*/
(function ($) {
Drupal.behaviors.getlocations_polylines = {
attach: function() {
var default_polyline_settings = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
};
$.each(Drupal.settings.getlocations_polylines, function (key, settings) {
var strokeColor = (settings.strokeColor ? settings.strokeColor : default_polyline_settings.strokeColor);
if (typeof strokeColor.match("/^#/") === null) {
strokeColor = '#' + strokeColor;
}
var strokeOpacity = (settings.strokeOpacity ? settings.strokeOpacity : default_polyline_settings.strokeOpacity);
var strokeWeight = (settings.strokeWeight ? settings.strokeWeight : default_polyline_settings.strokeWeight);
var clickable = (settings.clickable ? settings.clickable : default_polyline_settings.clickable);
var message = (settings.message ? settings.message : default_polyline_settings.message);
var polylines = settings.polylines;
var p_strokeColor = strokeColor;
var p_strokeOpacity = strokeOpacity;
var p_strokeWeight = strokeWeight;
var p_clickable = clickable;
var p_message = message;
var pl = [];
for (var i = 0; i < polylines.length; i++) {
pl = polylines[i];
if (pl.coords) {
if (pl.strokeColor) {
if (typeof pl.strokeColor.match("/^#/") === null) {
pl.strokeColor = '#' + pl.strokeColor;
}
p_strokeColor = pl.strokeColor;
}
if (pl.strokeOpacity) {
p_strokeOpacity = pl.strokeOpacity;
}
if (pl.strokeWeight) {
p_strokeWeight = pl.strokeWeight;
}
if (pl.clickable) {
p_clickable = pl.clickable;
}
if (pl.message) {
p_message = pl.message;
}
p_clickable = (p_clickable ? true : false);
var mcoords = [];
var poly = [];
scoords = pl.coords.split("|");
for (var s = 0; s < scoords.length; s++) {
var ll = scoords[s];
var lla = ll.split(",");
mcoords[s] = new google.maps.LatLng(parseFloat(lla[0]), parseFloat(lla[1]));
}
if (mcoords.length > 1) {
var polyOpts = {};
polyOpts.path = mcoords;
polyOpts.strokeColor = p_strokeColor;
polyOpts.strokeOpacity = p_strokeOpacity;
polyOpts.strokeWeight = p_strokeWeight;
polyOpts.clickable = p_clickable;
poly[i] = new google.maps.Polyline(polyOpts);
poly[i].setMap(getlocations_map[key]);
if (p_clickable && p_message) {
google.maps.event.addListener(poly[i], 'click', function(event) {
// close any previous instances
if (pushit) {
for (var i in getlocations_settings[key].infoBubbles) {
getlocations_settings[key].infoBubbles[i].close();
}
}
if (getlocations_settings[key].markeraction == 2) {
// infobubble
if (typeof(infoBubbleOptions) == 'object') {
var infoBubbleOpts = infoBubbleOptions;
}
else {
var infoBubbleOpts = {};
}
infoBubbleOpts.content = p_message;
infoBubbleOpts.position = event.latLng;
var iw = new InfoBubble(infoBubbleOpts);
}
else {
// infowindow
if (typeof(infoWindowOptions) == 'object') {
var infoWindowOpts = infoWindowOptions;
}
else {
var infoWindowOpts = {};
}
infoWindowOpts.content = p_message;
infoWindowOpts.position = event.latLng;
var iw = new google.maps.InfoWindow(infoWindowOpts);
}
iw.open(getlocations_map[key]);
if (pushit) {
getlocations_settings[key].infoBubbles.push(iw);
}
});
}
}
}
}
});
}
};
}(jQuery));
| Matwilk/ma | sites/all/modules/getlocations/js/getlocations_polylines.js | JavaScript | gpl-2.0 | 4,674 |
// script.aculo.us dragdrop.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
if(Object.isUndefined(Effect))
throw("dragdrop.js requires including script.aculo.us' effects.js library");
var Droppables = {
drops: [],
remove: function(element) {
this.drops = this.drops.reject(function(d) { return d.element==$(element) });
},
add: function(element) {
element = $(element);
var options = Object.extend({
greedy: true,
hoverclass: null,
tree: false
}, arguments[1] || { });
// cache containers
if(options.containment) {
options._containers = [];
var containment = options.containment;
if(Object.isArray(containment)) {
containment.each( function(c) { options._containers.push($(c)) });
} else {
options._containers.push($(containment));
}
}
if(options.accept) options.accept = [options.accept].flatten();
Element.makePositioned(element); // fix IE
options.element = element;
this.drops.push(options);
},
findDeepestChild: function(drops) {
deepest = drops[0];
for (i = 1; i < drops.length; ++i)
if (Element.isParent(drops[i].element, deepest.element))
deepest = drops[i];
return deepest;
},
isContained: function(element, drop) {
var containmentNode;
if(drop.tree) {
containmentNode = element.treeNode;
} else {
containmentNode = element.parentNode;
}
return drop._containers.detect(function(c) { return containmentNode == c });
},
isAffected: function(point, element, drop) {
return (
(drop.element!=element) &&
((!drop._containers) ||
this.isContained(element, drop)) &&
((!drop.accept) ||
(Element.classNames(element).detect(
function(v) { return drop.accept.include(v) } ) )) &&
Position.within(drop.element, point[0], point[1]) );
},
deactivate: function(drop) {
if(drop.hoverclass)
Element.removeClassName(drop.element, drop.hoverclass);
this.last_active = null;
},
activate: function(drop) {
if(drop.hoverclass)
Element.addClassName(drop.element, drop.hoverclass);
this.last_active = drop;
},
show: function(point, element) {
if(!this.drops.length) return;
var drop, affected = [];
this.drops.each( function(drop) {
if(Droppables.isAffected(point, element, drop))
affected.push(drop);
});
if(affected.length>0)
drop = Droppables.findDeepestChild(affected);
if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
if (drop) {
Position.within(drop.element, point[0], point[1]);
if(drop.onHover)
drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
if (drop != this.last_active) Droppables.activate(drop);
}
},
fire: function(event, element) {
if(!this.last_active) return;
Position.prepare();
if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
if (this.last_active.onDrop) {
this.last_active.onDrop(element, this.last_active.element, event);
return true;
}
},
reset: function() {
if(this.last_active)
this.deactivate(this.last_active);
}
};
var Draggables = {
drags: [],
observers: [],
register: function(draggable) {
if(this.drags.length == 0) {
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
this.eventKeypress = this.keyPress.bindAsEventListener(this);
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mousemove", this.eventMouseMove);
Event.observe(document, "keypress", this.eventKeypress);
}
this.drags.push(draggable);
},
unregister: function(draggable) {
this.drags = this.drags.reject(function(d) { return d==draggable });
if(this.drags.length == 0) {
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(document, "mousemove", this.eventMouseMove);
Event.stopObserving(document, "keypress", this.eventKeypress);
}
},
activate: function(draggable) {
if(draggable.options.delay) {
this._timeout = setTimeout(function() {
Draggables._timeout = null;
window.focus();
Draggables.activeDraggable = draggable;
}.bind(this), draggable.options.delay);
} else {
window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
this.activeDraggable = draggable;
}
},
deactivate: function() {
this.activeDraggable = null;
},
updateDrag: function(event) {
if(!this.activeDraggable) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
// Mozilla-based browsers fire successive mousemove events with
// the same coordinates, prevent needless redrawing (moz bug?)
if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
this._lastPointer = pointer;
this.activeDraggable.updateDrag(event, pointer);
},
endDrag: function(event) {
if(this._timeout) {
clearTimeout(this._timeout);
this._timeout = null;
}
if(!this.activeDraggable) return;
this._lastPointer = null;
this.activeDraggable.endDrag(event);
this.activeDraggable = null;
},
keyPress: function(event) {
if(this.activeDraggable)
this.activeDraggable.keyPress(event);
},
addObserver: function(observer) {
this.observers.push(observer);
this._cacheObserverCallbacks();
},
removeObserver: function(element) { // element instead of observer fixes mem leaks
this.observers = this.observers.reject( function(o) { return o.element==element });
this._cacheObserverCallbacks();
},
notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
if(this[eventName+'Count'] > 0)
this.observers.each( function(o) {
if(o[eventName]) o[eventName](eventName, draggable, event);
});
if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
},
_cacheObserverCallbacks: function() {
['onStart','onEnd','onDrag'].each( function(eventName) {
Draggables[eventName+'Count'] = Draggables.observers.select(
function(o) { return o[eventName]; }
).length;
});
}
};
/*--------------------------------------------------------------------------*/
var Draggable = Class.create({
initialize: function(element) {
var defaults = {
handle: false,
reverteffect: function(element, top_offset, left_offset) {
var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
queue: {scope:'_draggable', position:'end'}
});
},
endeffect: function(element) {
var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
queue: {scope:'_draggable', position:'end'},
afterFinish: function(){
Draggable._dragging[element] = false
}
});
},
zindex: 1000,
revert: false,
quiet: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
delay: 0
};
if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
Object.extend(defaults, {
starteffect: function(element) {
element._opacity = Element.getOpacity(element);
Draggable._dragging[element] = true;
new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
}
});
var options = Object.extend(defaults, arguments[1] || { });
this.element = $(element);
if(options.handle && Object.isString(options.handle))
this.handle = this.element.down('.'+options.handle, 0);
if(!this.handle) this.handle = $(options.handle);
if(!this.handle) this.handle = this.element;
if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
options.scroll = $(options.scroll);
this._isScrollChild = Element.childOf(this.element, options.scroll);
}
Element.makePositioned(this.element); // fix IE
this.options = options;
this.dragging = false;
this.eventMouseDown = this.initDrag.bindAsEventListener(this);
Event.observe(this.handle, "mousedown", this.eventMouseDown);
Draggables.register(this);
},
destroy: function() {
Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
Draggables.unregister(this);
},
currentDelta: function() {
return([
parseInt(Element.getStyle(this.element,'left') || '0'),
parseInt(Element.getStyle(this.element,'top') || '0')]);
},
initDrag: function(event) {
if(!Object.isUndefined(Draggable._dragging[this.element]) &&
Draggable._dragging[this.element]) return;
if(Event.isLeftClick(event)) {
// abort on form elements, fixes a Firefox issue
var src = Event.element(event);
if((tag_name = src.tagName.toUpperCase()) && (
tag_name=='INPUT' ||
tag_name=='SELECT' ||
tag_name=='OPTION' ||
tag_name=='BUTTON' ||
tag_name=='TEXTAREA')) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var pos = this.element.cumulativeOffset();
this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
Draggables.activate(this);
Event.stop(event);
}
},
startDrag: function(event) {
this.dragging = true;
if(!this.delta)
this.delta = this.currentDelta();
if(this.options.zindex) {
this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
this.element.style.zIndex = this.options.zindex;
}
if(this.options.ghosting) {
this._clone = this.element.cloneNode(true);
this._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
if (!this._originallyAbsolute)
Position.absolutize(this.element);
this.element.parentNode.insertBefore(this._clone, this.element);
}
if(this.options.scroll) {
if (this.options.scroll == window) {
var where = this._getWindowScroll(this.options.scroll);
this.originalScrollLeft = where.left;
this.originalScrollTop = where.top;
} else {
this.originalScrollLeft = this.options.scroll.scrollLeft;
this.originalScrollTop = this.options.scroll.scrollTop;
}
}
Draggables.notify('onStart', this, event);
if(this.options.starteffect) this.options.starteffect(this.element);
},
updateDrag: function(event, pointer) {
if(!this.dragging) this.startDrag(event);
if(!this.options.quiet){
Position.prepare();
Droppables.show(pointer, this.element);
}
Draggables.notify('onDrag', this, event);
this.draw(pointer);
if(this.options.change) this.options.change(this);
if(this.options.scroll) {
this.stopScrolling();
var p;
if (this.options.scroll == window) {
with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
} else {
p = Position.page(this.options.scroll);
p[0] += this.options.scroll.scrollLeft + Position.deltaX;
p[1] += this.options.scroll.scrollTop + Position.deltaY;
p.push(p[0]+this.options.scroll.offsetWidth);
p.push(p[1]+this.options.scroll.offsetHeight);
}
var speed = [0,0];
if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
this.startScrolling(speed);
}
// fix AppleWebKit rendering
if(Prototype.Browser.WebKit) window.scrollBy(0,0);
Event.stop(event);
},
finishDrag: function(event, success) {
this.dragging = false;
if(this.options.quiet){
Position.prepare();
var pointer = [Event.pointerX(event), Event.pointerY(event)];
Droppables.show(pointer, this.element);
}
if(this.options.ghosting) {
if (!this._originallyAbsolute)
Position.relativize(this.element);
if(IE)
this.element._originallyAbsolute = null;
else
delete this.element._originallyAbsolute;
Element.remove(this._clone);
this._clone = null;
}
var dropped = false;
if(success) {
dropped = Droppables.fire(event, this.element);
if (!dropped) dropped = false;
}
if(dropped && this.options.onDropped) this.options.onDropped(this.element);
Draggables.notify('onEnd', this, event);
var revert = this.options.revert;
if(revert && Object.isFunction(revert)) revert = revert(this.element);
var d = this.currentDelta();
if(revert && this.options.reverteffect) {
if (dropped == 0 || revert != 'failure')
this.options.reverteffect(this.element,
d[1]-this.delta[1], d[0]-this.delta[0]);
} else {
this.delta = d;
}
if(this.options.zindex)
this.element.style.zIndex = this.originalZ;
if(this.options.endeffect)
this.options.endeffect(this.element);
Draggables.deactivate(this);
Droppables.reset();
},
keyPress: function(event) {
if(event.keyCode!=Event.KEY_ESC) return;
this.finishDrag(event, false);
Event.stop(event);
},
endDrag: function(event) {
if(!this.dragging) return;
if(!event) var event = window.event;
this.stopScrolling();
this.finishDrag(event, true);
Event.stop(event);
},
draw: function(point) {
var pos = this.element.cumulativeOffset();
if(this.options.ghosting) {
var r = Position.realOffset(this.element);
pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
}
var d = this.currentDelta();
pos[0] -= d[0]; pos[1] -= d[1];
if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
}
var p = [0,1].map(function(i){
return (point[i]-pos[i]-this.offset[i])
}.bind(this));
if(this.options.snap) {
if(Object.isFunction(this.options.snap)) {
p = this.options.snap(p[0],p[1],this);
} else {
if(Object.isArray(this.options.snap)) {
p = p.map( function(v, i) {
return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this));
} else {
p = p.map( function(v) {
return (v/this.options.snap).round()*this.options.snap }.bind(this));
}
}}
var style = this.element.style;
if((!this.options.constraint) || (this.options.constraint=='horizontal'))
style.left = p[0] + "px";
if((!this.options.constraint) || (this.options.constraint=='vertical'))
style.top = p[1] + "px";
if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
},
stopScrolling: function() {
if(this.scrollInterval) {
clearInterval(this.scrollInterval);
this.scrollInterval = null;
Draggables._lastScrollPointer = null;
}
},
startScrolling: function(speed) {
if(!(speed[0] || speed[1])) return;
this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
this.lastScrolled = new Date();
this.scrollInterval = setInterval(this.scroll.bind(this), 10);
},
scroll: function() {
var current = new Date();
var delta = current - this.lastScrolled;
this.lastScrolled = current;
if(this.options.scroll == window) {
with (this._getWindowScroll(this.options.scroll)) {
if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
var d = delta / 1000;
this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
}
}
} else {
this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
}
Position.prepare();
Droppables.show(Draggables._lastPointer, this.element);
Draggables.notify('onDrag', this);
if (this._isScrollChild) {
Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
if (Draggables._lastScrollPointer[0] < 0)
Draggables._lastScrollPointer[0] = 0;
if (Draggables._lastScrollPointer[1] < 0)
Draggables._lastScrollPointer[1] = 0;
this.draw(Draggables._lastScrollPointer);
}
if(this.options.change) this.options.change(this);
},
_getWindowScroll: function(w) {
var T, L, W, H;
with (w.document) {
if (w.document.documentElement && documentElement.scrollTop) {
T = documentElement.scrollTop;
L = documentElement.scrollLeft;
} else if (w.document.body) {
T = body.scrollTop;
L = body.scrollLeft;
}
if (w.innerWidth) {
W = w.innerWidth;
H = w.innerHeight;
} else if (w.document.documentElement && documentElement.clientWidth) {
W = documentElement.clientWidth;
H = documentElement.clientHeight;
} else {
W = body.offsetWidth;
H = body.offsetHeight;
}
}
return { top: T, left: L, width: W, height: H };
}
});
Draggable._dragging = { };
/*--------------------------------------------------------------------------*/
var SortableObserver = Class.create({
initialize: function(element, observer) {
this.element = $(element);
this.observer = observer;
this.lastValue = Sortable.serialize(this.element);
},
onStart: function() {
this.lastValue = Sortable.serialize(this.element);
},
onEnd: function() {
Sortable.unmark();
if(this.lastValue != Sortable.serialize(this.element))
this.observer(this.element)
}
});
var Sortable = {
SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
sortables: { },
_findRootElement: function(element) {
while (element.tagName.toUpperCase() != "BODY") {
if(element.id && Sortable.sortables[element.id]) return element;
element = element.parentNode;
}
},
options: function(element) {
element = Sortable._findRootElement($(element));
if(!element) return;
return Sortable.sortables[element.id];
},
destroy: function(element){
element = $(element);
var s = Sortable.sortables[element.id];
if(s) {
Draggables.removeObserver(s.element);
s.droppables.each(function(d){ Droppables.remove(d) });
s.draggables.invoke('destroy');
delete Sortable.sortables[s.element.id];
}
},
create: function(element) {
element = $(element);
var options = Object.extend({
element: element,
tag: 'li', // assumes li children, override with tag: 'tagname'
dropOnEmpty: false,
tree: false,
treeTag: 'ul',
overlap: 'vertical', // one of 'vertical', 'horizontal'
constraint: 'vertical', // one of 'vertical', 'horizontal', false
containment: element, // also takes array of elements (or id's); or false
handle: false, // or a CSS class
only: false,
delay: 0,
hoverclass: null,
ghosting: false,
quiet: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
format: this.SERIALIZE_RULE,
// these take arrays of elements or ids and can be
// used for better initialization performance
elements: false,
handles: false,
onChange: Prototype.emptyFunction,
onUpdate: Prototype.emptyFunction
}, arguments[1] || { });
// clear any old sortable with same element
this.destroy(element);
// build options for the draggables
var options_for_draggable = {
revert: true,
quiet: options.quiet,
scroll: options.scroll,
scrollSpeed: options.scrollSpeed,
scrollSensitivity: options.scrollSensitivity,
delay: options.delay,
ghosting: options.ghosting,
constraint: options.constraint,
handle: options.handle };
if(options.starteffect)
options_for_draggable.starteffect = options.starteffect;
if(options.reverteffect)
options_for_draggable.reverteffect = options.reverteffect;
else
if(options.ghosting) options_for_draggable.reverteffect = function(element) {
element.style.top = 0;
element.style.left = 0;
};
if(options.endeffect)
options_for_draggable.endeffect = options.endeffect;
if(options.zindex)
options_for_draggable.zindex = options.zindex;
// build options for the droppables
var options_for_droppable = {
overlap: options.overlap,
containment: options.containment,
tree: options.tree,
hoverclass: options.hoverclass,
onHover: Sortable.onHover
};
var options_for_tree = {
onHover: Sortable.onEmptyHover,
overlap: options.overlap,
containment: options.containment,
hoverclass: options.hoverclass
};
// fix for gecko engine
Element.cleanWhitespace(element);
options.draggables = [];
options.droppables = [];
// drop on empty handling
if(options.dropOnEmpty || options.tree) {
Droppables.add(element, options_for_tree);
options.droppables.push(element);
}
(options.elements || this.findElements(element, options) || []).each( function(e,i) {
var handle = options.handles ? $(options.handles[i]) :
(options.handle ? $(e).select('.' + options.handle)[0] : e);
options.draggables.push(
new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
Droppables.add(e, options_for_droppable);
if(options.tree) e.treeNode = element;
options.droppables.push(e);
});
if(options.tree) {
(Sortable.findTreeElements(element, options) || []).each( function(e) {
Droppables.add(e, options_for_tree);
e.treeNode = element;
options.droppables.push(e);
});
}
// keep reference
this.sortables[element.identify()] = options;
// for onupdate
Draggables.addObserver(new SortableObserver(element, options.onUpdate));
},
// return all suitable-for-sortable elements in a guaranteed order
findElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.tag);
},
findTreeElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.treeTag);
},
onHover: function(element, dropon, overlap) {
if(Element.isParent(dropon, element)) return;
if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
return;
} else if(overlap>0.5) {
Sortable.mark(dropon, 'before');
if(dropon.previousSibling != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, dropon);
if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
} else {
Sortable.mark(dropon, 'after');
var nextElement = dropon.nextSibling || null;
if(nextElement != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, nextElement);
if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
}
},
onEmptyHover: function(element, dropon, overlap) {
var oldParentNode = element.parentNode;
var droponOptions = Sortable.options(dropon);
if(!Element.isParent(dropon, element)) {
var index;
var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
var child = null;
if(children) {
var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
for (index = 0; index < children.length; index += 1) {
if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
offset -= Element.offsetSize (children[index], droponOptions.overlap);
} else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
child = index + 1 < children.length ? children[index + 1] : null;
break;
} else {
child = children[index];
break;
}
}
}
dropon.insertBefore(element, child);
Sortable.options(oldParentNode).onChange(element);
droponOptions.onChange(element);
}
},
unmark: function() {
if(Sortable._marker) Sortable._marker.hide();
},
mark: function(dropon, position) {
// mark on ghosting only
var sortable = Sortable.options(dropon.parentNode);
if(sortable && !sortable.ghosting) return;
if(!Sortable._marker) {
Sortable._marker =
($('dropmarker') || Element.extend(document.createElement('DIV'))).
hide().addClassName('dropmarker').setStyle({position:'absolute'});
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
}
var offsets = dropon.cumulativeOffset();
Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
if(position=='after')
if(sortable.overlap == 'horizontal')
Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
else
Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
Sortable._marker.show();
},
_tree: function(element, options, parent) {
var children = Sortable.findElements(element, options) || [];
for (var i = 0; i < children.length; ++i) {
var match = children[i].id.match(options.format);
if (!match) continue;
var child = {
id: encodeURIComponent(match ? match[1] : null),
element: element,
parent: parent,
children: [],
position: parent.children.length,
container: $(children[i]).down(options.treeTag)
};
/* Get the element containing the children and recurse over it */
if (child.container)
this._tree(child.container, options, child);
parent.children.push (child);
}
return parent;
},
tree: function(element) {
element = $(element);
var sortableOptions = this.options(element);
var options = Object.extend({
tag: sortableOptions.tag,
treeTag: sortableOptions.treeTag,
only: sortableOptions.only,
name: element.id,
format: sortableOptions.format
}, arguments[1] || { });
var root = {
id: null,
parent: null,
children: [],
container: element,
position: 0
};
return Sortable._tree(element, options, root);
},
/* Construct a [i] index for a particular node */
_constructIndex: function(node) {
var index = '';
do {
if (node.id) index = '[' + node.position + ']' + index;
} while ((node = node.parent) != null);
return index;
},
sequence: function(element) {
element = $(element);
var options = Object.extend(this.options(element), arguments[1] || { });
return $(this.findElements(element, options) || []).map( function(item) {
return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
});
},
setSequence: function(element, new_sequence) {
element = $(element);
var options = Object.extend(this.options(element), arguments[2] || { });
var nodeMap = { };
this.findElements(element, options).each( function(n) {
if (n.id.match(options.format))
nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
n.parentNode.removeChild(n);
});
new_sequence.each(function(ident) {
var n = nodeMap[ident];
if (n) {
n[1].appendChild(n[0]);
delete nodeMap[ident];
}
});
},
serialize: function(element) {
element = $(element);
var options = Object.extend(Sortable.options(element), arguments[1] || { });
var name = encodeURIComponent(
(arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
if (options.tree) {
return Sortable.tree(element, arguments[1]).children.map( function (item) {
return [name + Sortable._constructIndex(item) + "[id]=" +
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
}).flatten().join('&');
} else {
return Sortable.sequence(element, arguments[1]).map( function(item) {
return name + "[]=" + encodeURIComponent(item);
}).join('&');
}
}
};
// Returns true if child is contained within element
Element.isParent = function(child, element) {
if (!child.parentNode || child == element) return false;
if (child.parentNode == element) return true;
return Element.isParent(child.parentNode, element);
};
Element.findChildren = function(element, only, recursive, tagName) {
if(!element.hasChildNodes()) return null;
tagName = tagName.toUpperCase();
if(only) only = [only].flatten();
var elements = [];
$A(element.childNodes).each( function(e) {
if(e.tagName && e.tagName.toUpperCase()==tagName &&
(!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
elements.push(e);
if(recursive) {
var grandchildren = Element.findChildren(e, only, recursive, tagName);
if(grandchildren) elements.push(grandchildren);
}
});
return (elements.length>0 ? elements.flatten() : []);
};
Element.offsetSize = function (element, type) {
return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
}; | olindata/debian-zabbix | frontends/php/js/scriptaculous/dragdrop.js | JavaScript | gpl-2.0 | 31,185 |
// **********************************************************************
//
// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
(function(module, require, exports)
{
var Ice = require("ice").Ice;
var Promise = Ice.Promise;
var test = function(b)
{
if(!b)
{
throw new Error("test failed");
}
};
//
// Create a new promise object and call function fn with
// the promise as its first argument, then return the new
// promise.
//
var deferred = function(fn)
{
var promise = new Promise();
fn.call(null, promise);
return promise;
};
var run = function(out)
{
var p = new Promise();
deferred(
function(promise)
{
out.write("Creating a promise object that is resolved and succeed... ");
var promise1 = new Promise().succeed(1024);
promise1.then(
function(i)
{
test(i === 1024);
test(promise1.succeeded());
out.writeLine("ok");
promise.succeed();
},
function(e)
{
promise.fail();
test(false, e);
});
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Creating a promise object that is resolved and failed... ");
var promise1 = new Promise().fail("promise.fail");
promise1.then(
function(i)
{
promise.fail();
test(false, i);
},
function(e)
{
test(e === "promise.fail");
test(promise1.failed());
out.writeLine("ok");
promise.succeed();
});
});
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Creating a promise object that is resolved and succeed with multiple arguments... ");
var promise1 = new Promise().succeed(1024, "Hello World!");
promise1.then(
function(i, msg)
{
test(i === 1024);
test(msg === "Hello World!");
test(promise1.succeeded());
out.writeLine("ok");
promise.succeed();
},
function(e)
{
promise.fail(e);
test(false, e);
});
});
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Creating a promise with a callback that returns a new value... ");
var promise1 = new Promise().succeed(1024);
promise1.then(
function(i)
{
test(i === 1024);
test(promise1.succeeded());
return "Hello World!";
},
function(e)
{
promise.fail();
test(false, e);
})
.then(
function(msg)
{
test(msg === "Hello World!");
out.writeLine("ok");
promise.succeed();
},
function(e)
{
promise.fail();
test(false, e);
});
});
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Creating a promise object that recovers from a failure... ");
var promise1 = new Promise().fail("promise.fail");
promise1.then(
function(i)
{
promise.fail();
test(false, "Succeed called.failed expected");
},
function(e)
{
test(e === "promise.fail");
test(promise1.failed());
return "Hello World!";
})
.then(
function(msg)
{
test(msg === "Hello World!");
out.writeLine("ok");
promise.succeed();
},
function(e)
{
promise.fail();
test(false, e);
});
});
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Creating a promise object that rethrow a.failure... ");
var promise1 = new Promise().fail("promise.fail");
promise1.then(
function(i)
{
promise.fail();
test(false, i);
},
function(e)
{
throw e;
})
.then(
function(msg)
{
promise.fail();
test(false, "Succeed called.failed expected");
},
function(e)
{
test(e === "promise.fail");
test(promise1.failed());
out.writeLine("ok");
promise.succeed();
});
});
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("A second call to then should produce the same results... ");
var promise1 = new Promise().succeed(1024);
promise1.then(
function(i)
{
test(i === 1024);
test(promise1.succeeded());
},
function(e)
{
promise.fail();
test(false, e);
});
promise1.then(
function(i)
{
test(i === 1024);
test(promise1.succeeded());
},
function(e)
{
promise.fail();
test(false, e);
});
promise1 = new Promise().fail("promise.fail");
promise1.then(
function(i)
{
promise.fail();
test(false, i);
},
function(e)
{
test(e === "promise.fail");
test(promise1.failed());
});
promise1.then(
function(i)
{
promise.fail();
test(false, i);
},
function(e)
{
test(e === "promise.fail");
test(promise1.failed());
out.writeLine("ok");
promise.succeed();
});
});
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Create a promise that is not yet resolved, but will succeed... ");
var promise1 = new Promise();
test(!promise1.completed());
promise1.then(
function(i)
{
test(i === 1024);
out.writeLine("ok");
promise.succeed();
},
function(e)
{
promise.fail();
test(false, e);
}
);
promise1.succeed(1024);
});
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Create a promise that is not yet resolved, but will.fail... ");
var promise1 = new Promise();
test(!promise1.completed());
promise1.then(
function(i)
{
promise.fail();
test(false, "Succeed called.failed expected");
},
function(e)
{
test(e === "promise.fail");
test(promise1.failed());
out.writeLine("ok");
promise.succeed();
}
);
promise1.fail("promise.fail");
});
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Create a promise chain that is not yet resolved, but will succeed... ");
var promise1 = new Promise();
var promise2 = new Promise();
var promise3 = new Promise();
promise1.then(
function(i)
{
test(i === 1);
return promise2;
},
function(e)
{
promise.fail();
test(false, e);
}
).then(
function(i)
{
test(i === 2);
return promise3;
},
function(e)
{
promise.fail();
test(false, e);
}
).then(
function(i)
{
test(i === 3);
return "Hello World!";
},
function(e)
{
promise.fail();
test(false, e);
}
).then(
function(msg)
{
test(promise1.succeeded() && promise2.succeeded() && promise3.succeeded());
test(msg === "Hello World!");
out.writeLine("ok");
promise.succeed();
},
function(e)
{
promise.fail();
test(false, e);
}
);
test(!promise1.completed() && !promise2.completed() && !promise3.completed());
promise1.succeed(1);
promise2.succeed(2);
promise3.succeed(3);
});
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Use exception method on a Promise that will.fail... ");
var promise1 = new Promise().fail("promise.fail");
promise1.exception(
function(e)
{
test(e === "promise.fail");
out.writeLine("ok");
promise.succeed();
}
);
});
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Promise exception propagation in succeed callback... ");
var promise1 = new Promise().fail("promise.fail");
promise1.then(
function()
{
promise.fail();
test(false, "response callback called but exception expected");
}
).then(
function()
{
promise.fail();
test(false, "response callback called but exception expected");
}
).exception(
function(e)
{
//
// since no exception handler was passed to the first `.then`, the error propagates.
//
test(e === "promise.fail");
out.writeLine("ok");
promise.succeed();
});
}
);
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Promise exception propagation in exception callback... ");
var promise1 = new Promise().fail("promise.fail");
promise1.then(
function()
{
promise.fail();
test(false, "response callback called but exception expected");
},
function(ex)
{
throw "promise.fail";
}
).then(
function()
{
promise.fail();
test(false, "response callback called but exception expected");
}
).then(
function()
{
promise.fail();
test(false, "response callback called but exception expected");
}
).exception(
function(e)
{
//
// since no exception handler was passed to the first `.then`, the error propagates.
//
test(e === "promise.fail");
out.writeLine("ok");
promise.succeed();
});
}
);
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Use Promise.all to wait for several promises and all succeed... ");
var promise1 = new Promise();
var promise2 = new Promise();
var promise3 = new Promise();
Promise.all(promise1, promise2, promise3).then(
function(r1, r2, r3)
{
test(r1.length === 1);
test(r1[0] === 1024);
test(r2.length === 2);
test(r2[0] === 1024);
test(r2[1] === 2048);
test(r3.length === 3);
test(r3[0] === 1024);
test(r3[1] === 2048);
test(r3[2] === 4096);
promise.succeed();
},
function()
{
promise.fail();
test(false);
}
);
//
// Now resolve the promise in the reverse order, all succeed callback
// will get the result in the right order.
//
promise3.succeed(1024, 2048, 4096);
promise2.succeed(1024, 2048);
promise1.succeed(1024);
}
);
})
.then(
function()
{
return deferred(
function(promise)
{
//
// Now try the same using an array of promises
//
var promise1 = new Promise();
var promise2 = new Promise();
var promise3 = new Promise();
Promise.all([promise1, promise2, promise3]).then(
function(r1, r2, r3)
{
test(r1.length === 1);
test(r1[0] === 1024);
test(r2.length === 2);
test(r2[0] === 1024);
test(r2[1] === 2048);
test(r3.length === 3);
test(r3[0] === 1024);
test(r3[1] === 2048);
test(r3[2] === 4096);
out.writeLine("ok");
promise.succeed();
},
function()
{
promise.fail();
test(false);
}
);
//
// Now resolve the promise in the reverse order, all succeed callback
// will get the result in the right order.
//
promise3.succeed(1024, 2048, 4096);
promise2.succeed(1024, 2048);
promise1.succeed(1024);
}
);
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Use Promise.all to wait for several promises and one fails... ");
var promise1 = new Promise();
var promise2 = new Promise();
var promise3 = new Promise();
Promise.all(promise1, promise2, promise3).then(
function(r1, r2, r3)
{
promise.fail(new Error());
},
function(e)
{
test(e === "promise.fail");
promise.succeed();
}
);
//
// Now resolve the promise in the reverse order.
//
promise3.succeed(1024, 2048, 4096);
promise2.succeed(1024, 2048);
promise1.fail("promise.fail");
}
);
})
.then(
function()
{
return deferred(
function(promise)
{
//
// Same as before but using an array of promises.
var promise1 = new Promise();
var promise2 = new Promise();
var promise3 = new Promise();
Promise.all([promise1, promise2, promise3]).then(
function(r1, r2, r3)
{
promise.fail(new Error());
},
function(e)
{
test(e === "promise.fail");
out.writeLine("ok");
promise.succeed();
}
);
//
// Now resolve the promise in the reverse order.
//
promise3.succeed(1024, 2048, 4096);
promise2.succeed(1024, 2048);
promise1.fail("promise.fail");
}
);
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Test finally on a succeed promise... ");
var p = new Promise().succeed(1024);
var called = false;
p.finally(
function(i)
{
called = true;
test(i == 1024);
return 1025;
}
).then(
function(i)
{
test(i == 1024);
test(called);
out.writeLine("ok");
promise.succeed();
}
).exception(
function(ex)
{
promise.fail(ex);
});
}
);
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Test finally on a failed promise... ");
var p = new Promise().fail("promise.failed");
var called = false;
p.finally(
function(e)
{
called = true;
test(e == "promise.failed");
return "foo";
}
).then(
function(i)
{
promise.fail(new Error());
}
).exception(
function(e)
{
test(called);
test(e == "promise.failed");
out.writeLine("ok");
promise.succeed();
});
}
);
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Test finally return a succeed promise... ");
var p = new Promise().succeed(1024);
var called = false;
p.finally(
function(e)
{
called = true;
return new Promise().succeed(2048);
}
).then(
function(i)
{
test(called);
test(i == 1024);
out.writeLine("ok");
promise.succeed();
}
).exception(
function(ex)
{
promise.fail(ex);
});
}
);
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Test finally return a fail promise... ");
var p = new Promise().succeed(1024);
var called = false;
p.finally(
function(e)
{
called = true;
return new Promise().fail(new Error("error"));
}
).then(
function(i)
{
test(called);
test(i == 1024);
out.writeLine("ok");
promise.succeed();
}
).exception(
function(ex)
{
promise.fail(ex);
});
}
);
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Test finally throw an exception... ");
var p = new Promise().succeed(1024);
var called = false;
p.finally(
function(e)
{
called = true;
throw new Error("error");
}
).then(
function(i)
{
test(called);
test(i == 1024);
out.writeLine("ok");
promise.succeed();
}
).exception(
function(ex)
{
promise.fail(ex);
});
}
);
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Test Promise.try... ");
Promise.try(
function()
{
out.writeLine("ok");
promise.succeed();
}
).exception(
function()
{
promise.fail(new Error("test failed"));
}
);
}
);
})
.then(
function()
{
return deferred(
function(promise)
{
out.write("Test promise delay... ");
var p = new Promise();
var start = Date.now();
p = p.succeed(10).delay(500).then(
function(i)
{
test(i == 10);
test(Date.now() - start >= 475 && Date.now() - start <= 525);
}
).exception(
function(ex)
{
promise.fail(ex);
});
//
// Now test the static version.
//
p = p.then(
function()
{
start = Date.now();
return Promise.delay(10, 500).then(
function(i)
{
test(i == 10);
test(Date.now() - start >= 475 && Date.now() - start <= 525);
}
).exception(
function(ex)
{
promise.fail(ex);
});
});
//
// Same but with fail
//
p.then(
function()
{
var f = new Promise();
start = Date.now();
return f.fail("failed").delay(500).then(
function(i)
{
test(false);
},
function(ex)
{
test(ex == "failed");
test(Date.now() - start >= 475 && Date.now() - start <= 525);
out.writeLine("ok");
promise.succeed();
}
).exception(
function(ex)
{
promise.fail(ex);
});
});
}
);
})
.then(
function(){
p.succeed();
},
function(ex){
p.fail(ex);
}
);
return p;
};
exports.__test__ = run;
}
(typeof(global) !== "undefined" && typeof(global.process) !== "undefined" ? module : undefined,
typeof(global) !== "undefined" && typeof(global.process) !== "undefined" ? require : window.Ice.__require,
typeof(global) !== "undefined" && typeof(global.process) !== "undefined" ? exports : window));
| elijah513/ice | js/test/Ice/promise/Client.js | JavaScript | gpl-2.0 | 34,762 |
jQuery.sap.declare("sap.ui.demo.myFiori.Component");
sap.ui.core.UIComponent.extend("sap.ui.demo.myFiori.Component", {
createContent : function() {
// create root view
var oView = sap.ui.view({
id : "app",
viewName : "sap.ui.demo.myFiori.view.App",
type : "JS",
viewData : { component : this }
});
// set data model on root view
var oModel = new sap.ui.model.json.JSONModel("model/mock.json");
oView.setModel(oModel);
// set i18n model
var i18nModel = new sap.ui.model.resource.ResourceModel({
bundleUrl : "i18n/messageBundle.properties"
});
oView.setModel(i18nModel, "i18n");
// set device model
var deviceModel = new sap.ui.model.json.JSONModel({
isPhone : jQuery.device.is.phone,
listMode : (jQuery.device.is.phone) ? "None" : "SingleSelectMaster",
listItemType : (jQuery.device.is.phone) ? "Active" : "Inactive"
});
deviceModel.setDefaultBindingMode("OneWay");
oView.setModel(deviceModel, "device");
// done
return oView;
}
}); | qmacro/SAPUI5-Fiori | Component.js | JavaScript | gpl-2.0 | 998 |
/*! jQuery UI - v1.10.4 - 2014-04-07
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
(function(t){t.effects.effect.shake=function(e,i){var s,n=t(this),a=["position","top","bottom","left","right","height","width"],o=t.effects.setMode(n,e.mode||"effect"),r=e.direction||"left",l=e.distance||20,h=e.times||3,c=2*h+1,u=Math.round(e.duration/c),d="up"===r||"down"===r?"top":"left",p="up"===r||"left"===r,f={},g={},m={},v=n.queue(),_=v.length;for(t.effects.save(n,a),n.show(),t.effects.createWrapper(n),f[d]=(p?"-=":"+=")+l,g[d]=(p?"+=":"-=")+2*l,m[d]=(p?"-=":"+=")+2*l,n.animate(f,u,e.easing),s=1;h>s;s++)n.animate(g,u,e.easing).animate(m,u,e.easing);n.animate(g,u,e.easing).animate(f,u/2,e.easing).queue(function(){"hide"===o&&n.hide(),t.effects.restore(n,a),t.effects.removeWrapper(n),i()}),_>1&&v.splice.apply(v,[1,0].concat(v.splice(_,c+1))),n.dequeue()}})(jQuery); | TabLand/timetabling | ux/lib/jquery/development-bundle/ui/minified/jquery.ui.effect-shake.min.js | JavaScript | gpl-3.0 | 914 |
var assert = require('assert')
, waatest = require('waatest')
, _ = require('underscore')
, async = require('async')
, helpers = require('../../helpers')
describe('dsp.osc~', function() {
var cos = Math.cos
, sin = Math.sin
afterEach(function() { helpers.afterEach() })
describe('contructor', function() {
it('should have frequency 0 by default', function(done) {
var patch = Pd.createPatch()
, osc = patch.createObject('osc~')
, dac = patch.createObject('dac~')
osc.o(0).connect(dac.i(0))
helpers.expectSamples(function() {}, [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
], done)
})
it('should take a frequency as first argument', function(done) {
var patch = Pd.createPatch()
, osc = patch.createObject('osc~', [440])
, dac = patch.createObject('dac~')
, k = 2*Math.PI*440 / Pd.getSampleRate()
osc.o(0).connect(dac.i(0))
helpers.expectSamples(function() {}, [
[1, cos(k*1), cos(k*2), cos(k*3), cos(k*4), cos(k*5), cos(k*6), cos(k*7), cos(k*8)],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
], done)
})
})
describe('i(0)', function() {
it('should update frequency when sending a message', function(done) {
var patch = Pd.createPatch()
, osc = patch.createObject('osc~', [440])
, dac = patch.createObject('dac~')
, k = 2*Math.PI*660 / Pd.getSampleRate()
osc.o(0).connect(dac.i(0))
helpers.expectSamples(function() {
osc.i(0).message([660])
}, [
[1, cos(k*1), cos(k*2), cos(k*3), cos(k*4), cos(k*5), cos(k*6), cos(k*7), cos(k*8)],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
], done)
})
it('should take input from dsp if an object is connected', function(done) {
var patch = Pd.createPatch()
, osc = patch.createObject('osc~', [440])
, dac = patch.createObject('dac~')
, line = patch.createObject('line~')
osc.o(0).connect(dac.i(0))
line.o(0).connect(osc.i(0))
helpers.expectSamples(function() {},
[
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
], done)
})
it('should take an input signal to modulate the frequency', function(done) {
var patch = Pd.createPatch()
, osc = patch.createObject('osc~')
, dac = patch.createObject('dac~')
, line = patch.createObject('line~')
, k = 2*Math.PI / Pd.getSampleRate()
, phases = [0], acc = 0
_.range(9).forEach(function(i) {
acc += (i * 10) * k
phases.push(acc)
})
osc.o(0).connect(dac.i(0))
line.o(0).connect(osc.i(0))
helpers.expectSamples(function() {
line.i(0).message([4410, 10]) // [0, 10, 20, 30, ...]
},
[
phases.map(cos),
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
], done)
})
it('should schedule frequency change in the future', function(done) {
var patch = Pd.createPatch()
, osc = patch.createObject('osc~', [440])
, dac = patch.createObject('dac~')
, k = 2*Math.PI*440 / Pd.getSampleRate()
, k2 = 2*Math.PI*660 / Pd.getSampleRate()
, phases = [0], acc = 0
_.range(8).forEach(function(i) {
acc += (i < 5) ? k : k2
phases.push(acc)
})
osc.o(0).connect(dac.i(0))
helpers.expectSamples(function() {
osc.i(0).future((1 / Pd.getSampleRate()) * 5 * 1000, [660])
}, [
phases.map(cos),
[0, 0, 0, 0, 0, 0, 0, 0, 0]
], done)
})
})
describe('i(1)', function() {
it('should reset the phase when receiving a message', function(done) {
var patch = Pd.createPatch()
, osc = patch.createObject('osc~', [440])
, dac = patch.createObject('dac~')
, k = 2*Math.PI*440 / Pd.getSampleRate()
osc.o(0).connect(dac.i(0))
async.series([
helpers.expectSamples.bind(helpers, function() {
osc.i(1).message([0.25])
}, [
[
cos(Math.PI / 2), cos(k*1 + Math.PI / 2), cos(k*2 + Math.PI / 2),
cos(k*3 + Math.PI / 2), cos(k*4 + Math.PI / 2), cos(k*5 + Math.PI / 2),
cos(k*6 + Math.PI / 2), cos(k*7 + Math.PI / 2), cos(k*8 + Math.PI / 2)
],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
]),
helpers.expectSamples.bind(helpers, function() {
osc.i(1).message([0.5])
}, [
[
-1, cos(k*1 + Math.PI), cos(k*2 + Math.PI),
cos(k*3 + Math.PI), cos(k*4 + Math.PI), cos(k*5 + Math.PI),
cos(k*6 + Math.PI), cos(k*7 + Math.PI), cos(k*8 + Math.PI)
],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
]),
helpers.expectSamples.bind(helpers, function() {
osc.i(1).message([0.75])
}, [
[0, sin(k*1), sin(k*2), sin(k*3), sin(k*4), sin(k*5), sin(k*6), sin(k*7), sin(k*8)],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
]),
helpers.expectSamples.bind(helpers, function() {
osc.i(1).message([1.25])
}, [
[
cos(Math.PI / 2), cos(k*1 + Math.PI / 2), cos(k*2 + Math.PI / 2),
cos(k*3 + Math.PI / 2), cos(k*4 + Math.PI / 2), cos(k*5 + Math.PI / 2),
cos(k*6 + Math.PI / 2), cos(k*7 + Math.PI / 2), cos(k*8 + Math.PI / 2)
],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
])
], done)
})
it.skip('should schedule phase change in the future', function(done) {
// To work properly we need to be able to schedule a connect and a disconnect
// in the future. That way we can setWaa the new oscillator at the right time.
})
})
})
describe('dsp.triangle~', function() {
afterEach(function() { helpers.afterEach() })
it('should generate a triangle', function(done) {
var patch = Pd.createPatch()
, triangle = patch.createObject('triangle~', [1])
, dac = patch.createObject('dac~')
, k = 4 / Pd.getSampleRate()
, acc = 0
, expected = []
for (var i = 0; i < 10; i++) {
expected.push(acc)
acc += k
}
triangle.o(0).connect(dac.i(0))
helpers.renderSamples(2, 10, function() {}, function(err, block) {
assert.deepEqual(
block[0].map(function(v) { return waatest.utils.round(v, 4) }),
expected.map(function(v) { return waatest.utils.round(v, 4) })
)
assert.deepEqual(block[1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
done()
})
})
})
describe('dsp.square~', function() {
afterEach(function() { helpers.afterEach() })
it('should generate a square', function(done) {
var patch = Pd.createPatch()
, sampleCount = 20
, square = patch.createObject('square~', [44100 / sampleCount])
, dac = patch.createObject('dac~')
, k = 4 / Pd.getSampleRate()
, acc = 0
, expected = []
for (var i = 0; i < sampleCount; i++) {
expected.push(acc)
acc += k
}
square.o(0).connect(dac.i(0))
helpers.renderSamples(2, sampleCount, function() {}, function(err, block) {
assert.equal(waatest.utils.round(block[0][0], 2), 0)
block[0].slice(1, sampleCount / 2).forEach(function(v) {
assert.ok(waatest.utils.round(v, 2) > 0.7)
})
assert.equal(waatest.utils.round(block[0][sampleCount / 2], 2), 0)
block[0].slice(sampleCount / 2 + 2).forEach(function(v) {
assert.ok(waatest.utils.round(v, 2) < -0.7)
})
assert.deepEqual(block[1], _.range(sampleCount).map(function() { return 0 }))
done()
})
})
})
describe.skip('dsp.phasor~', function() {
afterEach(function() { helpers.afterEach() })
describe('contructor', function() {
it.skip('should have frequency 0 by default', function(done) {
var patch = Pd.createPatch()
, phasor = patch.createObject('phasor~')
, dac = patch.createObject('dac~')
phasor.o(0).connect(dac.i(0))
helpers.expectSamples(function() {}, [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
], done)
})
it('should take a frequency as first argument', function(done) {
var patch = Pd.createPatch()
, phasor = patch.createObject('phasor~', [440])
, dac = patch.createObject('dac~')
, k = 1 / (Pd.getSampleRate() / 440)
phasor.o(0).connect(dac.i(0))
helpers.expectSamples(function() {}, [
[0, k, 2*k, 3*k, 4*k, 5*k, 6*k, 7*k, 8*k, 9*k],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
], done)
})
})
describe('i(0)', function() {
it('should update frequency when sending a message', function(done) {
var patch = Pd.createPatch()
, phasor = patch.createObject('phasor~', [440])
, dac = patch.createObject('dac~')
, k = 1 / (Pd.getSampleRate() / 660)
phasor.o(0).connect(dac.i(0))
helpers.expectSamples(function() {
phasor.i(0).message([660])
}, [
[0, k, 2*k, 3*k, 4*k, 5*k, 6*k, 7*k, 8*k, 9*k],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
], done)
})
it('should take an input signal to modulate the frequency', function(done) {
var patch = Pd.createPatch()
, phasor = patch.createObject('phasor~')
, dac = patch.createObject('dac~')
, line = patch.createObject('line~')
, k = 1 / Pd.getSampleRate()
, phases = [0], acc = 0
_.range(4410).forEach(function(i) {
if (i % 128 === 0)
k = 1 / (Pd.getSampleRate() / (i + 1))
acc += k
phases.push(acc % 1)
})
phasor.o(0).connect(dac.i(0))
line.o(0).connect(phasor.i(0))
helpers.expectSamples(function() {
line.i(0).message([10])
line.i(0).message([10 + 44100, 10]) // [0, 1, 2, 3, ...]
},
[
phases,
_.range(4410).map(function() { return 0 })
], done)
})
it.skip('should schedule frequency change in the future', function(done) {
var patch = Pd.createPatch()
, phasor = patch.createObject('phasor~', [440])
, dac = patch.createObject('dac~')
, k = 2*Math.PI*440 / Pd.getSampleRate()
, k2 = 2*Math.PI*660 / Pd.getSampleRate()
, phases = [0], acc = 0
_.range(8).forEach(function(i) {
acc += (i < 5) ? k : k2
phases.push(acc)
})
phasor.o(0).connect(dac.i(0))
helpers.expectSamples(function() {
phasor.i(0).future((1 / Pd.getSampleRate()) * 5 * 1000, [660])
}, [
phases.map(cos),
[0, 0, 0, 0, 0, 0, 0, 0, 0]
], done)
})
})
describe.skip('i(1)', function() {
it('should reset the phase when receiving a message', function(done) {
var patch = Pd.createPatch()
, phasor = patch.createObject('phasor~', [440])
, dac = patch.createObject('dac~')
, k = 2*Math.PI*440 / Pd.getSampleRate()
phasor.o(0).connect(dac.i(0))
async.series([
helpers.expectSamples.bind(helpers, function() {
phasor.i(1).message([0.25])
}, [
[
cos(Math.PI / 2), cos(k*1 + Math.PI / 2), cos(k*2 + Math.PI / 2),
cos(k*3 + Math.PI / 2), cos(k*4 + Math.PI / 2), cos(k*5 + Math.PI / 2),
cos(k*6 + Math.PI / 2), cos(k*7 + Math.PI / 2), cos(k*8 + Math.PI / 2)
],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
]),
helpers.expectSamples.bind(helpers, function() {
phasor.i(1).message([0.5])
}, [
[
-1, cos(k*1 + Math.PI), cos(k*2 + Math.PI),
cos(k*3 + Math.PI), cos(k*4 + Math.PI), cos(k*5 + Math.PI),
cos(k*6 + Math.PI), cos(k*7 + Math.PI), cos(k*8 + Math.PI)
],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
]),
helpers.expectSamples.bind(helpers, function() {
phasor.i(1).message([0.75])
}, [
[0, sin(k*1), sin(k*2), sin(k*3), sin(k*4), sin(k*5), sin(k*6), sin(k*7), sin(k*8)],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
]),
helpers.expectSamples.bind(helpers, function() {
phasor.i(1).message([1.25])
}, [
[
cos(Math.PI / 2), cos(k*1 + Math.PI / 2), cos(k*2 + Math.PI / 2),
cos(k*3 + Math.PI / 2), cos(k*4 + Math.PI / 2), cos(k*5 + Math.PI / 2),
cos(k*6 + Math.PI / 2), cos(k*7 + Math.PI / 2), cos(k*8 + Math.PI / 2)
],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
])
], done)
})
it.skip('should schedule phase change in the future', function(done) {
// To work properly we need to be able to schedule a connect and a disconnect
// in the future. That way we can setWaa the new oscillator at the right time.
})
})
}) | mcanthony/WebPd | test/browser/dsp/osc~phasor~triangle~square~-tests.js | JavaScript | gpl-3.0 | 12,793 |
var group__spi__dff =
[
[ "SPI_CR1_DFF_16BIT", "group__spi__dff.html#gaff3138f6c7be4a8a55699ffb40cdb4a8", null ],
[ "SPI_CR1_DFF_8BIT", "group__spi__dff.html#ga7cb377132c9f09bb43ca27057655a760", null ]
]; | Aghosh993/TARS_codebase | libopencm3/doc/stm32f4/html/group__spi__dff.js | JavaScript | gpl-3.0 | 212 |
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Lint = require("tslint");
var ErrorTolerantWalker_1 = require("./utils/ErrorTolerantWalker");
var Rule = (function (_super) {
__extends(Rule, _super);
function Rule() {
return _super.apply(this, arguments) || this;
}
Rule.prototype.apply = function (sourceFile) {
return this.applyWithWalker(new NoFunctionExpressionRuleWalker(sourceFile, this.getOptions()));
};
return Rule;
}(Lint.Rules.AbstractRule));
Rule.metadata = {
ruleName: 'no-function-expression',
type: 'maintainability',
description: 'Do not use function expressions; use arrow functions (lambdas) instead.',
options: null,
optionsDescription: '',
typescriptOnly: true,
issueClass: 'Non-SDL',
issueType: 'Warning',
severity: 'Important',
level: 'Opportunity for Excellence',
group: 'Clarity',
commonWeaknessEnumeration: '398, 710'
};
Rule.FAILURE_STRING = 'Use arrow function instead of function expression';
exports.Rule = Rule;
var NoFunctionExpressionRuleWalker = (function (_super) {
__extends(NoFunctionExpressionRuleWalker, _super);
function NoFunctionExpressionRuleWalker() {
return _super.apply(this, arguments) || this;
}
NoFunctionExpressionRuleWalker.prototype.visitFunctionExpression = function (node) {
var walker = new SingleFunctionWalker(this.getSourceFile(), this.getOptions());
node.getChildren().forEach(function (node) {
walker.walk(node);
});
if (!walker.isAccessingThis) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
}
_super.prototype.visitFunctionExpression.call(this, node);
};
return NoFunctionExpressionRuleWalker;
}(ErrorTolerantWalker_1.ErrorTolerantWalker));
var SingleFunctionWalker = (function (_super) {
__extends(SingleFunctionWalker, _super);
function SingleFunctionWalker() {
var _this = _super.apply(this, arguments) || this;
_this.isAccessingThis = false;
return _this;
}
SingleFunctionWalker.prototype.visitNode = function (node) {
if (node.getText() === 'this') {
this.isAccessingThis = true;
}
_super.prototype.visitNode.call(this, node);
};
SingleFunctionWalker.prototype.visitFunctionExpression = function (node) {
};
SingleFunctionWalker.prototype.visitArrowFunction = function (node) {
};
return SingleFunctionWalker;
}(ErrorTolerantWalker_1.ErrorTolerantWalker));
//# sourceMappingURL=noFunctionExpressionRule.js.map | dtysky/MoeNotes | tslint-contrib/noFunctionExpressionRule.js | JavaScript | gpl-3.0 | 2,841 |
define('ghost-admin/mirage/fixtures/roles', ['exports'], function (exports) {
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
exports['default'] = [{
id: 1,
uuid: 'b2576c4e-fa4e-41d4-8236-ced75f735222',
name: 'Administrator',
description: 'Administrators',
created_at: '2015-11-13T16:01:29.131Z',
created_by: 1,
updated_at: '2015-11-13T16:01:29.131Z',
updated_by: 1
}, {
id: 2,
uuid: '6ee03efb-322e-4f6e-9c91-bc228b5eec6b',
name: 'Editor',
description: 'Editors',
created_at: '2015-11-13T16:01:29.131Z',
created_by: 1,
updated_at: '2015-11-13T16:01:29.131Z',
updated_by: 1
}, {
id: 3,
uuid: 'de481b62-63f8-42c7-b5b9-6c5f5a877f53',
name: 'Author',
description: 'Authors',
created_at: '2015-11-13T16:01:29.131Z',
created_by: 1,
updated_at: '2015-11-13T16:01:29.131Z',
updated_by: 1
}, {
id: 4,
uuid: 'ac8cbaf6-e6be-4129-b0fb-ec9ddfa61056',
name: 'Owner',
description: 'Blog Owner',
created_at: '2015-11-13T16:01:29.132Z',
created_by: 1,
updated_at: '2015-11-13T16:01:29.132Z',
updated_by: 1
}];
}); | Elektro1776/latestEarthables | core/client/tmp/broccoli_persistent_filterbabel-output_path-OKbFKF1N.tmp/ghost-admin/mirage/fixtures/roles.js | JavaScript | gpl-3.0 | 1,286 |
var gulp = require('gulp');
var config = require('../../config.js');
var utils = require('../../utils.js');
gulp.task('copy-jquery-treeview-images', function(){
return gulp.src([config.paths.nodes + 'jquery-treeview/images/**/*'])
.pipe(gulp.dest( config.paths.build + 'vendors/jquery-treeview/images'));
});
gulp.task('build-jquery-treeview', ['copy-jquery-treeview-images'], function(){
// no standalone version used
/*utils.buildJsGroup([
config.paths.vendors + 'jquery-treeview/jquery.treeview.async.js'
], 'jquery.treeview.async', 'vendors/jquery-treeview');*/
return utils.buildJsGroup([
config.paths.nodes + 'jquery-treeview/jquery.treeview.js'
], 'jquery.treeview', 'vendors/jquery-treeview');
}); | nmaillat/Phraseanet | resources/gulp/components/vendors/jquery-treeview.js | JavaScript | gpl-3.0 | 754 |
var chai = require("chai");
chai.should();
require("./helpers/listdeps.js");
describe("VISH.Editor.Flashcard", function(){
//// OBJECT CREATION
it('should create a VISH.Editor.Flashcard object', function(){
VISH.Editor.Flashcard.should.be.an.instanceof(Object);
});
//// EXPORTED METHODS
it('should export init function', function(){
VISH.Editor.Flashcard.should.have.property('init');
});
it('should export getDummy function', function(){
VISH.Editor.Flashcard.should.have.property('getDummy');
});
it('should export onEnterSlideset function', function(){
VISH.Editor.Flashcard.should.have.property('onEnterSlideset');
});
it('should export onLeaveSlideset function', function(){
VISH.Editor.Flashcard.should.have.property('onLeaveSlideset');
});
it('should export beforeCreateSlidesetThumbnails function', function(){
VISH.Editor.Flashcard.should.have.property('beforeCreateSlidesetThumbnails');
});
it('should export getDefaultThumbnailURL function', function(){
VISH.Editor.Flashcard.should.have.property('getDefaultThumbnailURL');
});
it('should export preCopyActions function', function(){
VISH.Editor.Flashcard.should.have.property('preCopyActions');
});
it('should export postCopyActions function', function(){
VISH.Editor.Flashcard.should.have.property('postCopyActions');
});
//// METHOD RETURNS
describe("#getDummy", function(){
it('should return unknown', function(){
VISH.Editor.Flashcard.getDummy("slidesetId", "options").should.eql("<article id='slidesetId' type='flashcard' slidenumber='undefined'><div class='delete_slide'></div><img class='help_in_slide help_in_flashcard' src='undefinedvicons/helptutorial_circle_blank.png'/><div class='change_bg_button'></div></article>");
})
});
describe("#getDefaultThumbnailURL", function(){
it('should return unknown', function(){
VISH.Editor.Flashcard.getDefaultThumbnailURL().should.eql("undefinedtemplatesthumbs/flashcard_template.png");
})
});
});
| agordillo/vish_editor | test/VISH.Editor.Flashcard.test.js | JavaScript | agpl-3.0 | 2,141 |
var _Object$getOwnPropertyDescriptor = require("../core-js/object/get-own-property-descriptor");
var _Object$defineProperty = require("../core-js/object/define-property");
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)) {
var desc = _Object$defineProperty && _Object$getOwnPropertyDescriptor ? _Object$getOwnPropertyDescriptor(obj, key) : {};
if (desc.get || desc.set) {
_Object$defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
}
newObj.default = obj;
return newObj;
}
}
module.exports = _interopRequireWildcard; | ed1d1a8d/macweb | node_modules/@babel/runtime/helpers/interopRequireWildcard.js | JavaScript | agpl-3.0 | 818 |
var test = require('tape');
var parse = require('../').parse;
test('parse shell commands', function (t) {
t.same(parse('a \'b\' "c"'), [ 'a', 'b', 'c' ]);
t.same(
parse('beep "boop" \'foo bar baz\' "it\'s \\"so\\" groovy"'),
[ 'beep', 'boop', 'foo bar baz', 'it\'s "so" groovy' ]
);
t.same(parse('a b\\ c d'), [ 'a', 'b c', 'd' ]);
t.same(parse('\\$beep bo\\`op'), [ '$beep', 'bo`op' ]);
t.same(parse('echo "foo = \\"foo\\""'), [ 'echo', 'foo = "foo"' ]);
t.end();
});
| cgi-eoss/fstep | fs-tep-portal/src/main/resources/app/scripts/vendor/shell-quote/test/parse.js | JavaScript | agpl-3.0 | 519 |
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Copyright (C) 2012 Ravindra Nath Kakarla & Simon Newton
*/
// Global variable that holds the RDMTests object
rdmtests = undefined;
/**
* RDMTests class
*/
RDMTests = function() {
// An array to hold the test results
this.test_results = new Array();
this.tests_running = false;
// init tabs
$('#tabs').tabs({});
// setup dialog windows, one for general notifications and one for the
// download options.
this.notification = $('#rdm-tests-notification');
this.notification.dialog({
autoOpen: false,
closeOnEscape: false,
dialogClass: 'no-close',
draggable: false,
height: 160,
modal: true,
resizable: false,
});
this.save_options = $('#rdm-tests-save-options');
var save_buttons = [
{
text: 'Cancel',
click: function() { $(this).dialog('close'); }
},
{
text: 'Download',
click: function() { rdmtests.save_results() }
},
];
this.save_options.dialog({
autoOpen: false,
draggable: false,
height: 200,
modal: true,
resizable: false,
title: 'Download Options',
buttons: save_buttons,
});
this.error_notification = $('#rdm-error-notification');
var error_buttons = [
{
text: 'Dismiss',
click: function() { $(this).dialog('close'); }
},
{
text: 'Report Bug',
click: function() { rdmtests.report_bug() }
},
];
this.error_notification.dialog({
autoOpen: false,
buttons: error_buttons,
draggable: true,
height: 300,
modal: true,
resizable: true,
width: 550,
});
//Populate the filter with test categories
$('#rdm-tests-results-summary-filter-by_catg')
.append($('<option />').val('All').html('All'));
// and the other list in the download options dialog
$('#rdm-tests-save-catg')
.append($('<option />').val('All').html('All'));
};
/**
* AJAX loader image
* @this {RDMTests}
*/
RDMTests.ajax_loader = '<img src="/static/images/loader.gif" />';
/**
* How long to wait between polls of the test status. In milliseconds
* @this {RDMTests}
*/
RDMTests.poll_delay = 500;
/**
* Prepares the notification div and displays it on the page.
* @this {RDMTests}
* @param {Objec} options An object containing title and message to be
* displayed.
*
* {
* 'title': 'Title to display on notification',
* 'message': 'Notification Message',
* 'is_dismissable': true,
* 'buttons: [{'label': , 'on_click': {}],
* }
*/
RDMTests.prototype.set_notification = function(options) {
var title = '';
if (options.title != undefined || options.title != null) {
title = options.title;
}
this.notification.dialog('option', 'title', title);
var message = '';
if (options.message != undefined || options.message != null) {
message = options.message;
}
this.notification.html(message);
var button_list = options.buttons || [];
var buttons = []
if (options.is_dismissable != undefined || options.is_dismissable != null) {
buttons.push({
text: 'Ok',
click: function() { $(this).dialog('close'); }
});
} else {
for (var i = 0; i < button_list.length; ++i) {
var button = button_list[i];
buttons.push({
text: button['label'],
click: function() { button['on_click'](); },
});
}
}
this.notification.dialog('option', 'buttons', buttons);
this.notification.dialog('open');
};
/**
* A simplified version of the method above to display a dismissable dialog
* box.
*/
RDMTests.prototype.display_dialog_message = function(title, message) {
rdmtests.set_notification({
'title': title,
'message': message,
'is_dismissable': true
});
}
/**
* Clears the notification text and hides it from page.
* @this {RDMTests}
*/
RDMTests.prototype.clear_notification = function() {
this.notification.html();
this.notification.dialog('close');
};
/**
* Binds click, keypress and other events to DOMs and
* triggers the their respective handlers.
* @this {RDMTests}
*/
RDMTests.prototype.bind_events_to_doms = function() {
// key event handler
$(document).keydown(function(e) {
var key = e.keyCode || e.which;
var results_div = $('#rdm-tests-results');
var test_frame = $('#tests_control_frame');
// escape
if (results_div.css('display') == 'block' && key == 27) {
results_div.hide();
$('#tests_control_frame').show();
}
// enter
if (key == 13 && test_frame.css('display') == 'block' &&
!rdmtests.tests_running) {
rdmtests.validate_form();
}
});
// Elements on the responder test page
$('#universe_options').change(function() { rdmtests.update_device_list(); });
$('#devices_list').change(function() { rdmtests.device_list_changed(); });
$('#rdm-discovery-button').button().click(
function() { rdmtests.run_discovery(); }
);
$('#rdm-tests-selection-run_tests').button({
icons: {secondary: 'ui-icon-transferthick-e-w'}
}).click(function() { rdmtests.validate_form(); });
$('#rdm-tests-send_dmx_in_bg').change(function() {
$('#rdm-tests-dmx_options').toggle('fast');
});
// Elements on the responder test results page
$('#rdm-tests-results-button-dismiss').button({
icons: {secondary: 'ui-icon-arrowreturnthick-1-w'}
}).click(function() {
$('#rdm-tests-results').hide();
$('#tests_control_frame').show();
});
$('#rdm-tests-results-button-run_again').button({
icons: {secondary: 'ui-icon-transferthick-e-w'}
}).click(function() { rdmtests.run_tests(rdmtests.selected_tests); });
$('#rdm-tests-results-button-save-options').button({
icons: {secondary: 'ui-icon-disk'}
}).click(function() { rdmtests.save_options.dialog('open'); });
$.each($('.ola-expander'), function(i, fieldset) {
var legend = $(fieldset).find('legend');
legend.click(function() {
$(legend).find('span').first()
.toggleClass('ola-expander-collapsed ola-expander-expanded');
$(fieldset).find('div').toggle();
});
});
$.each([
$('#rdm-tests-results-summary-filter-by_catg'),
$('#rdm-tests-results-summary-filter-by_state')
], function(i, div) {
$(div).change(function() {
rdmtests.filter_results($('#rdm-tests-results-list'), {
'category': $('#rdm-tests-results-summary-filter-by_catg').val(),
'state': $('#rdm-tests-results-summary-filter-by_state').val()
});
});
});
// Elements on the publisher page
$('#publisher-collect-button').button({
icons: {secondary: 'ui-icon-search'}
}).click(function() { rdmtests.collect_data(); });
$('#publisher-clear-button').button({
icons: {secondary: 'ui-icon-cancel'}
}).click(function() {
$('#publisher-output').html('');
$('#publisher-upload-button').button('disable');
});
$('#publisher-upload-button').button({
disabled: true,
icons: {secondary: 'ui-icon-extlink'}
}).click(function() { rdmtests.upload_responder_info(); });
};
/**
* Download the saved results.
* @this {RDMTests}
*/
RDMTests.prototype.save_results = function() {
this.save_options.dialog('close');
var uid = $('#devices_list').val();
var url = ('/DownloadResults?uid=' + uid + '×tamp=' + this.timestamp +
'&state=' + $('#rdm-tests-save-state').val() + '&category=' +
$('#rdm-tests-save-catg').val());
if ($('#rdm-tests-include-debug').attr('checked')) {
url += '&debug=1';
}
if ($('#rdm-tests-include-description').attr('checked')) {
url += '&description=1';
}
$('#rdm-tests-download').attr('src', url);
};
/**
* Prepares a list item with appropriate color, definition and value.
* This will be appended to the results list.
* @this {RDMTests}
* @param {String} definition Key (or test definition) in TEST_RESULTS object.
* @return {Object} A jQuery object representation for a prepared list item.
*/
RDMTests.prototype.make_results_list_item = function(definition) {
var test_option = $('<option />').val(definition).text(definition);
rdmtests.add_state_class(
this.test_results[definition]['state'],
test_option);
return test_option;
};
/**
* Filters definitions in results list by category and state of test result.
* @this {RDMTests}
* @param {Object} results_dom A jQuery object representation of HTML <ul>
* which holds test result definitions.
* @param {Object} filter_options An Object containing selected filter options.
*/
RDMTests.prototype.filter_results = function(results_dom, filter_options) {
$(results_dom).html('');
var filter_category = filter_options['category'];
var filter_state = filter_options['state'];
if (filter_category == 'All') {
if (filter_state == 'All') {
for (var definition in this.test_results) {
$(results_dom).append(rdmtests.make_results_list_item(definition));
}
} else {
for (definition in this.test_results) {
if (this.test_results[definition]['state'] == filter_state) {
$(results_dom).append(rdmtests.make_results_list_item(definition));
}
}
}
} else {
if (filter_state == 'All') {
for (definition in this.test_results) {
if (this.test_results[definition]['category'] == filter_category) {
$(results_dom).append(rdmtests.make_results_list_item(definition));
}
}
} else {
for (definition in this.test_results) {
if (this.test_results[definition]['category'] == filter_category &&
this.test_results[definition]['state'] == filter_state) {
$(results_dom).append(rdmtests.make_results_list_item(definition));
}
}
}
}
};
/**
* Sends an AJAX request to the RDM Tests Server and
* triggers callback with the response.
* Automatically displays ERROR notifications when a request fails.
* @this {RDMTests}
* @param {String} request Request string.
* @param {Object} params An Object containing parameters to send to the server.
* @param {Object} callback Handler to trigger.
*/
RDMTests.prototype.query_server = function(request, params, callback) {
$.ajax({
url: request,
type: 'GET',
data: params,
dataType: 'json',
error: function(jqXHR, textStatus, errorThrown) {
rdmtests.display_dialog_message(
'Server Down',
'The RDM Test Server is not responding. Restart it and try again');
},
success: function(data) {
if (data['status'] == true) {
callback(data);
} else {
rdmtests.display_dialog_message('Server Error', data['error']);
}
},
cache: false
});
};
/**
* Updates the universe selector with available universes fetched
* from RDM Tests Server.
*/
RDMTests.prototype.update_universe_list = function() {
var t = this;
this.query_server('/GetUnivInfo', {},
function(data) { t.new_universe_list(data); });
};
/**
* Called when we receive a list of universes. This updates the universe lists.
*/
RDMTests.prototype.new_universe_list = function(data) {
var universes = data.universes;
this._update_universe_select($('#universe_options'), universes);
this._update_universe_select($('#publisher-universe-list'), universes);
if (universes.length == 0) {
rdmtests.set_notification({
'title': 'No universes found',
'message': ('Go to the <a href="http://' + location.hostname +
':9090" target="_blank">OLA Web UI</a> ' +
'and patch a device to a universe'),
'buttons': [{'label': 'Retry',
'on_click': function() {
rdmtests.clear_notification();
rdmtests.update_universe_list()
},
}
],
});
} else {
rdmtests.update_device_list();
}
};
/**
* Triggers Full Discovery of devices via AJAX request
* and updates the universe list.
*/
RDMTests.prototype.run_discovery = function() {
var universe = $('#universe_options').val();
if (universe == null || universe == undefined) {
rdmtests.display_dialog_message(
'No universe selected',
'Please select a universe to run discovery on.');
return;
}
rdmtests.set_notification({
'title': 'Running Full Discovery',
'message': RDMTests.ajax_loader
});
rdmtests.query_server('/RunDiscovery', {'u': universe}, function(data) {
var devices_list = $('#devices_list');
devices_list.empty();
if (data['status'] == true) {
var uids = data.uids;
$.each(uids, function(item) {
devices_list.append($('<option />').val(uids[item])
.text(uids[item]));
});
rdmtests.clear_notification();
}
});
};
/**
* Updates the patched devices list for selected universe.
*/
RDMTests.prototype.update_device_list = function() {
var universe_options = $('#universe_options');
var devices_list = $('#devices_list');
this.query_server('/GetDevices', {
'u': universe_options.val() }, function(data) {
if (data['status'] == true) {
devices_list.empty();
var uids = data.uids;
$.each(uids, function(item) {
devices_list.append($('<option />').val(uids[item]).text(uids[item]));
});
}
});
};
/**
* Called when the selected device changes.
*/
RDMTests.prototype.device_list_changed = function() {
$('#rdm-tests-selection-subset').attr('checked', true);
this._reset_failed_tests_list();
};
/**
* Fetches all Test Definitions available from the RDM Tests Server.
* Initializes the multiselect widget with definitions.
*/
RDMTests.prototype.fetch_test_defs = function() {
this.query_server('/GetTestDefs', {'c': 0}, function(data) {
var tests_selector = $('#rdm-tests-selection-tests_list');
var test_defs = data.test_defs;
$.each(data.test_defs, function(item) {
tests_selector.append($('<option />').val(test_defs[item])
.text(test_defs[item]));
});
$('#rdm-tests-selection-tests_list').multiselect({
sortable: false,
searchable: true
});
});
};
/**
* Triggers an AJAX call to run the tests with given Test Filter.
* @param {Array} test_filter An array of tests to run.
*/
RDMTests.prototype.run_tests = function(test_filter) {
this.tests_running = true;
this.set_notification({
'title': 'Running ' + test_filter.length + ' tests',
'message': '<div id="progressbar"></div>',
});
$('#progressbar').progressbar({});
this.selected_tests = test_filter;
this.query_server(
'/RunTests',
{
'u': $('#universe_options').val(),
'uid': $('#devices_list').val(),
'w': $('#write_delay').val(),
'f': ($('#rdm-tests-send_dmx_in_bg').attr('checked') ?
$('#dmx_frame_rate').val() : 0),
'c': $('#slot_count').val(),
'c': ($('#rdm-tests-send_dmx_in_bg').attr('checked') ?
$('#slot_count').val() : 128),
't': test_filter.join(',')
},
function(data) {
window.setTimeout(function() { rdmtests.stat_tests(); },
RDMTests.poll_delay);
}
);
};
/**
* Check if the tests are complete yet.
*/
RDMTests.prototype.stat_tests = function() {
this.query_server(
'/StatTests',
{},
function(data) {
rdmtests._stat_tests_response(data);
});
};
/**
* Resets the test results screen by clearing all the DOMs contents
* and hiding them.
*/
RDMTests.prototype.reset_results = function() {
$.each(['#rdm-tests-results-uid',
'#rdm-tests-results-duration',
'#rdm-tests-results-stats-figures',
'#rdm-tests-results-summary-by_catg-content',
'#rdm-tests-results-warnings-content',
'#rdm-tests-results-advisories-content',
'#rdm-tests-results-list'], function(i, dom) {
$(dom).html('');
});
$('#rdm-tests-results-summary-filter-by_state').val('All');
for (definition in this.test_results) {
delete this.test_results[definition];
}
};
/**
* Adds CSS class to the DOM based on the given state.
* This CSS class usually adds appropriate color to the text in the DOM.
* @param {String} state A valid test result state
* -- 'Passed', 'Failed', 'Broken', 'Not Run'.
* @param {Object} dom A jQuery object representation of the DOM
* to which the class needs to be added.
*/
RDMTests.prototype.add_state_class = function(state, dom) {
$(dom).removeClass($(dom).attr('class'));
switch (state) {
case 'Passed':
$(dom).addClass('test-state-passed');
break;
case 'Failed':
$(dom).addClass('test-state-failed');
break;
case 'Broken':
$(dom).addClass('test-state-broken');
break;
case 'Not Run':
$(dom).addClass('test-state-not_run');
break;
}
};
/**
* Initializes all the result screen DOMs and displays the results.
* @param {Object} results The response Object from the RDM Tests Server.
* which contains results.
*/
RDMTests.prototype.display_results = function(results) {
$('#tests_control_frame').hide();
rdmtests.reset_results();
$('#rdm-tests-results-uid').html(results['UID']);
var duration = Math.ceil(results['duration']);
if (duration == 1) {
$('#rdm-tests-results-duration').html(duration + ' second');
} else {
$('#rdm-tests-results-duration').html(duration + ' seconds');
}
for (key in results['stats']) {
$('#rdm-tests-results-stats-figures')
.append($('<td />').html(results['stats'][key]));
}
var category_lists = [$('#rdm-tests-results-summary-filter-by_catg'),
$('#rdm-tests-save-catg')];
$.each(category_lists,
function(i, dom) {
dom.html('');
dom.append($('<option />').val('All').html('All'));
});
// Summary of results by category
for (key in results['stats_by_catg']) {
var passed = results['stats_by_catg'][key]['passed'];
var total = results['stats_by_catg'][key]['total'];
if (total != 0) {
var percent = ' (' +
Math.ceil(passed / total * 100).toString() +
'%) </span>';
} else {
var percent = ' - </span>';
}
$('#rdm-tests-results-summary-by_catg-content')
.append($('<li />')
.html('<span>' +
key +
'</span>' +
'<span class="stats_by_catg">' +
passed.toString() +
' / ' +
total.toString() +
percent));
// update the lists as well
$.each(category_lists,
function(i, dom) {
dom.append($('<option />').val(key).html(key));
});
}
var number_of_warnings = 0;
var number_of_advisories = 0;
for (index in results['test_results']) {
var warnings = results['test_results'][index]['warnings'];
var advisories = results['test_results'][index]['advisories'];
var definition = results['test_results'][index]['definition'];
var state = results['test_results'][index]['state'];
//Populating a global variable with test results for faster lookups
this.test_results[definition] = results['test_results'][index];
number_of_warnings += warnings.length;
for (var i = 0; i < warnings.length; i++) {
$('#rdm-tests-results-warnings-content')
.append($('<li />')
.html(definition + ': ' + warnings[i]));
}
number_of_advisories += advisories.length;
for (var i = 0; i < advisories.length; i++) {
$('#rdm-tests-results-advisories-content')
.append($('<li />')
.html(definition + ': ' + advisories[i]));
}
var test_option = $('<option />').val(definition).text(definition);
rdmtests.add_state_class(state, test_option);
$('#rdm-tests-results-list').append(test_option);
}
//Update the Warnings and Advisories counter
$('#rdm-tests-results-warning-count').html(number_of_warnings.toString());
$('#rdm-tests-results-advisory-count').html(number_of_advisories.toString());
$('#rdm-tests-results-list').change(function() {
rdmtests.result_list_changed();
});
// select the first item
$('#rdm-tests-results-list').val(results['test_results'][0]['definition']);
rdmtests.result_list_changed();
$('#rdm-tests-results').show();
//Hide/Show Download Logs button
if (results['logs_disabled'] == true) {
$('#rdm-tests-results-button-save-options').hide();
} else {
$('#rdm-tests-results-button-save-options').show();
}
};
/**
* This is triggered when a definition in results summary is selected.
* The corresponding 'doc', 'debug' and category is updated in the info div.
*/
RDMTests.prototype.result_list_changed = function() {
var definition = $('#rdm-tests-results-list option:selected').text();
var state = this.test_results[definition]['state'];
$('#rdm-tests-results-info-title').html(definition);
rdmtests.add_state_class(state, $('#rdm-tests-results-info-state')
.html(state));
$('#rdm-tests-results-info-catg')
.html(this.test_results[definition]['category']);
$('#rdm-tests-results-info-doc')
.html(this.test_results[definition]['doc']);
var debug = this.test_results[definition]['debug'];
$('#rdm-tests-results-info-debug').html(debug.join('<br />'));
};
/**
* Validates the user input on Test Control Frame upon submission.
* Checks for proper threshold values and other parameters.
* @return {Boolean} True on successful validation.
*/
RDMTests.prototype.validate_form = function() {
this.isNumberField = function(dom) {
var value = $(dom).val();
if (value === '') {
return true;
}
if (isNaN(parseFloat(value)) || !isFinite(value)) {
var message = ($(dom).attr('id').replace('_', ' ').toUpperCase() +
' must be a number');
rdmtests.display_dialog_message('Error', message);
return false;
} else {
return true;
}
};
if ($('#devices_list option').size() < 1) {
rdmtests.display_dialog_message(
'Error',
'There are no devices patched to the selected universe!');
return false;
}
if (!(this.isNumberField($('#write_delay')) &&
this.isNumberField($('#dmx_frame_rate')) &&
this.isNumberField($('#slot_count')))) {
return false;
}
var slot_count_val = parseFloat($('#slot_count').val());
if (slot_count_val < 1 || slot_count_val > 512) {
rdmtests.display_dialog_message(
'Error',
'Invalid number of slots (expected: [1-512])');
return false;
}
var test_filter = ['all'];
if ($('#rdm-tests-selection-subset').attr('checked')) {
if ($('select[name="subset_test_defs"]').val() == null) {
rdmtests.display_dialog_message('Error',
'There are no tests selected to run');
return false;
} else {
test_filter = $('select[name="subset_test_defs"]').val();
}
} else if ($('#rdm-tests-selection-previously_failed').attr('checked')) {
if ($('select[name="failed_test_defs"]').val() == null) {
rdmtests.display_dialog_message(
'Error',
'There are no failed tests selected to run');
return false;
} else {
test_filter = $('select[name="failed_test_defs"]').val();
}
}
rdmtests.run_tests(test_filter);
};
/**
* Collect information for the RDM devices present on a universe.
*/
RDMTests.prototype.collect_data = function() {
$('#publisher-output').html('');
rdmtests.set_notification({
'title': 'Collecting Responder Data',
'message': RDMTests.ajax_loader
});
this.query_server(
'/RunCollector',
{ 'u': $('#publisher-universe-list').val(),
'skip_queued': $('#publisher-skip-queued-messages').attr('checked') ? true : false,
},
function(data) {
window.setTimeout(function() { rdmtests.stat_collector(); },
RDMTests.poll_delay);
}
);
};
/**
* Check if the collector is complete yet.
*/
RDMTests.prototype.stat_collector = function() {
this.query_server(
'/StatCollector',
{},
function(data) {
rdmtests._stat_collector_response(data);
});
};
/**
* Handle the response from a /StatCollector call
*/
RDMTests.prototype._stat_collector_response = function(data) {
if (data['completed']) {
rdmtests.clear_notification();
var exception = data['exception'];
if (exception != undefined) {
this.error_notification.dialog('option', 'title', 'Server Error');
$('#error-message').html(exception)
$('#traceback').html(data['traceback'])
this.error_notification.dialog('open');
this.exception = exception;
this.traceback = data['traceback'];
return;
}
$('#publisher-output').html(data['output']);
$('#publisher_upload_data').val(data['output']);
$('#publisher-upload-button').button('enable');
} else {
window.setTimeout(function() { rdmtests.stat_collector()},
RDMTests.poll_delay);
}
};
/**
* Upload the collected responder data.
*/
RDMTests.prototype.upload_responder_info = function() {
$('#publisher-upload-form').submit();
}
/**
* Open the bug report window using the most recent exception & traceback.
*/
RDMTests.prototype.report_bug = function() {
var comments = 'Error: ' + this.exception + '\n\n' + this.traceback;
var url = (
'http://code.google.com/p/open-lighting/issues/entry?' +
'summary=Bug%20Report%20From%20RDM%20Tests' +
'&comment=' + encodeURIComponent(comments));
window.open(url, '_blank');
};
/**
* Handle the response from a /StatTests call
*/
RDMTests.prototype._stat_tests_response = function(data) {
if (data['completed']) {
this.tests_running = false;
var exception = data['exception'];
if (exception != undefined) {
rdmtests.clear_notification();
this.error_notification.dialog('option', 'title', 'Server Error');
$('#error-message').html(exception)
$('#traceback').html(data['traceback'])
this.error_notification.dialog('open');
this.exception = exception;
this.traceback = data['traceback'];
return;
}
this.timestamp = data['timestamp'];
var failed_defs = new Array();
for (i in data['test_results']) {
switch (data['test_results'][i]['state']) {
case 'Failed':
failed_defs.push(data['test_results'][i]['definition']);
break;
}
}
this._reset_failed_tests_list();
var failed_tests = $('#rdm-tests-selection-failed_tests');
for (var i = 0; i < failed_defs.length; ++i) {
failed_tests.append($('<option />')
.val(failed_defs[i])
.text(failed_defs[i]));
}
failed_tests.multiselect();
rdmtests.clear_notification();
rdmtests.display_results(data);
} else {
// update progress here
var percent = data['tests_completed'] / data['total_tests'] * 100;
$('#progressbar').progressbar('option', 'value', percent);
window.setTimeout(function() { rdmtests.stat_tests()},
RDMTests.poll_delay);
}
};
/**
* Update a Universe <select> with new data.
*/
RDMTests.prototype._update_universe_select = function(select, universes) {
select.empty();
$.each(universes, function(i) {
var text = universes[i]._name + ' (' + universes[i]._id + ')';
select.append(
$('<option />').val(universes[i]._id).text(text));
});
};
/**
* Reset failed tests
*/
RDMTests.prototype._reset_failed_tests_list = function() {
var failed_tests = $('#rdm-tests-selection-failed_tests');
if (failed_tests.next().length > 0) {
failed_tests.multiselect('destroy');
}
failed_tests.html('');
};
/**
* Called once the page has loaded and we're ready to go.
*/
$(document).ready(function() {
rdmtests = new RDMTests();
rdmtests.bind_events_to_doms();
rdmtests.update_universe_list();
rdmtests.fetch_test_defs();
});
| mlba-team/open-lighting | tools/rdm/static/rdm_tests.js | JavaScript | lgpl-2.1 | 28,685 |
/**
* Copyright (c) 2010-present Abixen Systems. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
(function () {
'use strict';
angular
.module('platformChartModule')
.factory('ApplicationDataSource', ApplicationDataSource);
ApplicationDataSource.$inject = ['$resource'];
function ApplicationDataSource($resource) {
return $resource('/api/service/abixen/business-intelligence/control-panel/multi-visualisation/data-sources/', {}, {
query: {method: 'GET', isArray: false}
});
}
})(); | abixen/abixen-platform | abixen-platform-business-intelligence-service/src/main/web/service/abixen/business-intelligence/application/multi-visualisation/javascript/application-data-source.factory.js | JavaScript | lgpl-2.1 | 1,049 |
/*
* Waltz - Enterprise Architecture
* Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project
* See README.md for more information
*
* 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
*
*/
import _ from "lodash";
import BaseLookupService from "./BaseLookupService";
import {enums} from "./enums"
import preventNavigationService from "./prevent-navigation-service";
import serviceBroker from "./service-broker";
import {CORE_API} from "./core-api-utils";
import {toMap} from "../map-utils";
import {remote} from "../../svelte-stores/remote";
const displayNameService = new BaseLookupService();
const iconNameService = new BaseLookupService();
const iconColorService = new BaseLookupService();
const descriptionService = new BaseLookupService();
function loadFromServer(involvementKindService,
serviceBroker) {
serviceBroker
.loadAppData(CORE_API.DataTypeStore.findAll)
.then(result => {
// DEPRECATED, should be byId
const indexedByCode = _.keyBy(result.data, "code");
const indexedById = _.keyBy(result.data, "id");
displayNameService
.register("dataType", _.mapValues(indexedByCode, "name"))
.register("dataType", _.mapValues(indexedById, "name"))
;
descriptionService
.register("dataType", _.mapValues(indexedByCode, "description"))
.register("dataType", _.mapValues(indexedById, "description"))
;
});
involvementKindService
.loadInvolvementKinds()
.then(results => {
const indexedById = _.keyBy(results, "id");
displayNameService.register("involvementKind", _.mapValues(indexedById, "name"));
descriptionService.register("involvementKind", _.mapValues(indexedById, "description"));
});
serviceBroker
.loadAppData(CORE_API.MeasurableCategoryStore.findAll)
.then(result => {
const indexedById = _.keyBy(result.data, "id");
displayNameService.register("measurableCategory", _.mapValues(indexedById, "name"));
descriptionService.register("measurableCategory", _.mapValues(indexedById, "description"));
});
serviceBroker
.loadAppData(CORE_API.EntityNamedNoteTypeStore.findAll)
.then(result => {
const indexedById = _.keyBy(result.data, "id");
displayNameService.register("entityNamedNoteType", _.mapValues(indexedById, "name"));
descriptionService.register("entityNamedNoteType", _.mapValues(indexedById, "description"));
});
serviceBroker
.loadAppData(CORE_API.EnumValueStore.findAll)
.then(r => {
const keyFn = x => x.key;
_.chain(r.data)
.groupBy("type")
.each((xs, type) => {
displayNameService.register(type, toMap(xs, keyFn, x => x.name));
descriptionService.register(type, toMap(xs, keyFn, x => x.description));
iconNameService.register(type, toMap(xs, keyFn, x => x.icon));
iconColorService.register(type, toMap(xs, keyFn, x => x.iconColor));
})
.value();
});
}
export default (module) => {
module
.service("DisplayNameService", () => displayNameService)
.service("IconNameService", () => iconNameService)
.service("IconColorService", () => iconColorService)
.service("DescriptionService", () => descriptionService)
.service("PreventNavigationService", preventNavigationService)
.service("ServiceBroker", serviceBroker);
const keyFn = x => x.key;
_.each(enums, (xs, type) => {
displayNameService.register(type, toMap(xs, keyFn, x => x.name));
descriptionService.register(type, toMap(xs, keyFn, x => x.description));
iconNameService.register(type, toMap(xs, keyFn, x => x.icon));
iconColorService.register(type, toMap(xs, keyFn, x => x.iconColor));
});
loadFromServer.$inject = [
"InvolvementKindService",
"ServiceBroker"
];
function configServiceBroker($transitions, serviceBroker) {
$transitions.onBefore({}, (transition, state, opts) => {
remote.clear();
const promise = serviceBroker
.loadViewData(CORE_API.ClientCacheKeyStore.findAll)
.then(r => r.data)
.then(oldCacheKeys => {
serviceBroker.resetViewData();
return serviceBroker
.loadViewData(
CORE_API.ClientCacheKeyStore.findAll,
[],
{force: true})
.then(r => r.data)
.then(newCacheKeys => {
const differences = _.differenceWith(newCacheKeys, oldCacheKeys, _.isEqual);
if (differences.length > 0) {
serviceBroker.resetAppData();
}
});
});
transition.promise.finally(promise);
});
}
configServiceBroker.$inject = [
"$transitions",
"ServiceBroker"
];
module
.run(loadFromServer)
.run(configServiceBroker);
};
| khartec/waltz | waltz-ng/client/common/services/index.js | JavaScript | apache-2.0 | 5,860 |
/// Copyright (c) 2009 Microsoft Corporation
///
/// Redistribution and use in source and binary forms, with or without modification, are permitted provided
/// that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice, this list of conditions and
/// the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
/// the following disclaimer in the documentation and/or other materials provided with the distribution.
/// * Neither the name of Microsoft nor the names of its contributors may be used to
/// endorse or promote products derived from this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
/// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
/// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
/// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
/// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ES5Harness.registerTest({
id: "15.5.4.20-3-5",
path: "TestCases/chapter15/15.5/15.5.4/15.5.4.20/15.5.4.20-3-5.js",
description: "String.prototype.trim - 'S' is a string end with union of all LineTerminator and all WhiteSpace",
test: function testcase() {
var lineTerminatorsStr = "\u000A\u000D\u2028\u2029";
var whiteSpacesStr = "\u0009\u000A\u000B\u000C\u000D\u0020\u0085\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF";
var str = "abc" + whiteSpacesStr + lineTerminatorsStr ;
return (str.trim() === "abc");
},
precondition: function prereq() {
return fnExists(String.prototype.trim);
}
});
| hnafar/IronJS | Src/Tests/ietestcenter/chapter15/15.5/15.5.4/15.5.4.20/15.5.4.20-3-5.js | JavaScript | apache-2.0 | 2,301 |
import {BrowserWindow} from 'electron';
import {findItemById, findMenu} from 'browser/menus/utils';
import prefs from 'browser/utils/prefs';
/**
* Set a key of the item with the given value.
*/
export function setLocal (localKey, valueExpr) {
return function (item) {
item[localKey] = valueExpr.apply(this, arguments);
};
}
/**
* Sets a preference key.
*/
export function setPref (prefName, valueExpr) {
return function () {
prefs.set(prefName, valueExpr.apply(this, arguments));
};
}
/**
* Unsets a preference key.
*/
export function unsetPref (prefName) {
return function () {
prefs.unset(prefName);
};
}
/**
* Updates the value of a sibling item's key.
*/
export function updateSibling (siblingId, siblingKey, valueExpr) {
return function (item) {
const submenu = (this && this.submenu) || (item && item.menu && item.menu.items);
if (submenu) {
const sibling = submenu.find((i) => i.id === siblingId);
if (sibling) {
sibling[siblingKey] = valueExpr.apply(this, arguments);
}
}
};
}
/**
* Update an item from another menu.
*/
export function updateMenuItem (menuType, itemId) {
return function (...valueExprs) {
return function (exprCallback) {
return function () {
const menu = findMenu(menuType);
if (!menu) {
return log('menu not found', menuType);
}
const menuItem = findItemById(menu.items, itemId);
if (!menuItem) {
return log('menu item not found', itemId);
}
const values = valueExprs.map((e) => e.apply(this, arguments));
const expr = exprCallback(...values);
const browserWindow = BrowserWindow.getFocusedWindow();
expr.call(global, menuItem, browserWindow);
};
};
};
}
| rafael-neri/whatsapp-webapp | src/scripts/browser/menus/expressions/expr-parse.js | JavaScript | apache-2.0 | 1,790 |
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(function(global, utils) {
'use strict';
%CheckIsBootstrapping();
// -------------------------------------------------------------------
// Imports
var GlobalRegExp = global.RegExp;
var GlobalRegExpPrototype = GlobalRegExp.prototype;
var MakeTypeError;
utils.Import(function(from) {
MakeTypeError = from.MakeTypeError;
});
// -------------------------------------------------------------------
// ES6 21.2.5.15.
function RegExpGetUnicode() {
if (!IS_REGEXP(this)) {
// TODO(littledan): Remove this RegExp compat workaround
if (this === GlobalRegExpPrototype) {
%IncrementUseCounter(kRegExpPrototypeUnicodeGetter);
return UNDEFINED;
}
throw MakeTypeError(kRegExpNonRegExp, "RegExp.prototype.unicode");
}
return !!REGEXP_UNICODE(this);
}
%FunctionSetName(RegExpGetUnicode, "RegExp.prototype.unicode");
%SetNativeFlag(RegExpGetUnicode);
utils.InstallGetter(GlobalRegExp.prototype, 'unicode', RegExpGetUnicode);
})
| m0ppers/arangodb | 3rdParty/V8/V8-5.0.71.39/src/js/harmony-unicode-regexps.js | JavaScript | apache-2.0 | 1,124 |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.readFile = exports.stat = void 0;
const stat = (inputFileSystem, path) => new Promise((resolve, reject) => {
inputFileSystem.stat(path, (err, stats) => {
if (err) {
reject(err);
}
resolve(stats);
});
});
exports.stat = stat;
const readFile = (inputFileSystem, path) => new Promise((resolve, reject) => {
inputFileSystem.readFile(path, (err, stats) => {
if (err) {
reject(err);
}
resolve(stats);
});
});
exports.readFile = readFile; | cloudfoundry-community/asp.net5-buildpack | fixtures/node_apps/angular_dotnet/ClientApp/node_modules/copy-webpack-plugin/dist/utils/promisify.js | JavaScript | apache-2.0 | 569 |
/*! jQuery-ui-Slider-Pips - v1.11.3 - 2016-03-15
* Copyright (c) 2016 Simon Goellner <simey.me@gmail.com>; Licensed MIT */
(function($) {
"use strict";
var extensionMethods = {
// pips
pips: function( settings ) {
var slider = this,
i, j, p,
collection = "",
mousedownHandlers,
min = slider._valueMin(),
max = slider._valueMax(),
pips = ( max - min ) / slider.options.step,
$handles = slider.element.find(".ui-slider-handle"),
$pips;
var options = {
first: "label",
/* "label", "pip", false */
last: "label",
/* "label", "pip", false */
rest: "pip",
/* "label", "pip", false */
labels: false,
/* [array], { first: "string", rest: [array], last: "string" }, false */
prefix: "",
/* "", string */
suffix: "",
/* "", string */
step: ( pips > 100 ) ? Math.floor( pips * 0.05 ) : 1,
/* number */
formatLabel: function(value) {
return this.prefix + value + this.suffix;
}
/* function
must return a value to display in the pip labels */
};
if ( $.type( settings ) === "object" || $.type( settings ) === "undefined" ) {
$.extend( options, settings );
slider.element.data("pips-options", options );
} else {
if ( settings === "destroy" ) {
destroy();
} else if ( settings === "refresh" ) {
slider.element.slider( "pips", slider.element.data("pips-options") );
}
return;
}
// we don't want the step ever to be a floating point or negative
// (or 0 actually, so we'll set it to 1 in that case).
slider.options.pipStep = Math.abs( Math.round( options.step ) ) || 1;
// get rid of all pips that might already exist.
slider.element
.off( ".selectPip" )
.addClass("ui-slider-pips")
.find(".ui-slider-pip")
.remove();
// small object with functions for marking pips as selected.
var selectPip = {
single: function(value) {
this.resetClasses();
$pips
.filter(".ui-slider-pip-" + this.classLabel(value) )
.addClass("ui-slider-pip-selected");
if ( slider.options.range ) {
$pips.each(function(k, v) {
var pipVal = $(v).children(".ui-slider-label").data("value");
if (( slider.options.range === "min" && pipVal < value ) ||
( slider.options.range === "max" && pipVal > value )) {
$(v).addClass("ui-slider-pip-inrange");
}
});
}
},
range: function(values) {
this.resetClasses();
for ( i = 0; i < values.length; i++ ) {
$pips
.filter(".ui-slider-pip-" + this.classLabel(values[i]) )
.addClass("ui-slider-pip-selected-" + ( i + 1 ) );
}
if ( slider.options.range ) {
$pips.each(function(k, v) {
var pipVal = $(v).children(".ui-slider-label").data("value");
if ( pipVal > values[0] && pipVal < values[1] ) {
$(v).addClass("ui-slider-pip-inrange");
}
});
}
},
classLabel: function(value) {
return value.toString().replace(".", "-");
},
resetClasses: function() {
var regex = /(^|\s*)(ui-slider-pip-selected|ui-slider-pip-inrange)(-{1,2}\d+|\s|$)/gi;
$pips.removeClass( function(index, css) {
return ( css.match(regex) || [] ).join(" ");
});
}
};
function getClosestHandle( val ) {
var h, k,
sliderVals,
comparedVals,
closestVal,
tempHandles = [],
closestHandle = 0;
if ( slider.values() && slider.values().length ) {
// get the current values of the slider handles
sliderVals = slider.values();
// find the offset value from the `val` for each
// handle, and store it in a new array
comparedVals = $.map( sliderVals, function(v) {
return Math.abs( v - val );
});
// figure out the closest handles to the value
closestVal = Math.min.apply( Math, comparedVals );
// if a comparedVal is the closestVal, then
// set the value accordingly, and set the closest handle.
for ( h = 0; h < comparedVals.length; h++ ) {
if ( comparedVals[h] === closestVal ) {
tempHandles.push(h);
}
}
// set the closest handle to the first handle in array,
// just incase we have no _lastChangedValue to compare to.
closestHandle = tempHandles[0];
// now we want to find out if any of the closest handles were
// the last changed handle, if so we specify that handle to change
for ( k = 0; k < tempHandles.length; k++ ) {
if ( slider._lastChangedValue === tempHandles[k] ) {
closestHandle = tempHandles[k];
}
}
if ( slider.options.range && tempHandles.length === 2 ) {
if ( val > sliderVals[1] ) {
closestHandle = tempHandles[1];
} else if ( val < sliderVals[0] ) {
closestHandle = tempHandles[0];
}
}
}
return closestHandle;
}
function destroy() {
slider.element
.off(".selectPip")
.on("mousedown.slider", slider.element.data("mousedown-original") )
.removeClass("ui-slider-pips")
.find(".ui-slider-pip")
.remove();
}
// when we click on a label, we want to make sure the
// slider's handle actually goes to that label!
// so we check all the handles and see which one is closest
// to the label we clicked. If 2 handles are equidistant then
// we move both of them. We also want to trigger focus on the
// handle.
// without this method the label is just treated like a part
// of the slider and there's no accuracy in the selected value
function labelClick( label, e ) {
if (slider.option("disabled")) {
return;
}
var val = $(label).data("value"),
indexToChange = getClosestHandle( val );
if ( slider.values() && slider.values().length ) {
slider.options.values[ indexToChange ] = slider._trimAlignValue( val );
} else {
slider.options.value = slider._trimAlignValue( val );
}
slider._refreshValue();
slider._change( e, indexToChange );
}
// method for creating a pip. We loop this for creating all
// the pips.
function createPip( which ) {
var label,
percent,
number = which,
classes = "ui-slider-pip",
css = "",
value = slider.value(),
values = slider.values(),
labelValue,
classLabel,
labelIndex;
if ( which === "first" ) {
number = 0;
} else if ( which === "last" ) {
number = pips;
}
// labelValue is the actual value of the pip based on the min/step
labelValue = min + ( slider.options.step * number );
// classLabel replaces any decimals with hyphens
classLabel = labelValue.toString().replace(".", "-");
// get the index needed for selecting labels out of the array
labelIndex = Math.round( ( number - min ) / options.step );
// we need to set the human-readable label to either the
// corresponding element in the array, or the appropriate
// item in the object... or an empty string.
if ( $.type(options.labels) === "array" ) {
label = options.labels[ labelIndex ] || "";
} else if ( $.type( options.labels ) === "object" ) {
if ( which === "first" ) {
// set first label
label = options.labels.first || "";
} else if ( which === "last" ) {
// set last label
label = options.labels.last || "";
} else if ( $.type( options.labels.rest ) === "array" ) {
// set other labels, but our index should start at -1
// because of the first pip.
label = options.labels.rest[ labelIndex - 1 ] || "";
} else {
// urrggh, the options must be f**ked, just show nothing.
label = labelValue;
}
} else {
label = labelValue;
}
if ( which === "first" ) {
// first Pip on the Slider
percent = "0%";
classes += " ui-slider-pip-first";
classes += ( options.first === "label" ) ? " ui-slider-pip-label" : "";
classes += ( options.first === false ) ? " ui-slider-pip-hide" : "";
} else if ( which === "last" ) {
// last Pip on the Slider
percent = "100%";
classes += " ui-slider-pip-last";
classes += ( options.last === "label" ) ? " ui-slider-pip-label" : "";
classes += ( options.last === false ) ? " ui-slider-pip-hide" : "";
} else {
// all other Pips
percent = (( 100 / pips ) * which ).toFixed(4) + "%";
classes += ( options.rest === "label" ) ? " ui-slider-pip-label" : "";
classes += ( options.rest === false ) ? " ui-slider-pip-hide" : "";
}
classes += " ui-slider-pip-" + classLabel;
// add classes for the initial-selected values.
if ( values && values.length ) {
for ( i = 0; i < values.length; i++ ) {
if ( labelValue === values[i] ) {
classes += " ui-slider-pip-initial-" + ( i + 1 );
classes += " ui-slider-pip-selected-" + ( i + 1 );
}
}
if ( slider.options.range ) {
if ( labelValue > values[0] &&
labelValue < values[1] ) {
classes += " ui-slider-pip-inrange";
}
}
} else {
if ( labelValue === value ) {
classes += " ui-slider-pip-initial";
classes += " ui-slider-pip-selected";
}
if ( slider.options.range ) {
if (( slider.options.range === "min" && labelValue < value ) ||
( slider.options.range === "max" && labelValue > value )) {
classes += " ui-slider-pip-inrange";
}
}
}
css = ( slider.options.orientation === "horizontal" ) ?
"left: " + percent :
"bottom: " + percent;
// add this current pip to the collection
return "<span class=\"" + classes + "\" style=\"" + css + "\">" +
"<span class=\"ui-slider-line\"></span>" +
"<span class=\"ui-slider-label\" data-value=\"" +
labelValue + "\">" + options.formatLabel(label) + "</span>" +
"</span>";
}
// create our first pip
collection += createPip("first");
// for every stop in the slider where we need a pip; create one.
for ( p = slider.options.pipStep; p < pips; p += slider.options.pipStep ) {
collection += createPip( p );
}
// create our last pip
collection += createPip("last");
// append the collection of pips.
slider.element.append( collection );
// store the pips for setting classes later.
$pips = slider.element.find(".ui-slider-pip");
// store the mousedown handlers for later, just in case we reset
// the slider, the handler would be lost!
if ( $._data( slider.element.get(0), "events").mousedown &&
$._data( slider.element.get(0), "events").mousedown.length ) {
mousedownHandlers = $._data( slider.element.get(0), "events").mousedown;
} else {
mousedownHandlers = slider.element.data("mousedown-handlers");
}
slider.element.data("mousedown-handlers", mousedownHandlers.slice() );
// loop through all the mousedown handlers on the slider,
// and store the original namespaced (.slider) event handler so
// we can trigger it later.
for ( j = 0; j < mousedownHandlers.length; j++ ) {
if ( mousedownHandlers[j].namespace === "slider" ) {
slider.element.data("mousedown-original", mousedownHandlers[j].handler );
}
}
// unbind the mousedown.slider event, because it interferes with
// the labelClick() method (stops smooth animation), and decide
// if we want to trigger the original event based on which element
// was clicked.
slider.element
.off("mousedown.slider")
.on("mousedown.selectPip", function(e) {
var $target = $(e.target),
closest = getClosestHandle( $target.data("value") ),
$handle = $handles.eq( closest );
$handle.addClass("ui-state-active");
if ( $target.is(".ui-slider-label") ) {
labelClick( $target, e );
slider.element
.one("mouseup.selectPip", function() {
$handle
.removeClass("ui-state-active")
.focus();
});
} else {
var originalMousedown = slider.element.data("mousedown-original");
originalMousedown(e);
}
});
slider.element.on( "slide.selectPip slidechange.selectPip", function(e, ui) {
var $slider = $(this),
value = $slider.slider("value"),
values = $slider.slider("values");
if ( ui ) {
value = ui.value;
values = ui.values;
}
if ( slider.values() && slider.values().length ) {
selectPip.range( values );
} else {
selectPip.single( value );
}
});
},
// floats
float: function( settings ) {
var i,
slider = this,
min = slider._valueMin(),
max = slider._valueMax(),
value = slider._value(),
values = slider._values(),
tipValues = [],
$handles = slider.element.find(".ui-slider-handle");
var options = {
handle: true,
/* false */
pips: false,
/* true */
labels: false,
/* [array], { first: "string", rest: [array], last: "string" }, false */
prefix: "",
/* "", string */
suffix: "",
/* "", string */
event: "slidechange slide",
/* "slidechange", "slide", "slidechange slide" */
formatLabel: function(value) {
return this.prefix + value + this.suffix;
}
/* function
must return a value to display in the floats */
};
if ( $.type( settings ) === "object" || $.type( settings ) === "undefined" ) {
$.extend( options, settings );
slider.element.data("float-options", options );
} else {
if ( settings === "destroy" ) {
destroy();
} else if ( settings === "refresh" ) {
slider.element.slider( "float", slider.element.data("float-options") );
}
return;
}
if ( value < min ) {
value = min;
}
if ( value > max ) {
value = max;
}
if ( values && values.length ) {
for ( i = 0; i < values.length; i++ ) {
if ( values[i] < min ) {
values[i] = min;
}
if ( values[i] > max ) {
values[i] = max;
}
}
}
// add a class for the CSS
slider.element
.addClass("ui-slider-float")
.find(".ui-slider-tip, .ui-slider-tip-label")
.remove();
function destroy() {
slider.element
.off(".sliderFloat")
.removeClass("ui-slider-float")
.find(".ui-slider-tip, .ui-slider-tip-label")
.remove();
}
function getPipLabels( values ) {
// when checking the array we need to divide
// by the step option, so we store those values here.
var vals = [],
steppedVals = $.map( values, function(v) {
return Math.ceil(( v - min ) / slider.options.step);
});
// now we just get the values we need to return
// by looping through the values array and assigning the
// label if it exists.
if ( $.type( options.labels ) === "array" ) {
for ( i = 0; i < values.length; i++ ) {
vals[i] = options.labels[ steppedVals[i] ] || values[i];
}
} else if ( $.type( options.labels ) === "object" ) {
for ( i = 0; i < values.length; i++ ) {
if ( values[i] === min ) {
vals[i] = options.labels.first || min;
} else if ( values[i] === max ) {
vals[i] = options.labels.last || max;
} else if ( $.type( options.labels.rest ) === "array" ) {
vals[i] = options.labels.rest[ steppedVals[i] - 1 ] || values[i];
} else {
vals[i] = values[i];
}
}
} else {
for ( i = 0; i < values.length; i++ ) {
vals[i] = values[i];
}
}
return vals;
}
// apply handle tip if settings allows.
if ( options.handle ) {
// we need to set the human-readable label to either the
// corresponding element in the array, or the appropriate
// item in the object... or an empty string.
tipValues = ( slider.values() && slider.values().length ) ?
getPipLabels( values ) :
getPipLabels( [ value ] );
for ( i = 0; i < tipValues.length; i++ ) {
$handles
.eq( i )
.append( $("<span class=\"ui-slider-tip\">"+ options.formatLabel(tipValues[i]) +"</span>") );
}
}
if ( options.pips ) {
// if this slider also has pip-labels, we make those into tips, too.
slider.element.find(".ui-slider-label").each(function(k, v) {
var $this = $(v),
val = [ $this.data("value") ],
label,
$tip;
label = options.formatLabel( getPipLabels( val )[0] );
// create a tip element
$tip =
$("<span class=\"ui-slider-tip-label\">" + label + "</span>")
.insertAfter( $this );
});
}
// check that the event option is actually valid against our
// own list of the slider's events.
if ( options.event !== "slide" &&
options.event !== "slidechange" &&
options.event !== "slide slidechange" &&
options.event !== "slidechange slide" ) {
options.event = "slidechange slide";
}
// when slider changes, update handle tip label.
slider.element
.off(".sliderFloat")
.on( options.event + ".sliderFloat", function( e, ui ) {
var uiValue = ( $.type( ui.value ) === "array" ) ? ui.value : [ ui.value ],
val = options.formatLabel( getPipLabels( uiValue )[0] );
$(ui.handle)
.find(".ui-slider-tip")
.html( val );
});
}
};
$.extend(true, $.ui.slider.prototype, extensionMethods);
})(jQuery);
| a-rol/BOS-Project_SoftwareEngineering | webanwendung/js/jquery-ui-slider-pips.js | JavaScript | apache-2.0 | 24,066 |
var hooks = require('hooks');
hooks.before('GET /api/functions/{fx} -> 200', function(test, done) {
test.request.path = test.request.path.replace(/{fx}/, 'biologicalProcess');
return done();
});
| nbargnesi/openbel-server | tests/api-specification/functions_hook.js | JavaScript | apache-2.0 | 200 |
/**
* Created with IntelliJ IDEA.
* User: Win7
* Date: 15-11-3
* Time: 下午5:05
* To change this template use File | Settings | File Templates.
*/
//微信端标准版controller
| BeastBeaten/iluvcodingMain | mainSite-web/src/main/webapp/WEB-INF/views/indexPages/wechant/page_files.js | JavaScript | apache-2.0 | 186 |
'use strict';
angular.module('report-editor')
.controller('ListValidationsCtrl', function($scope, $state, $stateParams){
$scope.languageType = $stateParams.languageType;
})
;
| AndreSteenveld/cellstore | app/report/taxonomy/concept/formula/validations/list/list.js | JavaScript | apache-2.0 | 193 |
/**
* @license Copyright 2016 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
class MissingAfterPass {
beforePass() {}
pass() {}
}
module.exports = MissingAfterPass;
| umaar/lighthouse | lighthouse-core/test/fixtures/invalid-gatherers/missing-after-pass.js | JavaScript | apache-2.0 | 713 |
/*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file This file manages dynamic menus.
* @since 1.7.0
* @author minsung.jin@samsung.com
*/
define([
'external/lodash/lodash.min',
'webida-lib/plugins/command-system/system/command-system',
'webida-lib/plugins/workbench/plugin'
], function (
_,
commandSystem,
workbench
) {
'use strict';
var commandService = commandSystem.service;
function updateEditLineTopMenu(viewer) {
var widget;
var position;
var lineMenuItem = commandService.getTopMenuModel('line');
var lineMoveUpMenuItem = commandService.getTopMenuModel('line-move-up');
var lineMoveDownMenuItem = commandService.getTopMenuModel('line-move-down');
if (viewer) {
lineMenuItem.disabled = false;
widget = viewer.getWidget();
position = widget.getCursor();
if (position.line > 0) {
lineMoveUpMenuItem.disabled = false;
} else {
lineMoveUpMenuItem.disabled = true;
}
if (position.line < widget.lastLine()) {
lineMoveDownMenuItem.disabled = false;
} else {
lineMoveDownMenuItem.disabled = true;
}
} else {
lineMenuItem.disabled = true;
lineMoveUpMenuItem.disabled = true;
lineMoveDownMenuItem.disabled = true;
}
}
function updateEditTopMenu(viewer) {
var widget;
var history;
var undoMenuItem = commandService.getTopMenuModel('undo');
var redoMenuItem = commandService.getTopMenuModel('redo');
var deleteMenuItem = commandService.getTopMenuModel('delete');
var selectAllMenuItem = commandService.getTopMenuModel('select-all');
var selectLineMenuItem = commandService.getTopMenuModel('select-line');
if (viewer) {
widget = viewer.getWidget();
history = widget.getHistory();
if (history) {
if (history.done && history.done.length > 0) {
undoMenuItem.disabled = false;
} else {
undoMenuItem.disabled = true;
}
if (history.undone && history.undone.length > 0) {
redoMenuItem.disabled = false;
} else {
redoMenuItem.disabled = true;
}
} else {
undoMenuItem.disabled = true;
redoMenuItem.disabled = true;
}
deleteMenuItem.disabled = false;
selectAllMenuItem.disabled = false;
selectLineMenuItem.disabled = false;
} else {
undoMenuItem.disabled = true;
redoMenuItem.disabled = true;
deleteMenuItem.disabled = true;
selectAllMenuItem.disabled = true;
selectLineMenuItem.disabled = true;
}
updateEditLineTopMenu(viewer);
}
function updateFindTopMenu(viewer) {
var replaceMenuItem = commandService.getTopMenuModel('replace');
var findInFileMenuItem = commandService.getTopMenuModel('find-in-file');
var highlightToFindMenuItem = commandService.getTopMenuModel('highlight-to-find');
var findNextMenuItem = commandService.getTopMenuModel('find-next');
var findPreviousMenuItem = commandService.getTopMenuModel('find-previous');
if (viewer) {
replaceMenuItem.disabled = false;
findInFileMenuItem.disabled = false;
highlightToFindMenuItem.disabled = false;
if (viewer.execute('existSearchQuery')) {
findNextMenuItem.disabled = false;
findPreviousMenuItem.disabled = false;
} else {
findNextMenuItem.disabled = true;
findPreviousMenuItem.disabled = true;
}
} else {
replaceMenuItem.disabled = true;
findInFileMenuItem.disabled = true;
highlightToFindMenuItem.disabled = true;
findNextMenuItem.disabled = true;
findPreviousMenuItem.disabled = true;
}
}
function updateEditLineContextMenu(viewer) {
var widget;
var position;
var lineMenuItem = commandService.getContextMenuModel('line');
var lineMoveUpMenuItem = commandService.getContextMenuModel('line-move-up');
var lineMoveDownMenuItem = commandService.getContextMenuModel('line-move-down');
if (viewer) {
lineMenuItem.invisible = false;
widget = viewer.getWidget();
if (widget) {
position = widget.getCursor();
if (position.line > 0) {
lineMoveUpMenuItem.invisible = false;
} else {
lineMoveUpMenuItem.invisible = true;
}
if (position.line < widget.lastLine()) {
lineMoveDownMenuItem.invisible = false;
} else {
lineMoveDownMenuItem.invisible = true;
}
} else {
lineMoveUpMenuItem.invisible = true;
lineMoveDownMenuItem.invisible = true;
}
} else {
lineMenuItem.invisible = true;
lineMoveUpMenuItem.invisible = true;
lineMoveDownMenuItem.invisible = true;
}
}
function updateEditContextMenu(viewer) {
var widget;
var history;
var undoMenuItem = commandService.getContextMenuModel('undo');
var redoMenuItem = commandService.getContextMenuModel('redo');
var delimiterRedoMenuItem = commandService.getContextMenuModel('delimiter-redo');
var deleteMenuItem = commandService.getContextMenuModel('delete');
var selectAllMenuItem = commandService.getContextMenuModel('select-all');
var selectLineMenuItem = commandService.getContextMenuModel('select-line');
var delimiterSelectMenuItem = commandService.getContextMenuModel('delimiter-select');
if (viewer) {
widget = viewer.getWidget();
if (widget) {
history = widget.getHistory();
if (history) {
if (history.done && history.done.length > 0) {
undoMenuItem.invisible = false;
} else {
undoMenuItem.invisible = true;
}
if (history.undone && history.undone.length > 0) {
redoMenuItem.invisible = false;
} else {
redoMenuItem.invisible = true;
}
} else {
undoMenuItem.invisible = true;
redoMenuItem.invisible = true;
}
} else {
undoMenuItem.invisible = true;
redoMenuItem.invisible = true;
}
delimiterRedoMenuItem.invisible = false;
deleteMenuItem.invisible = false;
selectAllMenuItem.invisible = false;
selectLineMenuItem.invisible = false;
delimiterSelectMenuItem.invisible = false;
} else {
undoMenuItem.invisible = true;
redoMenuItem.invisible = true;
delimiterRedoMenuItem.invisible = true;
deleteMenuItem.invisible = true;
selectAllMenuItem.invisible = true;
selectLineMenuItem.invisible = true;
delimiterSelectMenuItem.invisible = true;
}
updateEditLineContextMenu(viewer);
}
function updateTopMenu() {
var page;
var partRegistry;
var editorParts;
var currentEditorPart;
var currentViewer;
page = workbench.getCurrentPage();
if (page) {
partRegistry = page.getPartRegistry();
if (partRegistry) {
editorParts = partRegistry.getEditorParts();
currentEditorPart = partRegistry.getCurrentEditorPart();
if (currentEditorPart) {
currentViewer = currentEditorPart.getViewer();
}
}
}
updateEditTopMenu(currentViewer);
updateFindTopMenu(currentViewer);
}
function updateContextMenu() {
var page;
var partRegistry;
var editorParts;
var currentEditorPart;
var currentViewer;
page = workbench.getCurrentPage();
if (page) {
partRegistry = page.getPartRegistry();
if (partRegistry) {
editorParts = partRegistry.getEditorParts();
currentEditorPart = partRegistry.getCurrentEditorPart();
if (currentEditorPart) {
currentViewer = currentEditorPart.getViewer();
}
}
}
updateEditContextMenu(currentViewer);
}
return {
updateTopMenu: updateTopMenu,
updateContextMenu: updateContextMenu
};
});
| minsung-jin/webida-client | apps/ide/src/plugins/webida.editor.text-editor/menus.js | JavaScript | apache-2.0 | 9,662 |
'use strict';
var extend = require('../helpers/clone-extend').extend;
/**
* Represents a strategy that enriches the API Key configuration (post loading).
*
* @class
*/
function EnrichClientConfigStrategy () {
}
EnrichClientConfigStrategy.prototype.process = function (config, callback) {
// If we have specified an API key in the root, then copy this to our client API key.
if (config.apiKey) {
var extendWith = {};
// Only copy if we have a value set.
// This is to things such as NULL defaults.
for (var key in config.apiKey) {
if (config.apiKey[key]) {
extendWith[key] = config.apiKey[key];
}
}
extend(config, {
client: {
apiKey: extendWith
}
})
}
// For backwards compatibility reasons, if no API key is specified we'll try
// to grab the API credentials out of our new format and shove it into the old
// format. This can go away once we cut a release and decide to no longer
// support the old configuration formatting.
if (!config.apiKey && config.client && config.client.apiKey) {
config.apiKey = config.client.apiKey;
}
callback(null, config);
};
module.exports = EnrichClientConfigStrategy;
| nikhil-ahuja/Express-React | node_modules/stormpath-config/lib/strategy/EnrichClientConfigStrategy.js | JavaScript | apache-2.0 | 1,206 |
function __processArg(obj, key) {
var arg = null;
if (obj) {
arg = obj[key] || null;
delete obj[key];
}
return arg;
}
function Controller() {
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "index";
this.args = arguments[0] || {};
if (arguments[0]) {
{
__processArg(arguments[0], "__parentSymbol");
}
{
__processArg(arguments[0], "$model");
}
{
__processArg(arguments[0], "__itemTemplate");
}
}
var $ = this;
var exports = {};
var __defers = {};
$.__views.index = Ti.UI.createWindow({
backgroundColor: "white",
id: "index"
});
$.__views.index && $.addTopLevelView($.__views.index);
$.__views.label = Ti.UI.createLabel({
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
color: "#000",
font: {
fontSize: 12
},
text: "Hello, World",
id: "label"
});
$.__views.index.add($.__views.label);
doClick ? $.addListener($.__views.label, "click", doClick) : __defers["$.__views.label!click!doClick"] = true;
exports.destroy = function() {};
_.extend($, $.__views);
var win2 = Alloy.createController("win2").getView();
win2.open();
__defers["$.__views.label!click!doClick"] && $.addListener($.__views.label, "click", doClick);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller; | mobilehero/adamantium | test/apps/testing/ALOY-656/_generated/mobileweb/alloy/controllers/index.js | JavaScript | apache-2.0 | 1,584 |
// Copyright 2014 Samsung Electronics Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var x = "abg", y = 'abh'
assert(x != y) | tilmannOSG/jerryscript | tests/jerry-test-suite/11/11.09/11.09.02/11.09.02-011.js | JavaScript | apache-2.0 | 645 |
'use strict';
describe('Directives: whatsNew', function () {
require('./whatsNew.directive.html');
beforeEach(
window.module(
require('./whatsNew.directive'),
require('angular-ui-bootstrap')
)
);
beforeEach(window.inject(function ($rootScope, $compile, whatsNewReader, viewStateCache, $q, $filter, $uibModal) {
this.scope = $rootScope.$new();
this.compile = $compile;
this.whatsNewReader = whatsNewReader;
this.viewStateCache = viewStateCache;
this.$filter = $filter;
this.$q = $q;
this.$uibModal = $uibModal;
}));
describe('with content', function() {
beforeEach(function() {
var lastUpdated = new Date().toString();
var expectedDate = this.$filter('timestamp')(lastUpdated);
spyOn(this.whatsNewReader, 'getWhatsNewContents').and.returnValue(this.$q.when({
contents: 'stuff',
lastUpdated: lastUpdated,
}));
this.lastUpdated = lastUpdated;
this.expectedDate = expectedDate;
});
it('should show updated label when view state has not been cached', function() {
var domNode = this.compile('<whats-new></whats-new>')(this.scope);
this.scope.$digest();
expect(domNode.find('a.unread').size()).toBe(1);
expect(domNode.find('a.unread').html().indexOf(this.expectedDate)).not.toBe(-1);
});
it('should show updated label when view state has different lastUpdated value than file', function() {
this.viewStateCache.whatsNew = {
get: function() {
return {
updateLastViewed: 'something else',
};
}
};
var domNode = this.compile('<whats-new></whats-new>')(this.scope);
this.scope.$digest();
expect(domNode.find('a.unread').size()).toBe(1);
expect(domNode.find('a.unread').html().indexOf(this.expectedDate)).not.toBe(-1);
});
it('should NOT show updated label when view state has same lastUpdated value as file', function() {
var lastUpdated = this.lastUpdated;
this.viewStateCache.whatsNew = {
get: function() {
return {
updateLastViewed: lastUpdated,
};
}
};
var domNode = this.compile('<whats-new></whats-new>')(this.scope);
this.scope.$digest();
expect(domNode.find('a.unread').size()).toBe(0);
});
it('should open modal when clicked, update and cache view state, then hide unread label', function() {
var writtenToCache = null;
this.viewStateCache.whatsNew = {
get: function() {
return {
updateLastViewed: null,
};
},
put: function(id, val) {
writtenToCache = val;
}
};
spyOn(this.$uibModal, 'open').and.returnValue({});
var domNode = this.compile('<whats-new></whats-new>')(this.scope);
this.scope.$digest();
expect(domNode.find('a.unread').size()).toBe(1);
domNode.find('a').click();
this.scope.$digest();
expect(this.$uibModal.open).toHaveBeenCalled();
expect(writtenToCache).not.toBeNull();
expect(writtenToCache.updateLastViewed).toBe(this.lastUpdated);
this.scope.$digest();
expect(domNode.find('a.unread').size()).toBe(0);
});
});
describe('no content', function() {
it('should not render the <ul>', function() {
spyOn(this.whatsNewReader, 'getWhatsNewContents').and.returnValue(this.$q.when(null));
var domNode = this.compile('<whats-new></whats-new>')(this.scope);
this.scope.$digest();
expect(domNode.find('ul').size()).toBe(0);
});
});
});
| zanthrash/deck-1 | app/scripts/modules/netflix/whatsNew/whatsNew.directive.spec.js | JavaScript | apache-2.0 | 3,608 |
// @flow
import * as Constants from './constants'
import type { Action } from '../types'
import type { RobotSettingsState, PerRobotRobotSettingsState } from './types'
export const INITIAL_STATE: RobotSettingsState = {}
const INITIAL_ROBOT_STATE: PerRobotRobotSettingsState = {
settings: [],
restartPath: null,
}
export function robotSettingsReducer(
state: RobotSettingsState = INITIAL_STATE,
action: Action
): RobotSettingsState {
switch (action.type) {
case Constants.FETCH_SETTINGS_SUCCESS:
case Constants.UPDATE_SETTING_SUCCESS: {
const { robotName, settings, restartPath } = action.payload
return { ...state, [robotName]: { settings, restartPath } }
}
case Constants.CLEAR_RESTART_PATH: {
const { robotName } = action.payload
const robotState = state[robotName] || INITIAL_ROBOT_STATE
return { ...state, [robotName]: { ...robotState, restartPath: null } }
}
}
return state
}
| Opentrons/labware | app/src/robot-settings/reducer.js | JavaScript | apache-2.0 | 952 |
import Feature from '../src/ol/Feature.js';
import Map from '../src/ol/Map.js';
import View from '../src/ol/View.js';
import IGC from '../src/ol/format/IGC.js';
import {LineString, Point} from '../src/ol/geom.js';
import {Tile as TileLayer, Vector as VectorLayer} from '../src/ol/layer.js';
import OSM, {ATTRIBUTION} from '../src/ol/source/OSM.js';
import VectorSource from '../src/ol/source/Vector.js';
import {Circle as CircleStyle, Fill, Stroke, Style} from '../src/ol/style.js';
const colors = {
'Clement Latour': 'rgba(0, 0, 255, 0.7)',
'Damien de Baesnt': 'rgba(0, 215, 255, 0.7)',
'Sylvain Dhonneur': 'rgba(0, 165, 255, 0.7)',
'Tom Payne': 'rgba(0, 255, 255, 0.7)',
'Ulrich Prinz': 'rgba(0, 215, 255, 0.7)'
};
const styleCache = {};
const styleFunction = function(feature) {
const color = colors[feature.get('PLT')];
let style = styleCache[color];
if (!style) {
style = new Style({
stroke: new Stroke({
color: color,
width: 3
})
});
styleCache[color] = style;
}
return style;
};
const vectorSource = new VectorSource();
const igcUrls = [
'data/igc/Clement-Latour.igc',
'data/igc/Damien-de-Baenst.igc',
'data/igc/Sylvain-Dhonneur.igc',
'data/igc/Tom-Payne.igc',
'data/igc/Ulrich-Prinz.igc'
];
function get(url, callback) {
const client = new XMLHttpRequest();
client.open('GET', url);
client.onload = function() {
callback(client.responseText);
};
client.send();
}
const igcFormat = new IGC();
for (let i = 0; i < igcUrls.length; ++i) {
get(igcUrls[i], function(data) {
const features = igcFormat.readFeatures(data,
{featureProjection: 'EPSG:3857'});
vectorSource.addFeatures(features);
});
}
const time = {
start: Infinity,
stop: -Infinity,
duration: 0
};
vectorSource.on('addfeature', function(event) {
const geometry = event.feature.getGeometry();
time.start = Math.min(time.start, geometry.getFirstCoordinate()[2]);
time.stop = Math.max(time.stop, geometry.getLastCoordinate()[2]);
time.duration = time.stop - time.start;
});
const map = new Map({
layers: [
new TileLayer({
source: new OSM({
attributions: [
'All maps © <a href="https://www.opencyclemap.org/">OpenCycleMap</a>',
ATTRIBUTION
],
url: 'https://{a-c}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png' +
'?apikey=0e6fc415256d4fbb9b5166a718591d71'
})
}),
new VectorLayer({
source: vectorSource,
style: styleFunction
})
],
target: 'map',
view: new View({
center: [703365.7089403362, 5714629.865071137],
zoom: 9
})
});
let point = null;
let line = null;
const displaySnap = function(coordinate) {
const closestFeature = vectorSource.getClosestFeatureToCoordinate(coordinate);
const info = document.getElementById('info');
if (closestFeature === null) {
point = null;
line = null;
info.innerHTML = ' ';
} else {
const geometry = closestFeature.getGeometry();
const closestPoint = geometry.getClosestPoint(coordinate);
if (point === null) {
point = new Point(closestPoint);
} else {
point.setCoordinates(closestPoint);
}
const date = new Date(closestPoint[2] * 1000);
info.innerHTML =
closestFeature.get('PLT') + ' (' + date.toUTCString() + ')';
const coordinates = [coordinate, [closestPoint[0], closestPoint[1]]];
if (line === null) {
line = new LineString(coordinates);
} else {
line.setCoordinates(coordinates);
}
}
map.render();
};
map.on('pointermove', function(evt) {
if (evt.dragging) {
return;
}
const coordinate = map.getEventCoordinate(evt.originalEvent);
displaySnap(coordinate);
});
map.on('click', function(evt) {
displaySnap(evt.coordinate);
});
const stroke = new Stroke({
color: 'rgba(255,0,0,0.9)',
width: 1
});
const style = new Style({
stroke: stroke,
image: new CircleStyle({
radius: 5,
fill: null,
stroke: stroke
})
});
map.on('postcompose', function(evt) {
const vectorContext = evt.vectorContext;
vectorContext.setStyle(style);
if (point !== null) {
vectorContext.drawGeometry(point);
}
if (line !== null) {
vectorContext.drawGeometry(line);
}
});
const featureOverlay = new VectorLayer({
source: new VectorSource(),
map: map,
style: new Style({
image: new CircleStyle({
radius: 5,
fill: new Fill({
color: 'rgba(255,0,0,0.9)'
})
})
})
});
document.getElementById('time').addEventListener('input', function() {
const value = parseInt(this.value, 10) / 100;
const m = time.start + (time.duration * value);
vectorSource.forEachFeature(function(feature) {
const geometry = /** @type {module:ol/geom/LineString~LineString} */ (feature.getGeometry());
const coordinate = geometry.getCoordinateAtM(m, true);
let highlight = feature.get('highlight');
if (highlight === undefined) {
highlight = new Feature(new Point(coordinate));
feature.set('highlight', highlight);
featureOverlay.getSource().addFeature(highlight);
} else {
highlight.getGeometry().setCoordinates(coordinate);
}
});
map.render();
});
| fredj/ol3 | examples/igc.js | JavaScript | bsd-2-clause | 5,190 |
'use strict';
var utils = require('./utils');
var iso = require('../../portable');
console.log('Client side code started');
//move to new lesson (4?)
console.log(iso.fibonacci.next());
console.log(iso.fibonacci.next());
console.log(iso.fibonacci.next());
console.log(iso.fibonacci.next());
console.log(iso.fibonacci.next());
console.log(iso.fibonacci.next());
console.log(iso.fibonacci.next());
console.log(iso.fibonacci.next());
console.log(iso.fibonacci.next()); | tutsplus/start-coding-es6-with-babel | 5_generators/client/app/main.js | JavaScript | bsd-2-clause | 467 |
(function() {
if(typeof(L) === "undefined")
return;
/**
* leaflet torque layer
*/
var LeafLetTorqueLayer = L.TorqueLayer.extend({
initialize: function(layerModel, leafletMap) {
var extra = layerModel.get('extra_params');
var query = this._getQuery(layerModel);
// initialize the base layers
L.TorqueLayer.prototype.initialize.call(this, {
table: layerModel.get('table_name'),
user: layerModel.get('user_name'),
column: layerModel.get('property'),
blendmode: layerModel.get('torque-blend-mode'),
resolution: 1,
//TODO: manage time columns
countby: 'count(cartodb_id)',
sql_api_domain: layerModel.get('sql_api_domain'),
sql_api_protocol: layerModel.get('sql_api_protocol'),
sql_api_port: layerModel.get('sql_api_port'),
tiler_protocol: layerModel.get('tiler_protocol'),
tiler_domain: layerModel.get('tiler_domain'),
tiler_port: layerModel.get('tiler_port'),
maps_api_template: layerModel.get('maps_api_template'),
stat_tag: layerModel.get('stat_tag'),
animationDuration: layerModel.get('torque-duration'),
steps: layerModel.get('torque-steps'),
sql: query,
visible: layerModel.get('visible'),
extra_params: {
api_key: extra ? extra.map_key: ''
},
cartodb_logo: layerModel.get('cartodb_logo'),
attribution: layerModel.get('attribution'),
cartocss: layerModel.get('cartocss') || layerModel.get('tile_style'),
named_map: layerModel.get('named_map'),
auth_token: layerModel.get('auth_token'),
no_cdn: layerModel.get('no_cdn'),
dynamic_cdn: layerModel.get('dynamic_cdn'),
loop: layerModel.get('loop') === false? false: true,
instanciateCallback: function() {
var cartocss = layerModel.get('cartocss') || layerModel.get('tile_style');
return '_cdbct_' + cdb.core.util.uniqueCallbackName(cartocss + query);
}
});
cdb.geo.LeafLetLayerView.call(this, layerModel, this, leafletMap);
// match leaflet events with backbone events
this.fire = this.trigger;
//this.setCartoCSS(layerModel.get('tile_style'));
if (layerModel.get('visible')) {
this.play();
}
this.bind('tilesLoaded', function() {
this.trigger('load');
}, this);
this.bind('tilesLoading', function() {
this.trigger('loading');
}, this);
},
onAdd: function(map) {
L.TorqueLayer.prototype.onAdd.apply(this, [map]);
// Add CartoDB logo
if (this.options.cartodb_logo != false)
cdb.geo.common.CartoDBLogo.addWadus({ left:8, bottom:8 }, 0, map._container)
},
_getQuery: function(layerModel) {
var query = layerModel.get('query');
var qw = layerModel.get('query_wrapper');
if(qw) {
query = _.template(qw)({ sql: query || ('select * from ' + layerModel.get('table_name')) });
}
return query;
},
_modelUpdated: function(model) {
var changed = this.model.changedAttributes();
if(changed === false) return;
changed.tile_style && this.setCartoCSS(this.model.get('tile_style'));
if ('query' in changed || 'query_wrapper' in changed) {
this.setSQL(this._getQuery(this.model));
}
if ('visible' in changed)
this.model.get('visible') ? this.show(): this.hide();
}
});
_.extend(LeafLetTorqueLayer.prototype, cdb.geo.LeafLetLayerView.prototype);
cdb.geo.LeafLetTorqueLayer = LeafLetTorqueLayer;
})();
| Stonelinks/cartodb-lite | src/geo/leaflet/torque.js | JavaScript | bsd-3-clause | 3,440 |
import reduceBy from './reduceBy.js';
/**
* Counts the elements of a list according to how many match each value of a
* key generated by the supplied function. Returns an object mapping the keys
* produced by `fn` to the number of occurrences in the list. Note that all
* keys are coerced to strings because of how JavaScript objects work.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig (a -> String) -> [a] -> {*}
* @param {Function} fn The function used to map values to keys.
* @param {Array} list The list to count elements from.
* @return {Object} An object mapping keys to number of occurrences in the list.
* @example
*
* const numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2];
* R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1}
*
* const letters = ['a', 'b', 'A', 'a', 'B', 'c'];
* R.countBy(R.toLower)(letters); //=> {'a': 3, 'b': 2, 'c': 1}
*/
var countBy = /*#__PURE__*/reduceBy(function (acc, elem) {
return acc + 1;
}, 0);
export default countBy; | endlessm/chromium-browser | third_party/devtools-frontend/src/node_modules/ramda/es/countBy.js | JavaScript | bsd-3-clause | 1,105 |
/* Copyright 2015 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
/**
* @fileoverview
* `cr-events` provides helpers for handling events in Chrome Polymer elements.
*
* Example:
*
* <cr-events id="events"></cr-events>
*
* Usage:
*
* this.$.events.forward(this.$.element, ['change']);
*
* @element cr-events
*/
Polymer({
/**
* Sets up an element to forward events across the shadow boundary, for events
* which normally stop at the root node (see http://goo.gl/WGMO9x).
* @param {!HTMLElement} element The element to forward events from.
* @param {!Array.<string>} events The events to forward.
*/
forward: function(element, events) {
for (var i = 0; i < events.length; i++)
element.addEventListener(events[i], this.forwardEvent_);
},
/**
* Forwards events that don't automatically cross the shadow boundary
* if the event should bubble.
* @param {!Event} e The event to forward.
* @param {*} detail Data passed when initializing the event.
* @param {Node=} opt_sender Node that declared the handler.
* @private
*/
forwardEvent_: function(e, detail, opt_sender) {
if (!e.bubbles)
return;
var node = e.path[e.path.length - 1];
if (node instanceof ShadowRoot) {
// Forward the event to the shadow host.
e.stopPropagation();
node.host.fire(e.type, detail, node.host, true, e.cancelable);
}
},
});
| sgraham/nope | ui/webui/resources/cr_elements/cr_events/cr_events.js | JavaScript | bsd-3-clause | 1,516 |
app.Maps = Backbone.Collection.extend({
model: app.Map,
url: '/api/maps',
});
| mudpuddle/transitmix | app/js/collections/Maps.js | JavaScript | isc | 82 |
'use strict'
const BB = require('bluebird')
const cacache = require('cacache')
const cacheKey = require('./util/cache-key')
const fetchFromManifest = require('./fetch').fromManifest
const finished = BB.promisify(require('mississippi').finished)
const minimatch = require('minimatch')
const normalize = require('normalize-package-data')
const optCheck = require('./util/opt-check')
const path = require('path')
const pipe = BB.promisify(require('mississippi').pipe)
const ssri = require('ssri')
const tar = require('tar')
// `finalizeManifest` takes as input the various kinds of manifests that
// manifest handlers ('lib/fetchers/*.js#manifest()') return, and makes sure
// they are:
//
// * filled out with any required data that the handler couldn't fill in
// * formatted consistently
// * cached so we don't have to repeat this work more than necessary
//
// The biggest thing this package might do is do a full tarball extraction in
// order to find missing bits of metadata required by the npm installer. For
// example, it will fill in `_shrinkwrap`, `_integrity`, and other details that
// the plain manifest handlers would require a tarball to fill out. If a
// handler returns everything necessary, this process is skipped.
//
// If we get to the tarball phase, the corresponding tarball handler for the
// requested type will be invoked and the entire tarball will be read from the
// stream.
//
module.exports = finalizeManifest
function finalizeManifest (pkg, spec, opts) {
const key = finalKey(pkg, spec)
opts = optCheck(opts)
const cachedManifest = (opts.cache && key && !opts.preferOnline && !opts.fullMetadata)
? cacache.get.info(opts.cache, key, opts)
: BB.resolve(null)
return cachedManifest.then(cached => {
if (cached && cached.metadata.manifest) {
return new Manifest(cached.metadata.manifest)
} else {
return tarballedProps(pkg, spec, opts).then(props => {
return pkg && pkg.name
? new Manifest(pkg, props, opts.fullMetadata)
: new Manifest(props, null, opts.fullMetadata)
}).then(manifest => {
const cacheKey = key || finalKey(manifest, spec)
if (!opts.cache || !cacheKey) {
return manifest
} else {
opts.metadata = {
id: manifest._id,
manifest,
type: 'finalized-manifest'
}
return cacache.put(
opts.cache, cacheKey, '.', opts
).then(() => manifest)
}
})
}
})
}
module.exports.Manifest = Manifest
function Manifest (pkg, fromTarball, fullMetadata) {
fromTarball = fromTarball || {}
if (fullMetadata) {
Object.assign(this, pkg)
}
this.name = pkg.name
this.version = pkg.version
this.engines = pkg.engines || fromTarball.engines
this.cpu = pkg.cpu || fromTarball.cpu
this.os = pkg.os || fromTarball.os
this.dependencies = pkg.dependencies || {}
this.optionalDependencies = pkg.optionalDependencies || {}
this.devDependencies = pkg.devDependencies || {}
const bundled = (
pkg.bundledDependencies ||
pkg.bundleDependencies ||
false
)
this.bundleDependencies = bundled
this.peerDependencies = pkg.peerDependencies || {}
this.deprecated = pkg.deprecated || false
// These depend entirely on each handler
this._resolved = pkg._resolved
// Not all handlers (or registries) provide these out of the box,
// and if they don't, we need to extract and read the tarball ourselves.
// These are details required by the installer.
this._integrity = pkg._integrity || fromTarball._integrity
this._shasum = pkg._shasum
this._shrinkwrap = pkg._shrinkwrap || fromTarball._shrinkwrap || null
this.bin = pkg.bin || fromTarball.bin || null
if (this.bin && Array.isArray(this.bin)) {
// Code yanked from read-package-json.
const m = (pkg.directories && pkg.directories.bin) || '.'
this.bin = this.bin.reduce((acc, mf) => {
if (mf && mf.charAt(0) !== '.') {
const f = path.basename(mf)
acc[f] = path.join(m, mf)
}
return acc
}, {})
}
this._id = null
// TODO - freezing and inextensibility pending npm changes. See test suite.
// Object.preventExtensions(this)
normalize(this)
// I don't want this why did you give it to me. Go away. 🔥🔥🔥🔥
delete this.readme
// Object.freeze(this)
}
// Some things aren't filled in by standard manifest fetching.
// If this function needs to do its work, it will grab the
// package tarball, extract it, and take whatever it needs
// from the stream.
function tarballedProps (pkg, spec, opts) {
const needsShrinkwrap = (!pkg || (
pkg._hasShrinkwrap !== false &&
!pkg._shrinkwrap
))
const needsBin = !!(!pkg || (
!pkg.bin &&
pkg.directories &&
pkg.directories.bin
))
const needsHash = !pkg || (!pkg._integrity && pkg._integrity !== false)
const needsManifest = !pkg || !pkg.name
const needsExtract = needsShrinkwrap || needsBin || needsManifest
if (!needsShrinkwrap && !needsBin && !needsHash && !needsManifest) {
return BB.resolve({})
} else {
opts = optCheck(opts)
const tarStream = fetchFromManifest(pkg, spec, opts)
const extracted = needsExtract && new tar.Parse()
return BB.join(
needsShrinkwrap && jsonFromStream('npm-shrinkwrap.json', extracted),
needsManifest && jsonFromStream('package.json', extracted),
needsBin && getPaths(extracted),
needsHash && ssri.fromStream(tarStream, { algorithms: ['sha1'] }),
needsExtract && pipe(tarStream, extracted),
(sr, mani, paths, hash) => {
if (needsManifest && !mani) {
const err = new Error(`Non-registry package missing package.json: ${spec}.`)
err.code = 'ENOPACKAGEJSON'
throw err
}
const extraProps = mani || {}
delete extraProps._resolved
// drain out the rest of the tarball
tarStream.resume()
// if we have directories.bin, we need to collect any matching files
// to add to bin
if (paths && paths.length) {
const dirBin = mani
? (mani && mani.directories && mani.directories.bin)
: (pkg && pkg.directories && pkg.directories.bin)
if (dirBin) {
extraProps.bin = {}
paths.forEach(filePath => {
if (minimatch(filePath, dirBin + '/**')) {
const relative = path.relative(dirBin, filePath)
if (relative && relative[0] !== '.') {
extraProps.bin[path.basename(relative)] = path.join(dirBin, relative)
}
}
})
}
}
return Object.assign(extraProps, {
_shrinkwrap: sr,
_resolved: (mani && mani._resolved) ||
(pkg && pkg._resolved) ||
spec.fetchSpec,
_integrity: hash && hash.toString()
})
}
)
}
}
function jsonFromStream (filename, dataStream) {
return BB.fromNode(cb => {
dataStream.on('error', cb)
dataStream.on('close', cb)
dataStream.on('entry', entry => {
const filePath = entry.header.path.replace(/[^/]+\//, '')
if (filePath !== filename) {
entry.resume()
} else {
let data = ''
entry.on('data', d => { data += d })
entry.on('error', cb)
finished(entry).then(() => {
try {
cb(null, JSON.parse(data))
} catch (err) {
cb(err)
}
}, err => {
cb(err)
})
}
})
})
}
function getPaths (dataStream) {
return BB.fromNode(cb => {
let paths = []
dataStream.on('error', cb)
dataStream.on('close', () => cb(null, paths))
dataStream.on('entry', function handler (entry) {
const filePath = entry.header.path.replace(/[^/]+\//, '')
entry.resume()
paths.push(filePath)
})
})
}
function finalKey (pkg, spec) {
if (pkg && pkg._uniqueResolved) {
// git packages have a unique, identifiable id, but no tar sha
return cacheKey(`${spec.type}-manifest`, pkg._uniqueResolved)
} else {
return (
pkg && pkg._integrity &&
cacheKey(
`${spec.type}-manifest`,
`${pkg._resolved}:${ssri.stringify(pkg._integrity)}`
)
)
}
}
| Jeck99/At-T | node_modules/npm/node_modules/pacote/lib/finalize-manifest.js | JavaScript | mit | 8,262 |
import convert from '../../src/app/utils/convert';
describe('Convert util tests', function() {
it("utf8ToHex encodes ascii", function() {
// Arrange:
let ascii = "Hello";
let expectedResult = "48656c6c6f";
// Act:
let result = convert.utf8ToHex(ascii);
// Assert:
expect(result).toEqual(expectedResult);
});
it("utf8ToHex encodes utf8", function() {
// Arrange:
let utf8 = "Любя, съешь щипцы, - вздохнёт мэр, - кайф жгуч";
let expectedResult = "d09bd18ed0b1d18f2c20d181d18ad0b5d188d18c20d189d0b8d0bfd186d18b2c202d20d0b2d0b7d0b4d0bed185d0bdd191d18220d0bcd18dd1802c202d20d0bad0b0d0b9d18420d0b6d0b3d183d187";
// Act:
let result = convert.utf8ToHex(utf8);
// Assert:
expect(result).toEqual(expectedResult);
});
it("hex2ua does not throw on invalid input", function() {
// Arrange:
let input = null;
// Act:
// toThrow requires a function, not an actual result, so wrap in bind
let result = convert.hex2ua.bind(null, {});
// Assert:
expect(result).not.toThrow();
});
it("hex2ua converts proper data", function() {
// Arrange:
let hex = "55aa90bb";
let expectedResult = new Uint8Array([85, 170, 144, 187]);
// Act:
let result = convert.hex2ua(hex);
// Assert:
expect(result).toEqual(expectedResult);
});
it("hex2ua discards odd bytes", function() {
// Arrange:
let hex = "55aa90b"
let expectedResult = new Uint8Array([85, 170, 144]);
// Act:
let result = convert.hex2ua(hex);
// Assert:
expect().toEqual(expectedResult);
});
it("ua2hex works on typed arrays", function() {
// Arrange:
let source = new Uint8Array([85, 170, 144, 187]);
let expectedResult = "55aa90bb";
// Act:
let result = convert.ua2hex(source);
// Assert:
expect(result).toEqual(expectedResult);
});
// this one is actually not a requirement...
it("ua2hex works on untyped arrays", function() {
// Arrange:
let source = [85, 170, 144, 187];
let expectedResult = "55aa90bb";
// Act:
let result = convert.ua2hex(source);
// Assert:
expect(result).toEqual(expectedResult);
});
// actually maybe it'd be good if it would throw ...
it("ua2hex does throws on invalid data", function() {
// Arrange:
let source = [256];
let data = null;
// Act:
let result = convert.ua2hex.bind(data, source);
// Assert:
expect(result).not.toThrow();
});
it("roundtrip ua2hex(hex2ua())", function() {
// Arrange:
let hex = "55aa90bb";
// Act:
let result = convert.ua2hex(convert.hex2ua(hex));
// Assert:
expect(result).toEqual(hex);
});
it("roundtrip hex2ua(ua2hex())", function() {
// Arrange:
let source = new Uint8Array([85, 170, 144, 187]);
// Act:
let result = convert.hex2ua(convert.ua2hex(source));
// Assert:
expect(result).toEqual(source);
});
it("hex2ua_reversed returns reversed array", function() {
// Arrange:
let hex = "55aa90bb";
let expectedResult = new Uint8Array([187, 144, 170, 85]);
// Act:
let result = convert.hex2ua_reversed(hex);
// Assert:
expect(result).toEqual(expectedResult);
});
it("hex2ua_reversed discards odd bytes", function() {
// Arrange:
let hex = "55aa90bb";
let expectedResult = new Uint8Array([144, 170, 85]);
// Act:
let result = convert.hex2ua_reversed(hex);
// Assert:
expect(result).toEqual(expectedResult);
});
it("hex2a encodes byte-to-byte", function() {
// Arrange:
let source = "90909055aa90bbc3bc";
let expectedResult = 9;
// Act:
let result = convert.hex2a(source).length;
// Assert:
expect(result).toEqual(expectedResult);
});
it("Can convert ua to words", function() {
// Arrange:
let ua = new Uint8Array([125, 109, 176, 209, 206, 169, 43, 155, 2, 2, 206, 98, 33, 74, 26, 25, 30, 25, 123, 238, 201, 175, 91, 63, 25, 79, 136, 232, 177, 18, 201, 127]);
let uaLength = 32;
let expectedResult = CryptoJS.enc.Hex.parse("7d6db0d1cea92b9b0202ce62214a1a191e197beec9af5b3f194f88e8b112c97f");
// Act:
let result = convert.ua2words(ua, uaLength).toString(CryptoJS.enc.Hex);
// Assert:
expect(CryptoJS.enc.Hex.parse(result)).toEqual(expectedResult);
});
it("Can convert words to ua", function() {
// Arrange:
let ua = new Uint8Array([125, 109, 176, 209, 206, 169, 43, 155, 2, 2, 206, 98, 33, 74, 26, 25, 30, 25, 123, 238, 201, 175, 91, 63, 25, 79, 136, 232, 177, 18, 201, 127]);
let words = CryptoJS.enc.Hex.parse("7d6db0d1cea92b9b0202ce62214a1a191e197beec9af5b3f194f88e8b112c97f");
let destUa = new Uint8Array(64);
let hash = CryptoJS.SHA3(words, {
outputLength: 512
});
// Act:
let result = convert.words2ua(words, hash);
// Assert:
expect(convert.hex2ua(result)).toEqual(ua);
});
}); | QuantumMechanics/NanoWallet | tests/specs/convert.spec.js | JavaScript | mit | 5,444 |
/*
Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.drawing.ui.dom.Pan"]){
dojo._hasResource["dojox.drawing.ui.dom.Pan"]=true;
dojo.provide("dojox.drawing.ui.dom.Pan");
dojo.require("dojox.drawing.plugins._Plugin");
dojo.deprecated("dojox.drawing.ui.dom.Pan","It may not even make it to the 1.4 release.",1.4);
dojox.drawing.ui.dom.Pan=dojox.drawing.util.oo.declare(dojox.drawing.plugins._Plugin,function(_1){
this.domNode=_1.node;
var _2;
dojo.connect(this.domNode,"click",this,"onSetPan");
dojo.connect(this.keys,"onKeyUp",this,"onKeyUp");
dojo.connect(this.keys,"onKeyDown",this,"onKeyDown");
dojo.connect(this.anchors,"onAnchorUp",this,"checkBounds");
dojo.connect(this.stencils,"register",this,"checkBounds");
dojo.connect(this.canvas,"resize",this,"checkBounds");
dojo.connect(this.canvas,"setZoom",this,"checkBounds");
dojo.connect(this.canvas,"onScroll",this,function(){
if(this._blockScroll){
this._blockScroll=false;
return;
}
_2&&clearTimeout(_2);
_2=setTimeout(dojo.hitch(this,"checkBounds"),200);
});
this._mouseHandle=this.mouse.register(this);
},{selected:false,type:"dojox.drawing.ui.dom.Pan",onKeyUp:function(_3){
if(_3.keyCode==32){
this.onSetPan(false);
}
},onKeyDown:function(_4){
if(_4.keyCode==32){
this.onSetPan(true);
}
},onSetPan:function(_5){
if(_5===true||_5===false){
this.selected=!_5;
}
if(this.selected){
this.selected=false;
dojo.removeClass(this.domNode,"selected");
}else{
this.selected=true;
dojo.addClass(this.domNode,"selected");
}
this.mouse.setEventMode(this.selected?"pan":"");
},onPanDrag:function(_6){
var x=_6.x-_6.last.x;
var y=_6.y-_6.last.y;
this.canvas.domNode.parentNode.scrollTop-=_6.move.y;
this.canvas.domNode.parentNode.scrollLeft-=_6.move.x;
this.canvas.onScroll();
},onStencilUp:function(_7){
this.checkBounds();
},onStencilDrag:function(_8){
},checkBounds:function(){
var _9=function(){
};
var _a=function(){
};
var t=Infinity,r=-Infinity,b=-Infinity,l=Infinity,sx=0,sy=0,dy=0,dx=0,mx=this.stencils.group?this.stencils.group.getTransform():{dx:0,dy:0},sc=this.mouse.scrollOffset(),_b=sc.left?10:0,_c=sc.top?10:0,ch=this.canvas.height,cw=this.canvas.width,z=this.canvas.zoom,_d=this.canvas.parentHeight,_e=this.canvas.parentWidth;
this.stencils.withSelected(function(m){
var o=m.getBounds();
_a("SEL BOUNDS:",o);
t=Math.min(o.y1+mx.dy,t);
r=Math.max(o.x2+mx.dx,r);
b=Math.max(o.y2+mx.dy,b);
l=Math.min(o.x1+mx.dx,l);
});
this.stencils.withUnselected(function(m){
var o=m.getBounds();
_a("UN BOUNDS:",o);
t=Math.min(o.y1,t);
r=Math.max(o.x2,r);
b=Math.max(o.y2,b);
l=Math.min(o.x1,l);
});
b*=z;
var _f=0,_10=0;
_9("Bottom test","b:",b,"z:",z,"ch:",ch,"pch:",_d,"top:",sc.top,"sy:",sy);
if(b>_d||sc.top){
_9("*bottom scroll*");
ch=Math.max(b,_d+sc.top);
sy=sc.top;
_f+=this.canvas.getScrollWidth();
}else{
if(!sy&&ch>_d){
_9("*bottom remove*");
ch=_d;
}
}
r*=z;
if(r>_e||sc.left){
cw=Math.max(r,_e+sc.left);
sx=sc.left;
_10+=this.canvas.getScrollWidth();
}else{
if(!sx&&cw>_e){
cw=_e;
}
}
cw+=_f*2;
ch+=_10*2;
this._blockScroll=true;
this.stencils.group&&this.stencils.group.applyTransform({dx:dx,dy:dy});
this.stencils.withUnselected(function(m){
m.transformPoints({dx:dx,dy:dy});
});
this.canvas.setDimensions(cw,ch,sx,sy);
}});
dojox.drawing.ui.dom.Pan.setup={name:"dojox.drawing.ui.dom.Pan",tooltip:"Pan Tool",iconClass:"iconPan"};
dojox.drawing.register(dojox.drawing.ui.dom.Pan.setup,"plugin");
}
| bjorns/logger | src/main/webapp/js/dojox/drawing/ui/dom/Pan.js | JavaScript | mit | 3,529 |
/*!
* Centralize this so we can more easily work around issues with people
* stubbing out `process.nextTick()` in tests using sinon:
* https://github.com/sinonjs/lolex#automatically-incrementing-mocked-time
* See gh-6074
*/
'use strict';
module.exports = function immediate(cb) {
return process.nextTick(cb);
};
| aguerny/LacquerTracker | node_modules/mongoose/lib/helpers/immediate.js | JavaScript | mit | 321 |
__webpack_public_path__ = window.__webpack_public_path__; // eslint-disable-line
import Global from './theme/global';
const getAccount = () => import('./theme/account');
const getLogin = () => import('./theme/auth');
const noop = null;
const pageClasses = {
account_orderstatus: getAccount,
account_order: getAccount,
account_addressbook: getAccount,
shippingaddressform: getAccount,
account_new_return: getAccount,
'add-wishlist': () => import('./theme/wishlist'),
account_recentitems: getAccount,
account_downloaditem: getAccount,
editaccount: getAccount,
account_inbox: getAccount,
account_saved_return: getAccount,
account_returns: getAccount,
account_paymentmethods: getAccount,
account_addpaymentmethod: getAccount,
account_editpaymentmethod: getAccount,
login: getLogin,
createaccount_thanks: getLogin,
createaccount: getLogin,
getnewpassword: getLogin,
forgotpassword: getLogin,
blog: noop,
blog_post: noop,
brand: () => import('./theme/brand'),
brands: noop,
cart: () => import('./theme/cart'),
category: () => import('./theme/category'),
compare: () => import('./theme/compare'),
page_contact_form: () => import('./theme/contact-us'),
error: noop,
404: noop,
giftcertificates: () => import('./theme/gift-certificate'),
giftcertificates_balance: () => import('./theme/gift-certificate'),
giftcertificates_redeem: () => import('./theme/gift-certificate'),
default: noop,
page: noop,
product: () => import('./theme/product'),
amp_product_options: () => import('./theme/product'),
search: () => import('./theme/search'),
rss: noop,
sitemap: noop,
newsletter_subscribe: noop,
wishlist: () => import('./theme/wishlist'),
wishlists: () => import('./theme/wishlist'),
};
const customClasses = {};
/**
* This function gets added to the global window and then called
* on page load with the current template loaded and JS Context passed in
* @param pageType String
* @param contextJSON
* @returns {*}
*/
window.stencilBootstrap = function stencilBootstrap(pageType, contextJSON = null, loadGlobal = true) {
const context = JSON.parse(contextJSON || '{}');
return {
load() {
$(() => {
// Load globals
if (loadGlobal) {
Global.load(context);
}
const importPromises = [];
// Find the appropriate page loader based on pageType
const pageClassImporter = pageClasses[pageType];
if (typeof pageClassImporter === 'function') {
importPromises.push(pageClassImporter());
}
// See if there is a page class default for a custom template
const customTemplateImporter = customClasses[context.template];
if (typeof customTemplateImporter === 'function') {
importPromises.push(customTemplateImporter());
}
// Wait for imports to resolve, then call load() on them
Promise.all(importPromises).then(imports => {
imports.forEach(imported => {
imported.default.load(context);
});
});
});
},
};
};
| sacr3dc0w/cornerstone | assets/js/app.js | JavaScript | mit | 3,380 |
/*
* macros.js: Test macros for director tests.
*
* (C) 2011, Nodejitsu Inc.
* MIT LICENSE
*
*/
var assert = require('assert'),
request = require('request');
exports.assertGet = function(port, uri, expected) {
var context = {
topic: function () {
request({ uri: 'http://localhost:' + port + '/' + uri }, this.callback);
}
};
context['should respond with `' + expected + '`'] = function (err, res, body) {
assert.isNull(err);
assert.equal(res.statusCode, 200);
assert.equal(body, expected);
};
return context;
};
exports.assertPost = function(port, uri, expected) {
return {
topic: function () {
request({
method: 'POST',
uri: 'http://localhost:' + port + '/' + uri,
body: JSON.stringify(expected)
}, this.callback);
},
"should respond with the POST body": function (err, res, body) {
assert.isNull(err);
assert.equal(res.statusCode, 200);
assert.deepEqual(JSON.parse(body), expected);
}
};
};
| caolan/director | test/server/helpers/macros.js | JavaScript | mit | 1,027 |
'use strict';
var createError = require('errno').create;
var BitcoreNodeError = createError('BitcoreNodeError');
var RPCError = createError('RPCError', BitcoreNodeError);
module.exports = {
Error: BitcoreNodeError,
RPCError: RPCError
};
| braydonf/bitcore-node | lib/errors.js | JavaScript | mit | 245 |
if(!!process.version) {
return module.exports = global.require("sys");
}
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var util = require('util');
var sysWarning;
if (!sysWarning) {
sysWarning = 'The "sys" module is now called "util". ' +
'It should have a similar interface.';
util.error(sysWarning);
}
exports.print = util.print;
exports.puts = util.puts;
exports.debug = util.debug;
exports.error = util.error;
exports.inspect = util.inspect;
exports.p = util.p;
exports.log = util.log;
exports.exec = util.exec;
exports.pump = util.pump;
exports.inherits = util.inherits;
| crcn-archive/sardines | lib/builtin/sys.js | JavaScript | mit | 1,687 |
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
}
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
define(["require", "exports", 'aurelia-framework', 'knockout'], function (require, exports, aurelia_framework_1, knockout_1) {
var Knockout = (function () {
function Knockout(element, ko) {
var self = this;
this.element = element;
console.log(ko);
this.heading = ko.observable('Welcome to the Aurelia Navigation App - With Knockout!');
this.firstName = ko.observable('John');
this.lastName = ko.observable('Doe');
this.fullName = ko.computed(function () {
return self.firstName() + ' ' + self.lastName();
});
}
Knockout.prototype.welcome = function () {
alert('Welcome, ' + this.firstName() + '!');
};
Knockout.prototype.attached = function () {
console.log(this.element);
knockout_1.default.applyBindings(this, document.querySelector('#knockout-template')[0]);
};
Knockout = __decorate([
aurelia_framework_1.inject(Element, knockout_1.default),
__metadata('design:paramtypes', [Object, Object])
], Knockout);
return Knockout;
})();
exports.Knockout = Knockout;
});
//# sourceMappingURL=knockout.js.map | JoshKLPA/aurelia-typescript | pwkad-aurelia-samples/pwkad-aurelia-samples/views/knockout.js | JavaScript | mit | 2,025 |
define([
"constants",
"mediator",
"utils",
"hbs!labelsTabTemplate"
], function(C, mediator, utils, labelsTabTemplate) {
"use strict";
var _MODULE_ID = "labelsTab";
var _openSections = {
panelOuterLabels: true,
panelInnerLabels: false,
panelLabelStyles: false,
panelLabelLines: false,
panelTooltips: false
};
var _render = function(tabEl, config) {
$(tabEl).html(labelsTabTemplate({
config: config,
openSections: _openSections
}));
utils.addColorpicker("mainLabelColor");
utils.addColorpicker("labelPercentageColor");
utils.addColorpicker("labelValueColor");
utils.addColorpicker("labelLinesColor");
$("#labelFormatExample").on("change", function() {
$("#labelFormat").val(this.value);
});
$("input[name=labelLineColorType]").on("change", function() {
mediator.publish(_MODULE_ID, C.EVENT.DEMO_PIE.RENDER.NO_ANIMATION);
});
$(".panelLabelSectionToggle").on("click", function() {
var $sectionHeading = $(this);
var section = $sectionHeading.data("section");
var $el = $("#" + section);
if ($sectionHeading.hasClass("expanded")) {
$el.hide("blind", function() { $sectionHeading.removeClass("expanded"); });
_openSections[section] = false;
} else {
$el.css("display", "none").removeClass("hidden").show("blind", function() { $sectionHeading.addClass("expanded"); });
_openSections[section] = true;
}
});
$("#labelLinesColor").on("focus", function() {
$("#labelLineColorType2")[0].checked = true;
mediator.publish(_MODULE_ID, C.EVENT.DEMO_PIE.RENDER.NO_ANIMATION);
});
};
var _getTabData = function() {
var lineColor = "segment";
if ($("#labelLineColorType2")[0].checked) {
lineColor = $("#labelLinesColor").val();
}
var outerHideWhenLessThanPercentage = null;
if ($("#hideOuterLabelCondition2")[0].checked) {
var val = $("#outerHideWhenLessThanPercentage").val();
if ($.isNumeric(val)) {
outerHideWhenLessThanPercentage = val;
}
}
var innerHideWhenLessThanPercentage = null;
if ($("#hideInnerLabelCondition2")[0].checked) {
var val = $("#innerHideWhenLessThanPercentage").val();
if ($.isNumeric(val)) {
innerHideWhenLessThanPercentage = val;
}
}
return {
outer: {
format: $("#outerLabel").val(),
hideWhenLessThanPercentage: outerHideWhenLessThanPercentage,
pieDistance: parseInt($("#pieDistance").val(), 10)
},
inner: {
format: $("#innerLabel").val(),
hideWhenLessThanPercentage: innerHideWhenLessThanPercentage
},
mainLabel: {
color: $("#mainLabelColor").val(),
font: $("#mainLabelFont").val(),
fontSize: $("#mainLabelFontSize").val()
},
percentage: {
color: $("#labelPercentageColor").val(),
font: $("#labelPercentageFont").val(),
fontSize: $("#labelPercentageFontSize").val(),
decimalPlaces: parseInt($("#percentageDecimalPlaces").val(), 10)
},
value: {
color: $("#labelValueColor").val(),
font: $("#labelValueFont").val(),
fontSize: $("#labelValueFontSize").val()
},
lines: {
enabled: $("#showLabelLines")[0].checked,
style: $("input[name=lineStyle]:checked").val(),
color: lineColor
},
truncation: {
enabled: $("#labelTruncation2")[0].checked,
truncateLength: parseInt($("#labelTruncationLength").val(), 10)
}
};
};
mediator.register(_MODULE_ID);
return {
render: _render,
getTabData: _getTabData
};
}); | benkeen/d3pie | website/pages/generator/tabs/labels/tabLabels.js | JavaScript | mit | 3,427 |
/*eslint-disable no-console*/
console.log('injected');
| mikekoetter/node-phantom-simple | test/fixtures/injecttest.js | JavaScript | mit | 55 |