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
// This file was procedurally generated from the following sources: // - src/dstr-assignment/obj-id-identifier-resolution-last.case // - src/dstr-assignment/default/for-of.template /*--- description: Evaluation of DestructuringAssignmentTarget (last of many) (For..of statement) esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation es6id: 13.7.5.11 features: [destructuring-binding] flags: [generated] info: | IterationStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement 1. Let keyResult be the result of performing ? ForIn/OfHeadEvaluation(« », AssignmentExpression, iterate). 2. Return ? ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement, keyResult, assignment, labelSet). 13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation [...] 4. If destructuring is true and if lhsKind is assignment, then a. Assert: lhs is a LeftHandSideExpression. b. Let assignmentPattern be the parse of the source text corresponding to lhs using AssignmentPattern as the goal symbol. [...] ---*/ var x = null; var w; var counter = 0; for ({ w, x } of [{ x: 4 }]) { assert.sameValue(x, 4); counter += 1; } assert.sameValue(counter, 1);
sebastienros/jint
Jint.Tests.Test262/test/language/statements/for-of/dstr-obj-id-identifier-resolution-last.js
JavaScript
bsd-2-clause
1,252
// Copyright (C) 2017 Robin Templeton. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- description: Octal BigInt literal containing an invalid digit esid: prod-NumericLiteral info: | NumericLiteral :: NumericLiteralBase NumericLiteralSuffix NumericLiteralBase :: DecimalLiteral BinaryIntegerLiteral OctalIntegerLiteral HexIntegerLiteral NumericLiteralSuffix :: n negative: phase: parse type: SyntaxError features: [BigInt] ---*/ throw "Test262: This statement should not be evaluated."; 0o9n;
sebastienros/jint
Jint.Tests.Test262/test/language/literals/bigint/octal-invalid-digit.js
JavaScript
bsd-2-clause
578
// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-init-null.case // - src/dstr-binding/error/gen-meth.template /*--- description: Value specifed for object binding pattern must be object coercible (null) (generator method) esid: sec-generator-function-definitions-runtime-semantics-propertydefinitionevaluation es6id: 14.4.13 features: [generators, destructuring-binding] flags: [generated] info: | GeneratorMethod : * PropertyName ( StrictFormalParameters ) { GeneratorBody } 1. Let propKey be the result of evaluating PropertyName. 2. ReturnIfAbrupt(propKey). 3. If the function code for this GeneratorMethod is strict mode code, let strict be true. Otherwise let strict be false. 4. Let scope be the running execution context's LexicalEnvironment. 5. Let closure be GeneratorFunctionCreate(Method, StrictFormalParameters, GeneratorBody, scope, strict). [...] 9.2.1 [[Call]] ( thisArgument, argumentsList) [...] 7. Let result be OrdinaryCallEvaluateBody(F, argumentsList). [...] 9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList ) 1. Let status be FunctionDeclarationInstantiation(F, argumentsList). [...] 9.2.12 FunctionDeclarationInstantiation(func, argumentsList) [...] 23. Let iteratorRecord be Record {[[iterator]]: CreateListIterator(argumentsList), [[done]]: false}. 24. If hasDuplicates is true, then [...] 25. Else, b. Let formalStatus be IteratorBindingInitialization for formals with iteratorRecord and env as arguments. [...] Runtime Semantics: BindingInitialization ObjectBindingPattern : { } 1. Return NormalCompletion(empty). ---*/ var obj = { *method({}) {} }; assert.throws(TypeError, function() { obj.method(null); });
sebastienros/jint
Jint.Tests.Test262/test/language/expressions/object/dstr-gen-meth-obj-init-null.js
JavaScript
bsd-2-clause
1,850
(function() { var LOAD_TIMEOUT = 60000; var PLAY_BUTTON = [0, 173, 0]; var PAUSE_BUTTON = [0, 172, 1]; // Code taken from BurninRubber-v0.js. function childAtPath(path) { var child = ((window.game || {}).stage) || {}; path.forEach((x) => child = ((child || {}).children || [])[x]); return child || null; } function clickButton(button) { if (!button || !button.events || !button.events.onInputDown) { throw 'cannot click null button'; } button.events.onInputDown.dispatch(); } var gameOver = false; window.muniverse = { init: function() { return pollAndWait(LOAD_TIMEOUT, function() { return window.game && window.game.isBooted && window.game.isRunning && window.game.state && window.game.state.getCurrentState().key === 'GameState' && childAtPath(PLAY_BUTTON) && window.game.tweens.getAll().length === 0; }).then(function() { window.faketime.pause(); GameState.prototype.onGameOver = () => gameOver = true; clickButton(childAtPath(PLAY_BUTTON)); childAtPath(PAUSE_BUTTON).events.onInputDown.removeAll(); window.faketime.advance(100); }); }, step: function(millis) { window.faketime.advance(millis); return Promise.resolve(gameOver); }, score: function() { // The score is -5 before the game starts. return Promise.resolve(Math.max(score, 0)); } }; })();
unixpickle/muniverse
games/injections/BirdyRush-v0.js
JavaScript
bsd-2-clause
1,488
// This file was procedurally generated from the following sources: // - src/function-forms/dflt-params-arg-val-undefined.case // - src/function-forms/default/async-func-expr-named.template /*--- description: Use of initializer when argument value is `undefined` (async function named expression) esid: sec-async-function-definitions features: [default-parameters] flags: [generated, async] info: | 14.6 Async Function Definitions AsyncFunctionExpression : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } 14.1.19 Runtime Semantics: IteratorBindingInitialization FormalsList : FormalsList , FormalParameter [...] 23. Let iteratorRecord be Record {[[Iterator]]: CreateListIterator(argumentsList), [[Done]]: false}. 24. If hasDuplicates is true, then [...] 25. Else, a. Perform ? IteratorBindingInitialization for formals with iteratorRecord and env as arguments. [...] ---*/ var callCount = 0; // Stores a reference `ref` for case evaluation var ref; ref = async function ref(fromLiteral = 23, fromExpr = 45, fromHole = 99) { assert.sameValue(fromLiteral, 23); assert.sameValue(fromExpr, 45); assert.sameValue(fromHole, 99); callCount = callCount + 1; }; ref(undefined, void 0).then(() => { assert.sameValue(callCount, 1, 'function invoked exactly once'); }).then($DONE, $DONE);
sebastienros/jint
Jint.Tests.Test262/test/language/expressions/async-function/named-dflt-params-arg-val-undefined.js
JavaScript
bsd-2-clause
1,404
var voxelPainter = require('./../') // Options var options = { container: '#container' } var painter = voxelPainter(options) var loopThrough = function(elements, cb) { [].forEach.call(elements, function(item) { cb(item) }) } // Color selector var colorSelector = document.querySelectorAll('.color-selector li') loopThrough(colorSelector, function(color) { color.addEventListener('click', function() { painter.setColor(this.getAttribute('data-color')) loopThrough(colorSelector, function(item) { item.className = '' }) this.className = 'selected' }, false) })
romainberger/voxel-painter-core
example/main.js
JavaScript
bsd-2-clause
604
// This file was procedurally generated from the following sources: // - src/spread/obj-mult-spread.case // - src/spread/default/super-call.template /*--- description: Multiple Object Spread operation (SuperCall) esid: sec-super-keyword-runtime-semantics-evaluation es6id: 12.3.5.1 features: [object-spread] flags: [generated] info: | SuperCall : super Arguments 1. Let newTarget be GetNewTarget(). 2. If newTarget is undefined, throw a ReferenceError exception. 3. Let func be GetSuperConstructor(). 4. ReturnIfAbrupt(func). 5. Let argList be ArgumentListEvaluation of Arguments. [...] Pending Runtime Semantics: PropertyDefinitionEvaluation PropertyDefinition:...AssignmentExpression 1. Let exprValue be the result of evaluating AssignmentExpression. 2. Let fromValue be GetValue(exprValue). 3. ReturnIfAbrupt(fromValue). 4. Let excludedNames be a new empty List. 5. Return CopyDataProperties(object, fromValue, excludedNames). ---*/ let o = {a: 2, b: 3}; let o2 = {c: 4, d: 5}; var callCount = 0; class Test262ParentClass { constructor(obj) { assert.sameValue(obj.a, 2); assert.sameValue(obj.b, 3); assert.sameValue(obj.c, 4); assert.sameValue(obj.d, 5); assert.sameValue(Object.keys(obj).length, 4); callCount += 1; } } class Test262ChildClass extends Test262ParentClass { constructor() { super({...o, ...o2}); } } new Test262ChildClass(); assert.sameValue(callCount, 1);
sebastienros/jint
Jint.Tests.Test262/test/language/expressions/super/call-spread-obj-mult-spread.js
JavaScript
bsd-2-clause
1,479
var tap = require('tap'), plan = tap.plan, test = tap.test, parser = require('../index'); var cfg53 = new parser.parser( { String: "got = 1\nhave = '$got'", InterPolateVars: true, AllowSingleQuoteInterpolation: true } ); var hash53 = cfg53.getall(); test("test AllowSingleQuoteInterpolation", function(t) { t.plan(1); t.is(hash53.have,"'1'", "check AllowSingleQuoteInterpolation" ); t.end(); });
dshadowwolf/config-general
t/29-test-allowsinglequoteinterpolation.js
JavaScript
bsd-2-clause
416
// Generated by CoffeeScript 1.9.3 /** * * @module cnode/view * @author vfasky <[email protected]> */ (function() { "use strict"; var api, mcore; mcore = require('mcoreExt'); api = require('./api'); module.exports = mcore.View.subclass({ constructor: mcore.View.prototype.constructor, beforeInit: function() { return this.api = api; } }); }).call(this);
vfasky/mcore
example/cnodejs/js/pack/cnode/1.0.0/src/view.js
JavaScript
bsd-2-clause
394
// Sorting the columns /** * @author zhixin wen <[email protected]> * version: 1.10.1 * https://github.com/wenzhixin/bootstrap-table/ */ !function ($) { 'use strict'; // TOOLS DEFINITION // ====================== var cachedWidth = null; // it only does '%s', and return '' when arguments are undefined var sprintf = function (str) { var args = arguments, flag = true, i = 1; str = str.replace(/%s/g, function () { var arg = args[i++]; if (typeof arg === 'undefined') { flag = false; return ''; } return arg; }); return flag ? str : ''; }; var getPropertyFromOther = function (list, from, to, value) { var result = ''; $.each(list, function (i, item) { if (item[from] === value) { result = item[to]; return false; } return true; }); return result; }; var getFieldIndex = function (columns, field) { var index = -1; $.each(columns, function (i, column) { if (column.field === field) { index = i; return false; } return true; }); return index; }; // http://jsfiddle.net/wenyi/47nz7ez9/3/ var setFieldIndex = function (columns) { var i, j, k, totalCol = 0, flag = []; for (i = 0; i < columns[0].length; i++) { totalCol += columns[0][i].colspan || 1; } for (i = 0; i < columns.length; i++) { flag[i] = []; for (j = 0; j < totalCol; j++) { flag[i][j] = false; } } for (i = 0; i < columns.length; i++) { for (j = 0; j < columns[i].length; j++) { var r = columns[i][j], rowspan = r.rowspan || 1, colspan = r.colspan || 1, index = $.inArray(false, flag[i]); if (colspan === 1) { r.fieldIndex = index; // when field is undefined, use index instead if (typeof r.field === 'undefined') { r.field = index; } } for (k = 0; k < rowspan; k++) { flag[i + k][index] = true; } for (k = 0; k < colspan; k++) { flag[i][index + k] = true; } } } }; var getScrollBarWidth = function () { if (cachedWidth === null) { var inner = $('<p/>').addClass('fixed-table-scroll-inner'), outer = $('<div/>').addClass('fixed-table-scroll-outer'), w1, w2; outer.append(inner); $('body').append(outer); w1 = inner[0].offsetWidth; outer.css('overflow', 'scroll'); w2 = inner[0].offsetWidth; if (w1 === w2) { w2 = outer[0].clientWidth; } outer.remove(); cachedWidth = w1 - w2; } return cachedWidth; }; var calculateObjectValue = function (self, name, args, defaultValue) { var func = name; if (typeof name === 'string') { // support obj.func1.func2 var names = name.split('.'); if (names.length > 1) { func = window; $.each(names, function (i, f) { func = func[f]; }); } else { func = window[name]; } } if (typeof func === 'object') { return func; } if (typeof func === 'function') { return func.apply(self, args); } if (!func && typeof name === 'string' && sprintf.apply(this, [name].concat(args))) { return sprintf.apply(this, [name].concat(args)); } return defaultValue; }; var compareObjects = function (objectA, objectB, compareLength) { // Create arrays of property names var objectAProperties = Object.getOwnPropertyNames(objectA), objectBProperties = Object.getOwnPropertyNames(objectB), propName = ''; if (compareLength) { // If number of properties is different, objects are not equivalent if (objectAProperties.length !== objectBProperties.length) { return false; } } for (var i = 0; i < objectAProperties.length; i++) { propName = objectAProperties[i]; // If the property is not in the object B properties, continue with the next property if ($.inArray(propName, objectBProperties) > -1) { // If values of same property are not equal, objects are not equivalent if (objectA[propName] !== objectB[propName]) { return false; } } } // If we made it this far, objects are considered equivalent return true; }; var escapeHTML = function (text) { if (typeof text === 'string') { return text .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#039;') .replace(/`/g, '&#x60;'); } return text; }; var getRealHeight = function ($el) { var height = 0; $el.children().each(function () { if (height < $(this).outerHeight(true)) { height = $(this).outerHeight(true); } }); return height; }; var getRealDataAttr = function (dataAttr) { for (var attr in dataAttr) { var auxAttr = attr.split(/(?=[A-Z])/).join('-').toLowerCase(); if (auxAttr !== attr) { dataAttr[auxAttr] = dataAttr[attr]; delete dataAttr[attr]; } } return dataAttr; }; var getItemField = function (item, field, escape) { var value = item; if (typeof field !== 'string' || item.hasOwnProperty(field)) { return escape ? escapeHTML(item[field]) : item[field]; } var props = field.split('.'); for (var p in props) { value = value && value[props[p]]; } return escape ? escapeHTML(value) : value; }; var isIEBrowser = function () { return !!(navigator.userAgent.indexOf("MSIE ") > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)); }; // BOOTSTRAP TABLE CLASS DEFINITION // ====================== var BootstrapTable = function (el, options) { this.options = options; this.$el = $(el); this.$el_ = this.$el.clone(); this.timeoutId_ = 0; this.timeoutFooter_ = 0; this.init(); }; BootstrapTable.DEFAULTS = { classes: 'table table-hover', locale: undefined, height: undefined, undefinedText: '-', sortName: undefined, sortOrder: 'asc', striped: false, columns: [[]], data: [], dataField: 'rows', method: 'get', url: undefined, ajax: undefined, cache: true, contentType: 'application/json', dataType: 'json', ajaxOptions: {}, queryParams: function (params) { return params; }, queryParamsType: 'limit', // undefined responseHandler: function (res) { return res; }, pagination: false, onlyInfoPagination: false, sidePagination: 'client', // client or server totalRows: 0, // server side need to set pageNumber: 1, pageSize: 10, pageList: [10, 25, 50, 100], paginationHAlign: 'right', //right, left paginationVAlign: 'bottom', //bottom, top, both paginationDetailHAlign: 'left', //right, left paginationPreText: '&lsaquo;', paginationNextText: '&rsaquo;', search: false, searchOnEnterKey: false, strictSearch: false, searchAlign: 'right', selectItemName: 'btSelectItem', showHeader: true, showFooter: false, showColumns: false, showPaginationSwitch: false, showRefresh: false, showToggle: false, buttonsAlign: 'right', smartDisplay: true, escape: false, minimumCountColumns: 1, idField: undefined, uniqueId: undefined, cardView: false, detailView: false, detailFormatter: function (index, row) { return ''; }, trimOnSearch: true, clickToSelect: false, singleSelect: false, toolbar: undefined, toolbarAlign: 'left', checkboxHeader: true, sortable: true, silentSort: true, maintainSelected: false, searchTimeOut: 500, searchText: '', iconSize: undefined, iconsPrefix: 'glyphicon', // glyphicon of fa (font awesome) icons: { paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down', paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up', refresh: 'glyphicon-refresh icon-refresh', toggle: 'glyphicon-list-alt icon-list-alt', columns: 'glyphicon-th icon-th', detailOpen: 'glyphicon-plus icon-plus', detailClose: 'glyphicon-minus icon-minus' }, rowStyle: function (row, index) { return {}; }, rowAttributes: function (row, index) { return {}; }, onAll: function (name, args) { return false; }, onClickCell: function (field, value, row, $element) { return false; }, onDblClickCell: function (field, value, row, $element) { return false; }, onClickRow: function (item, $element) { return false; }, onDblClickRow: function (item, $element) { return false; }, onSort: function (name, order) { return false; }, onCheck: function (row) { return false; }, onUncheck: function (row) { return false; }, onCheckAll: function (rows) { return false; }, onUncheckAll: function (rows) { return false; }, onCheckSome: function (rows) { return false; }, onUncheckSome: function (rows) { return false; }, onLoadSuccess: function (data) { return false; }, onLoadError: function (status) { return false; }, onColumnSwitch: function (field, checked) { return false; }, onPageChange: function (number, size) { return false; }, onSearch: function (text) { return false; }, onToggle: function (cardView) { return false; }, onPreBody: function (data) { return false; }, onPostBody: function () { return false; }, onPostHeader: function () { return false; }, onExpandRow: function (index, row, $detail) { return false; }, onCollapseRow: function (index, row) { return false; }, onRefreshOptions: function (options) { return false; }, onResetView: function () { return false; } }; BootstrapTable.LOCALES = []; BootstrapTable.LOCALES['en-US'] = BootstrapTable.LOCALES['en'] = { formatLoadingMessage: function () { return 'Loading, please wait...'; }, formatRecordsPerPage: function (pageNumber) { return sprintf('%s records per page', pageNumber); }, formatShowingRows: function (pageFrom, pageTo, totalRows) { return sprintf('Showing %s to %s of %s rows', pageFrom, pageTo, totalRows); }, formatDetailPagination: function (totalRows) { return sprintf('Showing %s rows', totalRows); }, formatSearch: function () { return 'Search'; }, formatNoMatches: function () { return 'No rooms currently available'; }, formatPaginationSwitch: function () { return 'Hide/Show pagination'; }, formatRefresh: function () { return 'Refresh'; }, formatToggle: function () { return 'Toggle'; }, formatColumns: function () { return 'Columns'; }, formatAllRows: function () { return 'All'; } }; $.extend(BootstrapTable.DEFAULTS, BootstrapTable.LOCALES['en-US']); BootstrapTable.COLUMN_DEFAULTS = { radio: false, checkbox: false, checkboxEnabled: true, field: undefined, title: undefined, titleTooltip: undefined, 'class': undefined, align: undefined, // left, right, center halign: undefined, // left, right, center falign: undefined, // left, right, center valign: undefined, // top, middle, bottom width: undefined, sortable: false, order: 'asc', // asc, desc visible: true, switchable: true, clickToSelect: true, formatter: undefined, footerFormatter: undefined, events: undefined, sorter: undefined, sortName: undefined, cellStyle: undefined, searchable: true, searchFormatter: true, cardVisible: true }; BootstrapTable.EVENTS = { 'all.bs.table': 'onAll', 'click-cell.bs.table': 'onClickCell', 'dbl-click-cell.bs.table': 'onDblClickCell', 'click-row.bs.table': 'onClickRow', 'dbl-click-row.bs.table': 'onDblClickRow', 'sort.bs.table': 'onSort', 'check.bs.table': 'onCheck', 'uncheck.bs.table': 'onUncheck', 'check-all.bs.table': 'onCheckAll', 'uncheck-all.bs.table': 'onUncheckAll', 'check-some.bs.table': 'onCheckSome', 'uncheck-some.bs.table': 'onUncheckSome', 'load-success.bs.table': 'onLoadSuccess', 'load-error.bs.table': 'onLoadError', 'column-switch.bs.table': 'onColumnSwitch', 'page-change.bs.table': 'onPageChange', 'search.bs.table': 'onSearch', 'toggle.bs.table': 'onToggle', 'pre-body.bs.table': 'onPreBody', 'post-body.bs.table': 'onPostBody', 'post-header.bs.table': 'onPostHeader', 'expand-row.bs.table': 'onExpandRow', 'collapse-row.bs.table': 'onCollapseRow', 'refresh-options.bs.table': 'onRefreshOptions', 'reset-view.bs.table': 'onResetView' }; BootstrapTable.prototype.init = function () { this.initLocale(); this.initContainer(); this.initTable(); this.initHeader(); this.initData(); this.initFooter(); this.initToolbar(); this.initPagination(); this.initBody(); this.initSearchText(); this.initServer(); }; BootstrapTable.prototype.initLocale = function () { if (this.options.locale) { var parts = this.options.locale.split(/-|_/); parts[0].toLowerCase(); parts[1] && parts[1].toUpperCase(); if ($.fn.bootstrapTable.locales[this.options.locale]) { // locale as requested $.extend(this.options, $.fn.bootstrapTable.locales[this.options.locale]); } else if ($.fn.bootstrapTable.locales[parts.join('-')]) { // locale with sep set to - (in case original was specified with _) $.extend(this.options, $.fn.bootstrapTable.locales[parts.join('-')]); } else if ($.fn.bootstrapTable.locales[parts[0]]) { // short locale language code (i.e. 'en') $.extend(this.options, $.fn.bootstrapTable.locales[parts[0]]); } } }; BootstrapTable.prototype.initContainer = function () { this.$container = $([ '<div class="bootstrap-table">', '<div class="fixed-table-toolbar"></div>', this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ? '<div class="fixed-table-pagination" style="clear: both;"></div>' : '', '<div class="fixed-table-container">', '<div class="fixed-table-header"><table></table></div>', '<div class="fixed-table-body">', '<div class="fixed-table-loading">', this.options.formatLoadingMessage(), '</div>', '</div>', '<div class="fixed-table-footer"><table><tr></tr></table></div>', this.options.paginationVAlign === 'bottom' || this.options.paginationVAlign === 'both' ? '<div class="fixed-table-pagination"></div>' : '', '</div>', '</div>' ].join('')); this.$container.insertAfter(this.$el); this.$tableContainer = this.$container.find('.fixed-table-container'); this.$tableHeader = this.$container.find('.fixed-table-header'); this.$tableBody = this.$container.find('.fixed-table-body'); this.$tableLoading = this.$container.find('.fixed-table-loading'); this.$tableFooter = this.$container.find('.fixed-table-footer'); this.$toolbar = this.$container.find('.fixed-table-toolbar'); this.$pagination = this.$container.find('.fixed-table-pagination'); this.$tableBody.append(this.$el); this.$container.after('<div class="clearfix"></div>'); this.$el.addClass(this.options.classes); if (this.options.striped) { this.$el.addClass('table-striped'); } if ($.inArray('table-no-bordered', this.options.classes.split(' ')) !== -1) { this.$tableContainer.addClass('table-no-bordered'); } }; BootstrapTable.prototype.initTable = function () { var that = this, columns = [], data = []; this.$header = this.$el.find('>thead'); if (!this.$header.length) { this.$header = $('<thead></thead>').appendTo(this.$el); } this.$header.find('tr').each(function () { var column = []; $(this).find('th').each(function () { column.push($.extend({}, { title: $(this).html(), 'class': $(this).attr('class'), titleTooltip: $(this).attr('title'), rowspan: $(this).attr('rowspan') ? +$(this).attr('rowspan') : undefined, colspan: $(this).attr('colspan') ? +$(this).attr('colspan') : undefined }, $(this).data())); }); columns.push(column); }); if (!$.isArray(this.options.columns[0])) { this.options.columns = [this.options.columns]; } this.options.columns = $.extend(true, [], columns, this.options.columns); this.columns = []; setFieldIndex(this.options.columns); $.each(this.options.columns, function (i, columns) { $.each(columns, function (j, column) { column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, column); if (typeof column.fieldIndex !== 'undefined') { that.columns[column.fieldIndex] = column; } that.options.columns[i][j] = column; }); }); // if options.data is setting, do not process tbody data if (this.options.data.length) { return; } this.$el.find('>tbody>tr').each(function () { var row = {}; // save tr's id, class and data-* attributes row._id = $(this).attr('id'); row._class = $(this).attr('class'); row._data = getRealDataAttr($(this).data()); $(this).find('td').each(function (i) { var field = that.columns[i].field; row[field] = $(this).html(); // save td's id, class and data-* attributes row['_' + field + '_id'] = $(this).attr('id'); row['_' + field + '_class'] = $(this).attr('class'); row['_' + field + '_rowspan'] = $(this).attr('rowspan'); row['_' + field + '_title'] = $(this).attr('title'); row['_' + field + '_data'] = getRealDataAttr($(this).data()); }); data.push(row); }); this.options.data = data; }; BootstrapTable.prototype.initHeader = function () { var that = this, visibleColumns = {}, html = []; this.header = { fields: [], styles: [], classes: [], formatters: [], events: [], sorters: [], sortNames: [], cellStyles: [], searchables: [] }; $.each(this.options.columns, function (i, columns) { html.push('<tr>'); if (i == 0 && !that.options.cardView && that.options.detailView) { html.push(sprintf('<th class="detail" rowspan="%s"><div class="fht-cell"></div></th>', that.options.columns.length)); } $.each(columns, function (j, column) { var text = '', halign = '', // header align style align = '', // body align style style = '', class_ = sprintf(' class="%s"', column['class']), order = that.options.sortOrder || column.order, unitWidth = 'px', width = column.width; if (column.width !== undefined && (!that.options.cardView)) { if (typeof column.width === 'string') { if (column.width.indexOf('%') !== -1) { unitWidth = '%'; } } } if (column.width && typeof column.width === 'string') { width = column.width.replace('%', '').replace('px', ''); } halign = sprintf('text-align: %s; ', column.halign ? column.halign : column.align); align = sprintf('text-align: %s; ', column.align); style = sprintf('vertical-align: %s; ', column.valign); style += sprintf('width: %s; ', (column.checkbox || column.radio) && !width ? '36px' : (width ? width + unitWidth : undefined)); if (typeof column.fieldIndex !== 'undefined') { that.header.fields[column.fieldIndex] = column.field; that.header.styles[column.fieldIndex] = align + style; that.header.classes[column.fieldIndex] = class_; that.header.formatters[column.fieldIndex] = column.formatter; that.header.events[column.fieldIndex] = column.events; that.header.sorters[column.fieldIndex] = column.sorter; that.header.sortNames[column.fieldIndex] = column.sortName; that.header.cellStyles[column.fieldIndex] = column.cellStyle; that.header.searchables[column.fieldIndex] = column.searchable; if (!column.visible) { return; } if (that.options.cardView && (!column.cardVisible)) { return; } visibleColumns[column.field] = column; } html.push('<th' + sprintf(' title="%s"', column.titleTooltip), column.checkbox || column.radio ? sprintf(' class="bs-checkbox %s"', column['class'] || '') : class_, sprintf(' style="%s"', halign + style), sprintf(' rowspan="%s"', column.rowspan), sprintf(' colspan="%s"', column.colspan), sprintf(' data-field="%s"', column.field), "tabindex='0'", '>'); html.push(sprintf('<div class="th-inner %s">', that.options.sortable && column.sortable ? 'sortable both' : '')); text = column.title; if (column.checkbox) { if (!that.options.singleSelect && that.options.checkboxHeader) { text = '<input name="btSelectAll" type="checkbox" />'; } that.header.stateField = column.field; } if (column.radio) { text = ''; that.header.stateField = column.field; that.options.singleSelect = true; } html.push(text); html.push('</div>'); html.push('<div class="fht-cell"></div>'); html.push('</div>'); html.push('</th>'); }); html.push('</tr>'); }); this.$header.html(html.join('')); this.$header.find('th[data-field]').each(function (i) { $(this).data(visibleColumns[$(this).data('field')]); }); this.$container.off('click', '.th-inner').on('click', '.th-inner', function (event) { var target = $(this); if (target.closest('.bootstrap-table')[0] !== that.$container[0]) return false; if (that.options.sortable && target.parent().data().sortable) { that.onSort(event); } }); this.$header.children().children().off('keypress').on('keypress', function (event) { if (that.options.sortable && $(this).data().sortable) { var code = event.keyCode || event.which; if (code == 13) { //Enter keycode that.onSort(event); } } }); if (!this.options.showHeader || this.options.cardView) { this.$header.hide(); this.$tableHeader.hide(); this.$tableLoading.css('top', 0); } else { this.$header.show(); this.$tableHeader.show(); this.$tableLoading.css('top', this.$header.outerHeight() + 1); // Assign the correct sortable arrow this.getCaret(); } this.$selectAll = this.$header.find('[name="btSelectAll"]'); this.$selectAll.off('click').on('click', function () { var checked = $(this).prop('checked'); that[checked ? 'checkAll' : 'uncheckAll'](); that.updateSelected(); }); }; BootstrapTable.prototype.initFooter = function () { if (!this.options.showFooter || this.options.cardView) { this.$tableFooter.hide(); } else { this.$tableFooter.show(); } }; /** * @param data * @param type: append / prepend */ BootstrapTable.prototype.initData = function (data, type) { if (type === 'append') { this.data = this.data.concat(data); } else if (type === 'prepend') { this.data = [].concat(data).concat(this.data); } else { this.data = data || this.options.data; } // Fix #839 Records deleted when adding new row on filtered table if (type === 'append') { this.options.data = this.options.data.concat(data); } else if (type === 'prepend') { this.options.data = [].concat(data).concat(this.options.data); } else { this.options.data = this.data; } if (this.options.sidePagination === 'server') { return; } this.initSort(); }; BootstrapTable.prototype.initSort = function () { var that = this, name = this.options.sortName, order = this.options.sortOrder === 'desc' ? -1 : 1, index = $.inArray(this.options.sortName, this.header.fields); if (index !== -1) { this.data.sort(function (a, b) { if (that.header.sortNames[index]) { name = that.header.sortNames[index]; } var aa = getItemField(a, name, that.options.escape), bb = getItemField(b, name, that.options.escape), value = calculateObjectValue(that.header, that.header.sorters[index], [aa, bb]); if (value !== undefined) { return order * value; } // Fix #161: undefined or null string sort bug. if (aa === undefined || aa === null) { aa = ''; } if (bb === undefined || bb === null) { bb = ''; } // IF both values are numeric, do a numeric comparison if ($.isNumeric(aa) && $.isNumeric(bb)) { // Convert numerical values form string to float. aa = parseFloat(aa); bb = parseFloat(bb); if (aa < bb) { return order * -1; } return order; } if (aa === bb) { return 0; } // If value is not a string, convert to string if (typeof aa !== 'string') { aa = aa.toString(); } if (aa.localeCompare(bb) === -1) { return order * -1; } return order; }); } }; BootstrapTable.prototype.onSort = function (event) { var $this = event.type === "keypress" ? $(event.currentTarget) : $(event.currentTarget).parent(), $this_ = this.$header.find('th').eq($this.index()); this.$header.add(this.$header_).find('span.order').remove(); if (this.options.sortName === $this.data('field')) { this.options.sortOrder = this.options.sortOrder === 'asc' ? 'desc' : 'asc'; } else { this.options.sortName = $this.data('field'); this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc'; } this.trigger('sort', this.options.sortName, this.options.sortOrder); $this.add($this_).data('order', this.options.sortOrder); // Assign the correct sortable arrow this.getCaret(); if (this.options.sidePagination === 'server') { this.initServer(this.options.silentSort); return; } this.initSort(); this.initBody(); }; BootstrapTable.prototype.initToolbar = function () { var that = this, html = [], timeoutId = 0, $keepOpen, $search, switchableCount = 0; if (this.$toolbar.find('.bars').children().length) { $('body').append($(this.options.toolbar)); } this.$toolbar.html(''); if (typeof this.options.toolbar === 'string' || typeof this.options.toolbar === 'object') { $(sprintf('<div class="bars pull-%s"></div>', this.options.toolbarAlign)) .appendTo(this.$toolbar) .append($(this.options.toolbar)); } // showColumns, showToggle, showRefresh html = [sprintf('<div class="columns columns-%s btn-group pull-%s">', this.options.buttonsAlign, this.options.buttonsAlign)]; if (typeof this.options.icons === 'string') { this.options.icons = calculateObjectValue(null, this.options.icons); } if (this.options.showPaginationSwitch) { html.push(sprintf('<button class="btn btn-default" type="button" name="paginationSwitch" title="%s">', this.options.formatPaginationSwitch()), sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.paginationSwitchDown), '</button>'); } if (this.options.showRefresh) { html.push(sprintf('<button class="btn btn-default' + sprintf(' btn-%s', this.options.iconSize) + '" type="button" name="refresh" title="%s">', this.options.formatRefresh()), sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.refresh), '</button>'); } if (this.options.showToggle) { html.push(sprintf('<button class="btn btn-default' + sprintf(' btn-%s', this.options.iconSize) + '" type="button" name="toggle" title="%s">', this.options.formatToggle()), sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.toggle), '</button>'); } if (this.options.showColumns) { html.push(sprintf('<div class="keep-open btn-group" title="%s">', this.options.formatColumns()), '<button type="button" class="btn btn-default' + sprintf(' btn-%s', this.options.iconSize) + ' dropdown-toggle" data-toggle="dropdown">', sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.columns), ' <span class="caret"></span>', '</button>', '<ul class="dropdown-menu" role="menu">'); $.each(this.columns, function (i, column) { if (column.radio || column.checkbox) { return; } if (that.options.cardView && (!column.cardVisible)) { return; } var checked = column.visible ? ' checked="checked"' : ''; if (column.switchable) { html.push(sprintf('<li>' + '<label><input type="checkbox" data-field="%s" value="%s"%s> %s</label>' + '</li>', column.field, i, checked, column.title)); switchableCount++; } }); html.push('</ul>', '</div>'); } html.push('</div>'); // Fix #188: this.showToolbar is for extensions if (this.showToolbar || html.length > 2) { this.$toolbar.append(html.join('')); } if (this.options.showPaginationSwitch) { this.$toolbar.find('button[name="paginationSwitch"]') .off('click').on('click', $.proxy(this.togglePagination, this)); } if (this.options.showRefresh) { this.$toolbar.find('button[name="refresh"]') .off('click').on('click', $.proxy(this.refresh, this)); } if (this.options.showToggle) { this.$toolbar.find('button[name="toggle"]') .off('click').on('click', function () { that.toggleView(); }); } if (this.options.showColumns) { $keepOpen = this.$toolbar.find('.keep-open'); if (switchableCount <= this.options.minimumCountColumns) { $keepOpen.find('input').prop('disabled', true); } $keepOpen.find('li').off('click').on('click', function (event) { event.stopImmediatePropagation(); }); $keepOpen.find('input').off('click').on('click', function () { var $this = $(this); that.toggleColumn(getFieldIndex(that.columns, $(this).data('field')), $this.prop('checked'), false); that.trigger('column-switch', $(this).data('field'), $this.prop('checked')); }); } if (this.options.search) { html = []; html.push( '<div class="pull-' + this.options.searchAlign + ' search">', sprintf('<input class="form-control' + sprintf(' input-%s', this.options.iconSize) + '" type="text" placeholder="%s">', this.options.formatSearch()), '</div>'); this.$toolbar.append(html.join('')); $search = this.$toolbar.find('.search input'); $search.off('keyup drop').on('keyup drop', function (event) { if (that.options.searchOnEnterKey) { if (event.keyCode !== 13) { return; } } clearTimeout(timeoutId); // doesn't matter if it's 0 timeoutId = setTimeout(function () { that.onSearch(event); }, that.options.searchTimeOut); }); if (isIEBrowser()) { $search.off('mouseup').on('mouseup', function (event) { clearTimeout(timeoutId); // doesn't matter if it's 0 timeoutId = setTimeout(function () { that.onSearch(event); }, that.options.searchTimeOut); }); } } }; BootstrapTable.prototype.onSearch = function (event) { var text = $.trim($(event.currentTarget).val()); // trim search input if (this.options.trimOnSearch && $(event.currentTarget).val() !== text) { $(event.currentTarget).val(text); } if (text === this.searchText) { return; } this.searchText = text; this.options.searchText = text; this.options.pageNumber = 1; this.initSearch(); this.updatePagination(); this.trigger('search', text); }; BootstrapTable.prototype.initSearch = function () { var that = this; if (this.options.sidePagination !== 'server') { var s = this.searchText && this.searchText.toLowerCase(); var f = $.isEmptyObject(this.filterColumns) ? null : this.filterColumns; // Check filter this.data = f ? $.grep(this.options.data, function (item, i) { for (var key in f) { if ($.isArray(f[key])) { if ($.inArray(item[key], f[key]) === -1) { return false; } } else if (item[key] !== f[key]) { return false; } } return true; }) : this.options.data; this.data = s ? $.grep(this.data, function (item, i) { for (var key in item) { key = $.isNumeric(key) ? parseInt(key, 10) : key; var value = item[key], column = that.columns[getFieldIndex(that.columns, key)], j = $.inArray(key, that.header.fields); // Fix #142: search use formatted data if (column && column.searchFormatter) { value = calculateObjectValue(column, that.header.formatters[j], [value, item, i], value); } var index = $.inArray(key, that.header.fields); if (index !== -1 && that.header.searchables[index] && (typeof value === 'string' || typeof value === 'number')) { if (that.options.strictSearch) { if ((value + '').toLowerCase() === s) { return true; } } else { if ((value + '').toLowerCase().indexOf(s) !== -1) { return true; } } } } return false; }) : this.data; } }; BootstrapTable.prototype.initPagination = function () { if (!this.options.pagination) { this.$pagination.hide(); return; } else { this.$pagination.show(); } var that = this, html = [], $allSelected = false, i, from, to, $pageList, $first, $pre, $next, $last, $number, data = this.getData(); if (this.options.sidePagination !== 'server') { this.options.totalRows = data.length; } this.totalPages = 0; if (this.options.totalRows) { if (this.options.pageSize === this.options.formatAllRows()) { this.options.pageSize = this.options.totalRows; $allSelected = true; } else if (this.options.pageSize === this.options.totalRows) { // Fix #667 Table with pagination, // multiple pages and a search that matches to one page throws exception var pageLst = typeof this.options.pageList === 'string' ? this.options.pageList.replace('[', '').replace(']', '') .replace(/ /g, '').toLowerCase().split(',') : this.options.pageList; if ($.inArray(this.options.formatAllRows().toLowerCase(), pageLst) > -1) { $allSelected = true; } } this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1; this.options.totalPages = this.totalPages; } if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) { this.options.pageNumber = this.totalPages; } this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1; this.pageTo = this.options.pageNumber * this.options.pageSize; if (this.pageTo > this.options.totalRows) { this.pageTo = this.options.totalRows; } html.push( '<div class="pull-' + this.options.paginationDetailHAlign + ' pagination-detail">', '<span class="pagination-info">', this.options.onlyInfoPagination ? this.options.formatDetailPagination(this.options.totalRows) : this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows), '</span>'); if (!this.options.onlyInfoPagination) { html.push('<span class="page-list">'); var pageNumber = [ sprintf('<span class="btn-group %s">', this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ? 'dropdown' : 'dropup'), '<button type="button" class="btn btn-default ' + sprintf(' btn-%s', this.options.iconSize) + ' dropdown-toggle" data-toggle="dropdown">', '<span class="page-size">', $allSelected ? this.options.formatAllRows() : this.options.pageSize, '</span>', ' <span class="caret"></span>', '</button>', '<ul class="dropdown-menu" role="menu">' ], pageList = this.options.pageList; if (typeof this.options.pageList === 'string') { var list = this.options.pageList.replace('[', '').replace(']', '') .replace(/ /g, '').split(','); pageList = []; $.each(list, function (i, value) { pageList.push(value.toUpperCase() === that.options.formatAllRows().toUpperCase() ? that.options.formatAllRows() : +value); }); } $.each(pageList, function (i, page) { if (!that.options.smartDisplay || i === 0 || pageList[i - 1] <= that.options.totalRows) { var active; if ($allSelected) { active = page === that.options.formatAllRows() ? ' class="active"' : ''; } else { active = page === that.options.pageSize ? ' class="active"' : ''; } pageNumber.push(sprintf('<li%s><a href="javascript:void(0)">%s</a></li>', active, page)); } }); pageNumber.push('</ul></span>'); html.push(this.options.formatRecordsPerPage(pageNumber.join(''))); html.push('</span>'); html.push('</div>', '<div class="pull-' + this.options.paginationHAlign + ' pagination">', '<ul class="pagination' + sprintf(' pagination-%s', this.options.iconSize) + '">', '<li class="page-pre"><a href="javascript:void(0)">' + this.options.paginationPreText + '</a></li>'); if (this.totalPages < 5) { from = 1; to = this.totalPages; } else { from = this.options.pageNumber - 2; to = from + 4; if (from < 1) { from = 1; to = 5; } if (to > this.totalPages) { to = this.totalPages; from = to - 4; } } if (this.totalPages >= 6) { if (this.options.pageNumber >= 3) { html.push('<li class="page-first' + (1 === this.options.pageNumber ? ' active' : '') + '">', '<a href="javascript:void(0)">', 1, '</a>', '</li>'); from++; } if (this.options.pageNumber >= 4) { if (this.options.pageNumber == 4 || this.totalPages == 6 || this.totalPages == 7) { from--; } else { html.push('<li class="page-first-separator disabled">', '<a href="javascript:void(0)">...</a>', '</li>'); } to--; } } if (this.totalPages >= 7) { if (this.options.pageNumber >= (this.totalPages - 2)) { from--; } } if (this.totalPages == 6) { if (this.options.pageNumber >= (this.totalPages - 2)) { to++; } } else if (this.totalPages >= 7) { if (this.totalPages == 7 || this.options.pageNumber >= (this.totalPages - 3)) { to++; } } for (i = from; i <= to; i++) { html.push('<li class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">', '<a href="javascript:void(0)">', i, '</a>', '</li>'); } if (this.totalPages >= 8) { if (this.options.pageNumber <= (this.totalPages - 4)) { html.push('<li class="page-last-separator disabled">', '<a href="javascript:void(0)">...</a>', '</li>'); } } if (this.totalPages >= 6) { if (this.options.pageNumber <= (this.totalPages - 3)) { html.push('<li class="page-last' + (this.totalPages === this.options.pageNumber ? ' active' : '') + '">', '<a href="javascript:void(0)">', this.totalPages, '</a>', '</li>'); } } html.push( '<li class="page-next"><a href="javascript:void(0)">' + this.options.paginationNextText + '</a></li>', '</ul>', '</div>'); } this.$pagination.html(html.join('')); if (!this.options.onlyInfoPagination) { $pageList = this.$pagination.find('.page-list a'); $first = this.$pagination.find('.page-first'); $pre = this.$pagination.find('.page-pre'); $next = this.$pagination.find('.page-next'); $last = this.$pagination.find('.page-last'); $number = this.$pagination.find('.page-number'); if (this.options.smartDisplay) { if (this.totalPages <= 1) { this.$pagination.find('div.pagination').hide(); } if (pageList.length < 2 || this.options.totalRows <= pageList[0]) { this.$pagination.find('span.page-list').hide(); } // when data is empty, hide the pagination this.$pagination[this.getData().length ? 'show' : 'hide'](); } if ($allSelected) { this.options.pageSize = this.options.formatAllRows(); } $pageList.off('click').on('click', $.proxy(this.onPageListChange, this)); $first.off('click').on('click', $.proxy(this.onPageFirst, this)); $pre.off('click').on('click', $.proxy(this.onPagePre, this)); $next.off('click').on('click', $.proxy(this.onPageNext, this)); $last.off('click').on('click', $.proxy(this.onPageLast, this)); $number.off('click').on('click', $.proxy(this.onPageNumber, this)); } }; BootstrapTable.prototype.updatePagination = function (event) { // Fix #171: IE disabled button can be clicked bug. if (event && $(event.currentTarget).hasClass('disabled')) { return; } if (!this.options.maintainSelected) { this.resetRows(); } this.initPagination(); if (this.options.sidePagination === 'server') { this.initServer(); } else { this.initBody(); } this.trigger('page-change', this.options.pageNumber, this.options.pageSize); }; BootstrapTable.prototype.onPageListChange = function (event) { var $this = $(event.currentTarget); $this.parent().addClass('active').siblings().removeClass('active'); this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase() ? this.options.formatAllRows() : +$this.text(); this.$toolbar.find('.page-size').text(this.options.pageSize); this.updatePagination(event); }; BootstrapTable.prototype.onPageFirst = function (event) { this.options.pageNumber = 1; this.updatePagination(event); }; BootstrapTable.prototype.onPagePre = function (event) { if ((this.options.pageNumber - 1) == 0) { this.options.pageNumber = this.options.totalPages; } else { this.options.pageNumber--; } this.updatePagination(event); }; BootstrapTable.prototype.onPageNext = function (event) { if ((this.options.pageNumber + 1) > this.options.totalPages) { this.options.pageNumber = 1; } else { this.options.pageNumber++; } this.updatePagination(event); }; BootstrapTable.prototype.onPageLast = function (event) { this.options.pageNumber = this.totalPages; this.updatePagination(event); }; BootstrapTable.prototype.onPageNumber = function (event) { if (this.options.pageNumber === +$(event.currentTarget).text()) { return; } this.options.pageNumber = +$(event.currentTarget).text(); this.updatePagination(event); }; BootstrapTable.prototype.initBody = function (fixedScroll) { var that = this, html = [], data = this.getData(); this.trigger('pre-body', data); this.$body = this.$el.find('>tbody'); if (!this.$body.length) { this.$body = $('<tbody></tbody>').appendTo(this.$el); } //Fix #389 Bootstrap-table-flatJSON is not working if (!this.options.pagination || this.options.sidePagination === 'server') { this.pageFrom = 1; this.pageTo = data.length; } for (var i = this.pageFrom - 1; i < this.pageTo; i++) { var key, item = data[i], style = {}, csses = [], data_ = '', attributes = {}, htmlAttributes = []; style = calculateObjectValue(this.options, this.options.rowStyle, [item, i], style); if (style && style.css) { for (key in style.css) { csses.push(key + ': ' + style.css[key]); } } attributes = calculateObjectValue(this.options, this.options.rowAttributes, [item, i], attributes); if (attributes) { for (key in attributes) { htmlAttributes.push(sprintf('%s="%s"', key, escapeHTML(attributes[key]))); } } if (item._data && !$.isEmptyObject(item._data)) { $.each(item._data, function (k, v) { // ignore data-index if (k === 'index') { return; } data_ += sprintf(' data-%s="%s"', k, v); }); } html.push('<tr', sprintf(' %s', htmlAttributes.join(' ')), sprintf(' id="%s"', $.isArray(item) ? undefined : item._id), sprintf(' class="%s"', style.classes || ($.isArray(item) ? undefined : item._class)), sprintf(' data-index="%s"', i), sprintf(' data-uniqueid="%s"', item[this.options.uniqueId]), sprintf('%s', data_), '>' ); if (this.options.cardView) { html.push(sprintf('<td colspan="%s">', this.header.fields.length)); } if (!this.options.cardView && this.options.detailView) { html.push('<td>', '<a class="detail-icon" href="javascript:">', sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.detailOpen), '</a>', '</td>'); } $.each(this.header.fields, function (j, field) { var text = '', value = getItemField(item, field, that.options.escape), type = '', cellStyle = {}, id_ = '', class_ = that.header.classes[j], data_ = '', rowspan_ = '', title_ = '', column = that.columns[getFieldIndex(that.columns, field)]; if (!column.visible) { return; } style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; ')); value = calculateObjectValue(column, that.header.formatters[j], [value, item, i], value); // handle td's id and class if (item['_' + field + '_id']) { id_ = sprintf(' id="%s"', item['_' + field + '_id']); } if (item['_' + field + '_class']) { class_ = sprintf(' class="%s"', item['_' + field + '_class']); } if (item['_' + field + '_rowspan']) { rowspan_ = sprintf(' rowspan="%s"', item['_' + field + '_rowspan']); } if (item['_' + field + '_title']) { title_ = sprintf(' title="%s"', item['_' + field + '_title']); } cellStyle = calculateObjectValue(that.header, that.header.cellStyles[j], [value, item, i], cellStyle); if (cellStyle.classes) { class_ = sprintf(' class="%s"', cellStyle.classes); } if (cellStyle.css) { var csses_ = []; for (var key in cellStyle.css) { csses_.push(key + ': ' + cellStyle.css[key]); } style = sprintf('style="%s"', csses_.concat(that.header.styles[j]).join('; ')); } if (item['_' + field + '_data'] && !$.isEmptyObject(item['_' + field + '_data'])) { $.each(item['_' + field + '_data'], function (k, v) { // ignore data-index if (k === 'index') { return; } data_ += sprintf(' data-%s="%s"', k, v); }); } if (column.checkbox || column.radio) { type = column.checkbox ? 'checkbox' : type; type = column.radio ? 'radio' : type; text = [sprintf(that.options.cardView ? '<div class="card-view %s">' : '<td class="bs-checkbox %s">', column['class'] || ''), '<input' + sprintf(' data-index="%s"', i) + sprintf(' name="%s"', that.options.selectItemName) + sprintf(' type="%s"', type) + sprintf(' value="%s"', item[that.options.idField]) + sprintf(' checked="%s"', value === true || (value && value.checked) ? 'checked' : undefined) + sprintf(' disabled="%s"', !column.checkboxEnabled || (value && value.disabled) ? 'disabled' : undefined) + ' />', that.header.formatters[j] && typeof value === 'string' ? value : '', that.options.cardView ? '</div>' : '</td>' ].join(''); item[that.header.stateField] = value === true || (value && value.checked); } else { value = typeof value === 'undefined' || value === null ? that.options.undefinedText : value; text = that.options.cardView ? ['<div class="card-view">', that.options.showHeader ? sprintf('<span class="title" %s>%s</span>', style, getPropertyFromOther(that.columns, 'field', 'title', field)) : '', sprintf('<span class="value">%s</span>', value), '</div>' ].join('') : [sprintf('<td%s %s %s %s %s %s>', id_, class_, style, data_, rowspan_, title_), value, '</td>' ].join(''); // Hide empty data on Card view when smartDisplay is set to true. if (that.options.cardView && that.options.smartDisplay && value === '') { // Should set a placeholder for event binding correct fieldIndex text = '<div class="card-view"></div>'; } } html.push(text); }); if (this.options.cardView) { html.push('</td>'); } html.push('</tr>'); } // show no records if (!html.length) { html.push('<tr class="no-records-found">', sprintf('<td colspan="%s">%s</td>', this.$header.find('th').length, this.options.formatNoMatches()), '</tr>'); } this.$body.html(html.join('')); if (!fixedScroll) { this.scrollTo(0); } // click to select by column this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', function (e) { var $td = $(this), $tr = $td.parent(), item = that.data[$tr.data('index')], index = $td[0].cellIndex, field = that.header.fields[that.options.detailView && !that.options.cardView ? index - 1 : index], column = that.columns[getFieldIndex(that.columns, field)], value = getItemField(item, field, that.options.escape); if ($td.find('.detail-icon').length) { return; } that.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td); that.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr); // if click to select - then trigger the checkbox/radio click if (e.type === 'click' && that.options.clickToSelect && column.clickToSelect) { var $selectItem = $tr.find(sprintf('[name="%s"]', that.options.selectItemName)); if ($selectItem.length) { $selectItem[0].click(); // #144: .trigger('click') bug } } }); this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', function () { var $this = $(this), $tr = $this.parent().parent(), index = $tr.data('index'), row = data[index]; // Fix #980 Detail view, when searching, returns wrong row // remove and update if ($tr.next().is('tr.detail-view')) { $this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailOpen)); $tr.next().remove(); that.trigger('collapse-row', index, row); } else { $this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailClose)); $tr.after(sprintf('<tr class="detail-view"><td colspan="%s"></td></tr>', $tr.find('td').length)); var $element = $tr.next().find('td'); var content = calculateObjectValue(that.options, that.options.detailFormatter, [index, row, $element], ''); if($element.length === 1) { $element.append(content); } that.trigger('expand-row', index, row, $element); } that.resetView(); }); this.$selectItem = this.$body.find(sprintf('[name="%s"]', this.options.selectItemName)); this.$selectItem.off('click').on('click', function (event) { event.stopImmediatePropagation(); var $this = $(this), checked = $this.prop('checked'), row = that.data[$this.data('index')]; if (that.options.maintainSelected && $(this).is(':radio')) { $.each(that.options.data, function (i, row) { row[that.header.stateField] = false; }); } row[that.header.stateField] = checked; if (that.options.singleSelect) { that.$selectItem.not(this).each(function () { that.data[$(this).data('index')][that.header.stateField] = false; }); that.$selectItem.filter(':checked').not(this).prop('checked', false); } that.updateSelected(); that.trigger(checked ? 'check' : 'uncheck', row, $this); }); $.each(this.header.events, function (i, events) { if (!events) { return; } // fix bug, if events is defined with namespace if (typeof events === 'string') { events = calculateObjectValue(null, events); } var field = that.header.fields[i], fieldIndex = $.inArray(field, that.getVisibleFields()); if (that.options.detailView && !that.options.cardView) { fieldIndex += 1; } for (var key in events) { that.$body.find('>tr:not(.no-records-found)').each(function () { var $tr = $(this), $td = $tr.find(that.options.cardView ? '.card-view' : 'td').eq(fieldIndex), index = key.indexOf(' '), name = key.substring(0, index), el = key.substring(index + 1), func = events[key]; $td.find(el).off(name).on(name, function (e) { var index = $tr.data('index'), row = that.data[index], value = row[field]; func.apply(this, [e, value, row, index]); }); }); } }); this.updateSelected(); this.resetView(); this.trigger('post-body'); }; BootstrapTable.prototype.initServer = function (silent, query) { var that = this, data = {}, params = { searchText: this.searchText, sortName: this.options.sortName, sortOrder: this.options.sortOrder }, request; if(this.options.pagination) { params.pageSize = this.options.pageSize === this.options.formatAllRows() ? this.options.totalRows : this.options.pageSize; params.pageNumber = this.options.pageNumber; } if (!this.options.url && !this.options.ajax) { return; } if (this.options.queryParamsType === 'limit') { params = { search: params.searchText, sort: params.sortName, order: params.sortOrder }; if (this.options.pagination) { params.limit = this.options.pageSize === this.options.formatAllRows() ? this.options.totalRows : this.options.pageSize; params.offset = this.options.pageSize === this.options.formatAllRows() ? 0 : this.options.pageSize * (this.options.pageNumber - 1); } } if (!($.isEmptyObject(this.filterColumnsPartial))) { params['filter'] = JSON.stringify(this.filterColumnsPartial, null); } data = calculateObjectValue(this.options, this.options.queryParams, [params], data); $.extend(data, query || {}); // false to stop request if (data === false) { return; } if (!silent) { this.$tableLoading.show(); } request = $.extend({}, calculateObjectValue(null, this.options.ajaxOptions), { type: this.options.method, url: this.options.url, data: this.options.contentType === 'application/json' && this.options.method === 'post' ? JSON.stringify(data) : data, cache: this.options.cache, contentType: this.options.contentType, dataType: this.options.dataType, success: function (res) { res = calculateObjectValue(that.options, that.options.responseHandler, [res], res); that.load(res); that.trigger('load-success', res); if (!silent) that.$tableLoading.hide(); }, error: function (res) { that.trigger('load-error', res.status, res); if (!silent) that.$tableLoading.hide(); } }); if (this.options.ajax) { calculateObjectValue(this, this.options.ajax, [request], null); } else { $.ajax(request); } }; BootstrapTable.prototype.initSearchText = function () { if (this.options.search) { if (this.options.searchText !== '') { var $search = this.$toolbar.find('.search input'); $search.val(this.options.searchText); this.onSearch({currentTarget: $search}); } } }; BootstrapTable.prototype.getCaret = function () { var that = this; $.each(this.$header.find('th'), function (i, th) { $(th).find('.sortable').removeClass('desc asc').addClass($(th).data('field') === that.options.sortName ? that.options.sortOrder : 'both'); }); }; BootstrapTable.prototype.updateSelected = function () { var checkAll = this.$selectItem.filter(':enabled').length && this.$selectItem.filter(':enabled').length === this.$selectItem.filter(':enabled').filter(':checked').length; this.$selectAll.add(this.$selectAll_).prop('checked', checkAll); this.$selectItem.each(function () { $(this).closest('tr')[$(this).prop('checked') ? 'addClass' : 'removeClass']('selected'); }); }; BootstrapTable.prototype.updateRows = function () { var that = this; this.$selectItem.each(function () { that.data[$(this).data('index')][that.header.stateField] = $(this).prop('checked'); }); }; BootstrapTable.prototype.resetRows = function () { var that = this; $.each(this.data, function (i, row) { that.$selectAll.prop('checked', false); that.$selectItem.prop('checked', false); if (that.header.stateField) { row[that.header.stateField] = false; } }); }; BootstrapTable.prototype.trigger = function (name) { var args = Array.prototype.slice.call(arguments, 1); name += '.bs.table'; this.options[BootstrapTable.EVENTS[name]].apply(this.options, args); this.$el.trigger($.Event(name), args); this.options.onAll(name, args); this.$el.trigger($.Event('all.bs.table'), [name, args]); }; BootstrapTable.prototype.resetHeader = function () { // fix #61: the hidden table reset header bug. // fix bug: get $el.css('width') error sometime (height = 500) clearTimeout(this.timeoutId_); this.timeoutId_ = setTimeout($.proxy(this.fitHeader, this), this.$el.is(':hidden') ? 100 : 0); }; BootstrapTable.prototype.fitHeader = function () { var that = this, fixedBody, scrollWidth, focused, focusedTemp; if (that.$el.is(':hidden')) { that.timeoutId_ = setTimeout($.proxy(that.fitHeader, that), 100); return; } fixedBody = this.$tableBody.get(0); scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth && fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ? getScrollBarWidth() : 0; this.$el.css('margin-top', -this.$header.outerHeight()); focused = $(':focus'); if (focused.length > 0) { var $th = focused.parents('th'); if ($th.length > 0) { var dataField = $th.attr('data-field'); if (dataField !== undefined) { var $headerTh = this.$header.find("[data-field='" + dataField + "']"); if ($headerTh.length > 0) { $headerTh.find(":input").addClass("focus-temp"); } } } } this.$header_ = this.$header.clone(true, true); this.$selectAll_ = this.$header_.find('[name="btSelectAll"]'); this.$tableHeader.css({ 'margin-right': scrollWidth }).find('table').css('width', this.$el.outerWidth()) .html('').attr('class', this.$el.attr('class')) .append(this.$header_); focusedTemp = $('.focus-temp:visible:eq(0)'); if (focusedTemp.length > 0) { focusedTemp.focus(); this.$header.find('.focus-temp').removeClass('focus-temp'); } // fix bug: $.data() is not working as expected after $.append() this.$header.find('th[data-field]').each(function (i) { that.$header_.find(sprintf('th[data-field="%s"]', $(this).data('field'))).data($(this).data()); }); var visibleFields = this.getVisibleFields(); this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) { var $this = $(this), index = i; if (that.options.detailView && !that.options.cardView) { if (i === 0) { that.$header_.find('th.detail').find('.fht-cell').width($this.innerWidth()); } index = i - 1; } that.$header_.find(sprintf('th[data-field="%s"]', visibleFields[index])) .find('.fht-cell').width($this.innerWidth()); }); // horizontal scroll event // TODO: it's probably better improving the layout than binding to scroll event this.$tableBody.off('scroll').on('scroll', function () { that.$tableHeader.scrollLeft($(this).scrollLeft()); if (that.options.showFooter && !that.options.cardView) { that.$tableFooter.scrollLeft($(this).scrollLeft()); } }); that.trigger('post-header'); }; BootstrapTable.prototype.resetFooter = function () { var that = this, data = that.getData(), html = []; if (!this.options.showFooter || this.options.cardView) { //do nothing return; } if (!this.options.cardView && this.options.detailView) { html.push('<td><div class="th-inner">&nbsp;</div><div class="fht-cell"></div></td>'); } $.each(this.columns, function (i, column) { var falign = '', // footer align style style = '', class_ = sprintf(' class="%s"', column['class']); if (!column.visible) { return; } if (that.options.cardView && (!column.cardVisible)) { return; } falign = sprintf('text-align: %s; ', column.falign ? column.falign : column.align); style = sprintf('vertical-align: %s; ', column.valign); html.push('<td', class_, sprintf(' style="%s"', falign + style), '>'); html.push('<div class="th-inner">'); html.push(calculateObjectValue(column, column.footerFormatter, [data], '&nbsp;') || '&nbsp;'); html.push('</div>'); html.push('<div class="fht-cell"></div>'); html.push('</div>'); html.push('</td>'); }); this.$tableFooter.find('tr').html(html.join('')); clearTimeout(this.timeoutFooter_); this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this), this.$el.is(':hidden') ? 100 : 0); }; BootstrapTable.prototype.fitFooter = function () { var that = this, $footerTd, elWidth, scrollWidth; clearTimeout(this.timeoutFooter_); if (this.$el.is(':hidden')) { this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this), 100); return; } elWidth = this.$el.css('width'); scrollWidth = elWidth > this.$tableBody.width() ? getScrollBarWidth() : 0; this.$tableFooter.css({ 'margin-right': scrollWidth }).find('table').css('width', elWidth) .attr('class', this.$el.attr('class')); $footerTd = this.$tableFooter.find('td'); this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) { var $this = $(this); $footerTd.eq(i).find('.fht-cell').width($this.innerWidth()); }); }; BootstrapTable.prototype.toggleColumn = function (index, checked, needUpdate) { if (index === -1) { return; } this.columns[index].visible = checked; this.initHeader(); this.initSearch(); this.initPagination(); this.initBody(); if (this.options.showColumns) { var $items = this.$toolbar.find('.keep-open input').prop('disabled', false); if (needUpdate) { $items.filter(sprintf('[value="%s"]', index)).prop('checked', checked); } if ($items.filter(':checked').length <= this.options.minimumCountColumns) { $items.filter(':checked').prop('disabled', true); } } }; BootstrapTable.prototype.toggleRow = function (index, uniqueId, visible) { if (index === -1) { return; } this.$body.find(typeof index !== 'undefined' ? sprintf('tr[data-index="%s"]', index) : sprintf('tr[data-uniqueid="%s"]', uniqueId)) [visible ? 'show' : 'hide'](); }; BootstrapTable.prototype.getVisibleFields = function () { var that = this, visibleFields = []; $.each(this.header.fields, function (j, field) { var column = that.columns[getFieldIndex(that.columns, field)]; if (!column.visible) { return; } visibleFields.push(field); }); return visibleFields; }; // PUBLIC FUNCTION DEFINITION // ======================= BootstrapTable.prototype.resetView = function (params) { var padding = 0; if (params && params.height) { this.options.height = params.height; } this.$selectAll.prop('checked', this.$selectItem.length > 0 && this.$selectItem.length === this.$selectItem.filter(':checked').length); if (this.options.height) { var toolbarHeight = getRealHeight(this.$toolbar), paginationHeight = getRealHeight(this.$pagination), height = this.options.height - toolbarHeight - paginationHeight; this.$tableContainer.css('height', height + 'px'); } if (this.options.cardView) { // remove the element css this.$el.css('margin-top', '0'); this.$tableContainer.css('padding-bottom', '0'); return; } if (this.options.showHeader && this.options.height) { this.$tableHeader.show(); this.resetHeader(); padding += this.$header.outerHeight(); } else { this.$tableHeader.hide(); this.trigger('post-header'); } if (this.options.showFooter) { this.resetFooter(); if (this.options.height) { padding += this.$tableFooter.outerHeight() + 1; } } // Assign the correct sortable arrow this.getCaret(); this.$tableContainer.css('padding-bottom', padding + 'px'); this.trigger('reset-view'); }; BootstrapTable.prototype.getData = function (useCurrentPage) { return (this.searchText || !$.isEmptyObject(this.filterColumns) || !$.isEmptyObject(this.filterColumnsPartial)) ? (useCurrentPage ? this.data.slice(this.pageFrom - 1, this.pageTo) : this.data) : (useCurrentPage ? this.options.data.slice(this.pageFrom - 1, this.pageTo) : this.options.data); }; BootstrapTable.prototype.load = function (data) { var fixedScroll = false; // #431: support pagination if (this.options.sidePagination === 'server') { this.options.totalRows = data.total; fixedScroll = data.fixedScroll; data = data[this.options.dataField]; } else if (!$.isArray(data)) { // support fixedScroll fixedScroll = data.fixedScroll; data = data.data; } this.initData(data); this.initSearch(); this.initPagination(); this.initBody(fixedScroll); }; BootstrapTable.prototype.append = function (data) { this.initData(data, 'append'); this.initSearch(); this.initPagination(); this.initSort(); this.initBody(true); }; BootstrapTable.prototype.prepend = function (data) { this.initData(data, 'prepend'); this.initSearch(); this.initPagination(); this.initSort(); this.initBody(true); }; BootstrapTable.prototype.remove = function (params) { var len = this.options.data.length, i, row; if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) { return; } for (i = len - 1; i >= 0; i--) { row = this.options.data[i]; if (!row.hasOwnProperty(params.field)) { continue; } if ($.inArray(row[params.field], params.values) !== -1) { this.options.data.splice(i, 1); } } if (len === this.options.data.length) { return; } this.initSearch(); this.initPagination(); this.initSort(); this.initBody(true); }; BootstrapTable.prototype.removeAll = function () { if (this.options.data.length > 0) { this.options.data.splice(0, this.options.data.length); this.initSearch(); this.initPagination(); this.initBody(true); } }; BootstrapTable.prototype.getRowByUniqueId = function (id) { var uniqueId = this.options.uniqueId, len = this.options.data.length, dataRow = null, i, row, rowUniqueId; for (i = len - 1; i >= 0; i--) { row = this.options.data[i]; if (row.hasOwnProperty(uniqueId)) { // uniqueId is a column rowUniqueId = row[uniqueId]; } else if(row._data.hasOwnProperty(uniqueId)) { // uniqueId is a row data property rowUniqueId = row._data[uniqueId]; } else { continue; } if (typeof rowUniqueId === 'string') { id = id.toString(); } else if (typeof rowUniqueId === 'number') { if ((Number(rowUniqueId) === rowUniqueId) && (rowUniqueId % 1 === 0)) { id = parseInt(id); } else if ((rowUniqueId === Number(rowUniqueId)) && (rowUniqueId !== 0)) { id = parseFloat(id); } } if (rowUniqueId === id) { dataRow = row; break; } } return dataRow; }; BootstrapTable.prototype.removeByUniqueId = function (id) { var len = this.options.data.length, row = this.getRowByUniqueId(id); if (row) { this.options.data.splice(this.options.data.indexOf(row), 1); } if (len === this.options.data.length) { return; } this.initSearch(); this.initPagination(); this.initBody(true); }; BootstrapTable.prototype.updateByUniqueId = function (params) { var rowId; if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) { return; } rowId = $.inArray(this.getRowByUniqueId(params.id), this.options.data); if (rowId === -1) { return; } $.extend(this.data[rowId], params.row); this.initSort(); this.initBody(true); }; BootstrapTable.prototype.insertRow = function (params) { if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) { return; } this.data.splice(params.index, 0, params.row); this.initSearch(); this.initPagination(); this.initSort(); this.initBody(true); }; BootstrapTable.prototype.updateRow = function (params) { if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) { return; } $.extend(this.data[params.index], params.row); this.initSort(); this.initBody(true); }; BootstrapTable.prototype.showRow = function (params) { if (!params.hasOwnProperty('index') && !params.hasOwnProperty('uniqueId')) { return; } this.toggleRow(params.index, params.uniqueId, true); }; BootstrapTable.prototype.hideRow = function (params) { if (!params.hasOwnProperty('index') && !params.hasOwnProperty('uniqueId')) { return; } this.toggleRow(params.index, params.uniqueId, false); }; BootstrapTable.prototype.getRowsHidden = function (show) { var rows = $(this.$body[0]).children().filter(':hidden'), i = 0; if (show) { for (; i < rows.length; i++) { $(rows[i]).show(); } } return rows; }; BootstrapTable.prototype.mergeCells = function (options) { var row = options.index, col = $.inArray(options.field, this.getVisibleFields()), rowspan = options.rowspan || 1, colspan = options.colspan || 1, i, j, $tr = this.$body.find('>tr'), $td; if (this.options.detailView && !this.options.cardView) { col += 1; } $td = $tr.eq(row).find('>td').eq(col); if (row < 0 || col < 0 || row >= this.data.length) { return; } for (i = row; i < row + rowspan; i++) { for (j = col; j < col + colspan; j++) { $tr.eq(i).find('>td').eq(j).hide(); } } $td.attr('rowspan', rowspan).attr('colspan', colspan).show(); }; BootstrapTable.prototype.updateCell = function (params) { if (!params.hasOwnProperty('index') || !params.hasOwnProperty('field') || !params.hasOwnProperty('value')) { return; } this.data[params.index][params.field] = params.value; if (params.reinit === false) { return; } this.initSort(); this.initBody(true); }; BootstrapTable.prototype.getOptions = function () { return this.options; }; BootstrapTable.prototype.getSelections = function () { var that = this; return $.grep(this.data, function (row) { return row[that.header.stateField]; }); }; BootstrapTable.prototype.getAllSelections = function () { var that = this; return $.grep(this.options.data, function (row) { return row[that.header.stateField]; }); }; BootstrapTable.prototype.checkAll = function () { this.checkAll_(true); }; BootstrapTable.prototype.uncheckAll = function () { this.checkAll_(false); }; BootstrapTable.prototype.checkInvert = function () { var that = this; var rows = that.$selectItem.filter(':enabled'); var checked = rows.filter(':checked'); rows.each(function() { $(this).prop('checked', !$(this).prop('checked')); }); that.updateRows(); that.updateSelected(); that.trigger('uncheck-some', checked); checked = that.getSelections(); that.trigger('check-some', checked); }; BootstrapTable.prototype.checkAll_ = function (checked) { var rows; if (!checked) { rows = this.getSelections(); } this.$selectAll.add(this.$selectAll_).prop('checked', checked); this.$selectItem.filter(':enabled').prop('checked', checked); this.updateRows(); if (checked) { rows = this.getSelections(); } this.trigger(checked ? 'check-all' : 'uncheck-all', rows); }; BootstrapTable.prototype.check = function (index) { this.check_(true, index); }; BootstrapTable.prototype.uncheck = function (index) { this.check_(false, index); }; BootstrapTable.prototype.check_ = function (checked, index) { var $el = this.$selectItem.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked); this.data[index][this.header.stateField] = checked; this.updateSelected(); this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el); }; BootstrapTable.prototype.checkBy = function (obj) { this.checkBy_(true, obj); }; BootstrapTable.prototype.uncheckBy = function (obj) { this.checkBy_(false, obj); }; BootstrapTable.prototype.checkBy_ = function (checked, obj) { if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) { return; } var that = this, rows = []; $.each(this.options.data, function (index, row) { if (!row.hasOwnProperty(obj.field)) { return false; } if ($.inArray(row[obj.field], obj.values) !== -1) { var $el = that.$selectItem.filter(':enabled') .filter(sprintf('[data-index="%s"]', index)).prop('checked', checked); row[that.header.stateField] = checked; rows.push(row); that.trigger(checked ? 'check' : 'uncheck', row, $el); } }); this.updateSelected(); this.trigger(checked ? 'check-some' : 'uncheck-some', rows); }; BootstrapTable.prototype.destroy = function () { this.$el.insertBefore(this.$container); $(this.options.toolbar).insertBefore(this.$el); this.$container.next().remove(); this.$container.remove(); this.$el.html(this.$el_.html()) .css('margin-top', '0') .attr('class', this.$el_.attr('class') || ''); // reset the class }; BootstrapTable.prototype.showLoading = function () { this.$tableLoading.show(); }; BootstrapTable.prototype.hideLoading = function () { this.$tableLoading.hide(); }; BootstrapTable.prototype.togglePagination = function () { this.options.pagination = !this.options.pagination; var button = this.$toolbar.find('button[name="paginationSwitch"] i'); if (this.options.pagination) { button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchDown); } else { button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchUp); } this.updatePagination(); }; BootstrapTable.prototype.refresh = function (params) { if (params && params.url) { this.options.url = params.url; this.options.pageNumber = 1; } this.initServer(params && params.silent, params && params.query); }; BootstrapTable.prototype.resetWidth = function () { if (this.options.showHeader && this.options.height) { this.fitHeader(); } if (this.options.showFooter) { this.fitFooter(); } }; BootstrapTable.prototype.showColumn = function (field) { this.toggleColumn(getFieldIndex(this.columns, field), true, true); }; BootstrapTable.prototype.hideColumn = function (field) { this.toggleColumn(getFieldIndex(this.columns, field), false, true); }; BootstrapTable.prototype.getHiddenColumns = function () { return $.grep(this.columns, function (column) { return !column.visible; }); }; BootstrapTable.prototype.filterBy = function (columns) { this.filterColumns = $.isEmptyObject(columns) ? {} : columns; this.options.pageNumber = 1; this.initSearch(); this.updatePagination(); }; BootstrapTable.prototype.scrollTo = function (value) { if (typeof value === 'string') { value = value === 'bottom' ? this.$tableBody[0].scrollHeight : 0; } if (typeof value === 'number') { this.$tableBody.scrollTop(value); } if (typeof value === 'undefined') { return this.$tableBody.scrollTop(); } }; BootstrapTable.prototype.getScrollPosition = function () { return this.scrollTo(); }; BootstrapTable.prototype.selectPage = function (page) { if (page > 0 && page <= this.options.totalPages) { this.options.pageNumber = page; this.updatePagination(); } }; BootstrapTable.prototype.prevPage = function () { if (this.options.pageNumber > 1) { this.options.pageNumber--; this.updatePagination(); } }; BootstrapTable.prototype.nextPage = function () { if (this.options.pageNumber < this.options.totalPages) { this.options.pageNumber++; this.updatePagination(); } }; BootstrapTable.prototype.toggleView = function () { this.options.cardView = !this.options.cardView; this.initHeader(); // Fixed remove toolbar when click cardView button. //that.initToolbar(); this.initBody(); this.trigger('toggle', this.options.cardView); }; BootstrapTable.prototype.refreshOptions = function (options) { //If the objects are equivalent then avoid the call of destroy / init methods if (compareObjects(this.options, options, true)) { return; } this.options = $.extend(this.options, options); this.trigger('refresh-options', this.options); this.destroy(); this.init(); }; BootstrapTable.prototype.resetSearch = function (text) { var $search = this.$toolbar.find('.search input'); $search.val(text || ''); this.onSearch({currentTarget: $search}); }; BootstrapTable.prototype.expandRow_ = function (expand, index) { var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', index)); if ($tr.next().is('tr.detail-view') === (expand ? false : true)) { $tr.find('> td > .detail-icon').click(); } }; BootstrapTable.prototype.expandRow = function (index) { this.expandRow_(true, index); }; BootstrapTable.prototype.collapseRow = function (index) { this.expandRow_(false, index); }; BootstrapTable.prototype.expandAllRows = function (isSubTable) { if (isSubTable) { var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', 0)), that = this, detailIcon = null, executeInterval = false, idInterval = -1; if (!$tr.next().is('tr.detail-view')) { $tr.find('> td > .detail-icon').click(); executeInterval = true; } else if (!$tr.next().next().is('tr.detail-view')) { $tr.next().find(".detail-icon").click(); executeInterval = true; } if (executeInterval) { try { idInterval = setInterval(function () { detailIcon = that.$body.find("tr.detail-view").last().find(".detail-icon"); if (detailIcon.length > 0) { detailIcon.click(); } else { clearInterval(idInterval); } }, 1); } catch (ex) { clearInterval(idInterval); } } } else { var trs = this.$body.children(); for (var i = 0; i < trs.length; i++) { this.expandRow_(true, $(trs[i]).data("index")); } } }; BootstrapTable.prototype.collapseAllRows = function (isSubTable) { if (isSubTable) { this.expandRow_(false, 0); } else { var trs = this.$body.children(); for (var i = 0; i < trs.length; i++) { this.expandRow_(false, $(trs[i]).data("index")); } } }; BootstrapTable.prototype.updateFormatText = function (name, text) { if (this.options[sprintf('format%s', name)]) { if (typeof text === 'string') { this.options[sprintf('format%s', name)] = function () { return text; }; } else if (typeof text === 'function') { this.options[sprintf('format%s', name)] = text; } } this.initToolbar(); this.initPagination(); this.initBody(); }; // BOOTSTRAP TABLE PLUGIN DEFINITION // ======================= var allowedMethods = [ 'getOptions', 'getSelections', 'getAllSelections', 'getData', 'load', 'append', 'prepend', 'remove', 'removeAll', 'insertRow', 'updateRow', 'updateCell', 'updateByUniqueId', 'removeByUniqueId', 'getRowByUniqueId', 'showRow', 'hideRow', 'getRowsHidden', 'mergeCells', 'checkAll', 'uncheckAll', 'checkInvert', 'check', 'uncheck', 'checkBy', 'uncheckBy', 'refresh', 'resetView', 'resetWidth', 'destroy', 'showLoading', 'hideLoading', 'showColumn', 'hideColumn', 'getHiddenColumns', 'filterBy', 'scrollTo', 'getScrollPosition', 'selectPage', 'prevPage', 'nextPage', 'togglePagination', 'toggleView', 'refreshOptions', 'resetSearch', 'expandRow', 'collapseRow', 'expandAllRows', 'collapseAllRows', 'updateFormatText' ]; $.fn.bootstrapTable = function (option) { var value, args = Array.prototype.slice.call(arguments, 1); this.each(function () { var $this = $(this), data = $this.data('bootstrap.table'), options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(), typeof option === 'object' && option); if (typeof option === 'string') { if ($.inArray(option, allowedMethods) < 0) { throw new Error("Unknown method: " + option); } if (!data) { return; } value = data[option].apply(data, args); if (option === 'destroy') { $this.removeData('bootstrap.table'); } } if (!data) { $this.data('bootstrap.table', (data = new BootstrapTable(this, options))); } }); return typeof value === 'undefined' ? this : value; }; $.fn.bootstrapTable.Constructor = BootstrapTable; $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS; $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS; $.fn.bootstrapTable.locales = BootstrapTable.LOCALES; $.fn.bootstrapTable.methods = allowedMethods; $.fn.bootstrapTable.utils = { sprintf: sprintf, getFieldIndex: getFieldIndex, compareObjects: compareObjects, calculateObjectValue: calculateObjectValue }; // BOOTSTRAP TABLE INIT // ======================= $(function () { $('[data-toggle="table"]').bootstrapTable(); }); }(jQuery);
ZombieHippie/cream
public/script/tablesorting.js
JavaScript
bsd-2-clause
100,297
/** * @module ol/layer/MapboxVector */ import BaseEvent from '../events/Event.js'; import EventType from '../events/EventType.js'; import GeometryType from '../geom/GeometryType.js'; import MVT from '../format/MVT.js'; import RenderFeature from '../render/Feature.js'; import SourceState from '../source/State.js'; import TileEventType from '../source/TileEventType.js'; import VectorTileLayer from '../layer/VectorTile.js'; import VectorTileSource from '../source/VectorTile.js'; import {Fill, Style} from '../style.js'; import {applyStyle, setupVectorSource} from 'ol-mapbox-style'; import {fromExtent} from '../geom/Polygon.js'; import {getValue} from 'ol-mapbox-style/dist/stylefunction.js'; const mapboxBaseUrl = 'https://api.mapbox.com'; /** * Gets the path from a mapbox:// URL. * @param {string} url The Mapbox URL. * @return {string} The path. * @private */ export function getMapboxPath(url) { const startsWith = 'mapbox://'; if (url.indexOf(startsWith) !== 0) { return ''; } return url.slice(startsWith.length); } /** * Turns mapbox:// sprite URLs into resolvable URLs. * @param {string} url The sprite URL. * @param {string} token The access token. * @return {string} A resolvable URL. * @private */ export function normalizeSpriteUrl(url, token) { const mapboxPath = getMapboxPath(url); if (!mapboxPath) { return url; } const startsWith = 'sprites/'; if (mapboxPath.indexOf(startsWith) !== 0) { throw new Error(`unexpected sprites url: ${url}`); } const sprite = mapboxPath.slice(startsWith.length); return `${mapboxBaseUrl}/styles/v1/${sprite}/sprite?access_token=${token}`; } /** * Turns mapbox:// glyphs URLs into resolvable URLs. * @param {string} url The glyphs URL. * @param {string} token The access token. * @return {string} A resolvable URL. * @private */ export function normalizeGlyphsUrl(url, token) { const mapboxPath = getMapboxPath(url); if (!mapboxPath) { return url; } const startsWith = 'fonts/'; if (mapboxPath.indexOf(startsWith) !== 0) { throw new Error(`unexpected fonts url: ${url}`); } const font = mapboxPath.slice(startsWith.length); return `${mapboxBaseUrl}/fonts/v1/${font}/0-255.pbf?access_token=${token}`; } /** * Turns mapbox:// style URLs into resolvable URLs. * @param {string} url The style URL. * @param {string} token The access token. * @return {string} A resolvable URL. * @private */ export function normalizeStyleUrl(url, token) { const mapboxPath = getMapboxPath(url); if (!mapboxPath) { return url; } const startsWith = 'styles/'; if (mapboxPath.indexOf(startsWith) !== 0) { throw new Error(`unexpected style url: ${url}`); } const style = mapboxPath.slice(startsWith.length); return `${mapboxBaseUrl}/styles/v1/${style}?&access_token=${token}`; } /** * Turns mapbox:// source URLs into vector tile URL templates. * @param {string} url The source URL. * @param {string} token The access token. * @param {string} tokenParam The access token key. * @return {string} A vector tile template. * @private */ export function normalizeSourceUrl(url, token, tokenParam) { const mapboxPath = getMapboxPath(url); if (!mapboxPath) { if (!token) { return url; } const urlObject = new URL(url, location.href); urlObject.searchParams.set(tokenParam, token); return decodeURI(urlObject.href); } return `https://{a-d}.tiles.mapbox.com/v4/${mapboxPath}/{z}/{x}/{y}.vector.pbf?access_token=${token}`; } /** * @classdesc * Event emitted on configuration or loading error. */ class ErrorEvent extends BaseEvent { /** * @param {Error} error error object. */ constructor(error) { super(EventType.ERROR); /** * @type {Error} */ this.error = error; } } /** * @typedef {Object} StyleObject * @property {Object<string, SourceObject>} sources The style sources. * @property {string} sprite The sprite URL. * @property {string} glyphs The glyphs URL. * @property {Array<LayerObject>} layers The style layers. */ /** * @typedef {Object} SourceObject * @property {string} url The source URL. * @property {SourceType} type The source type. * @property {Array<string>} [tiles] TileJSON tiles. */ /** * The Mapbox source type. * @enum {string} */ const SourceType = { VECTOR: 'vector', }; /** * @typedef {Object} LayerObject * @property {string} id The layer id. * @property {string} type The layer type. * @property {string} source The source id. * @property {Object} layout The layout. * @property {Object} paint The paint. */ /** * @typedef {Object} Options * @property {string} styleUrl The URL of the Mapbox style object to use for this layer. For a * style created with Mapbox Studio and hosted on Mapbox, this will look like * 'mapbox://styles/you/your-style'. * @property {string} [accessToken] The access token for your Mapbox style. This has to be provided * for `mapbox://` style urls. For `https://` and other urls, any access key must be the last query * parameter of the style url. * @property {string} [source] If your style uses more than one source, you need to use either the * `source` property or the `layers` property to limit rendering to a single vector source. The * `source` property corresponds to the id of a vector source in your Mapbox style. * @property {Array<string>} [layers] Limit rendering to the list of included layers. All layers * must share the same vector source. If your style uses more than one source, you need to use * either the `source` property or the `layers` property to limit rendering to a single vector * source. * @property {boolean} [declutter=true] Declutter images and text. Decluttering is applied to all * image and text styles of all Vector and VectorTile layers that have set this to `true`. The priority * is defined by the z-index of the layer, the `zIndex` of the style and the render order of features. * Higher z-index means higher priority. Within the same z-index, a feature rendered before another has * higher priority. * @property {string} [className='ol-layer'] A CSS class name to set to the layer element. * @property {number} [opacity=1] Opacity (0, 1). * @property {boolean} [visible=true] Visibility. * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering. The layer will not be * rendered outside of this extent. * @property {number} [zIndex] The z-index for layer rendering. At rendering time, the layers * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()` * method was used. * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be * visible. * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will * be visible. * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be * visible. * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will * be visible. * @property {import("../render.js").OrderFunction} [renderOrder] Render order. Function to be used when sorting * features before rendering. By default features are drawn in the order that they are created. Use * `null` to avoid the sort, but get an undefined draw order. * @property {number} [renderBuffer=100] The buffer in pixels around the tile extent used by the * renderer when getting features from the vector tile for the rendering or hit-detection. * Recommended value: Vector tiles are usually generated with a buffer, so this value should match * the largest possible buffer of the used tiles. It should be at least the size of the largest * point symbol or line width. * @property {import("./VectorTileRenderType.js").default|string} [renderMode='hybrid'] Render mode for vector tiles: * * `'hybrid'`: Polygon and line elements are rendered as images, so pixels are scaled during zoom * animations. Point symbols and texts are accurately rendered as vectors and can stay upright on * rotated views. * * `'vector'`: Everything is rendered as vectors. Use this mode for improved performance on vector * tile layers with only a few rendered features (e.g. for highlighting a subset of features of * another layer with the same source). * @property {import("../PluggableMap.js").default} [map] Sets the layer as overlay on a map. The map will not manage * this layer in its layers collection, and the layer will be rendered on top. This is useful for * temporary layers. The standard way to add a layer to a map and have it managed by the map is to * use {@link import("../PluggableMap.js").default#addLayer map.addLayer()}. * @property {boolean} [updateWhileAnimating=false] When set to `true`, feature batches will be * recreated during animations. This means that no vectors will be shown clipped, but the setting * will have a performance impact for large amounts of vector data. When set to `false`, batches * will be recreated when no animation is active. * @property {boolean} [updateWhileInteracting=false] When set to `true`, feature batches will be * recreated during interactions. See also `updateWhileAnimating`. * @property {number} [preload=0] Preload. Load low-resolution tiles up to `preload` levels. `0` * means no preloading. * @property {boolean} [useInterimTilesOnError=true] Use interim tiles on error. * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`. */ /** * @classdesc * A vector tile layer based on a Mapbox style that uses a single vector source. Configure * the layer with the `styleUrl` and `accessToken` shown in Mapbox Studio's share panel. * If the style uses more than one source, use the `source` property to choose a single * vector source. If you want to render a subset of the layers in the style, use the `layers` * property (all layers must share the same vector source). See the constructor options for * more detail. * * var map = new Map({ * view: new View({ * center: [0, 0], * zoom: 1 * }), * layers: [ * new MapboxVectorLayer({ * styleUrl: 'mapbox://styles/mapbox/bright-v9', * accessToken: 'your-mapbox-access-token-here' * }) * ], * target: 'map' * }); * * On configuration or loading error, the layer will trigger an `'error'` event. Listeners * will receive an object with an `error` property that can be used to diagnose the problem. * * @param {Options} options Options. * @extends {VectorTileLayer} * @fires module:ol/events/Event~BaseEvent#event:error * @api */ class MapboxVectorLayer extends VectorTileLayer { /** * @param {Options} options Layer options. At a minimum, `styleUrl` and `accessToken` * must be provided. */ constructor(options) { const declutter = 'declutter' in options ? options.declutter : true; const source = new VectorTileSource({ state: SourceState.LOADING, format: new MVT(), }); super({ source: source, declutter: declutter, className: options.className, opacity: options.opacity, visible: options.visible, zIndex: options.zIndex, minResolution: options.minResolution, maxResolution: options.maxResolution, minZoom: options.minZoom, maxZoom: options.maxZoom, renderOrder: options.renderOrder, renderBuffer: options.renderBuffer, renderMode: options.renderMode, map: options.map, updateWhileAnimating: options.updateWhileAnimating, updateWhileInteracting: options.updateWhileInteracting, preload: options.preload, useInterimTilesOnError: options.useInterimTilesOnError, properties: options.properties, }); this.sourceId = options.source; this.layers = options.layers; if (options.accessToken) { this.accessToken = options.accessToken; } else { const url = new URL(options.styleUrl, location.href); // The last search parameter is the access token url.searchParams.forEach((value, key) => { this.accessToken = value; this.accessTokenParam_ = key; }); } this.fetchStyle(options.styleUrl); } /** * Fetch the style object. * @param {string} styleUrl The URL of the style to load. * @protected */ fetchStyle(styleUrl) { const url = normalizeStyleUrl(styleUrl, this.accessToken); fetch(url) .then((response) => { if (!response.ok) { throw new Error( `unexpected response when fetching style: ${response.status}` ); } return response.json(); }) .then((style) => { this.onStyleLoad(style); }) .catch((error) => { this.handleError(error); }); } /** * Handle the loaded style object. * @param {StyleObject} style The loaded style. * @protected */ onStyleLoad(style) { let sourceId; let sourceIdOrLayersList; if (this.layers) { // confirm all layers share the same source const lookup = {}; for (let i = 0; i < style.layers.length; ++i) { const layer = style.layers[i]; if (layer.source) { lookup[layer.id] = layer.source; } } let firstSource; for (let i = 0; i < this.layers.length; ++i) { const candidate = lookup[this.layers[i]]; if (!candidate) { this.handleError( new Error(`could not find source for ${this.layers[i]}`) ); return; } if (!firstSource) { firstSource = candidate; } else if (firstSource !== candidate) { this.handleError( new Error( `layers can only use a single source, found ${firstSource} and ${candidate}` ) ); return; } } sourceId = firstSource; sourceIdOrLayersList = this.layers; } else { sourceId = this.sourceId; sourceIdOrLayersList = sourceId; } if (!sourceIdOrLayersList) { // default to the first source in the style sourceId = Object.keys(style.sources)[0]; sourceIdOrLayersList = sourceId; } if (style.sprite) { style.sprite = normalizeSpriteUrl(style.sprite, this.accessToken); } if (style.glyphs) { style.glyphs = normalizeGlyphsUrl(style.glyphs, this.accessToken); } const styleSource = style.sources[sourceId]; if (styleSource.type !== SourceType.VECTOR) { this.handleError( new Error(`only works for vector sources, found ${styleSource.type}`) ); return; } const source = this.getSource(); if (styleSource.url && styleSource.url.indexOf('mapbox://') === 0) { // Tile source url, handle it directly source.setUrl( normalizeSourceUrl( styleSource.url, this.accessToken, this.accessTokenParam_ ) ); applyStyle(this, style, sourceIdOrLayersList) .then(() => { this.configureSource(source, style); }) .catch((error) => { this.handleError(error); }); } else { // TileJSON url, let ol-mapbox-style handle it if (styleSource.tiles) { styleSource.tiles = styleSource.tiles.map((url) => normalizeSourceUrl(url, this.accessToken, this.accessTokenParam_) ); } setupVectorSource( styleSource, styleSource.url ? normalizeSourceUrl( styleSource.url, this.accessToken, this.accessTokenParam_ ) : undefined ).then((source) => { applyStyle(this, style, sourceIdOrLayersList) .then(() => { this.configureSource(source, style); }) .catch((error) => { this.configureSource(source, style); this.handleError(error); }); }); } } /** * Applies configuration from the provided source to this layer's source, * and reconfigures the loader to add a feature that renders the background, * if the style is configured with a background. * @param {import("../source/VectorTile.js").default} source The source to configure from. * @param {StyleObject} style The style to configure the background from. */ configureSource(source, style) { const targetSource = this.getSource(); if (source !== targetSource) { targetSource.setAttributions(source.getAttributions()); targetSource.setTileUrlFunction(source.getTileUrlFunction()); targetSource.setTileLoadFunction(source.getTileLoadFunction()); targetSource.tileGrid = source.tileGrid; } const background = style.layers.find( (layer) => layer.type === 'background' ); if ( background && (!background.layout || background.layout.visibility !== 'none') ) { const style = new Style({ fill: new Fill(), }); targetSource.addEventListener(TileEventType.TILELOADEND, (event) => { const tile = /** @type {import("../VectorTile.js").default} */ ( /** @type {import("../source/Tile.js").TileSourceEvent} */ (event) .tile ); const styleFuntion = () => { const opacity = /** @type {number} */ ( getValue( background, 'paint', 'background-opacity', tile.tileCoord[0] ) ) || 1; const color = /** @type {*} */ ( getValue(background, 'paint', 'background-color', tile.tileCoord[0]) ); style .getFill() .setColor([ color.r * 255, color.g * 255, color.b * 255, color.a * opacity, ]); return style; }; const extentGeometry = fromExtent( targetSource.tileGrid.getTileCoordExtent(tile.tileCoord) ); const renderFeature = new RenderFeature( GeometryType.POLYGON, extentGeometry.getFlatCoordinates(), extentGeometry.getEnds(), {layer: background.id}, undefined ); renderFeature.styleFunction = styleFuntion; tile.getFeatures().unshift(renderFeature); }); } targetSource.setState(SourceState.READY); } /** * Handle configuration or loading error. * @param {Error} error The error. * @protected */ handleError(error) { this.dispatchEvent(new ErrorEvent(error)); const source = this.getSource(); source.setState(SourceState.ERROR); } } export default MapboxVectorLayer;
ahocevar/ol3
src/ol/layer/MapboxVector.js
JavaScript
bsd-2-clause
18,944
var mongoose = require('mongoose'); module.exports = function (config) { mongoose.connect(config.db); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error...')); db.once('open', function callBack() { console.log('multivision is opened'); }); var userSchema = mongoose.Schema({ firstName: String, lastName: String, username: String }); var User = mongoose.model('User', userSchema); User.find({}).exec(function (err, collection) { if (collection.length === 0) { User.create({firstName: 'Joe', lastName: 'Eames', username: 'joe'}); User.create({firstName: 'John', lastName: 'Papa', username: 'john'}); User.create({firstName: 'Dan', lastName: 'Wahlin', username: 'dan'}); } }); };
dimylik/mean
server/config/mongoose.js
JavaScript
bsd-2-clause
850
/** * Copyright 2015 Fabian Grutschus. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the copyright holders. * * @author Fabian Grutschus <[email protected]> * @copyright 2015 Fabian Grutschus. All rights reserved. * @license BSD-2-Clause */ ;(function (global, storage) { var originalOnError = function () {}; if (typeof global.onerror === "function") { originalOnError = global.onerror; } var E = { storageKey: "fabiang_error_handler", register: function () { global.onerror = function () { var args = Array.prototype.slice.call(arguments); E.handle.apply(null, args); originalOnError.apply(null, args); }; E.registerForjQuery(); }, registerForjQuery: function () { if (typeof global.jQuery === "function") { jQuery(global.document).ajaxError(function (e, xhr, settings, message) { var error = { message: message.length > 0 ? message : "Unknown error", method: settings.type, url: settings.url, type: "ajaxError" }; E.store(error); }); } }, handle: function (message, file, lineno, column) { var error = { message: message, file: file, lineno: lineno, column: column, type: "error" }; E.store(error); }, store: function (error) { var errors = E.get(); errors.push(error); storage.setItem(E.storageKey, JSON.stringify(errors)); }, get: function () { if (null !== storage.getItem(E.storageKey)) { return JSON.parse(storage.getItem(E.storageKey)); } return []; }, clear: function () { storage.setItem(E.storageKey, "[]"); } }; global.ErrorHandler = E; E.register(); }(this, localStorage));
fabiang/mink-javascript-errors
src/ErrorHandler.js
JavaScript
bsd-2-clause
3,639
// This file was generated by silverstripe/cow from client/lang/src/el.js. // See https://github.com/tractorcow/cow for details if (typeof(ss) === 'undefined' || typeof(ss.i18n) === 'undefined') { if (typeof(console) !== 'undefined') { // eslint-disable-line no-console console.error('Class ss.i18n not defined'); // eslint-disable-line no-console } } else { ss.i18n.addDictionary('el', { "CMS.ALERTCLASSNAME": "The page type will be updated after the page is saved", "CMS.AddSubPage": "Προσθήκη νέας σελίδας εδώ", "CMS.ConfirmRestoreFromLive": "Are you sure you want to revert draft to when the page was last published?", "CMS.Duplicate": "Duplicate", "CMS.EditPage": "Edit", "CMS.ONLYSELECTTWO": "You can only compare two versions at this time.", "CMS.Restore": "Are you sure you want to restore this page from archive?", "CMS.RestoreToRoot": "Are you sure you want to restore this page from archive?\n\nBecause the parent page is not available this will be restored to the top level.", "CMS.RollbackToVersion": "Do you really want to roll back to version #%s of this page?", "CMS.ShowAsList": "Show children as list", "CMS.ThisPageAndSubpages": "This page and subpages", "CMS.ThisPageOnly": "Μόνο αυτή η σελίδα", "CMS.Unpublish": "Are you sure you want to remove your page from the published site?\n\nThis page will still be available in the sitetree as draft.", "CMS.UpdateURL": "Update URL", "CMS.ViewPage": "View" }); }
jonom/silverstripe-cms
client/lang/el.js
JavaScript
bsd-3-clause
1,533
import React from "react"; import Image from "@times-components/image"; import styleFactory from "./styles"; import propTypes from "./proptypes"; const MastHead = ({ publicationName, breakpoint }) => { let uri = "https://www.thetimes.co.uk/d/img/leaders-masthead-d17db00289.png"; let aspectRatio = 1435 / 250; let style = "mastheadStyleTimes"; const styles = styleFactory(breakpoint); if (publicationName !== "TIMES") { style = "mastheadStyleST"; aspectRatio = 243 / 45; uri = "https://www.thetimes.co.uk/d/img/logos/sundaytimes-with-crest-black-53d6e31fb8.png"; } return <Image aspectRatio={aspectRatio} style={styles[style]} uri={uri} />; }; MastHead.propTypes = propTypes; export default MastHead;
newsuk/times-components
packages/edition-slices/src/slices/leaders/masthead.js
JavaScript
bsd-3-clause
738
(function () { 'use strict'; angular.module('instance-info', ['motech-dashboard', 'instance-info.controllers', 'ngCookies', 'ui.bootstrap']).config( ['$routeProvider', function ($routeProvider) { $routeProvider. when('/instance-info/info', {templateUrl: '../instance-info/resources/partials/info.html', controller: 'InfoController'}); }]); }());
motech/perf
instance-info/src/main/resources/webapp/js/app.js
JavaScript
bsd-3-clause
399
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails oncall+relay */ 'use strict'; require('configureForRelayOSS'); jest .dontMock('GraphQLRange') .dontMock('GraphQLSegment'); const Relay = require('Relay'); const RelayRecordStore = require('RelayRecordStore'); const RelayRecordWriter = require('RelayRecordWriter'); const RelayTestUtils = require('RelayTestUtils'); describe('writeRelayQueryPayload()', () => { const {getNode, writePayload} = RelayTestUtils; beforeEach(() => { jest.resetModuleRegistry(); }); describe('default null', () => { it('writes missing scalar field as null', () => { const records = {}; const store = new RelayRecordStore({records}); const writer = new RelayRecordWriter(records, {}, false); const query = getNode(Relay.QL` query { node(id:"123") { id, name } } `); const payload = { node: { __typename: 'User', id: '123', }, }; const results = writePayload(store, writer, query, payload); expect(results).toEqual({ created: { '123': true, }, updated: {}, }); expect(store.getField('123', 'name')).toBe(null); }); it('writes missing linked field as null', () => { const records = {}; const store = new RelayRecordStore({records}); const writer = new RelayRecordWriter(records, {}, false); const query = getNode(Relay.QL` query { viewer { actor { id } } } `); const payload = { viewer: {}, }; const results = writePayload(store, writer, query, payload); expect(results).toEqual({ created: { 'client:1': true, }, updated: {}, }); expect(store.getRecordState('client:1')).toBe('EXISTENT'); expect(store.getLinkedRecordID('client:1', 'actor')).toBe(null); }); it('writes missing plural linked field as null', () => { const records = { '123': { __dataID__: '123', id: '123', }, }; const store = new RelayRecordStore({records}); const writer = new RelayRecordWriter(records, {}, false); const query = getNode(Relay.QL` query { node(id:"123") { allPhones { phoneNumber { displayNumber } } } } `); const payload = { node: { __typename: 'User', id: '123', }, }; const results = writePayload(store, writer, query, payload); expect(results).toEqual({ created: {}, updated: { '123': true, }, }); const phoneIDs = store.getLinkedRecordIDs('123', 'allPhones'); expect(phoneIDs).toEqual(null); }); it('writes missing connection as null', () => { const records = {}; const store = new RelayRecordStore({records}); const writer = new RelayRecordWriter(records, {}, false); const query = getNode(Relay.QL` query { node(id:"123") { friends(first:"3") { edges { cursor, node { id }, }, pageInfo { hasNextPage, hasPreviousPage, } } } } `); const payload = { node: { id: '123', __typename: 'User', }, }; const results = writePayload(store, writer, query, payload); expect(results).toEqual({ created: { '123': true, }, updated: {}, }); expect(store.getField('123', 'friends')).toBe(null); }); }); });
NevilleS/relay
src/traversal/__tests__/writeRelayQueryPayload_defaultNull-test.js
JavaScript
bsd-3-clause
4,160
// menubar.js // top menubar icon const path = require('path'); const db = require('../lib/db'); const switcher = require('../lib/switcher'); const {Tray, Menu} = require('electron').remote; const iconPath = path.join(__dirname, '../../resources/menubar-alt2.png'); let menubar = null; // prevent GC module.exports = function() { db.getCards().then(cards => { let template = []; cards.forEach(card => { template.push({ label: `Switch to ${card.nickname}`, click() { switcher.switchTo(card.address, card.username); } }); }); template = template.concat([ { type: 'separator' }, { label: 'Quit', selector: 'terminate:' } ]); menubar = new Tray(iconPath); menubar.setToolTip('Blue'); menubar.setContextMenu(Menu.buildFromTemplate(template)); }) .done(); };
mysticflute/blue
src/menu/menubar.js
JavaScript
bsd-3-clause
891
var class_app_store_1_1_models_1_1_category_instance = [ [ "category", "de/d27/class_app_store_1_1_models_1_1_category_instance.html#ac1e8313d7f7d58349cf972f2be0ae365", null ] ];
BuildmLearn/BuildmLearn-Store
WP/doc/DOxygen_HTML/de/d27/class_app_store_1_1_models_1_1_category_instance.js
JavaScript
bsd-3-clause
182
var CoreView = require('backbone/core-view'); var ModalsServiceModel = require('../../../../../javascripts/cartodb3/components/modals/modals-service-model'); var Router = require('../../../../../javascripts/cartodb3/routes/router'); describe('components/modals/modals-service-model', function () { beforeEach(function () { this.modals = new ModalsServiceModel(); this.willCreateModalSpy = jasmine.createSpy('willCreateModal'); this.didCreateModalSpy = jasmine.createSpy('didCreateModal'); this.modals.on('willCreateModal', this.willCreateModalSpy); this.modals.on('didCreateModal', this.didCreateModalSpy); }); describe('.create', function () { var contentView, contentView2; beforeEach(function () { spyOn(Router, 'navigate'); spyOn(document.body, 'appendChild'); contentView = new CoreView(); spyOn(contentView, 'render').and.callThrough(); this.modalView = this.modals.create(function () { return contentView; }); }); it('should return a modal view', function () { expect(this.modalView).toBeDefined(); }); it('should trigger a willCreateModal event', function () { expect(this.willCreateModalSpy).toHaveBeenCalled(); }); it('should trigger a didCreateModal event', function () { expect(this.didCreateModalSpy).toHaveBeenCalled(); }); it('should render the content view', function () { expect(contentView.render).toHaveBeenCalled(); }); it('should append the modal to the body', function () { expect(document.body.appendChild).toHaveBeenCalledWith(this.modalView.el); }); it('should add the special body class', function () { expect(document.body.className).toContain('is-inDialog'); }); describe('subsequent calls', function () { beforeEach(function () { contentView2 = new CoreView(); spyOn(contentView2, 'render').and.callThrough(); this.modalView2 = this.modals.create(function () { return contentView2; }); }); it('should reuse modal view', function () { expect(this.modalView2).toBe(this.modalView); }); it('should append the new modal to the body', function () { expect(document.body.appendChild).toHaveBeenCalledWith(this.modalView2.el); }); it('should keep the special body class', function () { expect(document.body.className).toContain('is-inDialog'); }); describe('when destroyed', function () { beforeEach(function () { jasmine.clock().install(); this.destroyOnceSpy = jasmine.createSpy('destroyedModal'); this.modals.onDestroyOnce(this.destroyOnceSpy); spyOn(this.modalView2, 'clean').and.callThrough(); this.modalView2.destroy(); }); afterEach(function () { jasmine.clock().uninstall(); }); it('should not clean the view right away but wait until after animation', function () { expect(this.modalView2.clean).not.toHaveBeenCalled(); }); it('should have closing animation', function () { expect(this.modalView2.el.className).toContain('is-closing'); expect(this.modalView2.el.className).not.toContain('is-opening'); }); it('should remove the special body class', function () { expect(document.body.className).not.toContain('is-inDialog'); }); describe('when close animation is done', function () { beforeEach(function () { jasmine.clock().tick(250); }); it('should have cleaned the view', function () { expect(this.modalView2.clean).toHaveBeenCalled(); }); it('should have triggered listener', function () { expect(this.destroyOnceSpy).toHaveBeenCalled(); }); }); }); }); }); });
splashblot/dronedb
lib/assets/test/spec/cartodb3/components/modals/modals-service-model.spec.js
JavaScript
bsd-3-clause
3,915
/* * Copyright (c) 2022 Snowplow Analytics Ltd * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder 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 HOLDER 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. */ import { nodeResolve } from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; import ts from 'rollup-plugin-ts'; import { banner } from '../../banner'; import compiler from '@ampproject/rollup-plugin-closure-compiler'; import { terser } from 'rollup-plugin-terser'; import cleanup from 'rollup-plugin-cleanup'; import pkg from './package.json'; import { builtinModules } from 'module'; const umdPlugins = [nodeResolve({ browser: true }), commonjs(), ts()]; const umdName = 'snowplowYouTubeTracking'; export default [ // CommonJS (for Node) and ES module (for bundlers) build. { input: './src/index.ts', plugins: [...umdPlugins, banner(true)], treeshake: { moduleSideEffects: ['sha1'] }, output: [{ file: pkg.main, format: 'umd', sourcemap: true, name: umdName }], }, { input: './src/index.ts', plugins: [...umdPlugins, compiler(), terser(), cleanup({ comments: 'none' }), banner(true)], treeshake: { moduleSideEffects: ['sha1'] }, output: [{ file: pkg.main.replace('.js', '.min.js'), format: 'umd', sourcemap: true, name: umdName }], }, { input: './src/index.ts', external: [...builtinModules, ...Object.keys(pkg.dependencies), ...Object.keys(pkg.devDependencies)], plugins: [ts(), banner(true)], output: [{ file: pkg.module, format: 'es', sourcemap: true }], }, ];
snowplow/snowplow-javascript-tracker
plugins/browser-plugin-youtube-tracking/rollup.config.js
JavaScript
bsd-3-clause
2,950
/** * Shake Table web interface. * * @author Michael Diponio <[email protected]> * @author Jesse Charlton <[email protected]> * @date 1/6/2013 */ /* ============================================================================ * == Shake Table. == * ============================================================================ */ function ShakeTable(is3DOF) { new WebUIApp(is3DOF ? Config3DOF() : Config2DOF()).setup().run(); } /** * 2 degree of freedom (2DOF) Shake Table interface. */ function Config2DOF() { return { anchor: "#shake-table-anchor", controller: "ShakeTableController", dataAction: "dataAndGraph", dataDuration: 30, dataPeriod: 10, pollPeriod: 1000, windowToggle: true, theme: Globals.THEMES.flat, cookie: "shaketable2dof", widgets: [ new MimicWidget(false), new Container("graphs-container", { title: "Graphs", reizable: true, left: -191, top: 540, widgets: [ new Graph("graph-displacement", { title: "Displacements", resizable: true, fields: { 'disp-graph-1': 'Base', 'disp-graph-2': 'Level 1', 'disp-graph-3': 'Level 2' }, minValue: -60, maxValue: 60, duration: 10, durationCtl: true, yLabel: "Displacement (mm)", fieldCtl: true, autoCtl: true, traceLabels: true, width: 832, height: 325, }), new Container("graphs-lissajous-container", { title: "Lissajous", widgets: [ new ScatterPlot("graph-lissajous-l0l1", { title: "L0 vs L1", xLabel: "L0 (mm)", yLabel: "L1 (mm)", autoScale: true, vertScales: 5, horizScales: 5, sampleSize: 125, fields: { 'disp-graph-1': 'disp-graph-2' }, labels: { 'disp-graph-1': "L0 vs L1", }, traceLabels: false, }), new ScatterPlot("graph-lissajous-l0l2", { title: "L0 vs L2", xLabel: "L0 (mm)", yLabel: "L2 (mm)", autoScale: true, vertScales: 5, horizScales: 5, sampleSize: 125, fields: { 'disp-graph-1': 'disp-graph-3' }, labels: { 'disp-graph-1': "L0 vs L2", }, traceLabels: false }), new ScatterPlot("graph-lissajous-l1l2", { title: "L1 vs L2", xLabel: "L1 (mm)", yLabel: "L2 (mm)", autoScale: true, vertScales: 5, horizScales: 5, sampleSize: 125, fields: { 'disp-graph-2': 'disp-graph-3' }, labels: { 'disp-graph-2': "L1 vs L2", }, traceLabels: false }), ], layout: new TabLayout({ position: TabLayout.POSITION.left, border: 0, }) }), new Container("fft-container", { title: "FFT", widgets: [ new FFTGraph("graph-fft", { title: "FFT", resizable: true, fields: { 'disp-graph-1': 'Base', 'disp-graph-2': 'Level 1', 'disp-graph-3': 'Level 2' }, xLabel: "Frequency (Hz)", yLabel: "Amplitude (mm)", horizScales: 10, maxValue: 30, period: 10, duration: 10, fieldCtl: true, autoScale: true, }), new Button("button-fft-export", { label: "Export FFT", link: "/primitive/file/pc/ShakeTableController/pa/exportFFT/fn/fft.txt", target: "_blank", width: 80, height: 20, resizable: false }) ], layout: new AbsoluteLayout({ coords: { "graph-fft": { x: 0, y: 0 }, "button-fft-export": { x: 20, y: -1 } } }) }), ], layout: new TabLayout({ position: TabLayout.POSITION.top, border: 10, }) }), new CameraStream("camera-stream", { resizable: true, left: -2, top: 5, videoWidth: 320, videoHeight: 240, swfParam: 'camera-swf', mjpegParam: 'camera-mjpeg', title: "Camera" }), new Container("controls-container", { title: "Controls", resizable: false, left: -2, top: 335, widgets: [ new Slider("slider-motor-speed", { field: "motor-speed", action: "setMotor", max: 8, precision: 2, label: "Motor Frequency", units: "Hz", vertical: false, }), new Slider("slider-coil-1", { length: 75, action: "setCoil", field: "coils-1-power", label: "Coil 1", vertical: true, scales: 2, units: "%" }), new Slider("slider-coil-2", { length: 75, action: "setCoil", field: "coils-2-power", label: "Coil 2", vertical: true, scales: 2, units: "%" }), new Container("container-control-buttons", { width: 200, widgets: [ new Switch("switch-motor-on", { field: "motor-on", action: "setMotor", label: "Motor", width: 96, }), new Switch("switch-coils-on", { field: "coils-on", action: "setCoils", label: "Coils", width: 92, }), new Switch("switch-coupling", { field: "motor-coil-couple", action: "setCouple", label: "Couple", width: 107, }), new Image("couple-to-motor" , { image: "/uts/shaketable/images/arrow-couple-left.png", }), new Image("couple-to-coils" , { image: "/uts/shaketable/images/arrow-couple-right.png", }), ], layout: new AbsoluteLayout({ border: 10, coords: { "switch-motor-on": { x: -5, y: 20 }, "switch-coils-on": { x: 100, y: 20 }, "switch-coupling": { x: 40, y: 80 }, "couple-to-motor": { x: 0, y: 55 }, "couple-to-coils": { x: 154, y: 55 }, } }) }), ], layout: new GridLayout({ padding: 5, columns: [ [ "container-control-buttons" ], [ "slider-motor-speed" ], [ "slider-coil-1" ], [ "slider-coil-2" ] ] }) }), new DataLogging("data-logger", { left: -193, top: 142, width: 183, height: 388, }) ] }; } /* * 3 degree of freedom (3DOF) Shake Table interface. */ function Config3DOF() { return { anchor: "#shake-table-anchor", controller: "ShakeTableController", dataAction: "dataAndGraph", dataDuration: 10, dataPeriod: 100, pollPeriod: 1000, windowToggle: true, theme: Globals.THEMES.flat, cookie: "shaketable", widgets: [ new Graph("graph-displacement", { title: "Graphs", resizable: true, width: 418, height: 328, left: 351, top: 423, fields: { 'disp-graph-1': 'Level 1', 'disp-graph-2': 'Level 2', 'disp-graph-3': 'Level 3' }, minValue: -60, maxValue: 60, duration: 10, yLabel: "Displacement (mm)", fieldCtl: false, autoCtl: false, durationCtl: false, traceLabels: false, }), new MimicWidget(true), new CameraStream("camera-stream", { resizable: true, left: 2, top: 45, videoWidth: 320, videoHeight: 240, swfParam: 'camera-swf', mjpegParam: 'camera-mjpeg', title: "Camera" }), new Container("controls-container", { title: "Controls", resizable: false, left: 2, top: 375, widgets: [ new Switch("switch-motor-on", { field: "motor-on", action: "setMotor", label: "Motor", }), new Switch("switch-coils-on", { field: "coils-on", action: "setCoils", label: "Dampening", }), new Slider("slider-motor-speed", { field: "motor-speed", action: "setMotor", max: 8, precision: 2, label: "Motor Frequency", units: "Hz", vertical: false, }) ], layout: new FlowLayout({ padding: 5, size: 320, vertical: false, center: true, }) }) ] }; } /* ============================================================================ * == Mimic Widget. == * ============================================================================ */ /** * Mimic Widget. This widget creates and controls the Shake Table Mimic. * * @param {boolean} is3DOF whether to display 2DOF or 3DOF configuration */ function MimicWidget(is3DOF) { Widget.call(this, "shaker-mimic", { title: "Model", windowed: true, resizable: true, preserveAspectRatio: true, minWidth: 320, minHeight: 410, closeable: true, shadeable: true, expandable: true, draggable: true, left: 338, top: 5, width: 334 }); /** Model dimensions in mm. */ this.model = { levelWidth: 200, // Width of the model armWidth: 70, // Width of the stroke arm connecting the motor to the model motorRadius: 10, // Radius of the motor wallHeight: 120, // Height of the walls levelHeight: 30, // Height of the levels trackHeight: 20, // Height of the track trackWidth: 300, // Width of track carHeight: 10, // Height of carriage carWidth: 120, // Width of carriage maxDisp: 60, // Maximum displacement of the diagram baseDisp: 0.7 // Displacement of the base when the motor is on }; /** Whether this mimic represents a 2DOF or a 3DOF widget. */ this.is3DOF = is3DOF; /** Number of levels in the model. */ this.numberLevels = this.is3DOF ? 4 : 3; /** Millimeters per pixel. */ this.mmPerPx = 1.475; /** The width of the diagram in pixels. */ this.width = undefined; /** The height of the diagram in pixels. */ this.height = undefined; /** The period in milliseconds. */ this.period = 10; /** Canvas context. */ this.ctx = null; /** Amplitude of displacement in mm. */ this.amp = [ 0, 0, 0, 0 ]; /** Angular frequency r/s. */ this.w = 0; /** Offsets of levels. */ this.o = [ 0, 0, 0, 0 ]; /** Frame count. */ this.fr = 0; /** Motor frequency. */ this.motor = 0; /** Coil power percentages. */ this.coils = [ undefined, undefined, undefined ]; /** Center line. */ this.cx = undefined; /** Animation interval. */ this.animateInterval = undefined; } MimicWidget.prototype = new Widget; MimicWidget.ANIMATE_PERIOD = 50; MimicWidget.prototype.init = function($container) { var canvas, thiz = this; this.mmPerPx = 1.475; if (this.window.width) { this.mmPerPx = 320 / this.window.width * 1.475; } /* The width of the canvas diagram is the width of the building model plus * the maximum possible displacement. */ this.width = this.px(this.model.levelWidth + this.model.maxDisp * 2) + this.px(100); this.height = this.px(this.model.levelHeight * (this.is3DOF ? 4 : 3) + this.model.wallHeight * (this.is3DOF ? 3: 2) + this.model.trackHeight + this.model.carHeight); this.cx = this.width / 2; /* Box. */ this.$widget = this._generate($container, "<div class='mimic'></div>"); this.$widget.css("height", "auto"); /* Canvas to draw display. */ canvas = Util.getCanvas(this.id + "-canvas", this.width, this.height); this.$widget.find(".mimic").append(canvas); this.ctx = canvas.getContext("2d"); this.ctx.translate(0.5, 0.5); /* Draw initial frame of zero position. */ this.drawFrame([0, 0, 0, 0]); this.boxWidth = this.$widget.width(); /* Start animation. */ this.animateInterval = setInterval(function() { thiz.animationFrame(); }, MimicWidget.ANIMATE_PERIOD); }; MimicWidget.prototype.consume = function(data) { var i, l, peaks = [], level, range, topLevel = this.numberLevels - 1; /* We need to find a list of peaks for each of the levels. */ for (l = 1; l <= this.numberLevels; l++) { if (!$.isArray(data["disp-graph-" + l])) continue; /* To find peaks we are searching for the values where the preceding value is * not larger than the subsequent value. */ level = [ ]; for (i = data["disp-graph-" + l].length - 2; i > 1; i--) { if (data["disp-graph-" + l][i] > data["disp-graph-" + l][i + 1] && data["disp-graph-" + l][i] >= data["disp-graph-" + l][i - 1]) { level.push(i); /* We only require a maximum of 5 peaks. */ if (level.length == 5) break; } } /* If we don't have the requiste number of peaks, don't update data. */ while (level.length < 5) return; peaks.push(level); /* Amplitude is a peak value. The amplitude we are using will the median * of the last 3 peaks. */ this.amp[l] = this.medianFilter([ data["disp-graph-" + l][level[0]], data["disp-graph-" + l][level[1]], data["disp-graph-" + l][level[2]] ]); /* Without a distinct signal, the model has an unrepresentative wiggle, * so we small amplitudes will be thresholded to 0. */ if (this.amp[l] < 2) this.amp[l] = 0; } /* Amplitude for the base is fixed at 0.7 mm but only applies if the motor * is active. */ this.amp[0] = data['motor-on'] ? this.model.baseDisp : 0; /* Angular frequency is derived by the periodicity of peaks. */ range = this.medianFilter([ peaks[topLevel][0] - peaks[topLevel][1], peaks[topLevel][1] - peaks[topLevel][2], peaks[topLevel][2] - peaks[topLevel][3], peaks[topLevel][3] - peaks[topLevel][4] ]); this.w = isFinite(i = 2 * Math.PI * 1 / (this.period / 1000 * range)) != Number.Infinity ? i : 0; /* Phase if determined based on the difference in peaks between the top * level and lower levels. */ for (l = 2; l < this.numberLevels - 1; l++) { this.o[l] = 2 * Math.PI * this.medianFilter([ peaks[l - 1][0] - peaks[topLevel][0], peaks[l - 1][1] - peaks[topLevel][1], peaks[l - 1][2] - peaks[topLevel][2], peaks[l - 1][3] - peaks[topLevel][3] ]) / range; } /** Coil states. */ if (this.is3DOF) { /* The 3DOF is either on or off. */ for (i = 0; i < this.coils.length; i++) this.coils[i] = data['coils-on'] ? 100 : 0; } else { this.coils[0] = data['coils-1-on'] ? data['coils-1-power'] : 0; this.coils[1] = data['coils-2-on'] ? data['coils-2-power'] : 0; } /* Motor details. */ this.motor = data['motor-on'] ? data['motor-speed'] : 0; }; /** * Runs a median filter on the algorithm. */ MimicWidget.prototype.medianFilter = function(data) { data = data.sort(function(a, b) { return a - b; }); return data[Math.round(data.length / 2)]; }; MimicWidget.prototype.animationFrame = function() { var disp = [], i; this.fr++; for (i = 1; i <= this.numberLevels; i++) { disp[i - 1] = this.amp[i] * Math.sin(this.w * MimicWidget.ANIMATE_PERIOD / 1000 * this.fr + this.o[i]); } this.drawFrame(disp, this.motor > 0 ? (this.w * MimicWidget.ANIMATE_PERIOD / 1000 * this.fr) : 0); }; /** * Animates the mimic. * * @param disp displacements of each level in mm * @param motor motor rotation */ MimicWidget.prototype.drawFrame = function(disp, motor) { /* Store the current transformation matrix. */ this.ctx.save(); /* Use the identity matrix while clearing the canvas to fix I.E not clearing. */ this.ctx.setTransform(1, 0, 0, 1, 0, 0); this.ctx.clearRect(0, 0, this.width, this.height); /* Restore the transform. */ this.ctx.restore(); this.drawTrackCarriageMotor(disp[0], motor); var l, xVert = [], yVert = []; /* Levels. */ for (l = 0; l < this.numberLevels; l++) { xVert.push(this.cx - this.px(this.model.levelWidth / 2 + disp[l])); yVert.push(this.height - this.px(this.model.trackHeight + this.model.carHeight) - this.px(this.model.levelHeight * (l + 1)) - this.px(this.model.wallHeight * l)); /* Coil. */ if (l > 0) this.drawCoil(yVert[l] + this.px(this.model.levelHeight / 2), this.coils[l - 1]); /* Mass. */ this.drawLevel(xVert[l], yVert[l], l); } /* Arm vertices. */ for (l = 0; l < xVert.length - 1; l++) { this.drawVertex(xVert[l], yVert[l], xVert[l + 1], yVert[l + 1] + this.px(this.model.levelHeight)); this.drawVertex(xVert[l] + this.px(this.model.levelWidth), yVert[l], xVert[l + 1] + this.px(this.model.levelWidth), yVert[l + 1] + this.px(this.model.levelHeight)); } this.drawGrid(); }; /** The widget of the coil box in mm. */ MimicWidget.COIL_BOX_WIDTH = 26; /** * Draws a coil. * * @param y the vertical position of coil * @param pw coil power */ MimicWidget.prototype.drawCoil = function(y, pw) { var gx = this.width - this.px(20), gy; this.ctx.strokeStyle = "#888888"; this.ctx.lineWidth = 1; this.ctx.beginPath(); this.ctx.moveTo(this.cx, y); this.ctx.lineTo(gx, y); this.ctx.moveTo(gx, y - this.px(this.model.levelHeight) / 2); this.ctx.lineTo(gx, y + this.px(this.model.levelHeight / 2)); for (gy = y - this.px(this.model.levelHeight) / 2; gy <= y + this.px(this.model.levelHeight) / 2; gy += this.px(this.model.levelHeight) / 4) { this.ctx.moveTo(gx, gy); this.ctx.lineTo(this.width, gy + this.px(5)); } this.ctx.stroke(); this.ctx.fillStyle = pw === undefined ? "#CCCCCC" : pw > 0 ? "#50C878" : "#ED2939"; this.ctx.fillRect(this.width - this.px(55), y - this.px(MimicWidget.COIL_BOX_WIDTH / 2), this.px(MimicWidget.COIL_BOX_WIDTH), this.px(MimicWidget.COIL_BOX_WIDTH)); this.ctx.strokeRect(this.width - this.px(55), y - this.px(MimicWidget.COIL_BOX_WIDTH / 2), this.px(MimicWidget.COIL_BOX_WIDTH), this.px(MimicWidget.COIL_BOX_WIDTH)); this.ctx.fillStyle = "#000000"; this.ctx.font = this.px(13) + "px sans-serif"; this.ctx.textAlign = "center"; this.ctx.textBaseline = "middle"; this.ctx.fillText("C", this.width - this.px(30) - this.px(MimicWidget.COIL_BOX_WIDTH / 2), y); }; MimicWidget.prototype.drawVertex = function(x0, y0, x1, y1) { this.ctx.strokeStyle = "#333333"; this.ctx.lineWidth = 2; this.ctx.beginPath(); this.ctx.moveTo(x0, y0); this.ctx.lineTo(x1, y1); this.ctx.stroke(); }; /** * Draws a level box from the top left position. * * @param x x coordinate * @param y y coordinate * @param l level number */ MimicWidget.prototype.drawLevel = function(x, y, l) { this.ctx.fillStyle = "#548DD4"; this.ctx.fillRect(x, y, this.px(this.model.levelWidth), this.px(this.model.levelHeight)); this.ctx.strokeStyle = "#333333"; this.ctx.lineWidth = 1.5; this.ctx.strokeRect(x, y, this.px(this.model.levelWidth), this.px(this.model.levelHeight)); if (l > 0) { this.ctx.fillStyle = "#000000"; this.ctx.font = this.px(13) + "px sans-serif"; this.ctx.textAlign = "center"; this.ctx.textBaseline = "middle"; this.ctx.fillText("M" + l, x + this.px(this.model.levelWidth) / 2, y + this.px(this.model.levelHeight / 2)); } }; /** * Draws the track, carriage and motor. * * @param d0 displacement of base level * @param motor motor rotation */ MimicWidget.prototype.drawTrackCarriageMotor = function(d0, motor) { var tx = this.cx - this.px(this.model.trackWidth / 2), ty = this.height - this.px(this.model.trackHeight), mx, my, mr; /* Track. */ this.ctx.fillStyle = "#AAAAAA"; this.ctx.fillRect(tx, ty, this.px(this.model.trackWidth), this.px(this.model.trackHeight)); this.ctx.strokeStyle = "#333333"; this.ctx.lineWidth = 1; this.ctx.strokeRect(tx, ty, this.px(this.model.trackWidth), this.px(this.model.trackHeight)); this.ctx.beginPath(); this.ctx.moveTo(tx, ty + this.px(this.model.trackHeight) / 2 - 1); this.ctx.lineTo(tx + this.px(this.model.trackWidth), ty + this.px(this.model.trackHeight) / 2 - 1); this.ctx.lineWidth = 2; this.ctx.stroke(); /* Carriage. */ this.ctx.fillStyle = "#666666"; this.ctx.fillRect(this.cx - this.px(this.model.levelWidth / 4 + 10) - this.px(d0), ty - this.px(10), this.px(20), this.px(20)); this.ctx.fillRect(this.cx + this.px(this.model.levelWidth / 4 - 10) - this.px(d0), ty - this.px(10), this.px(20), this.px(20)); this.ctx.strokeStyle = "#222222"; this.ctx.strokeRect(this.cx - this.px(this.model.levelWidth / 4 + 10) - this.px(d0), ty - this.px(10), this.px(20), this.px(20)); this.ctx.strokeRect(this.cx + this.px(this.model.levelWidth / 4 - 10) - this.px(d0), ty - this.px(10), this.px(20), this.px(20)); mx = this.px(40); my = this.height - this.px(44); mr = this.px(20); /* Arm. */ this.ctx.beginPath(); this.ctx.moveTo(mx - this.px(8 + d0), my - this.px(15)); this.ctx.lineTo(mx + this.px(8 - d0), my - this.px(15)); this.ctx.lineTo(mx + this.px(8 - d0), my - this.px(5)); this.ctx.lineTo(this.cx, my - this.px(5)); this.ctx.lineTo(this.cx, my + this.px(5)); this.ctx.lineTo(mx + this.px(8 - d0), my + this.px(5)); this.ctx.lineTo(mx + this.px(8 - d0), my + this.px(15)); this.ctx.lineTo(mx - this.px(8 + d0), my + this.px(15)); this.ctx.closePath(); this.ctx.fillStyle = "#AAAAAA"; this.ctx.fill(); this.ctx.clearRect(mx - this.px(2.5 + d0), my - this.px(9), this.px(5), this.px(18)); this.ctx.strokeStyle = "#333333"; this.ctx.stroke(); this.ctx.strokeRect(mx - this.px(2.5 + d0), my - this.px(9), this.px(5), this.px(18)); /* Motor. */ this.ctx.save(); this.ctx.globalCompositeOperation = "destination-over"; /* Couple between the motor and the arm. */ this.ctx.beginPath(); this.ctx.arc(mx, my - this.px(d0), this.px(4), 0, 2 * Math.PI); this.ctx.fillStyle = "#222222"; this.ctx.fill(); this.ctx.beginPath(); this.ctx.arc(mx, my, mr, -Math.PI / 18 + motor, Math.PI / 18 + motor, false); this.ctx.arc(mx, my, mr, Math.PI - Math.PI / 18 + motor, Math.PI + Math.PI / 18 + motor, false); this.ctx.closePath(); this.ctx.strokeStyle = "#333333"; this.ctx.stroke(); this.ctx.fillStyle = "#999999"; this.ctx.fill(); this.ctx.beginPath(); this.ctx.arc(mx, my, mr, 0, 2 * Math.PI); this.ctx.fillStyle = "#666666"; this.ctx.fill(); this.ctx.strokeStyle = "#333333"; this.ctx.stroke(); this.ctx.restore(); }; MimicWidget.GRID_WIDTH = 50; /** * Draws a grid. */ MimicWidget.prototype.drawGrid = function() { var d, dt = this.px(MimicWidget.GRID_WIDTH); this.ctx.save(); this.ctx.globalCompositeOperation = "destination-over"; /* Grid lines. */ this.ctx.beginPath(); for (d = this.cx - dt; d > 0; d -= dt) this.stippleLine(d, 0, d, this.height); for (d = this.cx + dt; d < this.width - dt; d+= dt) this.stippleLine(d, 0, d, this.height); for (d = dt; d < this.height; d += dt) this.stippleLine(0, d, this.width, d); this.ctx.strokeStyle = "#AAAAAA"; this.ctx.lineWidth = 1; this.ctx.stroke(); /* Units. */ this.ctx.beginPath(); this.ctx.moveTo(this.px(22), 0); this.ctx.lineTo(this.px(22), dt); this.ctx.moveTo(this.px(10), this.px(10)); this.ctx.lineTo(dt + this.px(10), this.px(10)); this.ctx.strokeStyle = "#555555"; this.ctx.stroke(); this.ctx.beginPath(); this.ctx.moveTo(this.px(22), 0); this.ctx.lineTo(this.px(22 + 2.5), this.px(5)); this.ctx.lineTo(this.px(22 - 2.5), this.px(5)); this.ctx.closePath(); this.ctx.fillStyle = "#555555"; this.ctx.fill(); this.ctx.beginPath(); this.ctx.moveTo(this.px(22), dt); this.ctx.lineTo(this.px(22 + 2.5), dt - this.px(5)); this.ctx.lineTo(this.px(22 - 2.5), dt - this.px(5)); this.ctx.closePath(); this.ctx.fill(); this.ctx.beginPath(); this.ctx.moveTo(this.px(10), this.px(10)); this.ctx.lineTo(this.px(15), this.px(7.5)); this.ctx.lineTo(this.px(15), this.px(12.5)); this.ctx.closePath(); this.ctx.fill(); this.ctx.beginPath(); this.ctx.moveTo(this.px(10) + dt, this.px(10)); this.ctx.lineTo(this.px(5) + dt, this.px(7.5)); this.ctx.lineTo(this.px(5) + dt, this.px(12.5)); this.ctx.closePath(); this.ctx.fill(); this.ctx.font = this.px(10) + "px sans-serif"; this.ctx.fillText(MimicWidget.GRID_WIDTH + "mm", this.px(40), this.px(20)); /* Center line. */ this.ctx.beginPath(); this.ctx.moveTo(this.cx, 0); this.ctx.lineTo(this.cx, this.height); this.ctx.moveTo(0, this.height / 2); this.ctx.strokeStyle = "#555555"; this.ctx.lineWidth = 1.5; this.ctx.stroke(); this.ctx.restore(); }; MimicWidget.STIPPLE_WIDTH = 10; /** * Draws a stippled line. * * @param x0 begin x coordinate * @param y0 begin y coordinate * @param x1 end x coordinate * @param y1 end y coordinate */ MimicWidget.prototype.stippleLine = function(x0, y0, x1, y1) { var p; if (x0 == x1) // Horizontal line { p = y0 - MimicWidget.STIPPLE_WIDTH; while (p < y1) { this.ctx.moveTo(x0, p += MimicWidget.STIPPLE_WIDTH); this.ctx.lineTo(x0, p += MimicWidget.STIPPLE_WIDTH); } } else if (y0 == y1) // Vertical line { p = x0 - MimicWidget.STIPPLE_WIDTH; while (p < x1) { this.ctx.moveTo(p += MimicWidget.STIPPLE_WIDTH, y0); this.ctx.lineTo(p += MimicWidget.STIPPLE_WIDTH, y0); } } else // Diagonal { throw "Diagonal lines not implemented."; } }; /** * Converts a pixel dimension to a millimetre dimension. * * @param px pixel dimension * @return millimetre dimension */ MimicWidget.prototype.mm = function(px) { return px * this.mmPerPx; }; /** * Converts a millimetre dimension to a pixel dimension. * * @param mm millimetre dimension * @return pixel dimension */ MimicWidget.prototype.px = function(mm) { return mm / this.mmPerPx; }; MimicWidget.prototype.resized = function(width, height) { if (this.animateInterval) { clearInterval(this.animateInterval); this.animateInterval = undefined; } height -= 63; this.$widget.find("canvas").attr({ width: width, height: height }); this.ctx.fillStyle = "#FAFAFA"; this.ctx.fillRect(0, 0, width, height); }; MimicWidget.prototype.resizeStopped = function(width, height) { this.mmPerPx *= this.boxWidth / width; this.width = this.px(this.model.levelWidth + this.model.maxDisp * 2) + this.px(100); this.cx = this.width / 2; this.height = this.px(this.model.levelHeight * (this.is3DOF ? 4 : 3) + this.model.wallHeight * (this.is3DOF ? 3: 2) + this.model.trackHeight + this.model.carHeight); this.boxWidth = width; this.$widget.find("canvas").attr({ width: this.width, height: this.height }); this.$widget.css("height", "auto"); if (!this.animateInterval) { var thiz = this; this.animateInterval = setInterval(function() { thiz.animationFrame(); }, MimicWidget.ANIMATE_PERIOD); } }; MimicWidget.prototype.destroy = function() { clearInterval(this.animateInterval); this.animateInterval = undefined; Widget.prototype.destroy.call(this); }; /** * Displays an FFT of one or more signals. * * @constructor * @param {string} id graph identifier * @param {object} config configuration object * @config {object} [fields] map of graphed data fields with field => label * @config {object} [colors] map of graph trace colors with field => color (optional) * @config {boolean} [autoScale] whether to autoscale the graph dependant (default off) * @config {integer} [minValue] minimum value that is graphed, implies not autoscaling (default 0) * @config {integer} [maxValue] maximum value that is graphed, implies not autoscaling (default 100) * @config {integer} [duration] number of seconds this graph displays (default 60) * @config {integer} [period] period betweeen samples in milliseconds (default 100) * @config {string} [xLabel] X axis label (default (Time (s)) * @config {String} [yLabel] Y axis label (optional) * @config {boolean} [traceLabels] whether to show trace labels (default true) * @config {boolean} [fieldCtl] whether data field displays can be toggled (default false) * @config {boolean} [autoCtl] whether autoscaling enable control is shown (default false) * @config {boolean} [durationCtl] whether duration control slider is displayed * @config {integer} [vertScales] number of vertical scales (default 5) * @config {integer} [horizScales] number of horizontal scales (default 8) */ function FFTGraph(id, config) { Graph.call(this, id, config); } FFTGraph.prototype = new Graph; FFTGraph.prototype.consume = function(data) { /* Not stopping updates when controls are showing , causes ugly blinking. */ if (this.showingControls) return; var i = 0; if (this.startTime == undefined) { this.startTime = data.start; this._updateIndependentScale(); } this.latestTime = data.time; for (i in this.dataFields) { if (data[i] === undefined) continue; this.dataFields[i].values = this.fftTransform( this._pruneSample(data[i], this.config.duration * 1000 / this.config.period)); this.dataFields[i].seconds = this.dataFields[i].values.length * this.config.period / 1000; this.displayedDuration = data.duration; } if (this.config.autoScale) { /* Determine graph scaling for this frame and label it. */ this._adjustScaling(); this._updateDependantScale(); } this._drawFrame(); }; FFTGraph.prototype._updateIndependentScale = function() { var i, $d = this.$widget.find(".graph-bottom-scale-0"), t; for (i = 0; i <= this.config.horizScales; i++) { t = 1000 * i / this.config.period / this.config.horizScales / 20; $d.html(Util.zeroPad(t, 1)); $d = $d.next(); } }; /** * Pads the length of the array with 0 until its length is a multiple of 2. * * @param {Array} arr array to pad * @return {Array} padded arary (same as input) */ FFTGraph.prototype.fftTransform = function(sample) { var i, n = sample.length, vals = new Array(n); /* The FFT is computed on complex numbers. */ for (i = 0; i < n; i++) { vals[i] = new Complex(sample[i], 0); } /* The Cooley-Turkey algorithm operates on samples whose length is a * multiple of 2. */ while (((n = vals.length) & (n - 1)) != 0) { vals.push(new Complex(0, 0)); } /** Apply the FFT transform. */ vals = fft(vals); /* We only care about the first 10 Hz. */ vals.splice(n / 20 - 1, n - n / 20); /* The plot is of the absolute values of the sample, then scaled . */ for (i = 0; i < vals.length; i++) { vals[i] = vals[i].abs() * 2 / n; } return vals; };
jeking3/web-interface
public/uts/shaketable/shaketable.js
JavaScript
bsd-3-clause
37,584
import { select } from '@storybook/addon-knobs'; import readme from '@ovh-ux/ui-kit.button/README.md'; const state = { label: 'State', options: { Normal: '', Disabled: 'disabled', }, default: '', }; export default { title: 'Design System/Components/Buttons/Native/Primary', parameters: { notes: readme, options: { showPanel: true, }, }, }; export const Default = () => ` <button class="oui-button oui-button_primary" ${select(state.label, state.options, state.default)}> Call to action </button> <button class="oui-button oui-button_primary oui-button_icon-left" ${select( state.label, state.options, state.default, )}> <span class="oui-icon oui-icon-folder" aria-hidden="true"></span> Call to action </button> <button class="oui-button oui-button_primary oui-button_icon-right" ${select( state.label, state.options, state.default, )}> Call to action <span class="oui-icon oui-icon-folder" aria-hidden="true"></span> </button>`; export const Large = () => ` <button class="oui-button oui-button_l oui-button_primary" ${select( state.label, state.options, state.default, )}> Call to action </button> <button class="oui-button oui-button_l oui-button_primary oui-button_icon-left" ${select( state.label, state.options, state.default, )}> <span class="oui-icon oui-icon-folder" aria-hidden="true"></span> Call to action </button> <button class="oui-button oui-button_l oui-button_primary oui-button_icon-right" ${select( state.label, state.options, state.default, )}> Call to action <span class="oui-icon oui-icon-folder" aria-hidden="true"></span> </button>`; export const Small = () => ` <button class="oui-button oui-button_s oui-button_primary" ${select( state.label, state.options, state.default, )}> OK </button> <button class="oui-button oui-button_s oui-button_primary" ${select( state.label, state.options, state.default, )}> <span class="oui-icon oui-icon-folder"></span> </button>`; export const Block = () => ` <button class="oui-button oui-button_block oui-button_primary" ${select( state.label, state.options, state.default, )}> Call to action </button> <button class="oui-button oui-button_block oui-button_primary oui-button_icon-left" ${select( state.label, state.options, state.default, )}> <span class="oui-icon oui-icon-folder"></span> Call to action </button> <button class="oui-button oui-button_block oui-button_primary oui-button_icon-right" ${select( state.label, state.options, state.default, )}> Call to action <span class="oui-icon oui-icon-folder"></span> </button>`; export const Group = () => ` <div class="oui-button-group"> <button class="oui-button oui-button_primary">Lorem</button> <button class="oui-button oui-button_primary">Ipsum</button> <button class="oui-button oui-button_primary">Dolor</button> <button class="oui-button oui-button_primary">Sit</button> <button class="oui-button oui-button_primary">Amet</button> </div>`;
ovh-ux/ovh-ui-kit
packages/apps/workshop/stories/design-system/components/button-native-primary.stories.js
JavaScript
bsd-3-clause
3,190
/// <reference path="../../server.d.ts" /> 'use strict'; module.exports = { ip: process.env.IP || undefined, server: { url: 'http://www.<%= appname %>.com' }<% if (filters.backend === 'mongo') { %>, mongo: { uri: 'mongodb://localhost/<%= slugName %>' }<% } %>, facebook: { clientID: '975041909195011', clientSecret: '6bcf8b64f80546cfd799a4f467cd1a20', callbackURL: '/auth/facebook/callback' } };
NovaeWorkshop/Nova
app/templates/server/config/environment/production.js
JavaScript
bsd-3-clause
465
export const SET_SEARCHED_POKEMONS = "SET_SEARCHED_POKEMONS"; export const SET_SEARCHED_QUERY = "SET_SEARCHED_QUERY"; export const SET_SEARCHED_TYPE = "SET_SEARCHED_TYPE"; export const RESET_SEARCHED_PARAMS = "RESET_SEARCHED_PARAMS"; export const RESET_SEARCHED_POKEMONS = "RESET_SEARCHED_POKEMONS"; export const REMOVE_SEARCHED_PARAMS_TYPE = "REMOVE_SEARCHED_PARAMS_TYPE";
esgiprojetninja/ninjaPokedex
public/js/lib/pokedex/actions/pokeSearchTypes.js
JavaScript
bsd-3-clause
374
describe("go.components.actions", function() { var actions = go.components.actions; var Model = go.components.models.Model; var testHelpers = go.testHelpers, assertRequest = testHelpers.rpc.assertRequest, response = testHelpers.rpc.response, noElExists = testHelpers.noElExists, oneElExists = testHelpers.oneElExists; describe("PopoverNotifierView", function() { var ActionView = actions.ActionView, PopoverNotifierView = actions.PopoverNotifierView; var action, notifier; beforeEach(function() { action = new ActionView({name: 'Crimp'}); action.$el.appendTo($('body')); notifier = new PopoverNotifierView({ delay: 0, busyWait: 0, action: action, bootstrap: { container: 'body', animation: false } }); sinon.stub( JST, 'components_notifiers_popover_busy', function() { return 'busy'; }); }); afterEach(function() { JST.components_notifiers_popover_busy.restore(); action.remove(); notifier.remove(); }); describe("when the action is invoked", function() { it("should show a notification", function() { assert(noElExists('.popover')); assert.equal(notifier.$el.text(), ''); action.trigger('invoke'); assert(oneElExists('.popover')); assert.equal(notifier.$el.text(), 'busy'); }); it("set the appropriate class name on the popover element", function() { var $popover = notifier.popover.tip(); assert(!$popover.hasClass('notifier')); assert(!$popover.hasClass('success')); assert(!$popover.hasClass('error')); assert(!$popover.hasClass('info')); action.trigger('invoke'); assert(!$popover.hasClass('success')); assert(!$popover.hasClass('error')); assert($popover.hasClass('notifier')); assert($popover.hasClass('info')); }); }); describe("when the action is successful", function() { beforeEach(function() { action.trigger('invoke'); }); it("should show a notification", function() { action.trigger('success'); assert.include(notifier.$el.text(), 'Crimp successful.'); }); it("set the appropriate class name on the popover element", function() { var $popover = notifier.popover.tip(); assert(!$popover.hasClass('success')); assert(!$popover.hasClass('error')); assert($popover.hasClass('notifier')); assert($popover.hasClass('info')); action.trigger('success'); assert(!$popover.hasClass('error')); assert(!$popover.hasClass('info')); assert($popover.hasClass('notifier')); assert($popover.hasClass('success')); }); }); describe("when the action is unsuccessful", function() { beforeEach(function() { action.trigger('invoke'); }); it("should show a notification", function() { action.trigger('error'); assert.include(notifier.$el.text(), 'Crimp failed.'); }); it("set the appropriate class name on the popover element", function() { var $popover = notifier.popover.tip(); assert(!$popover.hasClass('success')); assert(!$popover.hasClass('error')); assert($popover.hasClass('notifier')); assert($popover.hasClass('info')); action.trigger('error'); assert(!$popover.hasClass('success')); assert(!$popover.hasClass('info')); assert($popover.hasClass('notifier')); assert($popover.hasClass('error')); }); }); describe("when '.close' is clicked", function() { beforeEach(function() { action.trigger('success'); }); it("should close the popover", function() { assert(oneElExists('.popover')); notifier.$('.close').click(); assert(noElExists('.popover')); }); }); }); describe("ActionView", function() { var ActionView = actions.ActionView; var ToyActionView = ActionView.extend({ invoke: function() { this.trigger('invoke'); } }); var action; beforeEach(function() { action = new ToyActionView(); }); describe("when it is clicked", function() { it("should invoke its own action", function(done) { action.on('invoke', function() { done(); }); action.$el.click(); }); }); }); describe("SaveActionView", function() { var SaveActionView = actions.SaveActionView; var ToyModel = Model.extend({ url: '/test', methods: { create: {method: 's', params: ['a', 'b']} } }); var action; beforeEach(function() { action = new SaveActionView({ model: new ToyModel({a: 'foo', b: 'bar'}) }); }); describe(".invoke", function() { var server; beforeEach(function() { server = sinon.fakeServer.create(); }); afterEach(function() { server.restore(); }); it("should emit an 'invoke' event", function(done) { action.on('invoke', function() { done(); }); action.invoke(); }); it("should send its model's data to the server", function(done) { server.respondWith(function(req) { assertRequest(req, '/test', 's', ['foo', 'bar']); done(); }); action.invoke(); server.respond(); }); describe("when the request is successful", function() { it("should emit a 'success' event", function(done) { action.on('success', function() { done(); }); server.respondWith(response()); action.invoke(); server.respond(); }); }); describe("when the request is not successful", function() { it("should emit a 'failure' event", function(done) { action.on('error', function() { done(); }); server.respondWith([400, {}, '']); action.invoke(); server.respond(); }); }); }); }); describe("ResetActionView", function() { var ResetActionView = actions.ResetActionView; var action; beforeEach(function() { action = new ResetActionView({ model: new Model({a: 'foo', b: 'bar'}) }); }); describe(".invoke", function() { it("should emit an 'invoke' event", function(done) { action.on('invoke', function() { done(); }); action.invoke(); }); it("should reset its model to its initial state", function(done) { action.model.set('a', 'larp'); assert.deepEqual(action.model.toJSON(), {a: 'larp', b: 'bar'}); action.invoke(); action.once('success', function() { assert.deepEqual(action.model.toJSON(), {a: 'foo', b: 'bar'}); done(); }); }); }); }); });
praekelt/vumi-go
go/base/static/js/test/components/actions.test.js
JavaScript
bsd-3-clause
6,932
function showMessage(object, message){ if(message == null) message=""; object.text(message); } function getEmptyResultHtml(){ flushEmptyResultHtml(); var html = '<div class="emptyMsg text-center" class="text-center">列表为空</div>'; return html; } function flushEmptyResultHtml(){ $(".emptyMsg").remove(); } //一波分页搜索函数 function nextPage(){ var allPages = parseInt($("#allPages").text()); if(adminUserSelect["curPage"]+1 <= allPages){ adminUserSelect["curPage"]++; changeTable(); $("#curPage").text(adminUserSelect["curPage"]); } } function prevPage(){ if(adminUserSelect["curPage"]-1 >= 1){ adminUserSelect["curPage"]--; changeTable(); $("#curPage").text(adminUserSelect["curPage"]); } } function changeState(){ var state = parseInt($("#state-select").val()); adminUserSelect["state"] = state; adminUserSelect["curPage"] = 1; adminUserSelect["pageCount"] = 10; changeTable(); $("#curPage").text("1"); } function searchTextChange(){ var text = $("#searchText").val(); adminUserSelect["searchText"] = text; adminUserSelect["curPage"] = 1; adminUserSelect["pageCount"] = 10; changeTable(); $("#curPage").text("1"); } function displayLoading(switcher){ if(switcher==true){ $("#loading").show(); }else{ $("#loading").hide(); } } //操作checkbox函数 function checkAllBoxes(){ var grouper = $("#check-all")[0].checked; $("tbody :checkbox").each(function(){ $(this)[0].checked = grouper; }); } //清空checkbox function flushAllBoxes(checked){ $('tbody :checkbox').each(function(){ $(this)[0].checked = checked; }); } function getSelectedIdArray(){ var ids = new Array(0); $("tbody :checkbox").each(function(){ if($(this)[0].checked == true) ids.push(($(this)[0].id).split("-")[1]); }); return ids; } function getSellerLogoLink(){ }
liujiasheng/kuaidishu
public/js/adminCommon.js
JavaScript
bsd-3-clause
1,995
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; var PropTypes; var checkPropTypes; var React; var ReactDOM; var Component; var MyComponent; function resetWarningCache() { jest.resetModules(); checkPropTypes = require('prop-types/checkPropTypes'); PropTypes = require('ReactPropTypes'); } function getPropTypeWarningMessage(propTypes, object, componentName) { if (!console.error.calls) { spyOn(console, 'error'); } else { console.error.calls.reset(); } resetWarningCache(); checkPropTypes(propTypes, object, 'prop', 'testComponent'); const callCount = console.error.calls.count(); if (callCount > 1) { throw new Error('Too many warnings.'); } const message = console.error.calls.argsFor(0)[0] || null; console.error.calls.reset(); return message; } function typeCheckFail(declaration, value, expectedMessage) { const propTypes = { testProp: declaration, }; const props = { testProp: value, }; const message = getPropTypeWarningMessage(propTypes, props, 'testComponent'); expect(message).toContain(expectedMessage); } function typeCheckFailRequiredValues(declaration) { var specifiedButIsNullMsg = 'The prop `testProp` is marked as required in ' + '`testComponent`, but its value is `null`.'; var unspecifiedMsg = 'The prop `testProp` is marked as required in ' + '`testComponent`, but its value is \`undefined\`.'; var propTypes = {testProp: declaration}; // Required prop is null var message1 = getPropTypeWarningMessage( propTypes, {testProp: null}, 'testComponent', ); expect(message1).toContain(specifiedButIsNullMsg); // Required prop is undefined var message2 = getPropTypeWarningMessage( propTypes, {testProp: undefined}, 'testComponent', ); expect(message2).toContain(unspecifiedMsg); // Required prop is not a member of props object var message3 = getPropTypeWarningMessage(propTypes, {}, 'testComponent'); expect(message3).toContain(unspecifiedMsg); } function typeCheckPass(declaration, value) { const propTypes = { testProp: declaration, }; const props = { testProp: value, }; const message = getPropTypeWarningMessage(propTypes, props, 'testComponent'); expect(message).toBe(null); } function expectThrowInDevelopment(declaration, value) { var props = {testProp: value}; var propName = 'testProp' + Math.random().toString(); var componentName = 'testComponent' + Math.random().toString(); var message; try { declaration(props, propName, componentName, 'prop'); } catch (e) { message = e.message; } expect(message).toContain( 'Calling PropTypes validators directly is not supported', ); console.error.calls.reset(); } describe('ReactPropTypes', () => { beforeEach(() => { React = require('react'); ReactDOM = require('react-dom'); resetWarningCache(); }); describe('checkPropTypes', () => { it('does not return a value from a validator', () => { spyOn(console, 'error'); const propTypes = { foo(props, propName, componentName) { return new Error('some error'); }, }; const props = {foo: 'foo'}; const returnValue = checkPropTypes( propTypes, props, 'prop', 'testComponent', null, ); expect(console.error.calls.argsFor(0)[0]).toContain('some error'); expect(returnValue).toBe(undefined); }); it('does not throw if validator throws', () => { spyOn(console, 'error'); const propTypes = { foo(props, propName, componentName) { throw new Error('some error'); }, }; const props = {foo: 'foo'}; const returnValue = checkPropTypes( propTypes, props, 'prop', 'testComponent', null, ); expect(console.error.calls.argsFor(0)[0]).toContain('some error'); expect(returnValue).toBe(undefined); }); }); describe('Primitive Types', () => { it('should warn for invalid strings', () => { typeCheckFail( PropTypes.string, [], 'Invalid prop `testProp` of type `array` supplied to ' + '`testComponent`, expected `string`.', ); typeCheckFail( PropTypes.string, false, 'Invalid prop `testProp` of type `boolean` supplied to ' + '`testComponent`, expected `string`.', ); typeCheckFail( PropTypes.string, 0, 'Invalid prop `testProp` of type `number` supplied to ' + '`testComponent`, expected `string`.', ); typeCheckFail( PropTypes.string, {}, 'Invalid prop `testProp` of type `object` supplied to ' + '`testComponent`, expected `string`.', ); typeCheckFail( PropTypes.string, Symbol(), 'Invalid prop `testProp` of type `symbol` supplied to ' + '`testComponent`, expected `string`.', ); }); it('should fail date and regexp correctly', () => { typeCheckFail( PropTypes.string, new Date(), 'Invalid prop `testProp` of type `date` supplied to ' + '`testComponent`, expected `string`.', ); typeCheckFail( PropTypes.string, /please/, 'Invalid prop `testProp` of type `regexp` supplied to ' + '`testComponent`, expected `string`.', ); }); it('should not warn for valid values', () => { typeCheckPass(PropTypes.array, []); typeCheckPass(PropTypes.bool, false); typeCheckPass(PropTypes.func, function() {}); typeCheckPass(PropTypes.number, 0); typeCheckPass(PropTypes.string, ''); typeCheckPass(PropTypes.object, {}); typeCheckPass(PropTypes.object, new Date()); typeCheckPass(PropTypes.object, /please/); typeCheckPass(PropTypes.symbol, Symbol()); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass(PropTypes.string, null); typeCheckPass(PropTypes.string, undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues(PropTypes.string.isRequired); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.array, /please/); expectThrowInDevelopment(PropTypes.array, []); expectThrowInDevelopment(PropTypes.array.isRequired, /please/); expectThrowInDevelopment(PropTypes.array.isRequired, []); expectThrowInDevelopment(PropTypes.array.isRequired, null); expectThrowInDevelopment(PropTypes.array.isRequired, undefined); expectThrowInDevelopment(PropTypes.bool, []); expectThrowInDevelopment(PropTypes.bool, true); expectThrowInDevelopment(PropTypes.bool.isRequired, []); expectThrowInDevelopment(PropTypes.bool.isRequired, true); expectThrowInDevelopment(PropTypes.bool.isRequired, null); expectThrowInDevelopment(PropTypes.bool.isRequired, undefined); expectThrowInDevelopment(PropTypes.func, false); expectThrowInDevelopment(PropTypes.func, function() {}); expectThrowInDevelopment(PropTypes.func.isRequired, false); expectThrowInDevelopment(PropTypes.func.isRequired, function() {}); expectThrowInDevelopment(PropTypes.func.isRequired, null); expectThrowInDevelopment(PropTypes.func.isRequired, undefined); expectThrowInDevelopment(PropTypes.number, function() {}); expectThrowInDevelopment(PropTypes.number, 42); expectThrowInDevelopment(PropTypes.number.isRequired, function() {}); expectThrowInDevelopment(PropTypes.number.isRequired, 42); expectThrowInDevelopment(PropTypes.number.isRequired, null); expectThrowInDevelopment(PropTypes.number.isRequired, undefined); expectThrowInDevelopment(PropTypes.string, 0); expectThrowInDevelopment(PropTypes.string, 'foo'); expectThrowInDevelopment(PropTypes.string.isRequired, 0); expectThrowInDevelopment(PropTypes.string.isRequired, 'foo'); expectThrowInDevelopment(PropTypes.string.isRequired, null); expectThrowInDevelopment(PropTypes.string.isRequired, undefined); expectThrowInDevelopment(PropTypes.symbol, 0); expectThrowInDevelopment(PropTypes.symbol, Symbol('Foo')); expectThrowInDevelopment(PropTypes.symbol.isRequired, 0); expectThrowInDevelopment(PropTypes.symbol.isRequired, Symbol('Foo')); expectThrowInDevelopment(PropTypes.symbol.isRequired, null); expectThrowInDevelopment(PropTypes.symbol.isRequired, undefined); expectThrowInDevelopment(PropTypes.object, ''); expectThrowInDevelopment(PropTypes.object, {foo: 'bar'}); expectThrowInDevelopment(PropTypes.object.isRequired, ''); expectThrowInDevelopment(PropTypes.object.isRequired, {foo: 'bar'}); expectThrowInDevelopment(PropTypes.object.isRequired, null); expectThrowInDevelopment(PropTypes.object.isRequired, undefined); }); }); describe('Any type', () => { it('should should accept any value', () => { typeCheckPass(PropTypes.any, 0); typeCheckPass(PropTypes.any, 'str'); typeCheckPass(PropTypes.any, []); typeCheckPass(PropTypes.any, Symbol()); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass(PropTypes.any, null); typeCheckPass(PropTypes.any, undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues(PropTypes.any.isRequired); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.any, null); expectThrowInDevelopment(PropTypes.any.isRequired, null); expectThrowInDevelopment(PropTypes.any.isRequired, undefined); }); }); describe('ArrayOf Type', () => { it('should fail for invalid argument', () => { typeCheckFail( PropTypes.arrayOf({foo: PropTypes.string}), {foo: 'bar'}, 'Property `testProp` of component `testComponent` has invalid PropType notation inside arrayOf.', ); }); it('should support the arrayOf propTypes', () => { typeCheckPass(PropTypes.arrayOf(PropTypes.number), [1, 2, 3]); typeCheckPass(PropTypes.arrayOf(PropTypes.string), ['a', 'b', 'c']); typeCheckPass(PropTypes.arrayOf(PropTypes.oneOf(['a', 'b'])), ['a', 'b']); typeCheckPass(PropTypes.arrayOf(PropTypes.symbol), [Symbol(), Symbol()]); }); it('should support arrayOf with complex types', () => { typeCheckPass( PropTypes.arrayOf(PropTypes.shape({a: PropTypes.number.isRequired})), [{a: 1}, {a: 2}], ); function Thing() {} typeCheckPass(PropTypes.arrayOf(PropTypes.instanceOf(Thing)), [ new Thing(), new Thing(), ]); }); it('should warn with invalid items in the array', () => { typeCheckFail( PropTypes.arrayOf(PropTypes.number), [1, 2, 'b'], 'Invalid prop `testProp[2]` of type `string` supplied to ' + '`testComponent`, expected `number`.', ); }); it('should warn with invalid complex types', () => { function Thing() {} var name = Thing.name || '<<anonymous>>'; typeCheckFail( PropTypes.arrayOf(PropTypes.instanceOf(Thing)), [new Thing(), 'xyz'], 'Invalid prop `testProp[1]` of type `String` supplied to ' + '`testComponent`, expected instance of `' + name + '`.', ); }); it('should warn when passed something other than an array', () => { typeCheckFail( PropTypes.arrayOf(PropTypes.number), {'0': 'maybe-array', length: 1}, 'Invalid prop `testProp` of type `object` supplied to ' + '`testComponent`, expected an array.', ); typeCheckFail( PropTypes.arrayOf(PropTypes.number), 123, 'Invalid prop `testProp` of type `number` supplied to ' + '`testComponent`, expected an array.', ); typeCheckFail( PropTypes.arrayOf(PropTypes.number), 'string', 'Invalid prop `testProp` of type `string` supplied to ' + '`testComponent`, expected an array.', ); }); it('should not warn when passing an empty array', () => { typeCheckPass(PropTypes.arrayOf(PropTypes.number), []); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass(PropTypes.arrayOf(PropTypes.number), null); typeCheckPass(PropTypes.arrayOf(PropTypes.number), undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues( PropTypes.arrayOf(PropTypes.number).isRequired, ); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.arrayOf({foo: PropTypes.string}), { foo: 'bar', }); expectThrowInDevelopment(PropTypes.arrayOf(PropTypes.number), [ 1, 2, 'b', ]); expectThrowInDevelopment(PropTypes.arrayOf(PropTypes.number), { '0': 'maybe-array', length: 1, }); expectThrowInDevelopment( PropTypes.arrayOf(PropTypes.number).isRequired, null, ); expectThrowInDevelopment( PropTypes.arrayOf(PropTypes.number).isRequired, undefined, ); }); }); describe('Component Type', () => { beforeEach(() => { Component = class extends React.Component { static propTypes = { label: PropTypes.element.isRequired, }; render() { return <div>{this.props.label}</div>; } }; }); it('should support components', () => { typeCheckPass(PropTypes.element, <div />); }); it('should not support multiple components or scalar values', () => { typeCheckFail( PropTypes.element, [<div />, <div />], 'Invalid prop `testProp` of type `array` supplied to `testComponent`, ' + 'expected a single ReactElement.', ); typeCheckFail( PropTypes.element, 123, 'Invalid prop `testProp` of type `number` supplied to `testComponent`, ' + 'expected a single ReactElement.', ); typeCheckFail( PropTypes.element, 'foo', 'Invalid prop `testProp` of type `string` supplied to `testComponent`, ' + 'expected a single ReactElement.', ); typeCheckFail( PropTypes.element, false, 'Invalid prop `testProp` of type `boolean` supplied to `testComponent`, ' + 'expected a single ReactElement.', ); }); it('should be able to define a single child as label', () => { spyOn(console, 'error'); var container = document.createElement('div'); ReactDOM.render(<Component label={<div />} />, container); expectDev(console.error.calls.count()).toBe(0); }); it('should warn when passing no label and isRequired is set', () => { spyOn(console, 'error'); var container = document.createElement('div'); ReactDOM.render(<Component />, container); expectDev(console.error.calls.count()).toBe(1); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass(PropTypes.element, null); typeCheckPass(PropTypes.element, undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues(PropTypes.element.isRequired); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.element, [<div />, <div />]); expectThrowInDevelopment(PropTypes.element, <div />); expectThrowInDevelopment(PropTypes.element, 123); expectThrowInDevelopment(PropTypes.element, 'foo'); expectThrowInDevelopment(PropTypes.element, false); expectThrowInDevelopment(PropTypes.element.isRequired, null); expectThrowInDevelopment(PropTypes.element.isRequired, undefined); }); }); describe('Instance Types', () => { it('should warn for invalid instances', () => { function Person() {} function Cat() {} var personName = Person.name || '<<anonymous>>'; var dateName = Date.name || '<<anonymous>>'; var regExpName = RegExp.name || '<<anonymous>>'; typeCheckFail( PropTypes.instanceOf(Person), false, 'Invalid prop `testProp` of type `Boolean` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.', ); typeCheckFail( PropTypes.instanceOf(Person), {}, 'Invalid prop `testProp` of type `Object` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.', ); typeCheckFail( PropTypes.instanceOf(Person), '', 'Invalid prop `testProp` of type `String` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.', ); typeCheckFail( PropTypes.instanceOf(Date), {}, 'Invalid prop `testProp` of type `Object` supplied to ' + '`testComponent`, expected instance of `' + dateName + '`.', ); typeCheckFail( PropTypes.instanceOf(RegExp), {}, 'Invalid prop `testProp` of type `Object` supplied to ' + '`testComponent`, expected instance of `' + regExpName + '`.', ); typeCheckFail( PropTypes.instanceOf(Person), new Cat(), 'Invalid prop `testProp` of type `Cat` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.', ); typeCheckFail( PropTypes.instanceOf(Person), Object.create(null), 'Invalid prop `testProp` of type `<<anonymous>>` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.', ); }); it('should not warn for valid values', () => { function Person() {} function Engineer() {} Engineer.prototype = new Person(); typeCheckPass(PropTypes.instanceOf(Person), new Person()); typeCheckPass(PropTypes.instanceOf(Person), new Engineer()); typeCheckPass(PropTypes.instanceOf(Date), new Date()); typeCheckPass(PropTypes.instanceOf(RegExp), /please/); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass(PropTypes.instanceOf(String), null); typeCheckPass(PropTypes.instanceOf(String), undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues(PropTypes.instanceOf(String).isRequired); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.instanceOf(Date), {}); expectThrowInDevelopment(PropTypes.instanceOf(Date), new Date()); expectThrowInDevelopment(PropTypes.instanceOf(Date).isRequired, {}); expectThrowInDevelopment( PropTypes.instanceOf(Date).isRequired, new Date(), ); }); }); describe('React Component Types', () => { beforeEach(() => { MyComponent = class extends React.Component { render() { return <div />; } }; }); it('should warn for invalid values', () => { var failMessage = 'Invalid prop `testProp` supplied to ' + '`testComponent`, expected a ReactNode.'; typeCheckFail(PropTypes.node, true, failMessage); typeCheckFail(PropTypes.node, function() {}, failMessage); typeCheckFail(PropTypes.node, {key: function() {}}, failMessage); typeCheckFail(PropTypes.node, {key: <div />}, failMessage); }); it('should not warn for valid values', () => { typeCheckPass(PropTypes.node, <div />); typeCheckPass(PropTypes.node, false); typeCheckPass(PropTypes.node, <MyComponent />); typeCheckPass(PropTypes.node, 'Some string'); typeCheckPass(PropTypes.node, []); typeCheckPass(PropTypes.node, [ 123, 'Some string', <div />, ['Another string', [456], <span />, <MyComponent />], <MyComponent />, null, undefined, ]); }); it('should not warn for iterables', () => { var iterable = { '@@iterator': function() { var i = 0; return { next: function() { var done = ++i > 2; return {value: done ? undefined : <MyComponent />, done: done}; }, }; }, }; typeCheckPass(PropTypes.node, iterable); }); it('should not warn for entry iterables', () => { var iterable = { '@@iterator': function() { var i = 0; return { next: function() { var done = ++i > 2; return { value: done ? undefined : ['#' + i, <MyComponent />], done: done, }; }, }; }, }; iterable.entries = iterable['@@iterator']; typeCheckPass(PropTypes.node, iterable); }); it('should not warn for null/undefined if not required', () => { typeCheckPass(PropTypes.node, null); typeCheckPass(PropTypes.node, undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues(PropTypes.node.isRequired); }); it('should accept empty array for required props', () => { typeCheckPass(PropTypes.node.isRequired, []); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.node, 'node'); expectThrowInDevelopment(PropTypes.node, {}); expectThrowInDevelopment(PropTypes.node.isRequired, 'node'); expectThrowInDevelopment(PropTypes.node.isRequired, undefined); expectThrowInDevelopment(PropTypes.node.isRequired, undefined); }); }); describe('ObjectOf Type', () => { it('should fail for invalid argument', () => { typeCheckFail( PropTypes.objectOf({foo: PropTypes.string}), {foo: 'bar'}, 'Property `testProp` of component `testComponent` has invalid PropType notation inside objectOf.', ); }); it('should support the objectOf propTypes', () => { typeCheckPass(PropTypes.objectOf(PropTypes.number), {a: 1, b: 2, c: 3}); typeCheckPass(PropTypes.objectOf(PropTypes.string), { a: 'a', b: 'b', c: 'c', }); typeCheckPass(PropTypes.objectOf(PropTypes.oneOf(['a', 'b'])), { a: 'a', b: 'b', }); typeCheckPass(PropTypes.objectOf(PropTypes.symbol), { a: Symbol(), b: Symbol(), c: Symbol(), }); }); it('should support objectOf with complex types', () => { typeCheckPass( PropTypes.objectOf(PropTypes.shape({a: PropTypes.number.isRequired})), {a: {a: 1}, b: {a: 2}}, ); function Thing() {} typeCheckPass(PropTypes.objectOf(PropTypes.instanceOf(Thing)), { a: new Thing(), b: new Thing(), }); }); it('should warn with invalid items in the object', () => { typeCheckFail( PropTypes.objectOf(PropTypes.number), {a: 1, b: 2, c: 'b'}, 'Invalid prop `testProp.c` of type `string` supplied to `testComponent`, ' + 'expected `number`.', ); }); it('should warn with invalid complex types', () => { function Thing() {} var name = Thing.name || '<<anonymous>>'; typeCheckFail( PropTypes.objectOf(PropTypes.instanceOf(Thing)), {a: new Thing(), b: 'xyz'}, 'Invalid prop `testProp.b` of type `String` supplied to ' + '`testComponent`, expected instance of `' + name + '`.', ); }); it('should warn when passed something other than an object', () => { typeCheckFail( PropTypes.objectOf(PropTypes.number), [1, 2], 'Invalid prop `testProp` of type `array` supplied to ' + '`testComponent`, expected an object.', ); typeCheckFail( PropTypes.objectOf(PropTypes.number), 123, 'Invalid prop `testProp` of type `number` supplied to ' + '`testComponent`, expected an object.', ); typeCheckFail( PropTypes.objectOf(PropTypes.number), 'string', 'Invalid prop `testProp` of type `string` supplied to ' + '`testComponent`, expected an object.', ); typeCheckFail( PropTypes.objectOf(PropTypes.symbol), Symbol(), 'Invalid prop `testProp` of type `symbol` supplied to ' + '`testComponent`, expected an object.', ); }); it('should not warn when passing an empty object', () => { typeCheckPass(PropTypes.objectOf(PropTypes.number), {}); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass(PropTypes.objectOf(PropTypes.number), null); typeCheckPass(PropTypes.objectOf(PropTypes.number), undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues( PropTypes.objectOf(PropTypes.number).isRequired, ); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.objectOf({foo: PropTypes.string}), { foo: 'bar', }); expectThrowInDevelopment(PropTypes.objectOf(PropTypes.number), { a: 1, b: 2, c: 'b', }); expectThrowInDevelopment(PropTypes.objectOf(PropTypes.number), [1, 2]); expectThrowInDevelopment(PropTypes.objectOf(PropTypes.number), null); expectThrowInDevelopment(PropTypes.objectOf(PropTypes.number), undefined); }); }); describe('OneOf Types', () => { it('should warn but not error for invalid argument', () => { spyOn(console, 'error'); PropTypes.oneOf('red', 'blue'); expectDev(console.error).toHaveBeenCalled(); expectDev(console.error.calls.argsFor(0)[0]).toContain( 'Invalid argument supplied to oneOf, expected an instance of array.', ); typeCheckPass(PropTypes.oneOf('red', 'blue'), 'red'); }); it('should warn for invalid values', () => { typeCheckFail( PropTypes.oneOf(['red', 'blue']), true, 'Invalid prop `testProp` of value `true` supplied to ' + '`testComponent`, expected one of ["red","blue"].', ); typeCheckFail( PropTypes.oneOf(['red', 'blue']), [], 'Invalid prop `testProp` of value `` supplied to `testComponent`, ' + 'expected one of ["red","blue"].', ); typeCheckFail( PropTypes.oneOf(['red', 'blue']), '', 'Invalid prop `testProp` of value `` supplied to `testComponent`, ' + 'expected one of ["red","blue"].', ); typeCheckFail( PropTypes.oneOf([0, 'false']), false, 'Invalid prop `testProp` of value `false` supplied to ' + '`testComponent`, expected one of [0,"false"].', ); }); it('should not warn for valid values', () => { typeCheckPass(PropTypes.oneOf(['red', 'blue']), 'red'); typeCheckPass(PropTypes.oneOf(['red', 'blue']), 'blue'); typeCheckPass(PropTypes.oneOf(['red', 'blue', NaN]), NaN); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass(PropTypes.oneOf(['red', 'blue']), null); typeCheckPass(PropTypes.oneOf(['red', 'blue']), undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues(PropTypes.oneOf(['red', 'blue']).isRequired); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.oneOf(['red', 'blue']), true); expectThrowInDevelopment(PropTypes.oneOf(['red', 'blue']), null); expectThrowInDevelopment(PropTypes.oneOf(['red', 'blue']), undefined); }); }); describe('Union Types', () => { it('should warn but not error for invalid argument', () => { spyOn(console, 'error'); PropTypes.oneOfType(PropTypes.string, PropTypes.number); expectDev(console.error).toHaveBeenCalled(); expectDev(console.error.calls.argsFor(0)[0]).toContain( 'Invalid argument supplied to oneOfType, expected an instance of array.', ); typeCheckPass(PropTypes.oneOf(PropTypes.string, PropTypes.number), []); }); it('should warn if none of the types are valid', () => { typeCheckFail( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), [], 'Invalid prop `testProp` supplied to `testComponent`.', ); var checker = PropTypes.oneOfType([ PropTypes.shape({a: PropTypes.number.isRequired}), PropTypes.shape({b: PropTypes.number.isRequired}), ]); typeCheckFail( checker, {c: 1}, 'Invalid prop `testProp` supplied to `testComponent`.', ); }); it('should not warn if one of the types are valid', () => { var checker = PropTypes.oneOfType([PropTypes.string, PropTypes.number]); typeCheckPass(checker, null); typeCheckPass(checker, 'foo'); typeCheckPass(checker, 123); checker = PropTypes.oneOfType([ PropTypes.shape({a: PropTypes.number.isRequired}), PropTypes.shape({b: PropTypes.number.isRequired}), ]); typeCheckPass(checker, {a: 1}); typeCheckPass(checker, {b: 1}); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), null, ); typeCheckPass( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), undefined, ); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues( PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, ); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), [], ); expectThrowInDevelopment( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), null, ); expectThrowInDevelopment( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), undefined, ); }); }); describe('Shape Types', () => { it('should warn for non objects', () => { typeCheckFail( PropTypes.shape({}), 'some string', 'Invalid prop `testProp` of type `string` supplied to ' + '`testComponent`, expected `object`.', ); typeCheckFail( PropTypes.shape({}), ['array'], 'Invalid prop `testProp` of type `array` supplied to ' + '`testComponent`, expected `object`.', ); }); it('should not warn for empty values', () => { typeCheckPass(PropTypes.shape({}), undefined); typeCheckPass(PropTypes.shape({}), null); typeCheckPass(PropTypes.shape({}), {}); }); it('should not warn for an empty object', () => { typeCheckPass(PropTypes.shape({}).isRequired, {}); }); it('should not warn for non specified types', () => { typeCheckPass(PropTypes.shape({}), {key: 1}); }); it('should not warn for valid types', () => { typeCheckPass(PropTypes.shape({key: PropTypes.number}), {key: 1}); }); it('should warn for required valid types', () => { typeCheckFail( PropTypes.shape({key: PropTypes.number.isRequired}), {}, 'The prop `testProp.key` is marked as required in `testComponent`, ' + 'but its value is `undefined`.', ); }); it('should warn for the first required type', () => { typeCheckFail( PropTypes.shape({ key: PropTypes.number.isRequired, secondKey: PropTypes.number.isRequired, }), {}, 'The prop `testProp.key` is marked as required in `testComponent`, ' + 'but its value is `undefined`.', ); }); it('should warn for invalid key types', () => { typeCheckFail( PropTypes.shape({key: PropTypes.number}), {key: 'abc'}, 'Invalid prop `testProp.key` of type `string` supplied to `testComponent`, ' + 'expected `number`.', ); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass( PropTypes.shape(PropTypes.shape({key: PropTypes.number})), null, ); typeCheckPass( PropTypes.shape(PropTypes.shape({key: PropTypes.number})), undefined, ); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues( PropTypes.shape({key: PropTypes.number}).isRequired, ); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.shape({}), 'some string'); expectThrowInDevelopment(PropTypes.shape({foo: PropTypes.number}), { foo: 42, }); expectThrowInDevelopment( PropTypes.shape({key: PropTypes.number}).isRequired, null, ); expectThrowInDevelopment( PropTypes.shape({key: PropTypes.number}).isRequired, undefined, ); expectThrowInDevelopment(PropTypes.element, <div />); }); }); describe('Symbol Type', () => { it('should warn for non-symbol', () => { typeCheckFail( PropTypes.symbol, 'hello', 'Invalid prop `testProp` of type `string` supplied to ' + '`testComponent`, expected `symbol`.', ); typeCheckFail( PropTypes.symbol, function() {}, 'Invalid prop `testProp` of type `function` supplied to ' + '`testComponent`, expected `symbol`.', ); typeCheckFail( PropTypes.symbol, { '@@toStringTag': 'Katana', }, 'Invalid prop `testProp` of type `object` supplied to ' + '`testComponent`, expected `symbol`.', ); }); it('should not warn for a polyfilled Symbol', () => { var CoreSymbol = require('core-js/library/es6/symbol'); typeCheckPass(PropTypes.symbol, CoreSymbol('core-js')); }); }); describe('Custom validator', () => { beforeEach(() => { jest.resetModules(); }); it('should have been called with the right params', () => { var spy = jasmine.createSpy(); Component = class extends React.Component { static propTypes = {num: spy}; render() { return <div />; } }; var container = document.createElement('div'); ReactDOM.render(<Component num={5} />, container); expect(spy.calls.count()).toBe(1); expect(spy.calls.argsFor(0)[1]).toBe('num'); }); it('should have been called even if the prop is not present', () => { var spy = jasmine.createSpy(); Component = class extends React.Component { static propTypes = {num: spy}; render() { return <div />; } }; var container = document.createElement('div'); ReactDOM.render(<Component bla={5} />, container); expect(spy.calls.count()).toBe(1); expect(spy.calls.argsFor(0)[1]).toBe('num'); }); it("should have received the validator's return value", () => { spyOn(console, 'error'); var spy = jasmine .createSpy() .and.callFake(function(props, propName, componentName) { if (props[propName] !== 5) { return new Error('num must be 5!'); } }); Component = class extends React.Component { static propTypes = {num: spy}; render() { return <div />; } }; var container = document.createElement('div'); ReactDOM.render(<Component num={6} />, container); expectDev(console.error.calls.count()).toBe(1); expect( console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)'), ).toBe( 'Warning: Failed prop type: num must be 5!\n' + ' in Component (at **)', ); }); it('should not warn if the validator returned null', () => { spyOn(console, 'error'); var spy = jasmine .createSpy() .and.callFake(function(props, propName, componentName) { return null; }); Component = class extends React.Component { static propTypes = {num: spy}; render() { return <div />; } }; var container = document.createElement('div'); ReactDOM.render(<Component num={5} />, container); expectDev(console.error.calls.count()).toBe(0); }); }); });
flipactual/react
src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js
JavaScript
bsd-3-clause
37,790
.pragma library var tooltip = null function create(name, value, meta, defaultMargins, x, y, parent) { var component = Qt.createComponent("ToolTip.qml") var properties = {} properties.name = name properties.value = value properties.meta = meta properties.defaultMargins = defaultMargins properties.parentWidth = parent.width properties.parentHeight = parent.height tooltip = component.createObject(parent, properties); if (tooltip === null) console.error("error creating tooltip: " + component.errorString()) tooltip.x = x tooltip.y = y return tooltip } function createHelp(helpText, defaultMargins, x, y, parent) { var component = Qt.createComponent("Help.qml") var properties = {} properties.helpText = helpText properties.defaultMargins = defaultMargins tooltip = component.createObject(parent, properties); if (tooltip === null) console.error("error creating tooltip: " + component.errorString()) tooltip.x = x tooltip.y = y return tooltip } function destroy() { if (tooltip){ tooltip.destroy() tooltip = null } }
e1528532/libelektra
src/tools/qt-gui/qml/TooltipCreator.js
JavaScript
bsd-3-clause
1,067
// @flow import { RNFFmpeg, RNFFprobe, RNFFmpegConfig } from 'react-native-ffmpeg'; import { getHasMultipleFramesProbeCommand } from 'lib/media/video-utils'; import type { Dimensions, FFmpegStatistics, VideoInfo, } from 'lib/types/media-types'; const maxSimultaneousCalls = { process: 1, probe: 1, }; type CallCounter = typeof maxSimultaneousCalls; type QueuedCommandType = $Keys<CallCounter>; type QueuedCommand = { type: QueuedCommandType, runCommand: () => Promise<void>, }; class FFmpeg { queue: QueuedCommand[] = []; currentCalls: CallCounter = { process: 0, probe: 0 }; queueCommand<R>( type: QueuedCommandType, wrappedCommand: () => Promise<R>, ): Promise<R> { return new Promise((resolve, reject) => { const runCommand = async () => { try { const result = await wrappedCommand(); this.currentCalls[type]--; this.possiblyRunCommands(); resolve(result); } catch (e) { reject(e); } }; this.queue.push({ type, runCommand }); this.possiblyRunCommands(); }); } possiblyRunCommands() { let openSlots = {}; for (const type in this.currentCalls) { const currentCalls = this.currentCalls[type]; const maxCalls = maxSimultaneousCalls[type]; const callsLeft = maxCalls - currentCalls; if (!callsLeft) { return; } else if (currentCalls) { openSlots = { [type]: callsLeft }; break; } else { openSlots[type] = callsLeft; } } const toDefer = [], toRun = []; for (const command of this.queue) { const type: string = command.type; if (openSlots[type]) { openSlots = { [type]: openSlots[type] - 1 }; this.currentCalls[type]++; toRun.push(command); } else { toDefer.push(command); } } this.queue = toDefer; toRun.forEach(({ runCommand }) => runCommand()); } transcodeVideo( ffmpegCommand: string, inputVideoDuration: number, onTranscodingProgress: (percent: number) => void, ): Promise<{ rc: number, lastStats: ?FFmpegStatistics }> { const duration = inputVideoDuration > 0 ? inputVideoDuration : 0.001; const wrappedCommand = async () => { RNFFmpegConfig.resetStatistics(); let lastStats; RNFFmpegConfig.enableStatisticsCallback( (statisticsData: FFmpegStatistics) => { lastStats = statisticsData; const { time } = statisticsData; onTranscodingProgress(time / 1000 / duration); }, ); const ffmpegResult = await RNFFmpeg.execute(ffmpegCommand); return { ...ffmpegResult, lastStats }; }; return this.queueCommand('process', wrappedCommand); } generateThumbnail(videoPath: string, outputPath: string): Promise<number> { const wrappedCommand = () => FFmpeg.innerGenerateThumbnail(videoPath, outputPath); return this.queueCommand('process', wrappedCommand); } static async innerGenerateThumbnail( videoPath: string, outputPath: string, ): Promise<number> { const thumbnailCommand = `-i ${videoPath} -frames 1 -f singlejpeg ${outputPath}`; const { rc } = await RNFFmpeg.execute(thumbnailCommand); return rc; } getVideoInfo(path: string): Promise<VideoInfo> { const wrappedCommand = () => FFmpeg.innerGetVideoInfo(path); return this.queueCommand('probe', wrappedCommand); } static async innerGetVideoInfo(path: string): Promise<VideoInfo> { const info = await RNFFprobe.getMediaInformation(path); const videoStreamInfo = FFmpeg.getVideoStreamInfo(info); const codec = videoStreamInfo?.codec; const dimensions = videoStreamInfo && videoStreamInfo.dimensions; const format = info.format.split(','); const duration = info.duration / 1000; return { codec, format, dimensions, duration }; } static getVideoStreamInfo( info: Object, ): ?{ +codec: string, +dimensions: Dimensions } { if (!info.streams) { return null; } for (const stream of info.streams) { if (stream.type === 'video') { const codec: string = stream.codec; const width: number = stream.width; const height: number = stream.height; return { codec, dimensions: { width, height } }; } } return null; } hasMultipleFrames(path: string): Promise<boolean> { const wrappedCommand = () => FFmpeg.innerHasMultipleFrames(path); return this.queueCommand('probe', wrappedCommand); } static async innerHasMultipleFrames(path: string): Promise<boolean> { await RNFFprobe.execute(getHasMultipleFramesProbeCommand(path)); const probeOutput = await RNFFmpegConfig.getLastCommandOutput(); const numFrames = parseInt(probeOutput.lastCommandOutput); return numFrames > 1; } } const ffmpeg: FFmpeg = new FFmpeg(); export { ffmpeg };
Ashoat/squadcal
native/media/ffmpeg.js
JavaScript
bsd-3-clause
4,898
/* eslint-env node */ "use strict"; var fluid = require("infusion"); var gpii = fluid.registerNamespace("gpii"); fluid.registerNamespace("gpii.handlebars"); /** * * @typedef PrioritisedPathDef * @property {String} [priority] - The priority for this entry in the final array, relative to other path definitions. * @property {String} [namespace] - The namespace that other entries can use to express their priority. * @property {String} path - A package-relative path to be resolved. * */ /** * * A static function that uses `fluid.module.resolvePath` to resolve all paths, and return them ordered by priority. * * (See https://docs.fluidproject.org/infusion/development/Priorities.html) * * Used to consistently resolve the path to template and message bundle directories in the `handlebars`, `inline`, and * `dispatcher` modules. * * Takes a string describing a single path, or an array of strings describing multiple paths. Returns an array of * resolved paths. * * @param {Object<PrioritisedPathDef>|Object<String>} pathsToResolve - A map of paths to resolve. * @return {Array<String>} - An array of resolved paths. * */ gpii.handlebars.resolvePrioritisedPaths = function (pathsToResolve) { // Make sure that any short form (string) paths are resolved to structured path defs. var longFormPathDefs = fluid.transform(pathsToResolve, function (pathDef) { if (fluid.get(pathDef, "path")) { return pathDef; } else { return { path: pathDef }; } }); var prioritisedPathDefs = fluid.parsePriorityRecords(longFormPathDefs, "resource directory"); var resolvedPaths = fluid.transform(prioritisedPathDefs, function (pathDef) { var pathToResolve = fluid.get(pathDef, "path") || pathDef; return fluid.module.resolvePath(pathToResolve); }); return resolvedPaths; };
the-t-in-rtf/gpii-handlebars
src/js/server/lib/resolver.js
JavaScript
bsd-3-clause
1,883
// usage: log('inside coolFunc', this, arguments); // paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/ window.log = function f(){ log.history = log.history || []; log.history.push(arguments); if(this.console) { var args = arguments, newarr; args.callee = args.callee.caller; newarr = [].slice.call(args); if (typeof console.log === 'object') log.apply.call(console.log, console, newarr); else console.log.apply(console, newarr);}}; // make it safe to use console.log always (function(a){function b(){}for(var c="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),d;!!(d=c.pop());){a[d]=a[d]||b;}}) (function(){try{console.log();return window.console;}catch(a){return (window.console={});}}()); // place any jQuery/helper plugins in here, instead of separate, slower script files. // Bootstrap Dropdown /* ============================================================ * bootstrap-dropdown.js v2.0.0 * http://twitter.github.com/bootstrap/javascript.html#dropdowns * ============================================================ * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function( $ ){ "use strict" /* DROPDOWN CLASS DEFINITION * ========================= */ var toggle = '[data-toggle="dropdown"]' , Dropdown = function ( element ) { var $el = $(element).on('click.dropdown.data-api', this.toggle) $('html').on('click.dropdown.data-api', function () { $el.parent().removeClass('open') }) } Dropdown.prototype = { constructor: Dropdown , toggle: function ( e ) { var $this = $(this) , selector = $this.attr('data-target') , $parent , isActive if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = $(selector) $parent.length || ($parent = $this.parent()) isActive = $parent.hasClass('open') clearMenus() !isActive && $parent.toggleClass('open') return false } } function clearMenus() { $(toggle).parent().removeClass('open') } /* DROPDOWN PLUGIN DEFINITION * ========================== */ $.fn.dropdown = function ( option ) { return this.each(function () { var $this = $(this) , data = $this.data('dropdown') if (!data) $this.data('dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown /* APPLY TO STANDARD DROPDOWN ELEMENTS * =================================== */ $(function () { $('html').on('click.dropdown.data-api', clearMenus) $('body').on('click.dropdown.data-api', toggle, Dropdown.prototype.toggle) }) }( window.jQuery )
inkasjasonk/rs
research/base/static/js/plugins.js
JavaScript
bsd-3-clause
3,480
/** * Pimcore * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.pimcore.org/license * * @copyright Copyright (c) 2009-2010 elements.at New Media Solutions GmbH (http://www.elements.at) * @license http://www.pimcore.org/license New BSD License */ pimcore.registerNS("pimcore.object.tags.checkbox"); pimcore.object.tags.checkbox = Class.create(pimcore.object.tags.abstract, { type: "checkbox", initialize: function (data, fieldConfig) { this.data = ""; if (data) { this.data = data; } this.fieldConfig = fieldConfig; }, getGridColumnConfig: function(field) { return new Ext.grid.CheckColumn({ header: ts(field.label), dataIndex: field.key, renderer: function (key, value, metaData, record, rowIndex, colIndex, store) { if(record.data.inheritedFields[key] && record.data.inheritedFields[key].inherited == true) { metaData.css += " grid_value_inherited"; } metaData.css += ' x-grid3-check-col-td'; return String.format('<div class="x-grid3-check-col{0}">&#160;</div>', value ? '-on' : ''); }.bind(this, field.key) }); }, getGridColumnFilter: function(field) { return {type: 'boolean', dataIndex: field.key}; }, getLayoutEdit: function () { var checkbox = { fieldLabel: this.fieldConfig.title, name: this.fieldConfig.name, itemCls: "object_field" }; if (this.fieldConfig.width) { checkbox.width = this.fieldConfig.width; } this.component = new Ext.form.Checkbox(checkbox); this.component.setValue(this.data); return this.component; }, getLayoutShow: function () { this.component = this.getLayoutEdit(); this.component.disable(); return this.component; }, getValue: function () { return this.component.getValue(); }, getName: function () { return this.fieldConfig.name; }, isInvalidMandatory: function () { return false; } });
clime/pimcore-custom
static/js/pimcore/object/tags/checkbox.js
JavaScript
bsd-3-clause
2,339
// Box sizing in JavaScript // Copyright 2011 Google Inc. // see Purple/license.txt for BSD license // [email protected] define(['lib/nodelist/nodelist'], function (nodelist){ var Flexor = {}; Flexor.getChildernByClassName = function(parentBox, classname) { var hboxes = []; parentBox.childNodes.forEach(function (child) { if (child.classList && child.classList.contains(classname)) { hboxes.push(child); } }); return hboxes; }; Flexor.sizeHBoxes = function(boxes) { if (!boxes.length) { return; } var flexibles = this.flexibleBoxes(boxes); var remainingHeight = this.remainingHeight(boxes); if (remainingHeight <= 0) { console.error("Purple.Flexor: no remaining height"); return; } var remainder = 0; flexibles.forEach(function convertToHeight(box) { var flexible = parseInt(box.dataset.flexible); var floatingHeight = remainingHeight * (flexible / flexibles.totalFlexible) + remainder; var height = Math.floor(floatingHeight); remainder = floatingHeight - height; box.style.height = height+"px"; }); }; // return an array of boxes all having valid, non-zero data-flexible attributes Flexor.flexibleBoxes = function(boxes) { var flexibles = []; flexibles.totalFlexible = 0; boxes.forEach(function gatherFlexible(box) { var flexibleString = box.dataset.flexible; if (flexibleString) { var flexible = parseInt(flexibleString); if (!flexible) { console.error("Purple.Flexor: invalid flexible value "+flexibleString, box); box.removeAttribute('data-flexible'); return; } flexibles.push(box); flexibles.totalFlexible += flexible; } }); if (flexibles.length) { if (!flexibles.totalFlexible) { console.error("Purple.Flexor: no valid flexible values", flexibles); return []; } } return flexibles; }; // return the parent height minus all of the inflexible box heights Flexor.remainingHeight = function(boxes) { var remainingHeight = boxes[0].parentNode.getBoundingClientRect().height; boxes.forEach(function decrement(box) { if (!box.dataset.flexible) { remainingHeight -= box.getBoundingClientRect().height; } }); return remainingHeight; }; return Flexor; });
johnjbarton/Purple
ui/flexor.js
JavaScript
bsd-3-clause
2,344
/** * marked - a markdown parser * Copyright (c) 2011-2013, Christopher Jeffrey. (MIT Licensed) * https://github.com/chjj/marked * * @providesModule Marked * @jsx React.DOM */ /* eslint-disable sort-keys */ const React = require('React'); const Prism = require('Prism'); const Header = require('Header'); /** * Block-Level Grammar */ const block = { newline: /^\n+/, code: /^( {4}[^\n]+\n*)+/, fences: noop, hr: /^( *[-*_]){3,} *(?:\n+|$)/, heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/, nptable: noop, lheading: /^([^\n]+)\n *(=|-){3,} *\n*/, blockquote: /^( *>[^\n]+(\n[^\n]+)*\n*)+/, list: /^( *)(bull) [\s\S]+?(?:hr|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, html: /^ *(?:comment|closed|closing) *(?:\n{2,}|\s*$)/, def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/, table: noop, paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/, text: /^[^\n]+/, }; block.bullet = /(?:[*+-]|\d+\.)/; block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/; block.item = replace(block.item, 'gm')(/bull/g, block.bullet)(); block.list = replace(block.list)(/bull/g, block.bullet)('hr', /\n+(?=(?: *[-*_]){3,} *(?:\n+|$))/)(); block._tag = '(?!(?:' + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code' + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo' + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|@)\\b'; block.html = replace(block.html)('comment', /<!--[\s\S]*?-->/)('closed', /<(tag)[\s\S]+?<\/\1>/)('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)(/tag/g, block._tag)(); block.paragraph = replace(block.paragraph)('hr', block.hr)('heading', block.heading)('lheading', block.lheading)('blockquote', block.blockquote)('tag', '<' + block._tag)('def', block.def)(); /** * Normal Block Grammar */ block.normal = merge({}, block); /** * GFM Block Grammar */ block.gfm = merge({}, block.normal, { fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/, paragraph: /^/, }); block.gfm.paragraph = replace(block.paragraph)('(?!', '(?!' + block.gfm.fences.source.replace('\\1', '\\2') + '|')(); /** * GFM + Tables Block Grammar */ block.tables = merge({}, block.gfm, { nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/, table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/, }); /** * Block Lexer */ function Lexer(options) { this.tokens = []; this.tokens.links = {}; this.options = options || marked.defaults; this.rules = block.normal; if (this.options.gfm) { if (this.options.tables) { this.rules = block.tables; } else { this.rules = block.gfm; } } } /** * Expose Block Rules */ Lexer.rules = block; /** * Static Lex Method */ Lexer.lex = function(src, options) { const lexer = new Lexer(options); return lexer.lex(src); }; /** * Preprocessing */ Lexer.prototype.lex = function(src) { src = src .replace(/\r\n|\r/g, '\n') .replace(/\t/g, ' ') .replace(/\u00a0/g, ' ') .replace(/\u2424/g, '\n'); return this.token(src, true); }; /** * Lexing */ Lexer.prototype.token = function(_src, top) { let src = _src.replace(/^ +$/gm, ''); let next; let loose; let cap; let bull; let b; let item; let space; let i; let l; while (src) { // newline if (cap = this.rules.newline.exec(src)) { src = src.substring(cap[0].length); if (cap[0].length > 1) { this.tokens.push({ type: 'space', }); } } // code if (cap = this.rules.code.exec(src)) { src = src.substring(cap[0].length); cap = cap[0].replace(/^ {4}/gm, ''); this.tokens.push({ type: 'code', text: !this.options.pedantic ? cap.replace(/\n+$/, '') : cap, }); continue; } // fences (gfm) if (cap = this.rules.fences.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'code', lang: cap[2], text: cap[3], }); continue; } // heading if (cap = this.rules.heading.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'heading', depth: cap[1].length, text: cap[2], }); continue; } // table no leading pipe (gfm) if (top && (cap = this.rules.nptable.exec(src))) { src = src.substring(cap[0].length); item = { type: 'table', header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), cells: cap[3].replace(/\n$/, '').split('\n'), }; for (i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = 'right'; } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = 'center'; } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = 'left'; } else { item.align[i] = null; } } for (i = 0; i < item.cells.length; i++) { item.cells[i] = item.cells[i].split(/ *\| */); } this.tokens.push(item); continue; } // lheading if (cap = this.rules.lheading.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'heading', depth: cap[2] === '=' ? 1 : 2, text: cap[1], }); continue; } // hr if (cap = this.rules.hr.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'hr', }); continue; } // blockquote if (cap = this.rules.blockquote.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'blockquote_start', }); cap = cap[0].replace(/^ *> ?/gm, ''); // Pass `top` to keep the current // "toplevel" state. This is exactly // how markdown.pl works. this.token(cap, top); this.tokens.push({ type: 'blockquote_end', }); continue; } // list if (cap = this.rules.list.exec(src)) { src = src.substring(cap[0].length); bull = cap[2]; this.tokens.push({ type: 'list_start', ordered: bull.length > 1, }); // Get each top-level item. cap = cap[0].match(this.rules.item); next = false; l = cap.length; i = 0; for (; i < l; i++) { item = cap[i]; // Remove the list item's bullet // so it is seen as the next token. space = item.length; item = item.replace(/^ *([*+-]|\d+\.) +/, ''); // Outdent whatever the // list item contains. Hacky. if (~item.indexOf('\n ')) { // eslint-disable-line space -= item.length; item = !this.options.pedantic ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') : item.replace(/^ {1,4}/gm, ''); } // Determine whether the next list item belongs here. // Backpedal if it does not belong in this list. if (this.options.smartLists && i !== l - 1) { b = block.bullet.exec(cap[i + 1])[0]; if (bull !== b && !(bull.length > 1 && b.length > 1)) { src = cap.slice(i + 1).join('\n') + src; i = l - 1; } } // Determine whether item is loose or not. // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ // for discount behavior. loose = next || /\n\n(?!\s*$)/.test(item); if (i !== l - 1) { next = item[item.length - 1] === '\n'; if (!loose) {loose = next;} } this.tokens.push({ type: loose ? 'loose_item_start' : 'list_item_start', }); // Recurse. this.token(item, false); this.tokens.push({ type: 'list_item_end', }); } this.tokens.push({ type: 'list_end', }); continue; } // html if (cap = this.rules.html.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: this.options.sanitize ? 'paragraph' : 'html', pre: cap[1] === 'pre' || cap[1] === 'script', text: cap[0], }); continue; } // def if (top && (cap = this.rules.def.exec(src))) { src = src.substring(cap[0].length); this.tokens.links[cap[1].toLowerCase()] = { href: cap[2], title: cap[3], }; continue; } // table (gfm) if (top && (cap = this.rules.table.exec(src))) { src = src.substring(cap[0].length); item = { type: 'table', header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n'), }; for (i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = 'right'; } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = 'center'; } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = 'left'; } else { item.align[i] = null; } } for (i = 0; i < item.cells.length; i++) { item.cells[i] = item.cells[i] .replace(/^ *\| *| *\| *$/g, '') .split(/ *\| */); } this.tokens.push(item); continue; } // top-level paragraph if (top && (cap = this.rules.paragraph.exec(src))) { src = src.substring(cap[0].length); this.tokens.push({ type: 'paragraph', text: cap[1][cap[1].length - 1] === '\n' ? cap[1].slice(0, -1) : cap[1], }); continue; } // text if (cap = this.rules.text.exec(src)) { // Top-level should never reach here. src = src.substring(cap[0].length); this.tokens.push({ type: 'text', text: cap[0], }); continue; } if (src) { throw new Error('Infinite loop on byte: ' + src.charCodeAt(0)); } } return this.tokens; }; /** * Inline-Level Grammar */ const inline = { escape: /^\\([\\`*{}\[\]()#+\-.!_>])/, autolink: /^<([^ >]+(@|:\/)[^ >]+)>/, url: noop, tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/, link: /^!?\[(inside)\]\(href\)/, reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/, em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/, code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/, br: /^ {2,}\n(?!\s*$)/, del: noop, text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/, }; inline._inside = /(?:\[[^\]]*\]|[^\]]|\](?=[^\[]*\]))*/; inline._href = /\s*<?([^\s]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/; inline.link = replace(inline.link)('inside', inline._inside)('href', inline._href)(); inline.reflink = replace(inline.reflink)('inside', inline._inside)(); /** * Normal Inline Grammar */ inline.normal = merge({}, inline); /** * Pedantic Inline Grammar */ inline.pedantic = merge({}, inline.normal, { strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/, }); /** * GFM Inline Grammar */ inline.gfm = merge({}, inline.normal, { escape: replace(inline.escape)('])', '~|])')(), url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/, del: /^~~(?=\S)([\s\S]*?\S)~~/, text: replace(inline.text)(']|', '~]|')('|', '|https?://|')(), }); /** * GFM + Line Breaks Inline Grammar */ inline.breaks = merge({}, inline.gfm, { br: replace(inline.br)('{2,}', '*')(), text: replace(inline.gfm.text)('{2,}', '*')(), }); /** * Inline Lexer & Compiler */ function InlineLexer(links, options) { this.options = options || marked.defaults; this.links = links; this.rules = inline.normal; if (!this.links) { throw new Error('Tokens array requires a `links` property.'); } if (this.options.gfm) { if (this.options.breaks) { this.rules = inline.breaks; } else { this.rules = inline.gfm; } } else if (this.options.pedantic) { this.rules = inline.pedantic; } } /** * Expose Inline Rules */ InlineLexer.rules = inline; /** * Static Lexing/Compiling Method */ InlineLexer.output = function(src, links, options) { const inline = new InlineLexer(links, options); return inline.output(src); }; /** * Lexing/Compiling */ InlineLexer.prototype.output = function(src) { const out = []; let link; let text; let href; let cap; while (src) { // escape if (cap = this.rules.escape.exec(src)) { src = src.substring(cap[0].length); out.push(cap[1]); continue; } // autolink if (cap = this.rules.autolink.exec(src)) { src = src.substring(cap[0].length); if (cap[2] === '@') { text = cap[1][6] === ':' ? cap[1].substring(7) : cap[1]; href = 'mailto:' + text; } else { text = cap[1]; href = text; } out.push(React.DOM.a({href: this.sanitizeUrl(href)}, text)); continue; } // url (gfm) if (cap = this.rules.url.exec(src)) { src = src.substring(cap[0].length); text = cap[1]; href = text; out.push(React.DOM.a({href: this.sanitizeUrl(href)}, text)); continue; } // tag if (cap = this.rules.tag.exec(src)) { src = src.substring(cap[0].length); // TODO(alpert): Don't escape if sanitize is false out.push(cap[0]); continue; } // link if (cap = this.rules.link.exec(src)) { src = src.substring(cap[0].length); out.push(this.outputLink(cap, { href: cap[2], title: cap[3], })); continue; } // reflink, nolink if ((cap = this.rules.reflink.exec(src)) || (cap = this.rules.nolink.exec(src))) { src = src.substring(cap[0].length); link = (cap[2] || cap[1]).replace(/\s+/g, ' '); link = this.links[link.toLowerCase()]; if (!link || !link.href) { out.push.apply(out, this.output(cap[0][0])); src = cap[0].substring(1) + src; continue; } out.push(this.outputLink(cap, link)); continue; } // strong if (cap = this.rules.strong.exec(src)) { src = src.substring(cap[0].length); out.push(React.DOM.strong(null, this.output(cap[2] || cap[1]))); continue; } // em if (cap = this.rules.em.exec(src)) { src = src.substring(cap[0].length); out.push(React.DOM.em(null, this.output(cap[2] || cap[1]))); continue; } // code if (cap = this.rules.code.exec(src)) { src = src.substring(cap[0].length); out.push(React.DOM.code(null, cap[2])); continue; } // br if (cap = this.rules.br.exec(src)) { src = src.substring(cap[0].length); out.push(React.DOM.br(null, null)); continue; } // del (gfm) if (cap = this.rules.del.exec(src)) { src = src.substring(cap[0].length); out.push(React.DOM.del(null, this.output(cap[1]))); continue; } // text if (cap = this.rules.text.exec(src)) { src = src.substring(cap[0].length); out.push(this.smartypants(cap[0])); continue; } if (src) { throw new Error('Infinite loop on byte: ' + src.charCodeAt(0)); } } return out; }; /** * Sanitize a URL for a link or image */ InlineLexer.prototype.sanitizeUrl = function(url) { if (this.options.sanitize) { try { const prot = decodeURIComponent(url) .replace(/[^A-Za-z0-9:]/g, '') .toLowerCase(); if (prot.indexOf('javascript:') === 0) { // eslint-disable-line return '#'; } } catch (e) { return '#'; } } return url; }; /** * Compile Link */ InlineLexer.prototype.outputLink = function(cap, link) { if (cap[0][0] !== '!') { const shouldOpenInNewWindow = link.href.charAt(0) !== '/' && link.href.charAt(0) !== '#'; return React.DOM.a({ href: this.sanitizeUrl(link.href), title: link.title, target: shouldOpenInNewWindow ? '_blank' : '', }, this.output(cap[1])); } else { return React.DOM.img({ src: this.sanitizeUrl(link.href), alt: cap[1], title: link.title, }, null); } }; /** * Smartypants Transformations */ InlineLexer.prototype.smartypants = function(text) { if (!this.options.smartypants) {return text;} return text .replace(/--/g, '\u2014') .replace(/'([^']*)'/g, '\u2018$1\u2019') .replace(/"([^"]*)"/g, '\u201C$1\u201D') .replace(/\.{3}/g, '\u2026'); }; /** * Parsing & Compiling */ function Parser(options) { this.tokens = []; this.token = null; this.options = options || marked.defaults; } /** * Static Parse Method */ Parser.parse = function(src, options) { const parser = new Parser(options); return parser.parse(src); }; /** * Parse Loop */ Parser.prototype.parse = function(src) { this.inline = new InlineLexer(src.links, this.options); this.tokens = src.reverse(); const out = []; while (this.next()) { out.push(this.tok()); } return out; }; /** * Next Token */ Parser.prototype.next = function() { return this.token = this.tokens.pop(); }; /** * Preview Next Token */ Parser.prototype.peek = function() { return this.tokens[this.tokens.length - 1] || 0; }; /** * Parse Text Tokens */ Parser.prototype.parseText = function() { let body = this.token.text; while (this.peek().type === 'text') { body += '\n' + this.next().text; } return this.inline.output(body); }; /** * Parse Current Token */ Parser.prototype.tok = function() { // eslint-disable-line switch (this.token.type) { case 'space': { return []; } case 'hr': { return React.DOM.hr(null, null); } case 'heading': { return ( <Header level={this.token.depth} toSlug={this.token.text}> {this.inline.output(this.token.text)} </Header> ); } case 'code': { return <Prism>{this.token.text}</Prism>; } case 'table': { const table = []; const body = []; let row = []; let heading; let i; let cells; let j; // header for (i = 0; i < this.token.header.length; i++) { heading = this.inline.output(this.token.header[i]); row.push(React.DOM.th( this.token.align[i] ? {style: {textAlign: this.token.align[i]}} : null, heading )); } table.push(React.DOM.thead(null, React.DOM.tr(null, row))); // body for (i = 0; i < this.token.cells.length; i++) { row = []; cells = this.token.cells[i]; for (j = 0; j < cells.length; j++) { row.push(React.DOM.td( this.token.align[j] ? {style: {textAlign: this.token.align[j]}} : null, this.inline.output(cells[j]) )); } body.push(React.DOM.tr(null, row)); } table.push(React.DOM.thead(null, body)); return React.DOM.table(null, table); } case 'blockquote_start': { const body = []; while (this.next().type !== 'blockquote_end') { body.push(this.tok()); } return React.DOM.blockquote(null, body); } case 'list_start': { const type = this.token.ordered ? 'ol' : 'ul'; const body = []; while (this.next().type !== 'list_end') { body.push(this.tok()); } return React.DOM[type](null, body); } case 'list_item_start': { const body = []; while (this.next().type !== 'list_item_end') { body.push(this.token.type === 'text' ? this.parseText() : this.tok()); } return React.DOM.li(null, body); } case 'loose_item_start': { const body = []; while (this.next().type !== 'list_item_end') { body.push(this.tok()); } return React.DOM.li(null, body); } case 'html': { return React.DOM.div({ dangerouslySetInnerHTML: { __html: this.token.text, }, }); } case 'paragraph': { return this.options.paragraphFn ? this.options.paragraphFn.call(null, this.inline.output(this.token.text)) : React.DOM.p(null, this.inline.output(this.token.text)); } case 'text': { return this.options.paragraphFn ? this.options.paragraphFn.call(null, this.parseText()) : React.DOM.p(null, this.parseText()); } } }; /** * Helpers */ function replace(regex, opt) { regex = regex.source; opt = opt || ''; return function self(name, val) { if (!name) {return new RegExp(regex, opt);} val = val.source || val; val = val.replace(/(^|[^\[])\^/g, '$1'); regex = regex.replace(name, val); return self; }; } function noop() {} noop.exec = noop; function merge(obj) { let i = 1; let target; let key; for (; i < arguments.length; i++) { target = arguments[i]; for (key in target) { if (Object.prototype.hasOwnProperty.call(target, key)) { obj[key] = target[key]; } } } return obj; } /** * Marked */ function marked(src, opt, callback) { if (callback || typeof opt === 'function') { if (!callback) { callback = opt; opt = null; } if (opt) {opt = merge({}, marked.defaults, opt);} const highlight = opt.highlight; let tokens; let pending; let i = 0; try { tokens = Lexer.lex(src, opt); } catch (e) { return callback(e); } pending = tokens.length; const done = function(hi) { let out, err; if (hi !== true) { delete opt.highlight; } try { out = Parser.parse(tokens, opt); } catch (e) { err = e; } opt.highlight = highlight; return err ? callback(err) : callback(null, out); }; if (!highlight || highlight.length < 3) { return done(true); } if (!pending) {return done();} for (; i < tokens.length; i++) { (function(token) { if (token.type !== 'code') { return --pending || done(); } return highlight(token.text, token.lang, (err, code) => { if (code == null || code === token.text) { return --pending || done(); } token.text = code; token.escaped = true; --pending || done(); return undefined; }); })(tokens[i]); } return undefined; } try { if (opt) {opt = merge({}, marked.defaults, opt);} return Parser.parse(Lexer.lex(src, opt), opt); } catch (e) { e.message += '\nPlease report this to https://github.com/chjj/marked.'; if ((opt || marked.defaults).silent) { return [React.DOM.p(null, 'An error occurred:'), React.DOM.pre(null, e.message)]; } throw e; } } /** * Options */ marked.options = marked.setOptions = function(opt) { merge(marked.defaults, opt); return marked; }; marked.defaults = { gfm: true, tables: true, breaks: false, pedantic: false, sanitize: false, smartLists: false, silent: false, highlight: null, langPrefix: 'lang-', smartypants: false, paragraphFn: null, }; /** * Expose */ marked.Parser = Parser; marked.parser = Parser.parse; marked.Lexer = Lexer; marked.lexer = Lexer.lex; marked.InlineLexer = InlineLexer; marked.inlineLexer = InlineLexer.output; marked.parse = marked; const Marked = React.createClass({ render() { return <div>{marked(this.props.children, this.props)}</div>; }, }); module.exports = Marked;
mpontus/jest
website/core/Marked.js
JavaScript
bsd-3-clause
23,888
'use strict'; angular.module('authApp') .controller('LogoutCtrl', function ($scope, $location, djangoAuth) { djangoAuth.logout(); });
LABETE/TestYourProject
staticfiles/js/controllers/logout.js
JavaScript
bsd-3-clause
143
// This file was generated by silverstripe/cow from javascript/lang/src/fi.js. // See https://github.com/tractorcow/cow for details if(typeof(ss) == 'undefined' || typeof(ss.i18n) == 'undefined') { if(typeof(console) != 'undefined') console.error('Class ss.i18n not defined'); } else { ss.i18n.addDictionary('fi', { "Workflow.DeleteQuestion": "Are you sure you want to permanently delete this?", "Workflow.EMBARGOMESSAGETIME": "Saved drafts of this page will auto publish today at <a>%s</a>", "Workflow.EMBARGOMESSAGEDATE": "Saved drafts of this page will auto publish on <a>%s</a>", "Workflow.EMBARGOMESSAGEDATETIME": "Saved drafts of this page will auto publish on <a>%s at %s</a>", "Workflow.ProcessError": "Could not process workflow" }); }
icecaster/advancedworkflow
javascript/lang/fi.js
JavaScript
bsd-3-clause
766
"use strict"; const debug = require('debug')('ipc-stream'); const EventEmitter = require('events'); class IPCStream extends EventEmitter { // otherWindowId is the id of the window // channelId is the id of the service you want to communicate wth // running in that other window constructor(closeFn, remote, localStreamId, channelId) { super(); this._closeFn = closeFn; // so we can close this._remote = remote; this._localStreamId = localStreamId; this._remoteStreamId; this._channelId = channelId; // this is for debugging only } // DO NOT CALL this (it is called by IPChannel setRemoteStreamId(remoteStreamId) { debug("setRemoteStream:", remoteStreamId); if (this._remoteStreamId) { throw new Error("remoteStreamId already set"); } this._remoteStreamId = remoteStreamId; } send(...args) { if (!this._remoteStreamId) { throw new Error("remoteStreamId not set"); } this._remote.send('relay', this._remoteStreamId, ...args); } // do not call this directly disconnect() { debug("disconnect stream:", this._remoteStreamId, this._channelId); this.emit('disconnect'); this._remoteStreamId = null; } close() { debug("close:", this._localStreamId, this._channelId); if (this._remoteStreamId) { this._closeFn(); this._remote.send('disconnect', this._remoteStreamId); this._remoteStreamId = null; } } } module.exports = IPCStream;
greggman/other-window-ipc
lib/ipc-stream.js
JavaScript
bsd-3-clause
1,463
// Copyright (c) 2010 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. function onCursor() { var cursor = event.target.result; if (cursor === null) { debug('Reached end of object cursor.'); if (!gotObjectThroughCursor) { fail('Did not get object through cursor.'); return; } done(); return; } debug('Got object through cursor.'); shouldBe('event.target.result.key', '55'); shouldBe('event.target.result.value.aValue', '"foo"'); gotObjectThroughCursor = true; cursor.continue(); } function onKeyCursor() { var cursor = event.target.result; if (cursor === null) { debug('Reached end of key cursor.'); if (!gotKeyThroughCursor) { fail('Did not get key through cursor.'); return; } var request = index.openCursor(IDBKeyRange.only(55)); request.onsuccess = onCursor; request.onerror = unexpectedErrorCallback; gotObjectThroughCursor = false; return; } debug('Got key through cursor.'); shouldBe('event.target.result.key', '55'); shouldBe('event.target.result.primaryKey', '1'); gotKeyThroughCursor = true; cursor.continue(); } function getSuccess() { debug('Successfully got object through key in index.'); shouldBe('event.target.result.aKey', '55'); shouldBe('event.target.result.aValue', '"foo"'); var request = index.openKeyCursor(IDBKeyRange.only(55)); request.onsuccess = onKeyCursor; request.onerror = unexpectedErrorCallback; gotKeyThroughCursor = false; } function getKeySuccess() { debug('Successfully got key.'); shouldBe('event.target.result', '1'); var request = index.get(55); request.onsuccess = getSuccess; request.onerror = unexpectedErrorCallback; } function moreDataAdded() { debug('Successfully added more data.'); var request = index.getKey(55); request.onsuccess = getKeySuccess; request.onerror = unexpectedErrorCallback; } function indexErrorExpected() { debug('Existing index triggered on error as expected.'); var request = objectStore.put({'aKey': 55, 'aValue': 'foo'}, 1); request.onsuccess = moreDataAdded; request.onerror = unexpectedErrorCallback; } function indexSuccess() { debug('Index created successfully.'); shouldBe("index.name", "'myIndex'"); shouldBe("index.objectStore.name", "'test'"); shouldBe("index.keyPath", "'aKey'"); shouldBe("index.unique", "true"); try { request = objectStore.createIndex('myIndex', 'aKey', {unique: true}); fail('Re-creating an index must throw an exception'); } catch (e) { indexErrorExpected(); } } function createIndex(expect_error) { debug('Creating an index.'); try { window.index = objectStore.createIndex('myIndex', 'aKey', {unique: true}); indexSuccess(); } catch (e) { unexpectedErrorCallback(); } } function dataAddedSuccess() { debug('Data added'); createIndex(false); } function populateObjectStore() { debug('Populating object store'); deleteAllObjectStores(db); window.objectStore = db.createObjectStore('test'); var myValue = {'aKey': 21, 'aValue': '!42'}; var request = objectStore.add(myValue, 0); request.onsuccess = dataAddedSuccess; request.onerror = unexpectedErrorCallback; } function setVersion() { debug('setVersion'); window.db = event.target.result; var request = db.setVersion('new version'); request.onsuccess = populateObjectStore; request.onerror = unexpectedErrorCallback; } function test() { if ('webkitIndexedDB' in window) { indexedDB = webkitIndexedDB; IDBCursor = webkitIDBCursor; IDBKeyRange = webkitIDBKeyRange; IDBTransaction = webkitIDBTransaction; } debug('Connecting to indexedDB'); var request = indexedDB.open('name'); request.onsuccess = setVersion; request.onerror = unexpectedErrorCallback; }
aYukiSekiguchi/ACCESS-Chromium
chrome/test/data/indexeddb/index_test.js
JavaScript
bsd-3-clause
3,877
webpack = require('webpack') const path = require('path'); var CompressionPlugin = require("compression-webpack-plugin"); module.exports = { context: __dirname + '/source', entry: { javascript: './application.js', html: './index.html' }, loader: { appSettings: { env: "production" }, }, output: { path: __dirname + '/build', filename: '/application.js' }, resolve: { root: __dirname, extensions: ['', '.js'], modulesDirectories: ['node_modules', 'source', 'source/images'], fallback: __dirname }, module: { loaders: [ { test: /\.css$/, loaders: [ 'style?sourceMap', 'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]' ] }, { test: /\.js$/, loaders: ['babel-loader', 'eslint-loader'], include: [new RegExp(path.join(__dirname, 'source')), new RegExp(path.join(__dirname, 'tests'))] }, { test: /\.html$/, loader: 'file?name=[name].[ext]', }, { test: /\.(jpe?g|png|gif|svg)$/i, loaders: [ 'file?hash=sha512&digest=hex&name=[hash].[ext]', 'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false' ] } ], }, preLoaders: [ { test: /\.js$/, loaders: ['eslint'], include: [new RegExp(path.join(__dirname, 'source'))] } ], eslint: { failOnError: false, failOnWarning: false }, plugins: [ new webpack.ProvidePlugin({ 'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch' }), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.DedupePlugin(), new webpack.optimize.AggressiveMergingPlugin(), new webpack.optimize.UglifyJsPlugin({ sourceMap: false, compress: { sequences: true, dead_code: true, conditionals: true, booleans: true, unused: true, if_return: true, join_vars: true, drop_console: true }, mangle: { except: ['$super', '$', 'exports', 'require'] }, output: { comments: false } }), new CompressionPlugin({ asset: "[path].gz[query]", algorithm: "gzip", test: /\.js$|\.html$/, minRatio: 0.8 }) ] };
phorque/ac2-frontend
webpack-prod.config.js
JavaScript
bsd-3-clause
2,933
/** * echarts图表类:仪表盘 * * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。 * @author Kener (@Kener-林峰, [email protected]) * */ define(function (require) { var ComponentBase = require('../component/base'); var ChartBase = require('./base'); // 图形依赖 var GaugePointerShape = require('../util/shape/GaugePointer'); var TextShape = require('zrender/shape/Text'); var LineShape = require('zrender/shape/Line'); var RectangleShape = require('zrender/shape/Rectangle'); var CircleShape = require('zrender/shape/Circle'); var SectorShape = require('zrender/shape/Sector'); var ecConfig = require('../config'); var ecData = require('../util/ecData'); var zrUtil = require('zrender/tool/util'); /** * 构造函数 * @param {Object} messageCenter echart消息中心 * @param {ZRender} zr zrender实例 * @param {Object} series 数据 * @param {Object} component 组件 */ function Gauge(ecTheme, messageCenter, zr, option, myChart){ // 基类 ComponentBase.call(this, ecTheme, messageCenter, zr, option, myChart); // 图表基类 ChartBase.call(this); this.refresh(option); } Gauge.prototype = { type : ecConfig.CHART_TYPE_GAUGE, /** * 绘制图形 */ _buildShape : function () { var series = this.series; // 复用参数索引 this._paramsMap = {}; for (var i = 0, l = series.length; i < l; i++) { if (series[i].type == ecConfig.CHART_TYPE_GAUGE) { series[i] = this.reformOption(series[i]); this._buildSingleGauge(i); this.buildMark(i); } } this.addShapeList(); }, /** * 构建单个仪表盘 * * @param {number} seriesIndex 系列索引 */ _buildSingleGauge : function (seriesIndex) { var serie = this.series[seriesIndex]; this._paramsMap[seriesIndex] = { center : this.parseCenter(this.zr, serie.center), radius : this.parseRadius(this.zr, serie.radius), startAngle : serie.startAngle.toFixed(2) - 0, endAngle : serie.endAngle.toFixed(2) - 0 }; this._paramsMap[seriesIndex].totalAngle = this._paramsMap[seriesIndex].startAngle - this._paramsMap[seriesIndex].endAngle; this._colorMap(seriesIndex); this._buildAxisLine(seriesIndex); this._buildSplitLine(seriesIndex); this._buildAxisTick(seriesIndex); this._buildAxisLabel(seriesIndex); this._buildPointer(seriesIndex); this._buildTitle(seriesIndex); this._buildDetail(seriesIndex); }, // 轴线 _buildAxisLine : function (seriesIndex) { var serie = this.series[seriesIndex]; if (!serie.axisLine.show) { return; } var min = serie.min; var total = serie.max - min; var params = this._paramsMap[seriesIndex]; var center = params.center; var startAngle = params.startAngle; var totalAngle = params.totalAngle; var colorArray = params.colorArray; var lineStyle = serie.axisLine.lineStyle; var lineWidth = this.parsePercent(lineStyle.width, params.radius[1]); var r = params.radius[1]; var r0 = r - lineWidth; var sectorShape; var lastAngle = startAngle; var newAngle; for (var i = 0, l = colorArray.length; i < l; i++) { newAngle = startAngle - totalAngle * (colorArray[i][0] - min) / total; sectorShape = this._getSector( center, r0, r, newAngle, // startAngle lastAngle, // endAngle colorArray[i][1], // color lineStyle ); lastAngle = newAngle; sectorShape._animationAdd = 'r'; ecData.set(sectorShape, 'seriesIndex', seriesIndex); ecData.set(sectorShape, 'dataIndex', i); this.shapeList.push(sectorShape); } }, // 坐标轴分割线 _buildSplitLine : function (seriesIndex) { var serie = this.series[seriesIndex]; if (!serie.splitLine.show) { return; } var params = this._paramsMap[seriesIndex]; var splitNumber = serie.splitNumber; var min = serie.min; var total = serie.max - min; var splitLine = serie.splitLine; var length = this.parsePercent( splitLine.length, params.radius[1] ); var lineStyle = splitLine.lineStyle; var color = lineStyle.color; var center = params.center; var startAngle = params.startAngle * Math.PI / 180; var totalAngle = params.totalAngle * Math.PI / 180; var r = params.radius[1]; var r0 = r - length; var angle; var sinAngle; var cosAngle; for (var i = 0; i <= splitNumber; i++) { angle = startAngle - totalAngle / splitNumber * i; sinAngle = Math.sin(angle); cosAngle = Math.cos(angle); this.shapeList.push(new LineShape({ zlevel : this._zlevelBase + 1, hoverable : false, style : { xStart : center[0] + cosAngle * r, yStart : center[1] - sinAngle * r, xEnd : center[0] + cosAngle * r0, yEnd : center[1] - sinAngle * r0, strokeColor : color == 'auto' ? this._getColor(seriesIndex, min + total / splitNumber * i) : color, lineType : lineStyle.type, lineWidth : lineStyle.width, shadowColor : lineStyle.shadowColor, shadowBlur: lineStyle.shadowBlur, shadowOffsetX: lineStyle.shadowOffsetX, shadowOffsetY: lineStyle.shadowOffsetY } })); } }, // 小标记 _buildAxisTick : function (seriesIndex) { var serie = this.series[seriesIndex]; if (!serie.axisTick.show) { return; } var params = this._paramsMap[seriesIndex]; var splitNumber = serie.splitNumber; var min = serie.min; var total = serie.max - min; var axisTick = serie.axisTick; var tickSplit = axisTick.splitNumber; var length = this.parsePercent( axisTick.length, params.radius[1] ); var lineStyle = axisTick.lineStyle; var color = lineStyle.color; var center = params.center; var startAngle = params.startAngle * Math.PI / 180; var totalAngle = params.totalAngle * Math.PI / 180; var r = params.radius[1]; var r0 = r - length; var angle; var sinAngle; var cosAngle; for (var i = 0, l = splitNumber * tickSplit; i <= l; i++) { if (i % tickSplit === 0) { // 同splitLine continue; } angle = startAngle - totalAngle / l * i; sinAngle = Math.sin(angle); cosAngle = Math.cos(angle); this.shapeList.push(new LineShape({ zlevel : this._zlevelBase + 1, hoverable : false, style : { xStart : center[0] + cosAngle * r, yStart : center[1] - sinAngle * r, xEnd : center[0] + cosAngle * r0, yEnd : center[1] - sinAngle * r0, strokeColor : color == 'auto' ? this._getColor(seriesIndex, min + total / l * i) : color, lineType : lineStyle.type, lineWidth : lineStyle.width, shadowColor : lineStyle.shadowColor, shadowBlur: lineStyle.shadowBlur, shadowOffsetX: lineStyle.shadowOffsetX, shadowOffsetY: lineStyle.shadowOffsetY } })); } }, // 坐标轴文本 _buildAxisLabel : function (seriesIndex) { var serie = this.series[seriesIndex]; if (!serie.axisLabel.show) { return; } var splitNumber = serie.splitNumber; var min = serie.min; var total = serie.max - min; var textStyle = serie.axisLabel.textStyle; var textFont = this.getFont(textStyle); var color = textStyle.color; var params = this._paramsMap[seriesIndex]; var center = params.center; var startAngle = params.startAngle; var totalAngle = params.totalAngle; var r0 = params.radius[1] - this.parsePercent( serie.splitLine.length, params.radius[1] ) - 10; var angle; var sinAngle; var cosAngle; var value; for (var i = 0; i <= splitNumber; i++) { value = min + total / splitNumber * i; angle = startAngle - totalAngle / splitNumber * i; sinAngle = Math.sin(angle * Math.PI / 180); cosAngle = Math.cos(angle * Math.PI / 180); angle = (angle + 360) % 360; this.shapeList.push(new TextShape({ zlevel : this._zlevelBase + 1, hoverable : false, style : { x : center[0] + cosAngle * r0, y : center[1] - sinAngle * r0, color : color == 'auto' ? this._getColor(seriesIndex, value) : color, text : this._getLabelText(serie.axisLabel.formatter, value), textAlign : (angle >= 110 && angle <= 250) ? 'left' : (angle <= 70 || angle >= 290) ? 'right' : 'center', textBaseline : (angle >= 10 && angle <= 170) ? 'top' : (angle >= 190 && angle <= 350) ? 'bottom' : 'middle', textFont : textFont, shadowColor : textStyle.shadowColor, shadowBlur: textStyle.shadowBlur, shadowOffsetX: textStyle.shadowOffsetX, shadowOffsetY: textStyle.shadowOffsetY } })); } }, _buildPointer : function (seriesIndex) { var serie = this.series[seriesIndex]; if (!serie.pointer.show) { return; } var total = serie.max - serie.min; var pointer = serie.pointer; var params = this._paramsMap[seriesIndex]; var length = this.parsePercent(pointer.length, params.radius[1]); var width = this.parsePercent(pointer.width, params.radius[1]); var center = params.center; var value = this._getValue(seriesIndex); value = value < serie.max ? value : serie.max; var angle = (params.startAngle - params.totalAngle / total * (value - serie.min)) * Math.PI / 180; var color = pointer.color == 'auto' ? this._getColor(seriesIndex, value) : pointer.color; var pointShape = new GaugePointerShape({ zlevel : this._zlevelBase + 1, style : { x : center[0], y : center[1], r : length, startAngle : params.startAngle * Math.PI / 180, angle : angle, color : color, width : width, shadowColor : pointer.shadowColor, shadowBlur: pointer.shadowBlur, shadowOffsetX: pointer.shadowOffsetX, shadowOffsetY: pointer.shadowOffsetY }, highlightStyle : { brushType : 'fill', width : width > 2 ? 2 : (width / 2), color : '#fff' } }); ecData.pack( pointShape, this.series[seriesIndex], seriesIndex, this.series[seriesIndex].data[0], 0, this.series[seriesIndex].data[0].name, value ); this.shapeList.push(pointShape); this.shapeList.push(new CircleShape({ zlevel : this._zlevelBase + 2, hoverable : false, style : { x : center[0], y : center[1], r : pointer.width / 2.5, color : '#fff' } })); }, _buildTitle : function(seriesIndex) { var serie = this.series[seriesIndex]; if (!serie.title.show) { return; } var data = serie.data[0]; var name = typeof data.name != 'undefined' ? data.name : ''; if (name !== '') { var title = serie.title; var offsetCenter = title.offsetCenter; var textStyle = title.textStyle; var textColor = textStyle.color; var params = this._paramsMap[seriesIndex]; var x = params.center[0] + this.parsePercent(offsetCenter[0], params.radius[1]); var y = params.center[1] + this.parsePercent(offsetCenter[1], params.radius[1]); this.shapeList.push(new TextShape({ zlevel : this._zlevelBase + (Math.abs(x - params.center[0]) + Math.abs(y - params.center[1])) < textStyle.fontSize * 2 ? 2 : 1, hoverable : false, style : { x : x, y : y, color: textColor == 'auto' ? this._getColor(seriesIndex) : textColor, text: name, textAlign: 'center', textFont : this.getFont(textStyle), shadowColor : textStyle.shadowColor, shadowBlur: textStyle.shadowBlur, shadowOffsetX: textStyle.shadowOffsetX, shadowOffsetY: textStyle.shadowOffsetY } })); } }, _buildDetail : function(seriesIndex) { var serie = this.series[seriesIndex]; if (!serie.detail.show) { return; } var detail = serie.detail; var offsetCenter = detail.offsetCenter; var color = detail.backgroundColor; var textStyle = detail.textStyle; var textColor = textStyle.color; var params = this._paramsMap[seriesIndex]; var value = this._getValue(seriesIndex); var x = params.center[0] - detail.width / 2 + this.parsePercent(offsetCenter[0], params.radius[1]); var y = params.center[1] + this.parsePercent(offsetCenter[1], params.radius[1]); this.shapeList.push(new RectangleShape({ zlevel : this._zlevelBase + (Math.abs(x+detail.width/2 - params.center[0]) + Math.abs(y+detail.height/2 - params.center[1])) < textStyle.fontSize ? 2 : 1, hoverable : false, style : { x : x, y : y, width : detail.width, height : detail.height, brushType: 'both', color: color == 'auto' ? this._getColor(seriesIndex, value) : color, lineWidth : detail.borderWidth, strokeColor : detail.borderColor, shadowColor : detail.shadowColor, shadowBlur: detail.shadowBlur, shadowOffsetX: detail.shadowOffsetX, shadowOffsetY: detail.shadowOffsetY, text: this._getLabelText(detail.formatter, value), textFont: this.getFont(textStyle), textPosition: 'inside', textColor : textColor == 'auto' ? this._getColor(seriesIndex, value) : textColor } })); }, _getValue : function(seriesIndex) { var data = this.series[seriesIndex].data[0]; return typeof data.value != 'undefined' ? data.value : data; }, /** * 颜色索引 */ _colorMap : function (seriesIndex) { var serie = this.series[seriesIndex]; var min = serie.min; var total = serie.max - min; var color = serie.axisLine.lineStyle.color; if (!(color instanceof Array)) { color = [[1, color]]; } var colorArray = []; for (var i = 0, l = color.length; i < l; i++) { colorArray.push([color[i][0] * total + min, color[i][1]]); } this._paramsMap[seriesIndex].colorArray = colorArray; }, /** * 自动颜色 */ _getColor : function (seriesIndex, value) { if (typeof value == 'undefined') { value = this._getValue(seriesIndex); } var colorArray = this._paramsMap[seriesIndex].colorArray; for (var i = 0, l = colorArray.length; i < l; i++) { if (colorArray[i][0] >= value) { return colorArray[i][1]; } } return colorArray[colorArray.length - 1][1]; }, /** * 构建扇形 */ _getSector : function (center, r0, r, startAngle, endAngle, color, lineStyle) { return new SectorShape ({ zlevel : this._zlevelBase, hoverable : false, style : { x : center[0], // 圆心横坐标 y : center[1], // 圆心纵坐标 r0 : r0, // 圆环内半径 r : r, // 圆环外半径 startAngle : startAngle, endAngle : endAngle, brushType : 'fill', color : color, shadowColor : lineStyle.shadowColor, shadowBlur: lineStyle.shadowBlur, shadowOffsetX: lineStyle.shadowOffsetX, shadowOffsetY: lineStyle.shadowOffsetY } }); }, /** * 根据lable.format计算label text */ _getLabelText : function (formatter, value) { if (formatter) { if (typeof formatter == 'function') { return formatter(value); } else if (typeof formatter == 'string') { return formatter.replace('{value}', value); } } return value; }, /** * 刷新 */ refresh : function (newOption) { if (newOption) { this.option = newOption; this.series = newOption.series; } this.backupShapeList(); this._buildShape(); } }; zrUtil.inherits(Gauge, ChartBase); zrUtil.inherits(Gauge, ComponentBase); // 图表注册 require('../chart').define('gauge', Gauge); return Gauge; });
shaisxx/echarts
src/chart/gauge.js
JavaScript
bsd-3-clause
21,902
'use strict'; const assert = require('assert'); const { Observable } = require('rx-lite'); /** * * @param {Rx.Observable} observable * @param {function} fn * @returns {Rx.IPromise<void>} */ function checkError(observable, fn) { const OK = {}; return observable .catch(err => { fn(err); return Observable.just(OK); }) .toPromise() .then(value => { assert.deepStrictEqual(value, OK); }); } module.exports = checkError;
groupon/shared-store
test/check-error.js
JavaScript
bsd-3-clause
468
/** * Keydown * */ module.exports = function() { /* * this swallows backspace keys on any non-input element. * stops backspace -> back */ var rx = /INPUT|SELECT|TEXTAREA/i; $('body').bind("keydown keypress", function(e) { var key = e.keyCode || e.which; if( key == 8) { // 8 == backspace or ENTER if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){ e.preventDefault(); } } else if(key == 13) { } }); };
vulcan-estudios/bsk
src/app/helpers/events/keypress/backspace.js
JavaScript
bsd-3-clause
552
/* @flow */ 'use strict'; import { document } from '../dom/dom'; export default function () : boolean { return Boolean( (document) && (typeof document.querySelector !== 'undefined') ); }
cinecove/defunctr
lib/checks/hasQuerySelectorCheck.js
JavaScript
bsd-3-clause
201
var cdb = require('cartodb.js'); var $ = require('jquery'); var DatasetItem = require('./dataset_item_view'); var Utils = require('cdb.Utils'); var UploadConfig = require('../../../../background_importer/upload_config'); var pluralizeString = require('../../../../view_helpers/pluralize_string'); /** * Remote dataset item view * */ module.exports = DatasetItem.extend({ tagName: 'li', className: 'DatasetsList-item', events: { 'click .js-tag-link': '_onTagClick', 'click': '_toggleSelected' }, initialize: function() { this.elder('initialize'); this.template = cdb.templates.getTemplate('common/views/create/listing/remote_dataset_item'); this.table = new cdb.admin.CartoDBTableMetadata(this.model.get('external_source')); }, render: function() { var vis = this.model; var table = this.table; var tags = vis.get('tags') || []; var description = vis.get('description') && Utils.stripHTML(markdown.toHTML(vis.get('description'))) || ''; var source = vis.get('source') && markdown.toHTML(vis.get('source')) || ''; var d = { isRaster: vis.get('kind') === 'raster', geometryType: table.geomColumnTypes().length > 0 ? table.geomColumnTypes()[0] : '', title: vis.get('name'), source: source, description: description, timeDiff: moment(vis.get('updated_at')).fromNow(), tags: tags, tagsCount: tags.length, routerModel: this.routerModel, maxTagsToShow: 3, canImportDataset: this._canImportDataset(), rowCount: undefined, datasetSize: undefined }; var rowCount = table.get('row_count'); if (rowCount >= 0) { d.rowCount = ( rowCount < 10000 ? Utils.formatNumber(rowCount) : Utils.readizableNumber(rowCount) ); d.pluralizedRows = pluralizeString('Row', rowCount); } var datasetSize = table.get('size'); if (datasetSize >= 0) { d.datasetSize = Utils.readablizeBytes(datasetSize, true); } this.$el.html(this.template(d)); this._setItemClasses(); this._renderTooltips(); return this; }, _setItemClasses: function() { // Item selected? this.$el[ this.model.get('selected') ? 'addClass' : 'removeClass' ]('is--selected'); // Check if it is selectable this.$el[ this._canImportDataset() ? 'addClass' : 'removeClass' ]('DatasetsList-item--selectable'); // Check if it is importable this.$el[ this._canImportDataset() ? 'removeClass' : 'addClass' ]('DatasetsList-item--banned'); }, _renderTooltips: function() { this.addView( new cdb.common.TipsyTooltip({ el: this.$('.DatasetsList-itemStatus'), title: function(e) { return $(this).attr('data-title') } }) ) }, _onTagClick: function(ev) { if (ev) { this.killEvent(ev); } var tag = $(ev.target).val(); if (tag) { this.routerModel.set({ tag: tag, library: true }); } }, _canImportDataset: function() { return ( this.user.get('remaining_byte_quota') * UploadConfig.fileTimesBigger ) >= ( this.table.get('size') || 0 ) }, _toggleSelected: function(ev) { // Let links use default behaviour if (ev.target.tagName !== 'A') { this.killEvent(ev); if (this._canImportDataset() && this.options.createModel.canSelect(this.model)) { this.model.set('selected', !this.model.get('selected')); } } } });
raquel-ucl/cartodb
lib/assets/javascripts/cartodb/common/dialogs/create/listing/datasets/remote_dataset_item_view.js
JavaScript
bsd-3-clause
3,614
var a00494 = [ [ "calculate_nnz", "a00494.html#aca63ccfbd14352eade58fd2a2ec6b5e4", null ], [ "nnz_internal", "a00494.html#a710993cf2d56652448517817943ad10f", null ], [ "optimizeWildfire", "a00494.html#adc947c65dcf861c33a24399614c0791a", null ], [ "optimizeWildfire", "a00494.html#a33509e7a55b46fe677e682d01f8fbd87", null ], [ "optimizeWildfireNode", "a00494.html#aadd9b9f920ceaa21f31cb0695fc3c12d", null ], [ "optimizeWildfireNonRecursive", "a00494.html#ad11ffb44abea89e42c6de7a9f2f97221", null ] ];
devbharat/gtsam
doc/html/a00494.js
JavaScript
bsd-3-clause
523
'use strict'; angular.module('app.controllers', []) .controller('HomeController', ['$scope','CountryFactory', function($scope, CountryFactory){ $scope.paisSeleccionado = []; CountryFactory.getAllCountries(); $scope.mostrarPaises = function(){ CountryFactory.getAllCountries(); var countries = CountryFactory.getCountries(); $scope.paisSeleccionado = countries[0]; } $scope.crearPais = function(){ CountryFactory.crearPais(); } }])
UsuarioCristian/basic2015
api/assets/js/controllers/controllers.js
JavaScript
bsd-3-clause
450
/* * DisplayObject by Grant Skinner. Dec 5, 2010 * Visit http://easeljs.com/ for documentation, updates and examples. * * * Copyright (c) 2010 Grant Skinner * * 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. */ /** * The Easel Javascript library provides a retained graphics mode for canvas * including a full, hierarchical display list, a core interaction model, and * helper classes to make working with Canvas much easier. * @module EaselJS **/ (function(window) { /** * DisplayObject is an abstract class that should not be constructed directly. Instead construct subclasses such as * Sprite, Bitmap, and Shape. DisplayObject is the base class for all display classes in the CanvasDisplay library. * It defines the core properties and methods that are shared between all display objects. * @class DisplayObject * @constructor **/ DisplayObject = function() { this.initialize(); } var p = DisplayObject.prototype; /** * Suppresses errors generated when using features like hitTest, onPress/onClick, and getObjectsUnderPoint with cross * domain content * @property suppressCrossDomainErrors * @static * @type Boolean * @default false **/ DisplayObject.suppressCrossDomainErrors = false; /** * @property _hitTestCanvas * @type HTMLCanvasElement * @static * @protected **/ DisplayObject._hitTestCanvas = document.createElement("canvas"); DisplayObject._hitTestCanvas.width = DisplayObject._hitTestCanvas.height = 1; /** * @property _hitTestContext * @type CanvasRenderingContext2D * @static * @protected **/ DisplayObject._hitTestContext = DisplayObject._hitTestCanvas.getContext("2d"); /** * @property _workingMatrix * @type Matrix2D * @static * @protected **/ DisplayObject._workingMatrix = new Matrix2D(); /** * The alpha (transparency) for this display object. 0 is fully transparent, 1 is fully opaque. * @property alpha * @type Number * @default 1 **/ p.alpha = 1; /** * If a cache is active, this returns the canvas that holds the cached version of this display object. See cache() * for more information. READ-ONLY. * @property cacheCanvas * @type HTMLCanvasElement * @default null **/ p.cacheCanvas = null; /** * Unique ID for this display object. Makes display objects easier for some uses. * @property id * @type Number * @default -1 **/ p.id = -1; /** * Indicates whether to include this object when running Stage.getObjectsUnderPoint(). Setting this to true for * Sprites will cause the Sprite to be returned (not its children) regardless of whether it's mouseChildren property * is true. * @property mouseEnabled * @type Boolean * @default true **/ p.mouseEnabled = true; /** * An optional name for this display object. Included in toString(). Useful for debugging. * @property name * @type String * @default null **/ p.name = null; /** * A reference to the Sprite or Stage object that contains this display object, or null if it has not been added to * one. READ-ONLY. * @property parent * @final * @type DisplayObject * @default null **/ p.parent = null; /** * The x offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate around * it's center, you would set regX and regY to 50. * @property regX * @type Number * @default 0 **/ p.regX = 0; /** * The y offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate around * it's center, you would set regX and regY to 50. * @property regY * @type Number * @default 0 **/ p.regY = 0; /** * The rotation in degrees for this display object. * @property rotation * @type Number * @default 0 **/ p.rotation = 0; /** * The factor to stretch this display object horizontally. For example, setting scaleX to 2 will stretch the display * object to twice it's nominal width. * @property scaleX * @type Number * @default 1 **/ p.scaleX = 1; /** * The factor to stretch this display object vertically. For example, setting scaleY to 0.5 will stretch the display * object to half it's nominal height. * @property scaleY * @type Number * @default 1 **/ p.scaleY = 1; /** * The factor to skew this display object horizontally. * @property skewX * @type Number * @default 0 **/ p.skewX = 0; /** * The factor to skew this display object vertically. * @property skewY * @type Number * @default 0 **/ p.skewY = 0; /** * A shadow object that defines the shadow to render on this display object. Set to null to remove a shadow. If * null, this property is inherited from the parent container. * @property shadow * @type Shadow * @default null **/ p.shadow = null; /** * Indicates whether this display object should be rendered to the canvas and included when running * Stage.getObjectsUnderPoint(). * @property visible * @type Boolean * @default true **/ p.visible = true; /** * The x (horizontal) position of the display object, relative to its parent. * @property x * @type Number * @default 0 **/ p.x = 0; /** The y (vertical) position of the display object, relative to its parent. * @property y * @type Number * @default 0 **/ p.y = 0; /** * The composite operation indicates how the pixels of this display object will be composited with the elements * behind it. If null, this property is inherited from the parent container. For more information, read the * <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#compositing"> * whatwg spec on compositing</a>. * @property compositeOperation * @type String * @default null **/ p.compositeOperation = null; /** * Indicates whether the display object should have it's x & y position rounded prior to drawing it to stage. * This only applies if the enclosing stage has snapPixelsEnabled set to true, and the display object's composite * transform does not include any scaling, rotation, or skewing. The snapToPixel property is true by default for * Bitmap and BitmapSequence instances, and false for all other display objects. * @property snapToPixel * @type Boolean * @default false **/ p.snapToPixel = false; /** * The onPress callback is called when the user presses down on their mouse over this display object. The handler * is passed a single param containing the corresponding MouseEvent instance. You can subscribe to the onMouseMove * and onMouseUp callbacks of the event object to receive these events until the user releases the mouse button. * If an onPress handler is set on a container, it will receive the event if any of its children are clicked. * @event onPress * @param {MouseEvent} event MouseEvent with information about the event. **/ p.onPress = null; /** * The onClick callback is called when the user presses down on and then releases the mouse button over this * display object. The handler is passed a single param containing the corresponding MouseEvent instance. If an * onClick handler is set on a container, it will receive the event if any of its children are clicked. * @event onClick * @param {MouseEvent} event MouseEvent with information about the event. **/ p.onClick = null; /** * The onMouseOver callback is called when the user rolls over the display object. You must enable this event using * stage.enableMouseOver(). The handler is passed a single param containing the corresponding MouseEvent instance. * @event onMouseOver * @param {MouseEvent} event MouseEvent with information about the event. **/ p.onMouseOver = null; /** * The onMouseOut callback is called when the user rolls off of the display object. You must enable this event using * stage.enableMouseOver(). The handler is passed a single param containing the corresponding MouseEvent instance. * @event onMouseOut * @param {MouseEvent} event MouseEvent with information about the event. **/ p.onMouseOut = null; // private properties: /** * @property _cacheOffsetX * @protected * @type Number * @default 0 **/ p._cacheOffsetX = 0; /** * @property _cacheOffsetY * @protected * @type Number * @default 0 **/ p._cacheOffsetY = 0; /** * @property _cacheDraw * @protected * @type Boolean * @default false **/ p._cacheDraw = false; /** * @property _activeContext * @protected * @type CanvasRenderingContext2D * @default null **/ p._activeContext = null; /** * @property _restoreContext * @protected * @type Boolean * @default false **/ p._restoreContext = false; /** * @property _revertShadow * @protected * @type Boolean * @default false **/ p._revertShadow = false; /** * @property _revertX * @protected * @type Number * @default 0 **/ p._revertX = 0; /** * @property _revertY * @protected * @type Number * @default 0 **/ p._revertY = 0; /** * @property _revertAlpha * @protected * @type Number * @default 1 **/ p._revertAlpha = 1; // constructor: // separated so it can be easily addressed in subclasses: /** * Initialization method. * @method initialize * @protected */ p.initialize = function() { this.id = UID.get(); this.children = []; } // public methods: /** * Returns true or false indicating whether the display object would be visible if drawn to a canvas. * This does not account for whether it would be visible within the boundaries of the stage. * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. * @method isVisible * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas **/ p.isVisible = function() { return this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0; } /** * Draws the display object into the specified context ignoring it's visible, alpha, shadow, and transform. * Returns true if the draw was handled (useful for overriding functionality). * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. * @method draw * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache. * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back * into itself). **/ p.draw = function(ctx, ignoreCache) { if (ignoreCache || !this.cacheCanvas) { return false; } ctx.translate(this._cacheOffsetX, this._cacheOffsetY); ctx.drawImage(this.cacheCanvas, 0, 0); ctx.translate(-this._cacheOffsetX, -this._cacheOffsetY); return true; } /** * Draws the display object into a new canvas, which is then used for subsequent draws. For complex content * that does not change frequently (ex. a Sprite with many children that do not move, or a complex vector Shape), * this can provide for much faster rendering because the content does not need to be re-rendered each tick. The * cached display object can be moved, rotated, faded, etc freely, however if it's content changes, you must manually * update the cache by calling updateCache() or cache() again. You must specify the cache area via the x, y, w, * and h parameters. This defines the rectangle that will be rendered and cached using this display object's * coordinates. For example if you defined a Shape that drew a circle at 0, 0 with a radius of 25, you could call * myShape.cache(-25, -25, 50, 50) to cache the full shape. * @method cache * @param {Number} x The x coordinate origin for the cache region. * @param {Number} y The y coordinate origin for the cache region. * @param {Number} width The width of the cache region. * @param {Number} height The height of the cache region. **/ p.cache = function(x, y, width, height) { // draw to canvas. var ctx; if (this.cacheCanvas == null) { this.cacheCanvas = document.createElement("canvas"); } ctx = this.cacheCanvas.getContext("2d"); this.cacheCanvas.width = width; this.cacheCanvas.height = height; ctx.setTransform(1, 0, 0, 1, -x, -y); ctx.clearRect(0, 0, width+1, height+1); // because some browsers don't correctly clear if the width/height //remain the same. this.draw(ctx, true); this._cacheOffsetX = x; this._cacheOffsetY = y; } /** * Redraws the display object to its cache. Calling updateCache without an active cache will throw an error. * If compositeOperation is null the current cache will be cleared prior to drawing. Otherwise the display object * will be drawn over the existing cache using the specified compositeOperation. * @method updateCache * @param {String} compositeOperation The compositeOperation to use, or null to clear the cache and redraw it. * <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#compositing"> * whatwg spec on compositing</a>. **/ p.updateCache = function(compositeOperation) { if (this.cacheCanvas == null) { throw "cache() must be called before updateCache()"; } var ctx = this.cacheCanvas.getContext("2d"); ctx.setTransform(1, 0, 0, 1, -this._cacheOffsetX, -this._cacheOffsetY); if (!compositeOperation) { ctx.clearRect(0, 0, this.cacheCanvas.width+1, this.cacheCanvas.height+1); } else { ctx.globalCompositeOperation = compositeOperation; } this.draw(ctx, true); if (compositeOperation) { ctx.globalCompositeOperation = "source-over"; } } /** * Clears the current cache. See cache() for more information. * @method uncache **/ p.uncache = function() { this.cacheCanvas = null; this.cacheOffsetX = this.cacheOffsetY = 0; } /** * Returns the stage that this display object will be rendered on, or null if it has not been added to one. * @method getStage * @return {Stage} The Stage instance that the display object is a descendent of. null if the DisplayObject has not * been added to a Stage. **/ p.getStage = function() { var o = this; while (o.parent) { o = o.parent; } if (o instanceof Stage) { return o; } return null; } /** * Transforms the specified x and y position from the coordinate space of the display object * to the global (stage) coordinate space. For example, this could be used to position an HTML label * over a specific point on a nested display object. Returns a Point instance with x and y properties * correlating to the transformed coordinates on the stage. * @method localToGlobal * @param {Number} x The x position in the source display object to transform. * @param {Number} y The y position in the source display object to transform. * @return {Point} A Point instance with x and y properties correlating to the transformed coordinates * on the stage. **/ p.localToGlobal = function(x, y) { var mtx = this.getConcatenatedMatrix(); if (mtx == null) { return null; } mtx.append(1, 0, 0, 1, x, y); return new Point(mtx.tx, mtx.ty); } /** * Transforms the specified x and y position from the global (stage) coordinate space to the * coordinate space of the display object. For example, this could be used to determine * the current mouse position within the display object. Returns a Point instance with x and y properties * correlating to the transformed position in the display object's coordinate space. * @method globalToLocal * @param {Number} x The x position on the stage to transform. * @param {Number} y The y position on the stage to transform. * @return {Point} A Point instance with x and y properties correlating to the transformed position in the * display object's coordinate space. **/ p.globalToLocal = function(x, y) { var mtx = this.getConcatenatedMatrix(); if (mtx == null) { return null; } mtx.invert(); mtx.append(1, 0, 0, 1, x, y); return new Point(mtx.tx, mtx.ty); } /** * Transforms the specified x and y position from the coordinate space of this display object to the * coordinate space of the target display object. Returns a Point instance with x and y properties * correlating to the transformed position in the target's coordinate space. Effectively the same as calling * var pt = this.localToGlobal(x, y); pt = target.globalToLocal(pt.x, pt.y); * @method localToLocal * @param {Number} x The x position in the source display object to transform. * @param {Number} y The y position on the stage to transform. * @param {DisplayObject} target The target display object to which the coordinates will be transformed. * @return {Point} Returns a Point instance with x and y properties correlating to the transformed position * in the target's coordinate space. **/ p.localToLocal = function(x, y, target) { var pt = this.localToGlobal(x, y); return target.globalToLocal(pt.x, pt.y); } /** * Generates a concatenated Matrix2D object representing the combined transform of * the display object and all of its parent Containers up to the highest level ancestor * (usually the stage). This can be used to transform positions between coordinate spaces, * such as with localToGlobal and globalToLocal. * @method getConcatenatedMatrix * @param {Matrix2D} mtx Optional. A Matrix2D object to populate with the calculated values. If null, a new * Matrix object is returned. * @return {Matrix2D} a concatenated Matrix2D object representing the combined transform of * the display object and all of its parent Containers up to the highest level ancestor (usually the stage). **/ p.getConcatenatedMatrix = function(mtx) { if (mtx) { mtx.identity(); } else { mtx = new Matrix2D(); } var target = this; while (target != null) { mtx.prependTransform(target.x, target.y, target.scaleX, target.scaleY, target.rotation, target.skewX, target.skewY, target.regX, target.regY); mtx.prependProperties(target.alpha, target.shadow, target.compositeOperation); target = target.parent; } return mtx; } /** * Tests whether the display object intersects the specified local point (ie. draws a pixel with alpha > 0 at * the specified position). This ignores the alpha, shadow and compositeOperation of the display object, and all * transform properties including regX/Y. * @method hitTest * @param {Number} x The x position to check in the display object's local coordinates. * @param {Number} y The y position to check in the display object's local coordinates. * @return {Boolean} A Boolean indicting whether a visible portion of the DisplayObject intersect the specified * local Point. */ p.hitTest = function(x, y) { var ctx = DisplayObject._hitTestContext; var canvas = DisplayObject._hitTestCanvas; ctx.setTransform(1, 0, 0, 1, -x, -y); this.draw(ctx); var hit = this._testHit(ctx); canvas.width = 0; canvas.width = 1; return hit; } /** * Returns a clone of this DisplayObject. Some properties that are specific to this instance's current context are * reverted to their defaults (for example .parent). * @method clone @return {DisplayObject} A clone of the current DisplayObject instance. **/ p.clone = function() { var o = new DisplayObject(); this.cloneProps(o); return o; } /** * Returns a string representation of this object. * @method toString * @return {String} a string representation of the instance. **/ p.toString = function() { return "[DisplayObject (name="+ this.name +")]"; } // private methods: // separated so it can be used more easily in subclasses: /** * @method cloneProps * @protected * @param {DisplayObject} o The DisplayObject instance which will have properties from the current DisplayObject * instance copied into. **/ p.cloneProps = function(o) { o.alpha = this.alpha; o.name = this.name; o.regX = this.regX; o.regY = this.regY; o.rotation = this.rotation; o.scaleX = this.scaleX; o.scaleY = this.scaleY; o.shadow = this.shadow; o.skewX = this.skewX; o.skewY = this.skewY; o.visible = this.visible; o.x = this.x; o.y = this.y; o.mouseEnabled = this.mouseEnabled; o.compositeOperation = this.compositeOperation; } /** * @method applyShadow * @protected * @param {CanvasRenderingContext2D} ctx * @param {Shadow} shadow **/ p.applyShadow = function(ctx, shadow) { shadow = shadow || Shadow.identity; ctx.shadowColor = shadow.color; ctx.shadowOffsetX = shadow.offsetX; ctx.shadowOffsetY = shadow.offsetY; ctx.shadowBlur = shadow.blur; } /** * @method _testHit * @protected * @param {CanvasRenderingContext2D} ctx * @return {Boolean} **/ p._testHit = function(ctx) { try { var hit = ctx.getImageData(0, 0, 1, 1).data[3] > 1; } catch (e) { if (!DisplayObject.suppressCrossDomainErrors) { throw "An error has occured. This is most likely due to security restrictions on reading canvas pixel " + "data with local or cross-domain images."; } } return hit; } window.DisplayObject = DisplayObject; }(window));
PaulWoow/HTML5JUEGOGRAFICACION
Mini Valle PaJou/libs/easeljs/display/DisplayObject.js
JavaScript
bsd-3-clause
21,794
function installthis(id) { var answer = confirm('Are you sure ? '); if (answer){ //delete img... $.post(base_url+'/zfmodules/index/installmod/id/'+id, function(data){ window.location.reload(false); }); } } function installnotvalidthis(id) { var answer = confirm('Your module is not valid,\n if you continue, it\'s will be installed to another unique name,\n Are You sure ?'); if (answer){ //delete img... $.post(base_url+'/zfmodules/index/installmodtovalid/id/'+id, function(data){ window.location.reload(false); }); } }
samsonasik/zf_111_support_php532_with_modulewizard
public/themes/zend_prj/js/modules/modules.js
JavaScript
bsd-3-clause
751
$(function(){ function openPanel(){ require(['panel']); $('#admin_link').hide(); } if($.cookie('grass_panel')){ openPanel(); } $('#admin_link').on('click', function(e){ e.preventDefault(); openPanel(); }); }); require.config({ baseUrl: 'media/scripts', paths: { // 'doT': 'vendor/dot', 'riotjs': 'vendor/riot+compiler', 'panel': 'admin/panel', 'text': 'vendor/text' }, shim: { riotjs: { exports: 'riot' } } }); var riot; function loadCss(url) { var link = document.createElement("link"); link.type = "text/css"; link.rel = "stylesheet"; link.href = url; document.getElementsByTagName("head")[0].appendChild(link); }
grnrbt/grass
web/media/scripts/link.js
JavaScript
bsd-3-clause
781
/** * @decription mock file config * * 该文件实现路由的配置,在没有test准备好的情况下可以直接走这个mock数据 * key: 为要匹配的路由 * value: 为对应的参数配置 * method: get或者post,router的方法 * filename: 对应的mock文件 */ module.exports = { '/api/realtime': { method: "post", filename: "realtime.js" } };
changfuguo/vuejs-boilerplate
server/config/route.js
JavaScript
bsd-3-clause
383
$(document).ready(function(){ // Navigation var body_class = document.body.className; var hover_on_bg = "#c00"; var hover_on_co = "#fff"; var hover_off_bg = "#fff"; var hover_off_co = "#444"; var hover_delay = 200; $("#navigation li a").removeClass("hover"); $("#navigation li").each(function(){ if (this.className == body_class) { $('a', this).addClass("hover"); } else { $(this).hover(function(){ $('a', this).stop().animate({ backgroundColor: hover_on_bg, color: hover_on_co }, hover_delay); }, function(){ $('a', this).stop().animate({ backgroundColor: hover_off_bg, color: hover_off_co }, hover_delay); }); $(this).focus(function(){ $('a', this).stop().animate({ backgroundColor: hover_on_bg, color: hover_on_co }, hover_delay); }, function(){ $('a', this).stop().animate({ backgroundColor: hover_off_bg, color: hover_off_co }, hover_delay); }); } }); // About page first paragraph and clincher $("body.about div#article p:first").addClass("first"); $("body.about div#article p:last").append("<span class=\"clincher\">&#9632;</span>"); }); // E-mail address DOM insertion function email(email){ $("body.about div#article h4:eq(1)").before("<p><strong><a href=\"mailto:" + email + "\">" + email + "</a></strong></p>"); }
richardcornish/cyndiloza
cyndiloza/static/js/site.js
JavaScript
bsd-3-clause
1,360
$(function() { JQTWEET = { // Set twitter hash/user, number of tweets & id/class to append tweets // You need to clear tweet-date.txt before toggle between hash and user // for multiple hashtags, you can separate the hashtag with OR, eg: search: '', //leave this blank if you want to show user's tweet hash: '', user: '', //username numTweets:500, //number of tweets appendTo: '', useGridalicious: false, template: '<div class="item"> <div class="time"><p>{AGO}</p></div>\ <div class="tweet-wrapper">\ <div class="profile"><img href="{PHO}" src="{PHOP}"/></div>\ <div class="user">{USER}</div>\ <div class="text">{TEXT}</div><div class="img">{IMG}</div></div></div>', // core function of jqtweet // https://dev.twitter.com/docs/using-search loadTweets: function() { //console.log("We Made it here"); var request; // different JSON request {hash|user} if (JQTWEET.search) { request = { q: JQTWEET.search, count: JQTWEET.numTweets, api: 'search_tweets' } } else { request = { q: JQTWEET.user, count: JQTWEET.numTweets, api: 'statuses_userTimeline' } } $.ajax({ url: 'grabtweets.php', type: 'POST', dataType: 'json', data: request, success: function(data, textStatus, xhr) { if (data.httpstatus == 200) { if (JQTWEET.search) data = data.statuses; var text, name, img; try { // append tweets into page for (var i = 0; i < JQTWEET.numTweets; i++) { img = ''; url = 'http://twitter.com/' + data[i].user.screen_name + '/status/' + data[i].id_str; try { if (data[i].entities['media']) { img = '<img src="' + data[i].entities['media'][0].media_url + '" />'; } } catch (e) { //no media } $(JQTWEET.appendTo).append( JQTWEET.template.replace('{TEXT}', JQTWEET.ify.clean(data[i].text) ) .replace('{USER}', data[i].user.screen_name) .replace('{PHO}', data[i].user.profile_image_url) .replace('{PHOP}', data[i].user.profile_image_url) .replace('{IMG}', img) .replace('{AGO}', JQTWEET.timeAgo(data[i].created_at) ) .replace('{URL}', url ) ); } } catch (e) { //item is less than item count } if (JQTWEET.useGridalicious) { //run grid-a-licious $(JQTWEET.appendTo).gridalicious({ gutter: 13, width: 1080, animate: true }); } } else alert('no data returned'); } }); }, /** * relative time calculator FROM TWITTER * @param {string} twitter date string returned from Twitter API * @return {string} relative time like "2 minutes ago" */ timeAgo: function(dateString) { var rightNow = new Date(); var then = new Date(dateString); if ($.browser.msie) { // IE can't parse these crazy Ruby dates then = Date.parse(dateString.replace(/( \+)/, ' UTC$1')); } var diff = rightNow - then; var second = 1000, minute = second * 60, hour = minute * 60, day = hour * 24, week = day * 7; if (isNaN(diff) || diff < 0) { return ""; // return blank string if unknown } if (diff < second * 2) { // within 2 seconds return "right now"; } if (diff < minute) { return Math.floor(diff / second) + " seconds ago"; } if (diff < minute * 2) { return "about 1 minute ago"; } if (diff < hour) { return Math.floor(diff / minute) + " minutes ago"; } if (diff < hour * 2) { return "about 1 hour ago"; } if (diff < day) { return Math.floor(diff / hour) + " hours ago"; } if (diff > day && diff < day * 2) { return "yesterday"; } if (diff < day * 365) { return Math.floor(diff / day) + " days ago"; } else { return "over a year ago"; } }, // timeAgo() /** * The Twitalinkahashifyer! * http://www.dustindiaz.com/basement/ify.html * Eg: * ify.clean('your tweet text'); */ ify: { link: function(tweet) { return tweet.replace(/\b(((https*\:\/\/)|www\.)[^\"\']+?)(([!?,.\)]+)?(\s|$))/g, function(link, m1, m2, m3, m4) { var http = m2.match(/w/) ? 'http://' : ''; return '<a class="twtr-hyperlink" target="_blank" href="' + http + m1 + '">' + ((m1.length > 25) ? m1.substr(0, 24) + '...' : m1) + '</a>' + m4; }); }, at: function(tweet) { return tweet.replace(/\B[@@]([a-zA-Z0-9_]{1,20})/g, function(m, username) { return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/intent/user?screen_name=' + username + '">@' + username + '</a>'; }); }, list: function(tweet) { return tweet.replace(/\B[@@]([a-zA-Z0-9_]{1,20}\/\w+)/g, function(m, userlist) { return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/' + userlist + '">@' + userlist + '</a>'; }); }, hash: function(tweet) { return tweet.replace(/(^|\s+)#(\w+)/gi, function(m, before, hash) { return before + '<a target="_blank" class="twtr-hashtag" href="http://twitter.com/search?q=%23' + hash + '">#' + hash + '</a>'; }); }, clean: function(tweet) { return this.hash(this.at(this.list(this.link(tweet)))); } } // ify }; });
Amaceika/TowerWall
twitter-oauth/jquery.jstwitter.js
JavaScript
bsd-3-clause
6,798
CodeMirror.ternLint = function(cm, updateLinting, options) { function addAnnotation(error, found) { var startLine = error.startLine; var startChar = error.startChar; var endLine = error.endLine; var endChar = error.endChar; var message = error.message; found.push({ from : error.start, to : error.end, message : message }); } var getServer = (typeof options.server == "function") ? options.server : function(cm) {return options.server}; var query = { type : "lint", file : "#0", lineCharPositions : true }; var files = []; files.push({ type : "full", name : "[doc]", text : cm.getValue() }); var doc = { query : query, files : files }; getServer(cm).server.request(doc, function(error, response) { if (error) { updateLinting(cm, []); } else { var messages = response.messages; updateLinting(cm, messages); } }); };
daniel-lundin/tern-snabbt
demos/resources/tern-lint/codemirror/addon/lint/tern-lint.js
JavaScript
mit
952
/** * Fixes an issue with Bootstrap Date Picker * @see https://github.com/angular-ui/bootstrap/issues/2659 * * How does it work? AngularJS allows multiple directives with the same name, * and each is treated independently though they are instantiated based on the * same element/attribute/comment. * * So this directive goes along with ui.bootstrap's datepicker-popup directive. * @see http://angular-ui.github.io/bootstrap/versioned-docs/0.12.0/#/datepicker */ export default function datepickerPopup() { return { restrict: 'EAC', require: 'ngModel', link: function(scope, element, attr, controller) { //remove the default formatter from the input directive to prevent conflict controller.$formatters.shift(); } }; } datepickerPopup.$inject = [];
manekinekko/ng-admin
src/javascripts/ng-admin/Crud/field/datepickerPopup.js
JavaScript
mit
823
/* YUI 3.7.2 (build 5639) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('editor-base', function (Y, NAME) { /** * Base class for Editor. Handles the business logic of Editor, no GUI involved only utility methods and events. * * var editor = new Y.EditorBase({ * content: 'Foo' * }); * editor.render('#demo'); * * @class EditorBase * @extends Base * @module editor * @main editor * @submodule editor-base * @constructor */ var EditorBase = function() { EditorBase.superclass.constructor.apply(this, arguments); }, LAST_CHILD = ':last-child', BODY = 'body'; Y.extend(EditorBase, Y.Base, { /** * Internal reference to the Y.Frame instance * @property frame */ frame: null, initializer: function() { var frame = new Y.Frame({ designMode: true, title: EditorBase.STRINGS.title, use: EditorBase.USE, dir: this.get('dir'), extracss: this.get('extracss'), linkedcss: this.get('linkedcss'), defaultblock: this.get('defaultblock'), host: this }).plug(Y.Plugin.ExecCommand); frame.after('ready', Y.bind(this._afterFrameReady, this)); frame.addTarget(this); this.frame = frame; this.publish('nodeChange', { emitFacade: true, bubbles: true, defaultFn: this._defNodeChangeFn }); //this.plug(Y.Plugin.EditorPara); }, destructor: function() { this.frame.destroy(); this.detachAll(); }, /** * Copy certain styles from one node instance to another (used for new paragraph creation mainly) * @method copyStyles * @param {Node} from The Node instance to copy the styles from * @param {Node} to The Node instance to copy the styles to */ copyStyles: function(from, to) { if (from.test('a')) { //Don't carry the A styles return; } var styles = ['color', 'fontSize', 'fontFamily', 'backgroundColor', 'fontStyle' ], newStyles = {}; Y.each(styles, function(v) { newStyles[v] = from.getStyle(v); }); if (from.ancestor('b,strong')) { newStyles.fontWeight = 'bold'; } if (from.ancestor('u')) { if (!newStyles.textDecoration) { newStyles.textDecoration = 'underline'; } } to.setStyles(newStyles); }, /** * Holder for the selection bookmark in IE. * @property _lastBookmark * @private */ _lastBookmark: null, /** * Resolves the e.changedNode in the nodeChange event if it comes from the document. If * the event came from the document, it will get the last child of the last child of the document * and return that instead. * @method _resolveChangedNode * @param {Node} n The node to resolve * @private */ _resolveChangedNode: function(n) { var inst = this.getInstance(), lc, lc2, found; if (n && n.test(BODY)) { var sel = new inst.EditorSelection(); if (sel && sel.anchorNode) { n = sel.anchorNode; } } if (inst && n && n.test('html')) { lc = inst.one(BODY).one(LAST_CHILD); while (!found) { if (lc) { lc2 = lc.one(LAST_CHILD); if (lc2) { lc = lc2; } else { found = true; } } else { found = true; } } if (lc) { if (lc.test('br')) { if (lc.previous()) { lc = lc.previous(); } else { lc = lc.get('parentNode'); } } if (lc) { n = lc; } } } if (!n) { //Fallback to make sure a node is attached to the event n = inst.one(BODY); } return n; }, /** * The default handler for the nodeChange event. * @method _defNodeChangeFn * @param {Event} e The event * @private */ _defNodeChangeFn: function(e) { var startTime = (new Date()).getTime(); //Y.log('Default nodeChange function: ' + e.changedType, 'info', 'editor'); var inst = this.getInstance(), sel, cur, btag = inst.EditorSelection.DEFAULT_BLOCK_TAG; if (Y.UA.ie) { try { sel = inst.config.doc.selection.createRange(); if (sel.getBookmark) { this._lastBookmark = sel.getBookmark(); } } catch (ie) {} } e.changedNode = this._resolveChangedNode(e.changedNode); /* * @TODO * This whole method needs to be fixed and made more dynamic. * Maybe static functions for the e.changeType and an object bag * to walk through and filter to pass off the event to before firing.. */ switch (e.changedType) { case 'keydown': if (!Y.UA.gecko) { if (!EditorBase.NC_KEYS[e.changedEvent.keyCode] && !e.changedEvent.shiftKey && !e.changedEvent.ctrlKey && (e.changedEvent.keyCode !== 13)) { //inst.later(100, inst, inst.EditorSelection.cleanCursor); } } break; case 'tab': if (!e.changedNode.test('li, li *') && !e.changedEvent.shiftKey) { e.changedEvent.frameEvent.preventDefault(); Y.log('Overriding TAB key to insert HTML: HALTING', 'info', 'editor'); if (Y.UA.webkit) { this.execCommand('inserttext', '\t'); } else if (Y.UA.gecko) { this.frame.exec._command('inserthtml', EditorBase.TABKEY); } else if (Y.UA.ie) { this.execCommand('inserthtml', EditorBase.TABKEY); } } break; case 'backspace-up': // Fixes #2531090 - Joins text node strings so they become one for bidi if (Y.UA.webkit && e.changedNode) { e.changedNode.set('innerHTML', e.changedNode.get('innerHTML')); } break; } if (Y.UA.webkit && e.commands && (e.commands.indent || e.commands.outdent)) { /* * When executing execCommand 'indent or 'outdent' Webkit applies * a class to the BLOCKQUOTE that adds left/right margin to it * This strips that style so it is just a normal BLOCKQUOTE */ var bq = inst.all('.webkit-indent-blockquote, blockquote'); if (bq.size()) { bq.setStyle('margin', ''); } } var changed = this.getDomPath(e.changedNode, false), cmds = {}, family, fsize, classes = [], fColor = '', bColor = ''; if (e.commands) { cmds = e.commands; } var normal = false; Y.each(changed, function(el) { var tag = el.tagName.toLowerCase(), cmd = EditorBase.TAG2CMD[tag]; if (cmd) { cmds[cmd] = 1; } //Bold and Italic styles var s = el.currentStyle || el.style; if ((''+s.fontWeight) == 'normal') { normal = true; } if ((''+s.fontWeight) == 'bold') { //Cast this to a string cmds.bold = 1; } if (Y.UA.ie) { if (s.fontWeight > 400) { cmds.bold = 1; } } if (s.fontStyle == 'italic') { cmds.italic = 1; } if (s.textDecoration.indexOf('underline') > -1) { cmds.underline = 1; } if (s.textDecoration.indexOf('line-through') > -1) { cmds.strikethrough = 1; } var n = inst.one(el); if (n.getStyle('fontFamily')) { var family2 = n.getStyle('fontFamily').split(',')[0].toLowerCase(); if (family2) { family = family2; } if (family) { family = family.replace(/'/g, '').replace(/"/g, ''); } } fsize = EditorBase.NORMALIZE_FONTSIZE(n); var cls = el.className.split(' '); Y.each(cls, function(v) { if (v !== '' && (v.substr(0, 4) !== 'yui_')) { classes.push(v); } }); fColor = EditorBase.FILTER_RGB(n.getStyle('color')); var bColor2 = EditorBase.FILTER_RGB(s.backgroundColor); if (bColor2 !== 'transparent') { if (bColor2 !== '') { bColor = bColor2; } } }); if (normal) { delete cmds.bold; delete cmds.italic; } e.dompath = inst.all(changed); e.classNames = classes; e.commands = cmds; //TODO Dont' like this, not dynamic enough.. if (!e.fontFamily) { e.fontFamily = family; } if (!e.fontSize) { e.fontSize = fsize; } if (!e.fontColor) { e.fontColor = fColor; } if (!e.backgroundColor) { e.backgroundColor = bColor; } var endTime = (new Date()).getTime(); Y.log('_defNodeChangeTimer 2: ' + (endTime - startTime) + 'ms', 'info', 'selection'); }, /** * Walk the dom tree from this node up to body, returning a reversed array of parents. * @method getDomPath * @param {Node} node The Node to start from */ getDomPath: function(node, nodeList) { var domPath = [], domNode, inst = this.frame.getInstance(); domNode = inst.Node.getDOMNode(node); //return inst.all(domNode); while (domNode !== null) { if ((domNode === inst.config.doc.documentElement) || (domNode === inst.config.doc) || !domNode.tagName) { domNode = null; break; } if (!inst.DOM.inDoc(domNode)) { domNode = null; break; } //Check to see if we get el.nodeName and nodeType if (domNode.nodeName && domNode.nodeType && (domNode.nodeType == 1)) { domPath.push(domNode); } if (domNode == inst.config.doc.body) { domNode = null; break; } domNode = domNode.parentNode; } /*{{{ Using Node while (node !== null) { if (node.test('html') || node.test('doc') || !node.get('tagName')) { node = null; break; } if (!node.inDoc()) { node = null; break; } //Check to see if we get el.nodeName and nodeType if (node.get('nodeName') && node.get('nodeType') && (node.get('nodeType') == 1)) { domPath.push(inst.Node.getDOMNode(node)); } if (node.test('body')) { node = null; break; } node = node.get('parentNode'); } }}}*/ if (domPath.length === 0) { domPath[0] = inst.config.doc.body; } if (nodeList) { return inst.all(domPath.reverse()); } else { return domPath.reverse(); } }, /** * After frame ready, bind mousedown & keyup listeners * @method _afterFrameReady * @private */ _afterFrameReady: function() { var inst = this.frame.getInstance(); this.frame.on('dom:mouseup', Y.bind(this._onFrameMouseUp, this)); this.frame.on('dom:mousedown', Y.bind(this._onFrameMouseDown, this)); this.frame.on('dom:keydown', Y.bind(this._onFrameKeyDown, this)); if (Y.UA.ie) { this.frame.on('dom:activate', Y.bind(this._onFrameActivate, this)); this.frame.on('dom:beforedeactivate', Y.bind(this._beforeFrameDeactivate, this)); } this.frame.on('dom:keyup', Y.bind(this._onFrameKeyUp, this)); this.frame.on('dom:keypress', Y.bind(this._onFrameKeyPress, this)); this.frame.on('dom:paste', Y.bind(this._onPaste, this)); inst.EditorSelection.filter(); this.fire('ready'); }, /** * Caches the current cursor position in IE. * @method _beforeFrameDeactivate * @private */ _beforeFrameDeactivate: function(e) { if (e.frameTarget.test('html')) { //Means it came from a scrollbar return; } var inst = this.getInstance(), sel = inst.config.doc.selection.createRange(); if (sel.compareEndPoints && !sel.compareEndPoints('StartToEnd', sel)) { sel.pasteHTML('<var id="yui-ie-cursor">'); } }, /** * Moves the cached selection bookmark back so IE can place the cursor in the right place. * @method _onFrameActivate * @private */ _onFrameActivate: function(e) { if (e.frameTarget.test('html')) { //Means it came from a scrollbar return; } var inst = this.getInstance(), sel = new inst.EditorSelection(), range = sel.createRange(), cur = inst.all('#yui-ie-cursor'); if (cur.size()) { cur.each(function(n) { n.set('id', ''); if (range.moveToElementText) { try { range.moveToElementText(n._node); var moved = range.move('character', -1); if (moved === -1) { //Only move up if we actually moved back. range.move('character', 1); } range.select(); range.text = ''; } catch (e) {} } n.remove(); }); } }, /** * Fires nodeChange event * @method _onPaste * @private */ _onPaste: function(e) { this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'paste', changedEvent: e.frameEvent }); }, /** * Fires nodeChange event * @method _onFrameMouseUp * @private */ _onFrameMouseUp: function(e) { this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mouseup', changedEvent: e.frameEvent }); }, /** * Fires nodeChange event * @method _onFrameMouseDown * @private */ _onFrameMouseDown: function(e) { this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mousedown', changedEvent: e.frameEvent }); }, /** * Caches a copy of the selection for key events. Only creating the selection on keydown * @property _currentSelection * @private */ _currentSelection: null, /** * Holds the timer for selection clearing * @property _currentSelectionTimer * @private */ _currentSelectionTimer: null, /** * Flag to determine if we can clear the selection or not. * @property _currentSelectionClear * @private */ _currentSelectionClear: null, /** * Fires nodeChange event * @method _onFrameKeyDown * @private */ _onFrameKeyDown: function(e) { var inst, sel; if (!this._currentSelection) { if (this._currentSelectionTimer) { this._currentSelectionTimer.cancel(); } this._currentSelectionTimer = Y.later(850, this, function() { this._currentSelectionClear = true; }); inst = this.frame.getInstance(); sel = new inst.EditorSelection(e); this._currentSelection = sel; } else { sel = this._currentSelection; } inst = this.frame.getInstance(); sel = new inst.EditorSelection(); this._currentSelection = sel; if (sel && sel.anchorNode) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keydown', changedEvent: e.frameEvent }); if (EditorBase.NC_KEYS[e.keyCode]) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode], changedEvent: e.frameEvent }); this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-down', changedEvent: e.frameEvent }); } } }, /** * Fires nodeChange event * @method _onFrameKeyPress * @private */ _onFrameKeyPress: function(e) { var sel = this._currentSelection; if (sel && sel.anchorNode) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keypress', changedEvent: e.frameEvent }); if (EditorBase.NC_KEYS[e.keyCode]) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-press', changedEvent: e.frameEvent }); } } }, /** * Fires nodeChange event for keyup on specific keys * @method _onFrameKeyUp * @private */ _onFrameKeyUp: function(e) { var inst = this.frame.getInstance(), sel = new inst.EditorSelection(e); if (sel && sel.anchorNode) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keyup', selection: sel, changedEvent: e.frameEvent }); if (EditorBase.NC_KEYS[e.keyCode]) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-up', selection: sel, changedEvent: e.frameEvent }); } } if (this._currentSelectionClear) { this._currentSelectionClear = this._currentSelection = null; } }, /** * Pass through to the frame.execCommand method * @method execCommand * @param {String} cmd The command to pass: inserthtml, insertimage, bold * @param {String} val The optional value of the command: Helvetica * @return {Node/NodeList} The Node or Nodelist affected by the command. Only returns on override commands, not browser defined commands. */ execCommand: function(cmd, val) { var ret = this.frame.execCommand(cmd, val), inst = this.frame.getInstance(), sel = new inst.EditorSelection(), cmds = {}, e = { changedNode: sel.anchorNode, changedType: 'execcommand', nodes: ret }; switch (cmd) { case 'forecolor': e.fontColor = val; break; case 'backcolor': e.backgroundColor = val; break; case 'fontsize': e.fontSize = val; break; case 'fontname': e.fontFamily = val; break; } cmds[cmd] = 1; e.commands = cmds; this.fire('nodeChange', e); return ret; }, /** * Get the YUI instance of the frame * @method getInstance * @return {YUI} The YUI instance bound to the frame. */ getInstance: function() { return this.frame.getInstance(); }, /** * Renders the Y.Frame to the passed node. * @method render * @param {Selector/HTMLElement/Node} node The node to append the Editor to * @return {EditorBase} * @chainable */ render: function(node) { this.frame.set('content', this.get('content')); this.frame.render(node); return this; }, /** * Focus the contentWindow of the iframe * @method focus * @param {Function} fn Callback function to execute after focus happens * @return {EditorBase} * @chainable */ focus: function(fn) { this.frame.focus(fn); return this; }, /** * Handles the showing of the Editor instance. Currently only handles the iframe * @method show * @return {EditorBase} * @chainable */ show: function() { this.frame.show(); return this; }, /** * Handles the hiding of the Editor instance. Currently only handles the iframe * @method hide * @return {EditorBase} * @chainable */ hide: function() { this.frame.hide(); return this; }, /** * (Un)Filters the content of the Editor, cleaning YUI related code. //TODO better filtering * @method getContent * @return {String} The filtered content of the Editor */ getContent: function() { var html = '', inst = this.getInstance(); if (inst && inst.EditorSelection) { html = inst.EditorSelection.unfilter(); } //Removing the _yuid from the objects in IE html = html.replace(/ _yuid="([^>]*)"/g, ''); return html; } }, { /** * @static * @method NORMALIZE_FONTSIZE * @description Pulls the fontSize from a node, then checks for string values (x-large, x-small) * and converts them to pixel sizes. If the parsed size is different from the original, it calls * node.setStyle to update the node with a pixel size for normalization. */ NORMALIZE_FONTSIZE: function(n) { var size = n.getStyle('fontSize'), oSize = size; switch (size) { case '-webkit-xxx-large': size = '48px'; break; case 'xx-large': size = '32px'; break; case 'x-large': size = '24px'; break; case 'large': size = '18px'; break; case 'medium': size = '16px'; break; case 'small': size = '13px'; break; case 'x-small': size = '10px'; break; } if (oSize !== size) { n.setStyle('fontSize', size); } return size; }, /** * @static * @property TABKEY * @description The HTML markup to use for the tabkey */ TABKEY: '<span class="tab">&nbsp;&nbsp;&nbsp;&nbsp;</span>', /** * @static * @method FILTER_RGB * @param String css The CSS string containing rgb(#,#,#); * @description Converts an RGB color string to a hex color, example: rgb(0, 255, 0) converts to #00ff00 * @return String */ FILTER_RGB: function(css) { if (css.toLowerCase().indexOf('rgb') != -1) { var exp = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi"); var rgb = css.replace(exp, "$1,$2,$3,$4,$5").split(','); if (rgb.length == 5) { var r = parseInt(rgb[1], 10).toString(16); var g = parseInt(rgb[2], 10).toString(16); var b = parseInt(rgb[3], 10).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; css = "#" + r + g + b; } } return css; }, /** * @static * @property TAG2CMD * @description A hash table of tags to their execcomand's */ TAG2CMD: { 'b': 'bold', 'strong': 'bold', 'i': 'italic', 'em': 'italic', 'u': 'underline', 'sup': 'superscript', 'sub': 'subscript', 'img': 'insertimage', 'a' : 'createlink', 'ul' : 'insertunorderedlist', 'ol' : 'insertorderedlist' }, /** * Hash table of keys to fire a nodeChange event for. * @static * @property NC_KEYS * @type Object */ NC_KEYS: { 8: 'backspace', 9: 'tab', 13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 46: 'delete' }, /** * The default modules to use inside the Frame * @static * @property USE * @type Array */ USE: ['substitute', 'node', 'selector-css3', 'editor-selection', 'stylesheet'], /** * The Class Name: editorBase * @static * @property NAME */ NAME: 'editorBase', /** * Editor Strings. By default contains only the `title` property for the * Title of frame document (default "Rich Text Editor"). * * @static * @property STRINGS */ STRINGS: { title: 'Rich Text Editor' }, ATTRS: { /** * The content to load into the Editor Frame * @attribute content */ content: { value: '<br class="yui-cursor">', setter: function(str) { if (str.substr(0, 1) === "\n") { Y.log('Stripping first carriage return from content before injecting', 'warn', 'editor'); str = str.substr(1); } if (str === '') { str = '<br class="yui-cursor">'; } if (str === ' ') { if (Y.UA.gecko) { str = '<br class="yui-cursor">'; } } return this.frame.set('content', str); }, getter: function() { return this.frame.get('content'); } }, /** * The value of the dir attribute on the HTML element of the frame. Default: ltr * @attribute dir */ dir: { writeOnce: true, value: 'ltr' }, /** * @attribute linkedcss * @description An array of url's to external linked style sheets * @type String */ linkedcss: { value: '', setter: function(css) { if (this.frame) { this.frame.set('linkedcss', css); } return css; } }, /** * @attribute extracss * @description A string of CSS to add to the Head of the Editor * @type String */ extracss: { value: false, setter: function(css) { if (this.frame) { this.frame.set('extracss', css); } return css; } }, /** * @attribute defaultblock * @description The default tag to use for block level items, defaults to: p * @type String */ defaultblock: { value: 'p' } } }); Y.EditorBase = EditorBase; /** * @event nodeChange * @description Fired from several mouse/key/paste event points. * @param {Event.Facade} event An Event Facade object with the following specific properties added: * <dl> * <dt>changedEvent</dt><dd>The event that caused the nodeChange</dd> * <dt>changedNode</dt><dd>The node that was interacted with</dd> * <dt>changedType</dt><dd>The type of change: mousedown, mouseup, right, left, backspace, tab, enter, etc..</dd> * <dt>commands</dt><dd>The list of execCommands that belong to this change and the dompath that's associated with the changedNode</dd> * <dt>classNames</dt><dd>An array of classNames that are applied to the changedNode and all of it's parents</dd> * <dt>dompath</dt><dd>A sorted array of node instances that make up the DOM path from the changedNode to body.</dd> * <dt>backgroundColor</dt><dd>The cascaded backgroundColor of the changedNode</dd> * <dt>fontColor</dt><dd>The cascaded fontColor of the changedNode</dd> * <dt>fontFamily</dt><dd>The cascaded fontFamily of the changedNode</dd> * <dt>fontSize</dt><dd>The cascaded fontSize of the changedNode</dd> * </dl> * @type {Event.Custom} */ /** * @event ready * @description Fired after the frame is ready. * @param {Event.Facade} event An Event Facade object. * @type {Event.Custom} */ }, '3.7.2', {"requires": ["base", "frame", "node", "exec-command", "editor-selection"]});
spadin/coverphoto
node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/editor-base/editor-base-debug.js
JavaScript
mit
32,357
/** * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { fail } from '../util/assert'; /** * PersistencePromise<> is essentially a re-implementation of Promise<> except * it has a .next() method instead of .then() and .next() and .catch() callbacks * are executed synchronously when a PersistencePromise resolves rather than * asynchronously (Promise<> implementations use setImmediate() or similar). * * This is necessary to interoperate with IndexedDB which will automatically * commit transactions if control is returned to the event loop without * synchronously initiating another operation on the transaction. * * NOTE: .then() and .catch() only allow a single consumer, unlike normal * Promises. */ var PersistencePromise = /** @class */ (function () { function PersistencePromise(callback) { var _this = this; // NOTE: next/catchCallback will always point to our own wrapper functions, // not the user's raw next() or catch() callbacks. this.nextCallback = null; this.catchCallback = null; // When the operation resolves, we'll set result or error and mark isDone. this.result = undefined; this.error = null; this.isDone = false; // Set to true when .then() or .catch() are called and prevents additional // chaining. this.callbackAttached = false; callback(function (value) { _this.isDone = true; _this.result = value; if (_this.nextCallback) { // value should be defined unless T is Void, but we can't express // that in the type system. _this.nextCallback(value); } }, function (error) { _this.isDone = true; _this.error = error; if (_this.catchCallback) { _this.catchCallback(error); } }); } PersistencePromise.prototype.catch = function (fn) { return this.next(undefined, fn); }; PersistencePromise.prototype.next = function (nextFn, catchFn) { var _this = this; if (this.callbackAttached) { fail('Called next() or catch() twice for PersistencePromise'); } this.callbackAttached = true; if (this.isDone) { if (!this.error) { return this.wrapSuccess(nextFn, this.result); } else { return this.wrapFailure(catchFn, this.error); } } else { return new PersistencePromise(function (resolve, reject) { _this.nextCallback = function (value) { _this.wrapSuccess(nextFn, value).next(resolve, reject); }; _this.catchCallback = function (error) { _this.wrapFailure(catchFn, error).next(resolve, reject); }; }); } }; PersistencePromise.prototype.toPromise = function () { var _this = this; return new Promise(function (resolve, reject) { _this.next(resolve, reject); }); }; PersistencePromise.prototype.wrapUserFunction = function (fn) { try { var result = fn(); if (result instanceof PersistencePromise) { return result; } else { return PersistencePromise.resolve(result); } } catch (e) { return PersistencePromise.reject(e); } }; PersistencePromise.prototype.wrapSuccess = function (nextFn, value) { if (nextFn) { return this.wrapUserFunction(function () { return nextFn(value); }); } else { // If there's no nextFn, then R must be the same as T but we // can't express that in the type system. return PersistencePromise.resolve(value); } }; PersistencePromise.prototype.wrapFailure = function (catchFn, error) { if (catchFn) { return this.wrapUserFunction(function () { return catchFn(error); }); } else { return PersistencePromise.reject(error); } }; PersistencePromise.resolve = function (result) { return new PersistencePromise(function (resolve, reject) { resolve(result); }); }; PersistencePromise.reject = function (error) { return new PersistencePromise(function (resolve, reject) { reject(error); }); }; PersistencePromise.waitFor = function (all) { return all.reduce(function (promise, nextPromise, idx) { return promise.next(function () { return nextPromise; }); }, PersistencePromise.resolve()); }; PersistencePromise.map = function (all) { var results = []; var first = true; // initial is ignored, so we can cheat on the type. var initial = PersistencePromise.resolve(null); return all .reduce(function (promise, nextPromise) { return promise.next(function (result) { if (!first) { results.push(result); } first = false; return nextPromise; }); }, initial) .next(function (result) { results.push(result); return results; }); }; return PersistencePromise; }()); export { PersistencePromise }; //# sourceMappingURL=persistence_promise.js.map
aggiedefenders/aggiedefenders.github.io
node_modules/@firebase/firestore/dist/esm/src/local/persistence_promise.js
JavaScript
mit
6,111
MainIndexEstablishmentsListView = Backbone.View.extend({ events: { 'click .nav': 'navigate' }, initialize: function () { this.listenTo(this.collection, 'reset', this.render); }, render: function (e) { this.$el.html(''); if (this.collection.length > 0) { this.collection.each(function (establishment) { this.renderEstablishment(establishment); }, this); } else { this.$el.html(''); this.$el.html(render('establishments/index_no_results')); } }, renderEstablishment: function (establishment) { var establishment_view = new EstablishmentsIndexEstablishmentView({ tagName: 'li', model: establishment }); this.$el.append(establishment_view.el); }, navigate: function (e) { e.preventDefault(); App.navigate(e.target.pathname, { trigger: true }); } });
sealocal/yumhacker
app/assets/javascripts/views/main/index_establishments_list_view.js
JavaScript
mit
825
var rules = module.exports = []; function Checker(name, rule) { this.name = name; this.rule = rule; this.check = function(results) { var violations = [], that = this; results.filter(function(result) { return result.shortName !== '[[code]]'; }).forEach(function (result) { var violation = that.rule(result); if (violation) { if (!result.violations) { result.violations = []; } result.violations.push({ message: violation, source: that.name }); } violations.push(result); }); return violations; }; } rules.Checker = Checker; rules.push( new Checker("FunctionLength", function(result) { var config = result.config || {}; var functionLength = config.functionLength || 30; if (result.shortName !== 'module.exports' && result.lines > functionLength) { return result.shortName + " is " + result.lines + " lines long, maximum allowed is " + functionLength; } return null; }) ); rules.push( new Checker("CyclomaticComplexity", function(result) { var config = result.config || {}; var cyclomaticComplexity = config.cyclomaticComplexity || 10; if (result.complexity > cyclomaticComplexity) { return result.shortName + " has a cyclomatic complexity of " + result.complexity + ", maximum should be " + cyclomaticComplexity; } return null; }) ); rules.push( new Checker("NumberOfArguments", function(result) { var config = result.config || {}; var numberOfArguments = config.numberOfArguments || 5; if (result.ins > numberOfArguments) { return result.shortName + " has " + result.ins + " arguments, maximum allowed is " + numberOfArguments; } return null; }) );
yubin-huang/jscheckstyle
lib/rules.js
JavaScript
mit
1,979
const fs = require('fs'); const path = require('path'); const yoHelper = require('yeoman-test'); const yoAssert = require('yeoman-assert'); const generatorPath = '../packages/generator-emakinacee-react/generators/compute'; describe('Compute', () => { describe('without module', () => { before(() => { return yoHelper .run(path.join(__dirname, generatorPath)) .withArguments(['test-compute']); }); it('generates all files to shared location', () => { yoAssert.file([ './src/shared/computes/testCompute.js', './src/shared/computes/testCompute.spec.js', ]); }); it('compute file has valid content', (done) => { fs.readFile(path.join(__dirname, './snapshots/compute/compute.js'), 'utf8', (err, template) => { if (err) done(err); if (!template || template === '') done(new Error('Template snapshot does not exist or is empty')); yoAssert.fileContent( './src/shared/computes/testCompute.js', template ); done(); }); }); it('spec file has valid content', (done) => { fs.readFile(path.join(__dirname, './snapshots/compute/compute.spec.js'), 'utf8', (err, template) => { if (err) done(err); if (!template || template === '') done(new Error('Template snapshot does not exist or is empty')); yoAssert.fileContent( './src/shared/computes/testCompute.spec.js', template ); done(); }); }); }); describe('with module', () => { before(() => { return yoHelper .run(path.join(__dirname, generatorPath)) .withArguments(['test-compute', 'test-module']); }); it('generates all files to module location', () => { yoAssert.file([ './src/modules/TestModule/computes/testCompute.js', './src/modules/TestModule/computes/testCompute.spec.js', ]); }); it('compute file has valid content', (done) => { fs.readFile(path.join(__dirname, './snapshots/compute/compute.js'), 'utf8', (err, template) => { if (err) done(err); if (!template || template === '') done(new Error('Template snapshot does not exist or is empty')); yoAssert.fileContent( './src/modules/TestModule/computes/testCompute.js', template ); done(); }); }); it('spec file has valid content', (done) => { fs.readFile(path.join(__dirname, './snapshots/compute/compute.spec.js'), 'utf8', (err, template) => { if (err) done(err); if (!template || template === '') done(new Error('Template snapshot does not exist or is empty')); yoAssert.fileContent( './src/modules/TestModule/computes/testCompute.spec.js', template ); done(); }); }); }); });
emakina-cee-oss/generator-emakinacee-react
test/compute.test.js
JavaScript
mit
3,309
(function () { var KEY = { ENTER: 13, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40 }; function normalizeTokens(tokens) { return tokens.filter(function (token) { return !!token; }).map(function (token) { return token.toLowerCase(); }); } function newIndexNode() { return { ids: [], children: {} }; } function buildIndex(options) { var index = newIndexNode(); options.forEach(function (option, id) { var val = option.text || option.value, tokens = normalizeTokens(val.split(/\s+/)); tokens.forEach(function (token) { var ch, chars = token.split(''), node = index; while (ch = chars.shift()) { node = node.children[ch] || (node.children[ch] = newIndexNode()); node.ids.push(id); } }); }); return index; } function find(query, index, options) { var matches, tokens = normalizeTokens(query.split(/\s+/)); tokens.forEach(function (token) { var node = index, ch, chars = token.split(''); if (matches && matches.length === 0) { return false; } while (node && (ch = chars.shift())) { node = node.children[ch]; } if (node && chars.length === 0) { ids = node.ids.slice(0); matches = matches ? getIntersection(matches, ids) : ids; } else { matches = []; return false; } }); return matches ? unique(matches).map(function (id) { return options[id]; }) : []; } function unique(array) { var seen = {}, uniques = []; for (var i = 0; i < array.length; i++) { if (!seen[array[i]]) { seen[array[i]] = true; uniques.push(array[i]); } } return uniques; } function getIntersection(arrayA, arrayB) { var ai = 0, bi = 0, intersection = []; arrayA = arrayA.sort(compare); arrayB = arrayB.sort(compare); while (ai < arrayA.length && bi < arrayB.length) { if (arrayA[ai] < arrayB[bi]) { ai++; } else if (arrayA[ai] > arrayB[bi]) { bi++; } else { intersection.push(arrayA[ai]); ai++; bi++; } } return intersection; function compare(a, b) { return a - b; } } var BAutocompletePrototype = Object.create(HTMLElement.prototype, { options: { enumerable: true, get: function () { var list = document.querySelector('#' + this.getAttribute('list')); if (list && list.options) { CustomElements.upgrade(list); return Array.prototype.slice.call(list.options, 0); } return []; } }, index: { enumerable: true, get: function () { if (!this.__index) { this.__index = buildIndex(this.options); } return this.__index; } }, suggestionList: { enumerable: true, get: function () { return this.querySelector('ul'); } }, selectable: { enumerable: true, get: function () { return this.querySelector('b-selectable'); } }, input: { enumerable: true, get: function () { return this.querySelector('input[type=text]'); } }, createdCallback: { enumerable: true, value: function () { this.appendChild(this.template.content.cloneNode(true)); this.input.addEventListener('input', this.onInputChange.bind(this), false); this.input.addEventListener('focus', this.onInputFocus.bind(this), false); this.input.addEventListener('blur', this.onInputBlur.bind(this), false); this.selectable.addEventListener('mousedown', this.onSuggestionPick.bind(this), false); this.selectable.addEventListener('b-activate', this.pickSuggestion.bind(this), false); } }, handleAria: { enumerable: true, value: function () { this.setAttribute('role', 'combobox'); this.setAttribute('aria-autocomplete', 'list'); } }, onInputFocus: { enumerable: true, value: function (e) { this.keydownListener = this.keydownHandler.bind(this); this.input.addEventListener('keydown', this.keydownListener, false); } }, onInputBlur: { enumerable: true, value: function (e) { if (this.cancelBlur) { this.cancelBlur = false; return; } this.input.removeEventListener('keydown', this.keydownListener, false); this.hideSuggestionList(); } }, onSuggestionPick: { enumerable: true, value: function (e) { e.preventDefault(); this.cancelBlur = true; } }, keydownHandler: { enumerable: true, value: function (e) { e.stopPropagation(); switch (e.keyCode) { case KEY.ENTER: { this.selectable.activate(); break; } case KEY.DOWN: { if (!this.areSuggestionsVisible()) { this.showSuggestionList(); } else { this.selectable.selectNextItem(); } break; } case KEY.UP: { if (!this.areSuggestionsVisible()) { this.showSuggestionList(); } else { this.selectable.selectPreviousItem(); } break; } default: return; } e.preventDefault(); } }, onInputChange: { enumerable: true, value: function (e) { e.stopPropagation(); if (!this.areSuggestionsVisible()) { this.showSuggestionList(); this.input.focus(); } else { this.refreshSuggestionList(); } this.selectFirstSuggestion(); } }, filterOptions: { enumerable: true, value: function () { var query = this.input.value; if (!query) return this.options; return find(query, this.index, this.options); } }, paintSuggestionList: { enumerable: true, value: function () { this.selectable.unselect(); var list = this.suggestionList, options = this.filterOptions(); while (list.childNodes.length > 0) { list.removeChild(list.childNodes[0]); } options.forEach(function (option) { var li = document.createElement('li'); li.innerHTML = option.text || option.value; list.appendChild(li); }); } }, refreshSuggestionList: { enumerable: true, value: function () { this.paintSuggestionList(); } }, toggleSuggestionList: { enumerable: true, value: function (e) { if (e) { e.stopPropagation(); } this.areSuggestionsVisible() ? this.hideSuggestionList() : this.showSuggestionList(); this.input.focus(); } }, showSuggestionList: { enumerable: true, value: function () { this.paintSuggestionList(); this.selectable.setAttribute('visible', ''); } }, hideSuggestionList: { enumerable: true, value: function () { if (this.areSuggestionsVisible()) { this.selectable.removeAttribute('visible'); } } }, selectFirstSuggestion: { enumerable: true, value: function () { this.selectable.selectFirst(); } }, areSuggestionsVisible: { enumerable: true, value: function () { return this.selectable.hasAttribute('visible'); } }, pickSuggestion: { enumerable: true, value: function (e) { this.cancelBlur = false; this.input.value = this.getItemValue(e.detail.item); this.hideSuggestionList(); } }, getItemValue: { enumerable: true, value: function (itemIndex) { return this.querySelectorAll('li')[itemIndex].innerHTML; } } }); window.BAutocomplete = document.registerElement('b-autocomplete', { prototype: BAutocompletePrototype }); Object.defineProperty(BAutocompletePrototype, 'template', { get: function () { var fragment = document.createDocumentFragment(); var div = fragment.appendChild(document.createElement('div')); div.innerHTML = ' <input type="text" autocomplete="off" role="textbox" value=""> <b-selectable target="li"> <ul></ul> </b-selectable> '; while (child = div.firstChild) { fragment.insertBefore(child, div); } fragment.removeChild(div); return { content: fragment }; } }); }()); (function () { var BComboBoxPrototype = Object.create(BAutocomplete.prototype, { listToggle: { enumerable: true, get: function () { return this.querySelector('.b-combo-box-toggle'); } }, createdCallback: { enumerable: true, value: function () { this._super.createdCallback.call(this); this.listToggle.addEventListener('click', this.toggleSuggestionList.bind(this), false); } } }); window.BComboBox = document.registerElement('b-combo-box', { prototype: BComboBoxPrototype }); Object.defineProperty(BComboBox.prototype, '_super', { enumerable: false, writable: false, configurable: false, value: BAutocomplete.prototype }); Object.defineProperty(BComboBoxPrototype, 'template', { get: function () { var fragment = document.createDocumentFragment(); var div = fragment.appendChild(document.createElement('div')); div.innerHTML = ' <input type="text" autocomplete="off" role="textbox" value=""> <a class="b-combo-box-toggle"></a> <b-selectable target="li"> <ul></ul> </b-selectable> '; while (child = div.firstChild) { fragment.insertBefore(child, div); } fragment.removeChild(div); return { content: fragment }; } }); }());
bosonic-labs/b-autocomplete
dist/b-autocomplete.js
JavaScript
mit
12,927
const template = require("../../../layouts/hbs-loader")("base.ftl"); module.exports = template({ body: require("./html/body.ftl") });
chenwenzhang/frontend-scaffolding
src/pages/freemarker/index/html.js
JavaScript
mit
137
Jx().package("T.UI.Controls", function(J){ // 严格模式 'use strict'; var _crrentPluginId = 0; var defaults = { // 选项 // fooOption: true, // 覆写 类方法 // parseData: undefined, // 事件 // onFooSelected: undefined, // onFooChange: function(e, data){} timeZone: 'Etc/UTC', // format: false, format: 'YYYY-MM-DD HH:mm:ss', dayViewHeaderFormat: 'MMMM YYYY', // extraFormats: false, stepping: 1, minDate: false, maxDate: false, useCurrent: true, // collapse: true, // locale: moment.locale(), defaultDate: false, disabledDates: false, enabledDates: false, icons: { time: 'glyphicon glyphicon-time', date: 'glyphicon glyphicon-calendar', up: 'glyphicon glyphicon-chevron-up', down: 'glyphicon glyphicon-chevron-down', previous: 'glyphicon glyphicon-chevron-left', next: 'glyphicon glyphicon-chevron-right', today: 'glyphicon glyphicon-screenshot', clear: 'glyphicon glyphicon-trash', close: 'glyphicon glyphicon-remove' }, tooltips: { today: '现在', clear: '清除', close: '关闭', selectMonth: '选择月份', prevMonth: '上一月', nextMonth: '下一月', selectYear: '选择年份', prevYear: '上一年', nextYear: '下一年', selectDecade: '选择年代', prevDecade: '上一年代', nextDecade: '下一年代', prevCentury: '上一世纪', nextCentury: '下一世纪', pickHour: '选择小时', incrementHour: '增加小时', decrementHour: '减少小时', pickMinute: '选择分钟', incrementMinute: '增加分钟', decrementMinute: '减少分钟', pickSecond: '选择秒', incrementSecond: '增加秒', decrementSecond: '减少秒', togglePeriod: 'AM/PM', selectTime: '选择时间' }, // useStrict: false, // sideBySide: false, daysOfWeekDisabled: false, calendarWeeks: false, viewMode: 'days', // toolbarPlacement: 'default', showTodayButton: true, showClear: true, showClose: true, // widgetPositioning: { // horizontal: 'auto', // vertical: 'auto' // }, // widgetParent: null, ignoreReadonly: false, keepOpen: false, focusOnShow: true, inline: false, keepInvalid: false, datepickerInput: '.datepickerinput', // debug: false, allowInputToggle: false, disabledTimeIntervals: false, disabledHours: false, enabledHours: false, // viewValue: false }; var attributeMap = { // fooOption: 'foo-option' format: 'format' }; // 常量 var viewModes = ['days', 'months', 'years', 'decades'], keyMap = { 'up': 38, 38: 'up', 'down': 40, 40: 'down', 'left': 37, 37: 'left', 'right': 39, 39: 'right', 'tab': 9, 9: 'tab', 'escape': 27, 27: 'escape', 'enter': 13, 13: 'enter', 'pageUp': 33, 33: 'pageUp', 'pageDown': 34, 34: 'pageDown', 'shift': 16, 16: 'shift', 'control': 17, 17: 'control', 'space': 32, 32: 'space', 't': 84, 84: 't', 'delete': 46, 46: 'delete' }, keyState = {}; // moment.js 接口 function getMoment (format, d) { // var tzEnabled = false, // returnMoment, // currentZoneOffset, // incomingZoneOffset, // timeZoneIndicator, // dateWithTimeZoneInfo; // if (moment.tz !== undefined && this.settings.timeZone !== undefined && this.settings.timeZone !== null && this.settings.timeZone !== '') { // tzEnabled = true; // } // if (d === undefined || d === null) { // if (tzEnabled) { // returnMoment = moment().tz(this.settings.timeZone).startOf('d'); // } else { // returnMoment = moment().startOf('d'); // } // } else { // if (tzEnabled) { // currentZoneOffset = moment().tz(this.settings.timeZone).utcOffset(); // incomingZoneOffset = moment(d, parseFormats, this.settings.useStrict).utcOffset(); // if (incomingZoneOffset !== currentZoneOffset) { // timeZoneIndicator = moment().tz(this.settings.timeZone).format('Z'); // dateWithTimeZoneInfo = moment(d, parseFormats, this.settings.useStrict).format('YYYY-MM-DD[T]HH:mm:ss') + timeZoneIndicator; // returnMoment = moment(dateWithTimeZoneInfo, parseFormats, this.settings.useStrict).tz(this.settings.timeZone); // } else { // returnMoment = moment(d, parseFormats, this.settings.useStrict).tz(this.settings.timeZone); // } // } else { // returnMoment = moment(d, parseFormats, this.settings.useStrict); // } // } var returnMoment; if (d === undefined || d === null) { returnMoment= moment().startOf('d'); } else{ // returnMoment = moment(d, format, this.settings.useStrict); // Moment's parser is very forgiving, and this can lead to undesired behavior. // As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. // Strict parsing requires that the format and input match exactly. returnMoment = moment(d, format, false); } return returnMoment; } // 格式,细粒度 function isEnabled(format, granularity) { switch (granularity) { case 'y': return format.indexOf('Y') !== -1; case 'M': return format.indexOf('M') !== -1; case 'd': return format.toLowerCase().indexOf('d') !== -1; case 'h': case 'H': return format.toLowerCase().indexOf('h') !== -1; case 'm': return format.indexOf('m') !== -1; case 's': return format.indexOf('s') !== -1; default: return false; } } function hasTime(format) { return (isEnabled(format, 'h') || isEnabled(format, 'm') || isEnabled(format, 's')); } function hasDate(format) { return (isEnabled(format, 'y') || isEnabled(format, 'M') || isEnabled(format, 'd')); } function isValid(settings, targetMoment, granularity) { if (!targetMoment.isValid()) { return false; } if (settings.disabledDates && granularity === 'd' && settings.disabledDates[targetMoment.format('YYYY-MM-DD')] === true) { return false; } if (settings.enabledDates && granularity === 'd' && (settings.enabledDates[targetMoment.format('YYYY-MM-DD')] !== true)) { return false; } if (settings.minDate && targetMoment.isBefore(settings.minDate, granularity)) { return false; } if (settings.maxDate && targetMoment.isAfter(settings.maxDate, granularity)) { return false; } if (settings.daysOfWeekDisabled && granularity === 'd' && settings.daysOfWeekDisabled.indexOf(targetMoment.day()) !== -1) { return false; } if (settings.disabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && settings.disabledHours[targetMoment.format('H')] === true) { return false; } if (settings.enabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && (settings.enabledHours[targetMoment.format('H')] !== true)) { return false; } if (settings.disabledTimeIntervals && (granularity === 'h' || granularity === 'm' || granularity === 's')) { var found = false; $.each(settings.disabledTimeIntervals, function () { if (targetMoment.isBetween(this[0], this[1])) { found = true; return false; } }); if (found) { return false; } } return true; } // notifyEvent: function (e) { // if (e.type === 'dp.change' && ((e.date && e.date.isSame(e.oldDate)) || (!e.date && !e.oldDate))) { // return; // } // element.trigger(e); // }, var Widget=new J.Class({ defaults: defaults, attributeMap: attributeMap, settings: {}, value: null, // data: {}, // templates: {}, use24Hours: false, minViewModeNumber: 0, // 最小视图模式,选到这个模式以后关闭弹出窗口。 currentViewMode: 0, // 构造函数 init: function(elements, options){ this.inputElements = elements; // 直接使用容器类实例的设置 this.settings=options; // // TODO:临时措施 // this.use24Hours= false; // this.currentViewMode= 0; this.initFormatting(); // this.initSettings(options); // // this.value= this.element.val(); var now= getMoment(this.settings.format); this.value= now; this.viewValue=this.value; this.buildHtml(); this.initElements(); this.buildObservers(); this.bindEvents(); // this.bindEventsInterface(); this.refresh(); }, initFormatting: function () { // Time LT 8:30 PM // Time with seconds LTS 8:30:25 PM // Month numeral, day of month, year L 09/04/1986 // l 9/4/1986 // Month name, day of month, year LL September 4 1986 // ll Sep 4 1986 // Month name, day of month, year, time LLL September 4 1986 8:30 PM // lll Sep 4 1986 8:30 PM // Month name, day of month, day of week, year, time LLLL Thursday, September 4 1986 8:30 PM // llll Thu, Sep 4 1986 8:30 PM // var format= this.settings.format || 'L LT'; // var context= this; // this.actualFormat = format.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput) { // var value= context.getValue(); // var newinput = value.localeData().longDateFormat(formatInput) || formatInput; // return newinput.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput2) { //temp fix for #740 // return value.localeData().longDateFormat(formatInput2) || formatInput2; // }); // }); // parseFormats = this.settings.extraFormats ? this.settings.extraFormats.slice() : []; // parseFormats = []; // if (parseFormats.indexOf(format) < 0 && parseFormats.indexOf(this.actualFormat) < 0) { // parseFormats.push(this.actualFormat); // } // this.use24Hours = (this.actualFormat.toLowerCase().indexOf('a') < 1 && this.actualFormat.replace(/\[.*?\]/g, '').indexOf('h') < 1); this.use24Hours = (this.settings.format.toLowerCase().indexOf('a') < 1 && this.settings.format.replace(/\[.*?\]/g, '').indexOf('h') < 1); if (isEnabled(this.settings.format, 'y')) { this.minViewModeNumber = 2; } if (isEnabled(this.settings.format, 'M')) { this.minViewModeNumber = 1; } if (isEnabled(this.settings.format, 'd')) { this.minViewModeNumber = 0; } this.currentViewMode = Math.max(this.minViewModeNumber, this.currentViewMode); }, buildHtml: function(){ // 星期表头 var currentDate= this.viewValue.clone().startOf('w').startOf('d'); var htmlDow= this.settings.calendarWeeks === true ? '<th class="cw">#</th>' : ''; while (currentDate.isBefore(this.viewValue.clone().endOf('w'))) { htmlDow += '<th class="dow">'+currentDate.format('dd')+'</th>'; currentDate.add(1, 'd'); } htmlDow= '<tr>'+htmlDow+'</tr>'; // 月份 var monthsShort = this.viewValue.clone().startOf('y').startOf('d'); var htmlMonths= ''; while (monthsShort.isSame(this.viewValue, 'y')) { htmlMonths += '<span class="month" data-action="selectMonth">'+monthsShort.format('MMM')+'</span>'; monthsShort.add(1, 'M'); } // 日期视图 var dateView = ''+ '<div class="datepicker'+((hasDate(this.settings.format) && hasTime(this.settings.format)) ? ' col-md-6' : '')+'">'+ ' <div class="datepicker-days">'+ ' <table class="table-condensed">'+ ' <thead>'+ ' <tr>'+ ' <th class="prev" data-action="previous"><span class="'+this.settings.icons.previous+'" title="'+this.settings.tooltips.prevMonth+'"></span></th>'+ ' <th class="picker-switch" data-action="pickerSwitch" colspan="'+(this.settings.calendarWeeks ? '6' : '5')+'" title="'+this.settings.tooltips.selectMonth+'"></th>'+ ' <th class="next" data-action="next"><span class="'+this.settings.icons.next+'" title="'+this.settings.tooltips.nextMonth+'"></span></th>'+ ' </tr>'+ htmlDow+ ' </thead>'+ ' <tbody>'+ ' </tbody>'+ ' <table/>'+ ' </div>'+ ' <div class="datepicker-months">'+ ' <table class="table-condensed">'+ ' <thead>'+ ' <tr>'+ ' <th class="prev" data-action="previous"><span class="'+this.settings.icons.previous+'" title="'+this.settings.tooltips.prevYear+'"></span></th>'+ ' <th class="picker-switch" data-action="pickerSwitch" colspan="'+(this.settings.calendarWeeks ? '6' : '5')+'" title="'+this.settings.tooltips.selectYear+'"></th>'+ ' <th class="next" data-action="next"><span class="'+this.settings.icons.next+'" title="'+this.settings.tooltips.nextYear+'"></span></th>'+ ' </tr>'+ ' </thead>'+ ' <tbody>'+ ' <tr><td colspan="'+(this.settings.calendarWeeks ? '8' : '7')+'">'+htmlMonths+'</td></tr>'+ ' </tbody>'+ ' <table/>'+ ' </div>'+ ' <div class="datepicker-years">'+ ' <table class="table-condensed">'+ ' <thead>'+ ' <tr>'+ ' <th class="prev" data-action="previous"><span class="'+this.settings.icons.previous+'" title="'+this.settings.tooltips.prevDecade+'"></span></th>'+ ' <th class="picker-switch" data-action="pickerSwitch" colspan="'+(this.settings.calendarWeeks ? '6' : '5')+'" title="'+this.settings.tooltips.selectDecade+'"></th>'+ ' <th class="next" data-action="next"><span class="'+this.settings.icons.next+'" title="'+this.settings.tooltips.nextDecade+'"></span></th>'+ ' </tr>'+ ' </thead>'+ ' <tbody>'+ ' <tr><td colspan="'+(this.settings.calendarWeeks ? '8' : '7')+'"></td></tr>'+ ' </tbody>'+ ' <table/>'+ ' </div>'+ ' <div class="datepicker-decades">'+ ' <table class="table-condensed">'+ ' <thead>'+ ' <tr>'+ ' <th class="prev" data-action="previous"><span class="'+this.settings.icons.previous+'" title="'+this.settings.tooltips.prevCentury+'"></span></th>'+ ' <th class="picker-switch" data-action="pickerSwitch" colspan="'+(this.settings.calendarWeeks ? '6' : '5')+'"></th>'+ ' <th class="next" data-action="next"><span class="'+this.settings.icons.next+'" title="'+this.settings.tooltips.nextCentury+'"></span></th>'+ ' </tr>'+ ' </thead>'+ ' <tbody>'+ ' <tr><td colspan="'+(this.settings.calendarWeeks ? '8' : '7')+'"></td></tr>'+ ' </tbody>'+ ' <table/>'+ ' </div>'+ '</div>'; // 小时选择按钮 var htmlHours= ''; if(isEnabled(this.settings.format, 'h')){ var currentHour = this.viewValue.clone().startOf('d'); if (this.viewValue.hour() > 11 && !this.use24Hours) { currentHour.hour(12); } while (currentHour.isSame(this.viewValue, 'd') && (this.use24Hours || (this.viewValue.hour() < 12 && currentHour.hour() < 12) || this.viewValue.hour() > 11)) { if (currentHour.hour() % 4 === 0) { htmlHours += '<tr>'; } htmlHours += ''+ '<td data-action="selectHour" class="hour' + (!isValid(this.settings,currentHour, 'h') ? ' disabled' : '') + '">' + currentHour.format(this.use24Hours ? 'HH' : 'hh') + '</td>'; if (currentHour.hour() % 4 === 3) { htmlHours += '</tr>'; } currentHour.add(1, 'h'); } } // 分钟选择按钮 var htmlMinutes= ''; if(isEnabled(this.settings.format, 'm')){ var currentMinute = this.viewValue.clone().startOf('h'); var step = this.settings.stepping === 1 ? 5 : this.settings.stepping; while (this.viewValue.isSame(currentMinute, 'h')) { if (currentMinute.minute() % (step * 4) === 0) { htmlMinutes += '<tr>'; } htmlMinutes +=''+ '<td data-action="selectMinute" class="minute' + (!isValid(this.settings,currentMinute, 'm') ? ' disabled' : '') + '">' + currentMinute.format('mm') + '</td>'; if (currentMinute.minute() % (step * 4) === step * 3) { htmlMinutes += '</tr>'; } currentMinute.add(step, 'm'); } } // 秒选择按钮 var htmlSeconds= ''; if(isEnabled(this.settings.format, 's')){ var currentSecond = this.viewValue.clone().startOf('m'); while (this.viewValue.isSame(currentSecond, 'm')) { if (currentSecond.second() % 20 === 0) { htmlSeconds += '<tr>'; } htmlSeconds += ''+ '<td data-action="selectSecond" class="second' + (!isValid(this.settings,currentSecond, 's') ? ' disabled' : '') + '">' + currentSecond.format('ss') + '</td>'; if (currentSecond.second() % 20 === 15) { htmlSeconds += '</tr>'; } currentSecond.add(5, 's'); } } // 时间视图 var timeView = ''+ '<div class="timepicker'+((hasDate(this.settings.format) && hasTime(this.settings.format)) ? ' col-md-6' : '')+'">'+ ' <div class="timepicker-picker">'+ ' <table class="table-condensed">'+ ' <tr>'+ (isEnabled(this.settings.format, 'h') ? ' <td>'+ ' <a href="#" class="btn" data-action="incrementHours" tabindex="-1" title="'+this.settings.tooltips.incrementHour+'">'+ ' <span class="'+this.settings.icons.up+'"></span>'+ ' </a>'+ ' </td>' : '')+ (isEnabled(this.settings.format, 'm') ? ((isEnabled(this.settings.format, 'h') ? ' <td class="separator"></td>' : '')+ ' <td>'+ ' <a href="#" class="btn" data-action="incrementMinutes" tabindex="-1" title="'+this.settings.tooltips.incrementMinute+'">'+ ' <span class="'+this.settings.icons.up+'"></span>'+ ' </a>'+ ' </td>') : '')+ (isEnabled(this.settings.format, 's') ? ((isEnabled(this.settings.format, 'm') ? ' <td class="separator"></td>' : '')+ ' <td>'+ ' <a href="#" class="btn" data-action="incrementSeconds" tabindex="-1" title="'+this.settings.tooltips.incrementSecond+'">'+ ' <span class="'+this.settings.icons.up+'"></span>'+ ' </a>'+ ' </td>') : '')+ (this.use24Hours ? ' <td class="separator"></td>' : '')+ ' </tr>'+ ' <tr>'+ (isEnabled(this.settings.format, 'h') ? ' <td>'+ ' <span class="timepicker-hour" data-action="showHours" data-time-component="hours" title="'+this.settings.tooltips.pickHour+'"></span>'+ ' </td>' : '')+ (isEnabled(this.settings.format, 'm') ? ((isEnabled(this.settings.format, 'h') ? ' <td class="separator">:</td>' : '')+ ' <td>'+ ' <span class="timepicker-minute" data-action="showMinutes" data-time-component="minutes" title="'+this.settings.tooltips.pickMinute+'"></span>'+ ' </td>') : '')+ (isEnabled(this.settings.format, 's') ? ((isEnabled(this.settings.format, 'm') ? ' <td class="separator">:</td>' : '')+ ' <td>'+ ' <span class="timepicker-second" data-action="showSeconds" data-time-component="seconds" title="'+this.settings.tooltips.pickSecond+'"></span>'+ ' </td>') : '')+ (this.use24Hours ? ' <td class="separator">'+ ' <button class="btn btn-primary" data-action="togglePeriod" tabindex="-1" title="'+this.settings.tooltips.togglePeriod+'"></button>'+ ' </td>' : '')+ ' </tr>'+ ' <tr>'+ ' <td>'+ ' <a href="#" class="btn" data-action="decrementHours" tabindex="-1" title="'+this.settings.tooltips.decrementHour+'">'+ ' <span class="'+this.settings.icons.down+'"></span>'+ ' </a>'+ ' </td>'+ (isEnabled(this.settings.format, 'm') ? ((isEnabled(this.settings.format, 'h') ? ' <td class="separator"></td>' : '')+ ' <td>'+ ' <a href="#" class="btn" data-action="decrementMinutes" tabindex="-1" title="'+this.settings.tooltips.decrementMinute+'">'+ ' <span class="'+this.settings.icons.down+'"></span>'+ ' </a>'+ ' </td>') : '')+ (isEnabled(this.settings.format, 's') ? ((isEnabled(this.settings.format, 'm') ? ' <td class="separator"></td>' : '')+ ' <td>'+ ' <a href="#" class="btn" data-action="decrementSeconds" tabindex="-1" title="'+this.settings.tooltips.decrementSecond+'">'+ ' <span class="'+this.settings.icons.down+'"></span>'+ ' </a>'+ ' </td>') : '')+ (this.use24Hours ? ' <td class="separator"></td>' : '')+ ' </tr>'+ ' </table>'+ ' </div>'+ (isEnabled(this.settings.format, 'h') ? ' <div class="timepicker-hours">'+ ' <table class="table-condensed">'+htmlHours+'</table>'+ ' </div>' : '')+ (isEnabled(this.settings.format, 'm') ? ' <div class="timepicker-minutes">'+ ' <table class="table-condensed">'+htmlMinutes+'</table>'+ ' </div>' : '')+ (isEnabled(this.settings.format, 's') ? ' <div class="timepicker-seconds">'+ ' <table class="table-condensed">'+htmlSeconds+'</table>'+ ' </div>' : '')+ '</div>'; var toolbar2 = ''+ '<table class="table-condensed">'+ ' <tbody>'+ ' <tr>'+ (this.settings.showTodayButton ? ' <td><a data-action="today" title="'+this.settings.tooltips.today+'"><span class="'+this.settings.icons.today+'"></span></a></td>' : '')+ // ((!this.settings.sideBySide && hasDate(this.settings.format) && hasTime(this.settings.format))? // ' <td><a data-action="togglePicker" title="'+this.settings.tooltips.selectTime+'"><span class="'+this.settings.icons.time+'"></span></a></td>' : '')+ (this.settings.showClear ? ' <td><a data-action="clear" title="'+this.settings.tooltips.clear+'"><span class="'+this.settings.icons.clear+'"></span></a></td>' : '')+ (this.settings.showClose ? ' <td><a data-action="close" title="'+this.settings.tooltips.close+'"><span class="'+this.settings.icons.close+'"></span></a></td>' : '')+ ' </tr>'+ ' </tbody>'+ '</table>'; // var toolbar = '<li class="'+'picker-switch' + (this.settings.collapse ? ' accordion-toggle' : '')+'">'+toolbar2+'<li>'; var toolbar = '<li class="picker-switch">'+toolbar2+'<li>'; var templateCssClass= 't-dtpicker-widget'; if (!this.settings.inline) { templateCssClass += ' dropdown-menu'; } if (this.use24Hours) { templateCssClass += ' usetwentyfour'; } if (isEnabled(this.settings.format, 's') && !this.use24Hours) { templateCssClass += ' wider'; } var htmlTemplate = ''; if (hasDate(this.settings.format) && hasTime(this.settings.format)) { htmlTemplate = ''+ '<div class="'+templateCssClass+' timepicker-sbs">'+ ' <div class="row">'+ dateView+ timeView+ toolbar+ ' </div>'+ '</div>'; } else{ htmlTemplate = ''+ '<div class="'+templateCssClass+'">'+ ' <ul class="list-unstyled">'+ (hasDate(this.settings.format) ? ' <li>'+dateView+'</li>' : '')+ // '+(this.settings.collapse && hasTime(this.settings.format) ? ' class="collapse in"' : '')+' (hasTime(this.settings.format) ? ' <li>'+dateView+'</li>' : '')+ // '+(this.settings.collapse && hasTime(this.settings.format) ? ' class="collapse in"' : '')+' ' <li>'+toolbar+'</li>'+ ' </ul>'+ '</div>'; } this.container= $(htmlTemplate); this.inputElements.view.after(this.container); // this.inputElements.widgetContainer.append(this.container); }, initElements: function(){ // var context= this; this.elements={ // original: this.element//, decades: $('.datepicker-decades', this.container), years: $('.datepicker-years', this.container), months: $('.datepicker-months', this.container), days: $('.datepicker-days', this.container), hour: $('.timepicker-hour', this.container), hours: $('.timepicker-hours', this.container), minute: $('.timepicker-minute', this.container), minutes: $('.timepicker-minutes', this.container), second: $('.timepicker-second', this.container), seconds: $('.timepicker-seconds', this.container)//, // view: $('input[type=text]', this.container) // getTab: function(levelIndex){ // var tabSelector='.t-level-tab-'+levelIndex; // return $(tabSelector, context.container); // } }; if(this.settings.inline){ this.show(); } this.elements.hours.hide(); this.elements.minutes.hide(); this.elements.seconds.hide(); }, buildObservers: function(){ var context= this; var datePickerModes= [ { navFnc: 'M', navStep: 1 }, { navFnc: 'y', navStep: 1 }, { navFnc: 'y', navStep: 10 }, { navFnc: 'y', navStep: 100 } ]; this.observers= { next: function () { var navStep = datePickerModes[this.currentViewMode].navStep; var navFnc = datePickerModes[this.currentViewMode].navFnc; this.viewValue.add(navStep, navFnc); // TODO: with ViewMode this.refreshDate(); // viewUpdate(navFnc); }, previous: function () { var navFnc = datePickerModes[this.currentViewMode].navFnc; var navStep = datePickerModes[this.currentViewMode].navStep; this.viewValue.subtract(navStep, navFnc); // TODO: with ViewMode this.refreshDate(); // viewUpdate(navFnc); }, pickerSwitch: function () { this.showMode(1); }, selectMonth: function (e) { var month = $(e.target).closest('tbody').find('span').index($(e.target)); this.viewValue.month(month); if (this.currentViewMode === this.minViewModeNumber) { this.setValue(this.value.clone().year(this.viewValue.year()).month(this.viewValue.month())); if (!this.settings.inline) { this.hide(); } } else { this.showMode(-1); // fillDate(); this.refreshDays(); } // viewUpdate('M'); }, selectYear: function (e) { var year = parseInt($(e.target).text(), 10) || 0; this.viewValue.year(year); if (this.currentViewMode === this.minViewModeNumber) { this.setValue(this.value.clone().year(this.viewValue.year())); if (!this.settings.inline) { this.hide(); } } else { this.showMode(-1); this.refreshMonths(); } // viewUpdate('YYYY'); }, selectDecade: function (e) { var year = parseInt($(e.target).data('selection'), 10) || 0; this.viewValue.year(year); if (this.currentViewMode === this.minViewModeNumber) { this.setValue(this.value.clone().year(this.viewValue.year())); if (!this.settings.inline) { this.hide(); } } else { this.showMode(-1); this.refreshYears(); } // viewUpdate('YYYY'); }, selectDay: function (e) { var day = this.viewValue.clone(); if ($(e.target).is('.old')) { day.subtract(1, 'M'); } if ($(e.target).is('.new')) { day.add(1, 'M'); } this.setValue(day.date(parseInt($(e.target).text(), 10))); if (!hasTime(this.settings.format) && !this.settings.keepOpen && !this.settings.inline) { this.hide(); } }, incrementHours: function () { var newDate = this.value.clone().add(1, 'h'); if (isValid(this.settings,newDate, 'h')) { this.setValue(newDate); } }, incrementMinutes: function () { var newDate = this.value.clone().add(this.settings.stepping, 'm'); if (isValid(this.settings,newDate, 'm')) { this.setValue(newDate); } }, incrementSeconds: function () { var newDate = this.value.clone().add(1, 's'); if (isValid(this.settings,newDate, 's')) { this.setValue(newDate); } }, decrementHours: function () { var newDate = this.value.clone().subtract(1, 'h'); if (isValid(this.settings,newDate, 'h')) { this.setValue(newDate); } }, decrementMinutes: function () { var newDate = this.value.clone().subtract(this.settings.stepping, 'm'); if (isValid(this.settings,newDate, 'm')) { this.setValue(newDate); } }, decrementSeconds: function () { var newDate = this.value.clone().subtract(1, 's'); if (isValid(this.settings,newDate, 's')) { this.setValue(newDate); } }, togglePeriod: function () { this.setValue(this.value.clone().add((this.value.hours() >= 12) ? -12 : 12, 'h')); }, // togglePicker: function (e) { // var $this = $(e.target), // $parent = $this.closest('ul'), // expanded = $parent.find('.in'), // closed = $parent.find('.collapse:not(.in)'), // collapseData; // if (expanded && expanded.length) { // collapseData = expanded.data('collapse'); // if (collapseData && collapseData.transitioning) { // return; // } // if (expanded.collapse) { // if collapse plugin is available through bootstrap.js then use it // expanded.collapse('hide'); // closed.collapse('show'); // } else { // otherwise just toggle in class on the two views // expanded.removeClass('in'); // closed.addClass('in'); // } // if ($this.is('span')) { // $this.toggleClass(this.settings.icons.time + ' ' + this.settings.icons.date); // } else { // $this.find('span').toggleClass(this.settings.icons.time + ' ' + this.settings.icons.date); // } // // NOTE: uncomment if toggled state will be restored in show() // //if (component) { // // component.find('span').toggleClass(this.settings.icons.time + ' ' + this.settings.icons.date); // //} // } // }, showPicker: function () { context.container.find('.timepicker > div:not(.timepicker-picker)').hide(); context.container.find('.timepicker .timepicker-picker').show(); }, showHours: function () { context.container.find('.timepicker .timepicker-picker').hide(); context.container.find('.timepicker .timepicker-hours').show(); }, showMinutes: function () { context.container.find('.timepicker .timepicker-picker').hide(); context.container.find('.timepicker .timepicker-minutes').show(); }, showSeconds: function () { context.container.find('.timepicker .timepicker-picker').hide(); context.container.find('.timepicker .timepicker-seconds').show(); }, selectHour: function (e) { var hour = parseInt($(e.target).text(), 10); if (!this.use24Hours) { if (this.value.hours() >= 12) { if (hour !== 12) { hour += 12; } } else { if (hour === 12) { hour = 0; } } } this.setValue(this.value.clone().hours(hour)); this.observers.showPicker.call(this); }, selectMinute: function (e) { this.setValue(this.value.clone().minutes(parseInt($(e.target).text(), 10))); this.observers.showPicker(); }, selectSecond: function (e) { this.setValue(this.value.clone().seconds(parseInt($(e.target).text(), 10))); this.observers.showPicker(); }, clear: function(){ this.clear(); }, today: function () { var todaysDate = getMoment(); if (isValid(this.settings,todaysDate, 'd')) { this.setValue(todaysDate); } }, close: function(){ this.hide(); } }; this.keyBinds= { up: function (widget) { if (!widget) { return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(7, 'd')); } else { this.date(d.clone().add(this.stepping(), 'm')); } }, down: function (widget) { if (!widget) { this.show(); return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(7, 'd')); } else { this.date(d.clone().subtract(this.stepping(), 'm')); } }, 'control up': function (widget) { if (!widget) { return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'y')); } else { this.date(d.clone().add(1, 'h')); } }, 'control down': function (widget) { if (!widget) { return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'y')); } else { this.date(d.clone().subtract(1, 'h')); } }, left: function (widget) { if (!widget) { return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'd')); } }, right: function (widget) { if (!widget) { return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'd')); } }, pageUp: function (widget) { if (!widget) { return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'M')); } }, pageDown: function (widget) { if (!widget) { return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'M')); } }, enter: function () { this.hide(); }, escape: function () { this.hide(); }, //tab: function (widget) { //this break the flow of the form. disabling for now // var toggle = widget.find('.picker-switch a[data-action="togglePicker"]'); // if(toggle.length > 0) toggle.click(); //}, 'control space': function (widget) { if (widget.find('.timepicker').is(':visible')) { widget.find('.btn[data-action="togglePeriod"]').click(); } }, t: function () { this.date(getMoment(this.settings.format)); }, 'delete': function () { this.clear(); } }; }, bindEvents: function(){ var context= this; var element= this.element; this.inputElements.button.on('click', $.proxy(this.show, this)); this.container.on('click', '[data-action]', $.proxy(this.doAction, this)); // this handles clicks on the widget this.container.on('mousedown', false); $(window).on('resize', $.proxy(this.place, this)); // element.on('click', $.proxy(this.onFooClick, this)); }, // bindEventsInterface: function(){ // var context= this; // var element= this.element; // if(this.settings.onFooSelected){ // element.on('click.t.template', $.proxy(this.settings.onFooSelected, this)); // } // }, render: function(){}, // 事件处理 // onFooClick: function(e, data){ // ; // }, place: function () { // var position = (component || element).position(), // offset = (component || element).offset(), var position = this.inputElements.view.position(); var offset = this.inputElements.view.offset(); // vertical = this.settings.widgetPositioning.vertical, // horizontal = this.settings.widgetPositioning.horizontal, var vertical; var horizontal; var parent; // if (this.settings.widgetParent) { // parent = this.settings.widgetParent.append(widget); // } else if (element.is('input')) { // parent = this.inputElements.view.after(this.container).parent(); // } else if (this.settings.inline) { // parent = this.inputElements.view.append(widget); // return; // } else { // parent = this.inputElements.view; // this.inputElements.view.children().first().after(widget); // } parent = this.inputElements.view.parent(); // Top and bottom logic // if (vertical === 'auto') { if (offset.top + this.container.height() * 1.5 >= $(window).height() + $(window).scrollTop() && this.container.height() + this.inputElements.view.outerHeight() < offset.top) { vertical = 'top'; } else { vertical = 'bottom'; } // } // // Left and right logic // if (horizontal === 'auto') { if (parent.width() < offset.left + this.container.outerWidth() / 2 && offset.left + this.container.outerWidth() > $(window).width()) { horizontal = 'right'; } else { horizontal = 'left'; } // } if (vertical === 'top') { this.container.addClass('top').removeClass('bottom'); } else { this.container.addClass('bottom').removeClass('top'); } if (horizontal === 'right') { this.container.addClass('pull-right'); } else { this.container.removeClass('pull-right'); } // find the first parent element that has a relative css positioning if (parent.css('position') !== 'relative') { parent = parent.parents().filter(function () { return $(this).css('position') === 'relative'; }).first(); } // if (parent.length === 0) { // throw new Error('datetimepicker component should be placed within a relative positioned container'); // } this.container.css({ top: vertical === 'top' ? 'auto' : position.top + this.inputElements.view.outerHeight(), bottom: vertical === 'top' ? position.top + this.inputElements.view.outerHeight() : 'auto', left: horizontal === 'left' ? (parent === this.inputElements.view ? 0 : position.left) : 'auto', right: horizontal === 'left' ? 'auto' : parent.outerWidth() - this.inputElements.view.outerWidth() - (parent === this.inputElements.view ? 0 : position.left) }); }, // viewUpdate: function (e) { // if (e === 'y') { // e = 'YYYY'; // } // // notifyEvent({ // // type: 'dp.update', // // change: e, // // viewValue: this.viewValue.clone() // // }); // }, // dir 方向 加一或减一 showMode: function (dir) { if (dir) { this.currentViewMode = Math.max(this.minViewModeNumber, Math.min(3, this.currentViewMode + dir)); } // this.container.find('.datepicker > div').hide().filter('.datepicker-' + datePickerModes[this.currentViewMode].clsName).show(); this.container.find('.datepicker > div').hide().filter('.datepicker-' + viewModes[this.currentViewMode]).show(); }, fillDate: function () { }, fillTime: function () { }, // update: function () { // if (!widget) { // return; // } // fillDate(); // fillTime(); // }, // setValue: function (targetMoment) { // var oldDate = unset ? null : this.value; // // case of calling setValue(null or false) // if (!targetMoment) { // unset = true; // input.val(''); // element.data('date', ''); // notifyEvent({ // type: 'dp.change', // date: false, // oldDate: oldDate // }); // update(); // return; // } // targetMoment = targetMoment.clone().locale(this.settings.locale); // if (this.settings.stepping !== 1) { // targetMoment.minutes((Math.round(targetMoment.minutes() / this.settings.stepping) * this.settings.stepping) % 60).seconds(0); // } // if (isValid(this.settings,targetMoment)) { // this.value = targetMoment; // this.viewValue = this.value.clone(); // input.val(this.value.format(this.actualFormat)); // element.data('date', this.value.format(this.actualFormat)); // unset = false; // update(); // notifyEvent({ // type: 'dp.change', // date: this.value.clone(), // oldDate: oldDate // }); // } else { // if (!this.settings.keepInvalid) { // input.val(unset ? '' : this.value.format(this.actualFormat)); // } // notifyEvent({ // type: 'dp.error', // date: targetMoment // }); // } // }, hide: function () { ///<summary>Hides the widget. Possibly will emit dp.hide</summary> // var transitioning = false; // if (!widget) { // return picker; // } // Ignore event if in the middle of a picker transition // this.container.find('.collapse').each(function () { // var collapseData = $(this).data('collapse'); // if (collapseData && collapseData.transitioning) { // transitioning = true; // return false; // } // return true; // }); // if (transitioning) { // return;// picker; // } // if (component && component.hasClass('btn')) { // component.toggleClass('active'); this.inputElements.button.toggleClass('active'); // } this.container.hide(); $(window).off('resize', this.place); this.container.off('click', '[data-action]'); this.container.off('mousedown', false); // this.container.remove(); // widget = false; // notifyEvent({ // type: 'dp.hide', // date: this.value.clone() // }); this.inputElements.view.blur(); // return picker; }, clear: function () { this.setValue(null); this.viewValue= getMoment(this.settings.format); }, /******************************************************************************** * * Widget UI interaction functions * ********************************************************************************/ doAction: function (e) { var jqTarget= $(e.currentTarget); if (jqTarget.is('.disabled')) { return false; } var action= jqTarget.data('action'); this.observers[action].apply(this, arguments); return false; }, show: function () { if(this.inputElements.original.prop('disabled')){ return; } // ///<summary>Shows the widget. Possibly will emit dp.show and dp.change</summary> // var currentMoment, // useCurrentGranularity = { // 'year': function (m) { // return m.month(0).date(1).hours(0).seconds(0).minutes(0); // }, // 'month': function (m) { // return m.date(1).hours(0).seconds(0).minutes(0); // }, // 'day': function (m) { // return m.hours(0).seconds(0).minutes(0); // }, // 'hour': function (m) { // return m.seconds(0).minutes(0); // }, // 'minute': function (m) { // return m.seconds(0); // } // }; // if (input.prop('disabled') || (!this.settings.ignoreReadonly && input.prop('readonly')) || widget) { // return picker; // } // if (input.val() !== undefined && input.val().trim().length !== 0) { // setValue(this.parseInputDate(input.val().trim())); // // } else if (this.settings.useCurrent && unset && ((input.is('input') && input.val().trim().length === 0) || this.settings.inline)) { // } else if (this.settings.useCurrent && ((input.is('input') && input.val().trim().length === 0) || this.settings.inline)) { // currentMoment = getMoment(); // if (typeof this.settings.useCurrent === 'string') { // currentMoment = useCurrentGranularity[this.settings.useCurrent](currentMoment); // } // setValue(currentMoment); // } // widget = getTemplate(); // fillDow(); // fillMonths(); // widget.find('.timepicker-hours').hide(); // widget.find('.timepicker-minutes').hide(); // widget.find('.timepicker-seconds').hide(); // update(); // if (component && component.hasClass('btn')) { // component.toggleClass('active'); // } // widget.show(); this.showMode(); this.place(); this.container.show(); // if (this.settings.focusOnShow && !input.is(':focus')) { // input.focus(); // } // notifyEvent({ // type: 'dp.show' // }); // return picker; }, toggle: function () { /// <summary>Shows or hides the widget</summary> return (widget ? hide() : show()); }, keydown: function (e) { var handler = null, index, index2, pressedKeys = [], pressedModifiers = {}, currentKey = e.which, keyBindKeys, allModifiersPressed, pressed = 'p'; keyState[currentKey] = pressed; for (index in keyState) { if (keyState.hasOwnProperty(index) && keyState[index] === pressed) { pressedKeys.push(index); if (parseInt(index, 10) !== currentKey) { pressedModifiers[index] = true; } } } for (index in this.settings.keyBinds) { if (this.settings.keyBinds.hasOwnProperty(index) && typeof (this.settings.keyBinds[index]) === 'function') { keyBindKeys = index.split(' '); if (keyBindKeys.length === pressedKeys.length && keyMap[currentKey] === keyBindKeys[keyBindKeys.length - 1]) { allModifiersPressed = true; for (index2 = keyBindKeys.length - 2; index2 >= 0; index2--) { if (!(keyMap[keyBindKeys[index2]] in pressedModifiers)) { allModifiersPressed = false; break; } } if (allModifiersPressed) { handler = this.settings.keyBinds[index]; break; } } } } if (handler) { handler.call(picker, widget); e.stopPropagation(); e.preventDefault(); } }, keyup: function (e) { keyState[e.which] = 'r'; e.stopPropagation(); e.preventDefault(); }, change: function (e) { var val = $(e.target).val().trim(), parsedDate = val ? this.parseInputDate(val) : null; setValue(parsedDate); e.stopImmediatePropagation(); return false; }, indexGivenDates: function (givenDatesArray) { // Store given enabledDates and disabledDates as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledDates['2014-02-27'] === true) var givenDatesIndexed = {}; $.each(givenDatesArray, function () { var dDate = this.parseInputDate(this); if (dDate.isValid()) { givenDatesIndexed[dDate.format('YYYY-MM-DD')] = true; } }); return (Object.keys(givenDatesIndexed).length) ? givenDatesIndexed : false; }, indexGivenHours: function (givenHoursArray) { // Store given enabledHours and disabledHours as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledHours['2014-02-27'] === true) var givenHoursIndexed = {}; $.each(givenHoursArray, function () { givenHoursIndexed[this] = true; }); return (Object.keys(givenHoursIndexed).length) ? givenHoursIndexed : false; }, // API refresh: function(){ this.refreshDate(); this.refreshTime(); }, refreshDate: function(){ if (!hasDate(this.settings.format)) { return; } this.refreshDecades(); this.refreshYears(); this.refreshMonths(); this.refreshDays(); }, refreshDecades: function(){ var decadesViewHeader = this.elements.decades.find('th'); var startDecade = moment({y: this.viewValue.year() - (this.viewValue.year() % 100) - 1}); var startedAt = startDecade.clone(); var endDecade = startDecade.clone().add(100, 'y'); this.elements.decades.find('.disabled').removeClass('disabled'); if (startDecade.isSame(moment({y: 1900})) || (this.settings.minDate && this.settings.minDate.isAfter(startDecade, 'y'))) { decadesViewHeader.eq(0).addClass('disabled'); } decadesViewHeader.eq(1).text(startDecade.year() + '-' + endDecade.year()); if (startDecade.isSame(moment({y: 2000})) || (this.settings.maxDate && this.settings.maxDate.isBefore(endDecade, 'y'))) { decadesViewHeader.eq(2).addClass('disabled'); } var htmlTemplate = ''; while (!startDecade.isAfter(endDecade, 'y')) { htmlTemplate += ''+ '<span '+ ' data-action="selectDecade" '+ ' class="decade' + (startDecade.isSame(this.value, 'y') ? ' active' : '') + (!isValid(this.settings,startDecade, 'y') ? ' disabled' : '') + '" '+ ' data-selection="' + (startDecade.year() + 6) + '">' + (startDecade.year() + 1) + ' - ' + (startDecade.year() + 12) + '</span>'; startDecade.add(12, 'y'); } htmlTemplate += '<span></span><span></span><span></span>'; //push the dangling block over, at least this way it's even this.elements.decades.find('td').html(htmlTemplate); decadesViewHeader.eq(1).text((startedAt.year() + 1) + '-' + (startDecade.year())); }, refreshYears: function(){ var yearsViewHeader = this.elements.years.find('th'); var startYear = this.viewValue.clone().subtract(5, 'y'); var endYear = this.viewValue.clone().add(6, 'y'); this.elements.years.find('.disabled').removeClass('disabled'); if (this.settings.minDate && this.settings.minDate.isAfter(startYear, 'y')) { yearsViewHeader.eq(0).addClass('disabled'); } yearsViewHeader.eq(1).text(startYear.year() + '-' + endYear.year()); if (this.settings.maxDate && this.settings.maxDate.isBefore(endYear, 'y')) { yearsViewHeader.eq(2).addClass('disabled'); } var htmlTemplate = ''; while (!startYear.isAfter(endYear, 'y')) { htmlTemplate += ''+ '<span '+ ' data-action="selectYear" '+ ' class="year' + (startYear.isSame(this.value, 'y') ? ' active' : '') + (!isValid(this.settings,startYear, 'y') ? ' disabled' : '') + '">' + startYear.year() + '</span>'; startYear.add(1, 'y'); } this.elements.years.find('td').html(htmlTemplate); }, refreshMonths: function(){ var monthsViewHeader = this.elements.months.find('th'); var months = this.elements.months.find('tbody').find('span'); this.elements.months.find('.disabled').removeClass('disabled'); if (!isValid(this.settings,this.viewValue.clone().subtract(1, 'y'), 'y')) { monthsViewHeader.eq(0).addClass('disabled'); } monthsViewHeader.eq(1).text(this.viewValue.year()); if (!isValid(this.settings,this.viewValue.clone().add(1, 'y'), 'y')) { monthsViewHeader.eq(2).addClass('disabled'); } // 当前月 months.removeClass('active'); if (this.value.isSame(this.viewValue, 'y')) { months.eq(this.value.month()).addClass('active'); } var context= this; months.each(function (index) { if (!isValid(context.settings,context.viewValue.clone().month(index), 'M')) { $(this).addClass('disabled'); } }); }, refreshDays: function(){ var daysViewHeader = this.elements.days.find('th'); this.elements.days.find('.disabled').removeClass('disabled'); if (!isValid(this.settings,this.viewValue.clone().subtract(1, 'M'), 'M')) { daysViewHeader.eq(0).addClass('disabled'); } daysViewHeader.eq(1).text(this.viewValue.format(this.settings.dayViewHeaderFormat)); if (!isValid(this.settings,this.viewValue.clone().add(1, 'M'), 'M')) { daysViewHeader.eq(2).addClass('disabled'); } // 本月第一个星期的第一天 var currentDate = this.viewValue.clone().startOf('M').startOf('w').startOf('d'); var htmlTemplate= ''; for (var i = 0; i < 42; i++) { //always display 42 days (should show 6 weeks) var clsName = ''; if (currentDate.isBefore(this.viewValue, 'M')) { clsName += ' old'; } if (currentDate.isAfter(this.viewValue, 'M')) { clsName += ' new'; } if (currentDate.isSame(this.value, 'd')) { clsName += ' active'; } if (!isValid(this.settings,currentDate, 'd')) { clsName += ' disabled'; } if (currentDate.isSame(getMoment(), 'd')) { clsName += ' today'; } if (currentDate.day() === 0 || currentDate.day() === 6) { clsName += ' weekend'; } htmlTemplate += ''+ (currentDate.weekday() === 0 ? '<tr>' : '')+ (this.settings.calendarWeeks ? ' <td class="cw">'+currentDate.week()+'</td>' : '')+ ' <td '+ ' data-action="selectDay" '+ ' data-day="' + currentDate.format('L') + '" '+ ' class="day' + clsName + '">' + currentDate.date() + ' </td>'+ (currentDate.weekday() === 6 ? '</tr>' : ''); currentDate.add(1, 'd'); } this.elements.days.find('tbody').empty().append(htmlTemplate); }, refreshTime: function(){ if (!hasTime(this.settings.format)) { return; } if (!this.use24Hours) { var toggle = this.container.find('.timepicker [data-action=togglePeriod]'); var newDate = this.value.clone().add((this.value.hours() >= 12) ? -12 : 12, 'h'); toggle.text(this.value.format('A')); if (isValid(this.settings,newDate, 'h')) { toggle.removeClass('disabled'); } else { toggle.addClass('disabled'); } } this.refreshHours(); this.refreshMinutes(); this.refreshSeconds(); }, refreshHours: function(){ var currentHour = this.viewValue.clone().startOf('d'); this.elements.hour.text(currentHour.format(this.use24Hours ? 'HH' : 'hh')); }, refreshMinutes: function(){ var currentMinute = this.viewValue.clone().startOf('h'); this.elements.minute.text(currentMinute.format('mm')); }, refreshSeconds: function(){ var currentSecond = this.viewValue.clone().startOf('m'); this.elements.second.text(currentSecond.format('ss')); }, setValue: function(value){ // var oValue= this.parseInputDate(value); if(!value || !isValid(this.settings,value)){ this.inputElements.original.val(''); this.inputElements.view.val(''); this.value=null; } else{ this.inputElements.original.val(value.format(this.settings.format)); this.inputElements.view.val(value.format(this.settings.format)); this.value=value; } }, enable: function(){}, disable: function(){}, destroy: function(){} }); this.DTPicker = new J.Class({extend: T.UI.BaseControl},{ defaults: defaults, attributeMap: attributeMap, settings: {}, templates: {}, elements: {}, // minViewModeNumber: 0, // 最小视图模式,选到这个模式以后关闭弹出窗口。 // currentViewMode: 0, // use24Hours: true, // viewValue: false, // widget: false, // picker: {}, // date, // input, // component: false, // actualFormat, // parseFormats, // datePickerModes: [ // { // clsName: 'days', // navFnc: 'M', // navStep: 1 // }, // { // clsName: 'months', // navFnc: 'y', // navStep: 1 // }, // { // clsName: 'years', // navFnc: 'y', // navStep: 10 // }, // { // clsName: 'decades', // navFnc: 'y', // navStep: 100 // } // ], // verticalModes: ['top', 'bottom', 'auto'], // horizontalModes: ['left', 'right', 'auto'], // toolbarPlacements: ['default', 'top', 'bottom'], // 构造函数 init: function(element, options){ var jqElement=$(element); // this.elements.original= $(element); // // 防止多次初始化 // if (this.isInitialized()) { // return this.getRef(); // } // this.initialize(element); // $.extend(true, options, dataToOptions()); // picker.options(options); this.initSettings(jqElement, options); this.initStates(jqElement); this.buildHtml(jqElement); this.initElements(); this.buildObservers(); this.bindEvents(); // this.bindEventsInterface(); // if (!this.settings.inline && !input.is('input')) { // throw new Error('Could not initialize DateTimePicker without an input element'); // } if (this.settings.inline) { this.show(); } }, initStates: function(element){ // this.value= this.element.val(); // Set defaults for date here now instead of in var declaration // this.initFormatting(); // if (input.is('input') && input.val().trim().length !== 0) { // this.setValue(this.parseInputDate(input.val().trim())); // } // else if (this.settings.defaultDate && input.attr('placeholder') === undefined) { // this.setValue(this.settings.defaultDate); // } // this.setValue(this.parseInputDate(this.element.val().trim())); // this.setValue(this.parseInputDate(element.val().trim())); var value= this.parseInputDate(element.val().trim()); if(!value || !isValid(this.settings,value)){ element.val(''); } else{ element.val(value.format(this.settings.format)); } }, buildHtml: function(element){ var htmlTemplate = ''+ '<div class="t-dtpicker-container input-group">' + ' <input type="text" class="form-control">' + // data-toggle="dropdown" ' <div class="input-group-btn">' + ' <button type="button" class="btn btn-default">' + // data-toggle="modal" data-target="#myModal"> ' <span class="glyphicon glyphicon-calendar"></span>' + ' </button>' + ' </div>' + // ' <div class="t-dtpicker-widget-container">'+ // dropdown-menu // ' </div>'+ '</div>'; var container = $(htmlTemplate); this.elements={ original: element, container: container, view: $('input[type=text]', container), button: $('button', container)//, // widgetContainer: $('.t-dtpicker-widget-container', container)//, // getTab: function(levelIndex){ // var tabSelector='.t-level-tab-'+levelIndex; // return $(tabSelector, context.container); // } }; // this.element.after(this.container); }, initElements: function(){ // var context= this; // // initializing element and component attributes // if (this.element.is('input')) { // input = element; // } else { // input = element.find(this.settings.datepickerInput); // if (input.size() === 0) { // input = element.find('input'); // } else if (!input.is('input')) { // throw new Error('CSS class "' + this.settings.datepickerInput + '" cannot be applied to non input element'); // } // } // if (element.hasClass('input-group')) { // // in case there is more then one 'input-group-addon' Issue #48 // if (element.find('.datepickerbutton').size() === 0) { // component = element.find('.input-group-addon'); // } else { // component = element.find('.datepickerbutton'); // } // } // var elements={ // // original: this.element, // view: $('input[type=text]', this.container), // button: $('button', this.container), // widgetContainer: $('.t-dtpicker-widget-container', this.container)//, // // getTab: function(levelIndex){ // // var tabSelector='.t-level-tab-'+levelIndex; // // return $(tabSelector, context.container); // // } // }; // this.elements= $.extend(true, {}, this.elements, elements); this.elements.original.before(this.elements.container); this.elements.original.hide(); this.elements.view.val(this.elements.original.val()); if (this.elements.original.prop('disabled')) { this.disable(); } this.widget= new Widget(this.elements, this.settings); }, transferAttributes: function(){ //this.settings.placeholder = this.$source.attr('data-placeholder') || this.settings.placeholder //this.$element.attr('placeholder', this.settings.placeholder) // this.elements.target.attr('name', this.elements.original.attr('name')) // this.elements.target.val(this.elements.original.val()) // this.elements.original.removeAttr('name') // Remove from source otherwise form will pass parameter twice. this.elements.view.attr('required', this.elements.original.attr('required')) this.elements.view.attr('rel', this.elements.original.attr('rel')) this.elements.view.attr('title', this.elements.original.attr('title')) this.elements.view.attr('class', this.elements.original.attr('class')) this.elements.view.attr('tabindex', this.elements.original.attr('tabindex')) this.elements.original.removeAttr('tabindex') if (this.elements.original.attr('disabled')!==undefined){ this.disable(); } }, buildObservers: function(){}, bindEvents: function(){ var context= this; var element= this.elements.original; this.elements.view.on({ 'change': $.proxy(this.change, this), // 'blur': this.settings.debug ? '' : hide, 'blur': $.proxy(this.hide, this), 'keydown': $.proxy(this.keydown, this), 'keyup': $.proxy(this.keyup, this), // 'focus': this.settings.allowInputToggle ? show : '' 'focus': $.proxy(this.widget.show, this.widget), 'click': $.proxy(this.widget.show, this.widget) }); // if (this.elements.original.is('input')) { // input.on({ // 'focus': show // }); // } else if (component) { // component.on('click', toggle); // component.on('mousedown', false); // } // element.on('click', $.proxy(this.onFooClick, this)); }, // bindEventsInterface: function(){ // var context= this; // var element= this.elements.original; // if(this.settings.onFooSelected){ // element.on('click.t.template', $.proxy(this.settings.onFooSelected, this)); // } // }, render: function(){}, // 事件处理 // onFooClick: function(e, data){ // ; // }, parseInputDate: function (inputDate) { if (this.settings.parseInputDate === undefined) { if (moment.isMoment(inputDate) || inputDate instanceof Date) { inputDate = moment(inputDate); } else { inputDate = getMoment(this.settings.format, inputDate); } } else { inputDate = this.settings.parseInputDate(inputDate); } // inputDate.locale(this.settings.locale); return inputDate; }, // API getValue: function(){ var sValue= this.elements.original.val(); var oValue= this.parseInputDate(sValue); return oValue; }, setValue: function(value){ // var oValue= this.parseInputDate(value); if(!value || !isValid(this.settings,value)){ this.elements.original.val(''); } else{ this.elements.original.val(value.format(this.settings.format)); } }, refresh: function(){}, enable: function(){ this.elements.original.prop('disabled', false); this.elements.button.removeClass('disabled'); }, disable: function(){ this.hide(); this.elements.original.prop('disabled', true); this.elements.button.addClass('disabled'); }, destroy: function(){ this.hide(); this.elements.original.off({ 'change': change, 'blur': blur, 'keydown': keydown, 'keyup': keyup, 'focus': this.settings.allowInputToggle ? hide : '' }); // if (this.elements.original.is('input')) { // input.off({ // 'focus': show // }); // } else if (component) { // component.off('click', toggle); // component.off('mousedown', false); // } // this.elements.original.removeData('DateTimePicker'); // this.elements.original.removeData('date'); } }); });
staticmatrix/Triangle
src/framework/controls/dtpicker/dtpicker.js
JavaScript
mit
82,149
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.FormField = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _class, _desc, _value, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _class3, _temp; var _config = require('../config'); var _aureliaFramework = require('aurelia-framework'); var _aureliaViewManager = require('aurelia-view-manager'); var _logger = require('../logger'); function _initDefineProp(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); } function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; } function _initializerWarningHelper(descriptor, context) { throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.'); } var FormField = exports.FormField = (_dec = (0, _aureliaFramework.customElement)('form-field'), _dec2 = (0, _aureliaViewManager.resolvedView)('spoonx/form', 'form-field'), _dec3 = (0, _aureliaFramework.inject)(_config.Config, _aureliaViewManager.ViewManager, Element), _dec4 = (0, _aureliaFramework.bindable)({ defaultBindingMode: _aureliaFramework.bindingMode.twoWay }), _dec5 = (0, _aureliaFramework.computedFrom)('value', 'element'), _dec6 = (0, _aureliaFramework.computedFrom)('element'), _dec7 = (0, _aureliaFramework.computedFrom)('element'), _dec8 = (0, _aureliaFramework.computedFrom)('view'), _dec9 = (0, _aureliaFramework.computedFrom)('element'), _dec(_class = _dec2(_class = _dec3(_class = (_class2 = (_temp = _class3 = function () { function FormField(config, viewManager, element) { _initDefineProp(this, 'element', _descriptor, this); _initDefineProp(this, 'model', _descriptor2, this); _initDefineProp(this, 'value', _descriptor3, this); _initDefineProp(this, 'message', _descriptor4, this); _initDefineProp(this, 'description', _descriptor5, this); this.config = config; this.viewManager = viewManager; this.formField = this; this.elementDOM = element; } FormField.prototype.attached = function attached() { if (!this.element.key) { _logger.logger.debug('key not defined in element of type ' + this.element.type + ' using model for value'); } if (this.element.attached) { this.element.attached.call(this, this.elementDOM); } }; FormField.prototype.detached = function detached() { if (this.element.detached) { this.element.detached.call(this, this.elementDOM); } }; FormField.prototype.elementChanged = function elementChanged(element) { this.element.id = 'sx-form-' + element.type + '-' + element.key + '-' + FormField.elementCount; FormField.elementCount += 1; return this.element; }; _createClass(FormField, [{ key: 'visible', get: function get() { return typeof this.element.hidden === 'function' ? this.element.hidden(this.value) : !this.element.hidden; } }, { key: 'label', get: function get() { return this.element.label || this.element.key; } }, { key: 'view', get: function get() { var type = this.type; this.element.type = type; return this.viewManager.resolve('spoonx/form', type); } }, { key: 'hasViewModel', get: function get() { return !this.view.endsWith('.html'); } }, { key: 'type', get: function get() { var type = this.element.type; var alias = this.config.fetch('aliases', type); var previous = []; while (alias && !(alias in previous)) { type = alias; alias = this.config.fetch('aliases', type); previous.push(type); } return type; } }]); return FormField; }(), _class3.elementCount = 0, _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'element', [_aureliaFramework.bindable], { enumerable: true, initializer: null }), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'model', [_aureliaFramework.bindable], { enumerable: true, initializer: null }), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'value', [_dec4], { enumerable: true, initializer: null }), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, 'message', [_aureliaFramework.bindable], { enumerable: true, initializer: null }), _descriptor5 = _applyDecoratedDescriptor(_class2.prototype, 'description', [_aureliaFramework.bindable], { enumerable: true, initializer: null }), _applyDecoratedDescriptor(_class2.prototype, 'visible', [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, 'visible'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'label', [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, 'label'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'view', [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, 'view'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'hasViewModel', [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, 'hasViewModel'), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, 'type', [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, 'type'), _class2.prototype)), _class2)) || _class) || _class) || _class);
RWOverdijk/aurelia-form
dist/commonjs/component/form-field.js
JavaScript
mit
6,802
'use strict'; angular.module('contactServices', []) // Factory responsible for assembling the form data before it's passed over the php .factory('assembleFormDataService', function(){ return { populateFormData: function(fname, lname, address, city, zipcode, mnumber, lnumber, relation, email, photoSubmit){ var formData = new FormData(); formData.append("fname", fname); formData.append("lname", lname); formData.append("address", address); formData.append("city", city); formData.append("zipcode", zipcode); formData.append("mnumber", mnumber); formData.append("lnumber", lnumber); formData.append("relation", relation); formData.append("email", email); formData.append("photo", photoSubmit); return formData; } }; }) // One big team service that handles the individual components we'll need for the teams .factory('contactService', ['$http', function($http){ return { contactsList: function(callback){ $http.get('contacts/contacts.php?action=list').success(callback); }, contactsDetails: function(id, callback){ $http.get('contacts/contacts.php?action=detail&id=' + id).success(callback); }, addContacts: function(readyFormData, callback){ $http.post('contacts/contacts.php?action=add', readyFormData, { transformRequest: angular.identity, headers: { "Content-Type": undefined } }).success(callback); }, editContact: function(id, readyFormData, callback){ $http.post('contacts/contacts.php?action=edit&id=' + id, readyFormData, { transformRequest: angular.identity, headers: { "Content-Type": undefined } }).success(callback); }, deleteContact: function(id, callback){ $http.post('contacts/contacts.php?action=delete&id=' + id).success(callback); } } }]);
andrewwiik/VTHSCompSciClub
admin/contacts/js/contactServices.js
JavaScript
mit
1,741
/* * The MIT License * * Copyright 2017 kuniaki. * * 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 webpack = require('webpack'); module.exports = { entry: { "index": './index.ts' }, devtool: "source-map", output: { path: __dirname + "/../../public_html/", filename: "./js/[name].js" }, resolve: { // Add `.ts` and `.tsx` as a resolvable extension. extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js'] }, plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', Popper: ['popper.js', 'default'] }) ], module: { loaders: [ {test: /\.tsx?$/, loader: 'ts-loader'}, {test: /\.png$/, loader: "file-loader?name=img/[name].[ext]"}, {test: /\.html$/, loader: "file-loader?name=[name].[ext]"}, { test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.svg$/, loader: 'url-loader?mimetype=image/svg+xml' }, { test: /\.woff$/, loader: 'url-loader?mimetype=application/font-woff' }, { test: /\.woff2$/, loader: 'url-loader?mimetype=application/font-woff' }, { test: /\.eot$/, loader: 'url-loader?mimetype=application/font-woff' }, { test: /\.ttf$/, loader: 'url-loader?mimetype=application/font-woff' }, { test: /\.(scss)$/, use: [{ loader: 'style-loader' // inject CSS to page }, { loader: 'css-loader' // translates CSS into CommonJS modules }, { loader: 'postcss-loader', // Run post css actions options: { plugins: function () { // post css plugins, can be exported to postcss.config.js return [ require('precss'), require('autoprefixer') ]; } } }, { loader: 'sass-loader' // compiles SASS to CSS }] } ] } };
sugiuraii/WebSocketGaugeClientNeo
src/index/webpack.config.js
JavaScript
mit
3,486
var searchData= [ ['basepath',['BASEPATH',['../index_8php.html#ad39801cabfd338dc5524466fe793fda9',1,'index.php']]] ];
forstermatth/LIIS
refman/search/variables_62.js
JavaScript
mit
120
// 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. 'use strict'; const common = require('../common'); const ArrayStream = require('../common/arraystream'); const { hijackStderr, restoreStderr } = require('../common/hijackstdio'); const assert = require('assert'); const path = require('path'); const fixtures = require('../common/fixtures'); const { builtinModules } = require('module'); const hasInspector = process.features.inspector; if (!common.isMainThread) common.skip('process.chdir is not available in Workers'); // We have to change the directory to ../fixtures before requiring repl // in order to make the tests for completion of node_modules work properly // since repl modifies module.paths. process.chdir(fixtures.fixturesDir); const repl = require('repl'); function getNoResultsFunction() { return common.mustCall((err, data) => { assert.ifError(err); assert.deepStrictEqual(data[0], []); }); } const works = [['inner.one'], 'inner.o']; const putIn = new ArrayStream(); const testMe = repl.start('', putIn); // Some errors are passed to the domain, but do not callback testMe._domain.on('error', assert.ifError); // Tab Complete will not break in an object literal putIn.run([ 'var inner = {', 'one:1' ]); testMe.complete('inner.o', getNoResultsFunction()); testMe.complete('console.lo', common.mustCall(function(error, data) { assert.deepStrictEqual(data, [['console.log'], 'console.lo']); })); testMe.complete('console?.lo', common.mustCall((error, data) => { assert.deepStrictEqual(data, [['console?.log'], 'console?.lo']); })); testMe.complete('console?.zzz', common.mustCall((error, data) => { assert.deepStrictEqual(data, [[], 'console?.zzz']); })); testMe.complete('console?.', common.mustCall((error, data) => { assert(data[0].includes('console?.log')); assert.strictEqual(data[1], 'console?.'); })); // Tab Complete will return globally scoped variables putIn.run(['};']); testMe.complete('inner.o', common.mustCall(function(error, data) { assert.deepStrictEqual(data, works); })); putIn.run(['.clear']); // Tab Complete will not break in an ternary operator with () putIn.run([ 'var inner = ( true ', '?', '{one: 1} : ' ]); testMe.complete('inner.o', getNoResultsFunction()); putIn.run(['.clear']); // Tab Complete will return a simple local variable putIn.run([ 'var top = function() {', 'var inner = {one:1};' ]); testMe.complete('inner.o', getNoResultsFunction()); // When you close the function scope tab complete will not return the // locally scoped variable putIn.run(['};']); testMe.complete('inner.o', getNoResultsFunction()); putIn.run(['.clear']); // Tab Complete will return a complex local variable putIn.run([ 'var top = function() {', 'var inner = {', ' one:1', '};' ]); testMe.complete('inner.o', getNoResultsFunction()); putIn.run(['.clear']); // Tab Complete will return a complex local variable even if the function // has parameters putIn.run([ 'var top = function(one, two) {', 'var inner = {', ' one:1', '};' ]); testMe.complete('inner.o', getNoResultsFunction()); putIn.run(['.clear']); // Tab Complete will return a complex local variable even if the // scope is nested inside an immediately executed function putIn.run([ 'var top = function() {', '(function test () {', 'var inner = {', ' one:1', '};' ]); testMe.complete('inner.o', getNoResultsFunction()); putIn.run(['.clear']); // The definition has the params and { on a separate line. putIn.run([ 'var top = function() {', 'r = function test (', ' one, two) {', 'var inner = {', ' one:1', '};' ]); testMe.complete('inner.o', getNoResultsFunction()); putIn.run(['.clear']); // Currently does not work, but should not break, not the { putIn.run([ 'var top = function() {', 'r = function test ()', '{', 'var inner = {', ' one:1', '};' ]); testMe.complete('inner.o', getNoResultsFunction()); putIn.run(['.clear']); // Currently does not work, but should not break putIn.run([ 'var top = function() {', 'r = function test (', ')', '{', 'var inner = {', ' one:1', '};' ]); testMe.complete('inner.o', getNoResultsFunction()); putIn.run(['.clear']); // Make sure tab completion works on non-Objects putIn.run([ 'var str = "test";' ]); testMe.complete('str.len', common.mustCall(function(error, data) { assert.deepStrictEqual(data, [['str.length'], 'str.len']); })); putIn.run(['.clear']); // Tab completion should not break on spaces const spaceTimeout = setTimeout(function() { throw new Error('timeout'); }, 1000); testMe.complete(' ', common.mustCall(function(error, data) { assert.ifError(error); assert.strictEqual(data[1], ''); assert.ok(data[0].includes('globalThis')); clearTimeout(spaceTimeout); })); // Tab completion should pick up the global "toString" object, and // any other properties up the "global" object's prototype chain testMe.complete('toSt', common.mustCall(function(error, data) { assert.deepStrictEqual(data, [['toString'], 'toSt']); })); // Own properties should shadow properties on the prototype putIn.run(['.clear']); putIn.run([ 'var x = Object.create(null);', 'x.a = 1;', 'x.b = 2;', 'var y = Object.create(x);', 'y.a = 3;', 'y.c = 4;' ]); testMe.complete('y.', common.mustCall(function(error, data) { assert.deepStrictEqual(data, [['y.b', '', 'y.a', 'y.c'], 'y.']); })); // Tab complete provides built in libs for require() putIn.run(['.clear']); testMe.complete('require(\'', common.mustCall(function(error, data) { assert.strictEqual(error, null); builtinModules.forEach((lib) => { assert( data[0].includes(lib) || lib.startsWith('_') || lib.includes('/'), `${lib} not found` ); }); const newModule = 'foobar'; assert(!builtinModules.includes(newModule)); repl.builtinModules.push(newModule); testMe.complete('require(\'', common.mustCall((_, [modules]) => { assert.strictEqual(data[0].length + 1, modules.length); assert(modules.includes(newModule)); })); })); testMe.complete("require\t( 'n", common.mustCall(function(error, data) { assert.strictEqual(error, null); assert.strictEqual(data.length, 2); assert.strictEqual(data[1], 'n'); // There is only one Node.js module that starts with n: assert.strictEqual(data[0][0], 'net'); assert.strictEqual(data[0][1], ''); // It's possible to pick up non-core modules too data[0].slice(2).forEach((completion) => { assert.match(completion, /^n/); }); })); { const expected = ['@nodejsscope', '@nodejsscope/']; // Require calls should handle all types of quotation marks. for (const quotationMark of ["'", '"', '`']) { putIn.run(['.clear']); testMe.complete('require(`@nodejs', common.mustCall((err, data) => { assert.strictEqual(err, null); assert.deepStrictEqual(data, [expected, '@nodejs']); })); putIn.run(['.clear']); // Completions should not be greedy in case the quotation ends. const input = `require(${quotationMark}@nodejsscope${quotationMark}`; testMe.complete(input, common.mustCall((err, data) => { assert.strictEqual(err, null); assert.deepStrictEqual(data, [[], undefined]); })); } } { putIn.run(['.clear']); // Completions should find modules and handle whitespace after the opening // bracket. testMe.complete('require \t("no_ind', common.mustCall((err, data) => { assert.strictEqual(err, null); assert.deepStrictEqual(data, [['no_index', 'no_index/'], 'no_ind']); })); } // Test tab completion for require() relative to the current directory { putIn.run(['.clear']); const cwd = process.cwd(); process.chdir(__dirname); ['require(\'.', 'require(".'].forEach((input) => { testMe.complete(input, common.mustCall((err, data) => { assert.strictEqual(err, null); assert.strictEqual(data.length, 2); assert.strictEqual(data[1], '.'); assert.strictEqual(data[0].length, 2); assert.ok(data[0].includes('./')); assert.ok(data[0].includes('../')); })); }); ['require(\'..', 'require("..'].forEach((input) => { testMe.complete(input, common.mustCall((err, data) => { assert.strictEqual(err, null); assert.deepStrictEqual(data, [['../'], '..']); })); }); ['./', './test-'].forEach((path) => { [`require('${path}`, `require("${path}`].forEach((input) => { testMe.complete(input, common.mustCall((err, data) => { assert.strictEqual(err, null); assert.strictEqual(data.length, 2); assert.strictEqual(data[1], path); assert.ok(data[0].includes('./test-repl-tab-complete')); })); }); }); ['../parallel/', '../parallel/test-'].forEach((path) => { [`require('${path}`, `require("${path}`].forEach((input) => { testMe.complete(input, common.mustCall((err, data) => { assert.strictEqual(err, null); assert.strictEqual(data.length, 2); assert.strictEqual(data[1], path); assert.ok(data[0].includes('../parallel/test-repl-tab-complete')); })); }); }); { const path = '../fixtures/repl-folder-extensions/f'; testMe.complete(`require('${path}`, common.mustCall((err, data) => { assert.ifError(err); assert.strictEqual(data.length, 2); assert.strictEqual(data[1], path); assert.ok(data[0].includes('../fixtures/repl-folder-extensions/foo.js')); })); } process.chdir(cwd); } // Make sure tab completion works on context properties putIn.run(['.clear']); putIn.run([ 'var custom = "test";' ]); testMe.complete('cus', common.mustCall(function(error, data) { assert.deepStrictEqual(data, [['custom'], 'cus']); })); // Make sure tab completion doesn't crash REPL with half-baked proxy objects. // See: https://github.com/nodejs/node/issues/2119 putIn.run(['.clear']); putIn.run([ 'var proxy = new Proxy({}, {ownKeys: () => { throw new Error(); }});' ]); testMe.complete('proxy.', common.mustCall(function(error, data) { assert.strictEqual(error, null); assert(Array.isArray(data)); })); // Make sure tab completion does not include integer members of an Array putIn.run(['.clear']); putIn.run(['var ary = [1,2,3];']); testMe.complete('ary.', common.mustCall(function(error, data) { assert.strictEqual(data[0].includes('ary.0'), false); assert.strictEqual(data[0].includes('ary.1'), false); assert.strictEqual(data[0].includes('ary.2'), false); })); // Make sure tab completion does not include integer keys in an object putIn.run(['.clear']); putIn.run(['var obj = {1:"a","1a":"b",a:"b"};']); testMe.complete('obj.', common.mustCall(function(error, data) { assert.strictEqual(data[0].includes('obj.1'), false); assert.strictEqual(data[0].includes('obj.1a'), false); assert(data[0].includes('obj.a')); })); // Don't try to complete results of non-simple expressions putIn.run(['.clear']); putIn.run(['function a() {}']); testMe.complete('a().b.', getNoResultsFunction()); // Works when prefixed with spaces putIn.run(['.clear']); putIn.run(['var obj = {1:"a","1a":"b",a:"b"};']); testMe.complete(' obj.', common.mustCall((error, data) => { assert.strictEqual(data[0].includes('obj.1'), false); assert.strictEqual(data[0].includes('obj.1a'), false); assert(data[0].includes('obj.a')); })); // Works inside assignments putIn.run(['.clear']); testMe.complete('var log = console.lo', common.mustCall((error, data) => { assert.deepStrictEqual(data, [['console.log'], 'console.lo']); })); // Tab completion for defined commands putIn.run(['.clear']); testMe.complete('.b', common.mustCall((error, data) => { assert.deepStrictEqual(data, [['break'], 'b']); })); putIn.run(['.clear']); putIn.run(['var obj = {"hello, world!": "some string", "key": 123}']); testMe.complete('obj.', common.mustCall((error, data) => { assert.strictEqual(data[0].includes('obj.hello, world!'), false); assert(data[0].includes('obj.key')); })); // Tab completion for files/directories { putIn.run(['.clear']); process.chdir(__dirname); const readFileSyncs = ['fs.readFileSync("', 'fs.promises.readFileSync("']; if (!common.isWindows) { readFileSyncs.forEach((readFileSync) => { const fixturePath = `${readFileSync}../fixtures/test-repl-tab-completion`; testMe.complete(fixturePath, common.mustCall((err, data) => { assert.strictEqual(err, null); assert.ok(data[0][0].includes('.hiddenfiles')); assert.ok(data[0][1].includes('hellorandom.txt')); assert.ok(data[0][2].includes('helloworld.js')); })); testMe.complete(`${fixturePath}/hello`, common.mustCall((err, data) => { assert.strictEqual(err, null); assert.ok(data[0][0].includes('hellorandom.txt')); assert.ok(data[0][1].includes('helloworld.js')); }) ); testMe.complete(`${fixturePath}/.h`, common.mustCall((err, data) => { assert.strictEqual(err, null); assert.ok(data[0][0].includes('.hiddenfiles')); }) ); testMe.complete(`${readFileSync}./xxxRandom/random`, common.mustCall((err, data) => { assert.strictEqual(err, null); assert.strictEqual(data[0].length, 0); }) ); const testPath = fixturePath.slice(0, -1); testMe.complete(testPath, common.mustCall((err, data) => { assert.strictEqual(err, null); assert.ok(data[0][0].includes('test-repl-tab-completion')); assert.strictEqual( data[1], path.basename(testPath) ); })); }); } } [ Array, Buffer, Uint8Array, Uint16Array, Uint32Array, Uint8ClampedArray, Int8Array, Int16Array, Int32Array, Float32Array, Float64Array, ].forEach((type) => { putIn.run(['.clear']); if (type === Array) { putIn.run([ 'var ele = [];', 'for (let i = 0; i < 1e6 + 1; i++) ele[i] = 0;', 'ele.biu = 1;' ]); } else if (type === Buffer) { putIn.run(['var ele = Buffer.alloc(1e6 + 1); ele.biu = 1;']); } else { putIn.run([`var ele = new ${type.name}(1e6 + 1); ele.biu = 1;`]); } hijackStderr(common.mustNotCall()); testMe.complete('ele.', common.mustCall((err, data) => { restoreStderr(); assert.ifError(err); const ele = (type === Array) ? [] : (type === Buffer ? Buffer.alloc(0) : new type(0)); assert.strictEqual(data[0].includes('ele.biu'), true); data[0].forEach((key) => { if (!key || key === 'ele.biu') return; assert.notStrictEqual(ele[key.substr(4)], undefined); }); })); }); // check Buffer.prototype.length not crashing. // Refs: https://github.com/nodejs/node/pull/11961 putIn.run['.clear']; testMe.complete('Buffer.prototype.', common.mustCall()); const testNonGlobal = repl.start({ input: putIn, output: putIn, useGlobal: false }); const builtins = [['Infinity', 'Int16Array', 'Int32Array', 'Int8Array'], 'I']; if (common.hasIntl) { builtins[0].push('Intl'); } testNonGlobal.complete('I', common.mustCall((error, data) => { assert.deepStrictEqual(data, builtins); })); // To test custom completer function. // Sync mode. const customCompletions = 'aaa aa1 aa2 bbb bb1 bb2 bb3 ccc ddd eee'.split(' '); const testCustomCompleterSyncMode = repl.start({ prompt: '', input: putIn, output: putIn, completer: function completer(line) { const hits = customCompletions.filter((c) => c.startsWith(line)); // Show all completions if none found. return [hits.length ? hits : customCompletions, line]; } }); // On empty line should output all the custom completions // without complete anything. testCustomCompleterSyncMode.complete('', common.mustCall((error, data) => { assert.deepStrictEqual(data, [ customCompletions, '' ]); })); // On `a` should output `aaa aa1 aa2` and complete until `aa`. testCustomCompleterSyncMode.complete('a', common.mustCall((error, data) => { assert.deepStrictEqual(data, [ 'aaa aa1 aa2'.split(' '), 'a' ]); })); // To test custom completer function. // Async mode. const testCustomCompleterAsyncMode = repl.start({ prompt: '', input: putIn, output: putIn, completer: function completer(line, callback) { const hits = customCompletions.filter((c) => c.startsWith(line)); // Show all completions if none found. callback(null, [hits.length ? hits : customCompletions, line]); } }); // On empty line should output all the custom completions // without complete anything. testCustomCompleterAsyncMode.complete('', common.mustCall((error, data) => { assert.deepStrictEqual(data, [ customCompletions, '' ]); })); // On `a` should output `aaa aa1 aa2` and complete until `aa`. testCustomCompleterAsyncMode.complete('a', common.mustCall((error, data) => { assert.deepStrictEqual(data, [ 'aaa aa1 aa2'.split(' '), 'a' ]); })); // Tab completion in editor mode const editorStream = new ArrayStream(); const editor = repl.start({ stream: editorStream, terminal: true, useColors: false }); editorStream.run(['.clear']); editorStream.run(['.editor']); editor.completer('Uin', common.mustCall((error, data) => { assert.deepStrictEqual(data, [['Uint'], 'Uin']); })); editorStream.run(['.clear']); editorStream.run(['.editor']); editor.completer('var log = console.l', common.mustCall((error, data) => { assert.deepStrictEqual(data, [['console.log'], 'console.l']); })); { // Tab completion of lexically scoped variables const stream = new ArrayStream(); const testRepl = repl.start({ stream }); stream.run([` let lexicalLet = true; const lexicalConst = true; class lexicalKlass {} `]); ['Let', 'Const', 'Klass'].forEach((type) => { const query = `lexical${type[0]}`; const expected = hasInspector ? [[`lexical${type}`], query] : [[], `lexical${type[0]}`]; testRepl.complete(query, common.mustCall((error, data) => { assert.deepStrictEqual(data, expected); })); }); }
enclose-io/compiler
current/test/parallel/test-repl-tab-complete.js
JavaScript
mit
19,230
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, Link, browserHistory } from 'react-router'; import App from './App'; import NotFound from './Pages/NotFound/NotFound'; import Users from './Pages/Users/Users'; import Chats from './Pages/Chats/Chats'; import './index.css'; ReactDOM.render( <Router history={browserHistory}> <Route path="/" component={App}> <Route path="users" component={Users}/> <Route path="chats" component={Chats}/> </Route> <Route path="*" component={NotFound}/> </Router>, document.getElementById('root'));
ParkDyel/practice
WebDev/FE/JS/Reactjs/PRWF/src/index.js
JavaScript
mit
599
/** * @license * Visual Blocks Editor * * Copyright 2016 Google Inc. * https://developers.google.com/blockly/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Events fired as a result of actions in Blockly's editor. * @author [email protected] (Neil Fraser) */ 'use strict'; /** * Events fired as a result of actions in Blockly's editor. * @namespace Blockly.Events */ goog.provide('Blockly.Events'); goog.require('Blockly.utils'); /** * Group ID for new events. Grouped events are indivisible. * @type {string} * @private */ Blockly.Events.group_ = ''; /** * Sets whether the next event should be added to the undo stack. * @type {boolean} */ Blockly.Events.recordUndo = true; /** * Allow change events to be created and fired. * @type {number} * @private */ Blockly.Events.disabled_ = 0; /** * Name of event that creates a block. Will be deprecated for BLOCK_CREATE. * @const */ Blockly.Events.CREATE = 'create'; /** * Name of event that creates a block. * @const */ Blockly.Events.BLOCK_CREATE = Blockly.Events.CREATE; /** * Name of event that deletes a block. Will be deprecated for BLOCK_DELETE. * @const */ Blockly.Events.DELETE = 'delete'; /** * Name of event that deletes a block. * @const */ Blockly.Events.BLOCK_DELETE = Blockly.Events.DELETE; /** * Name of event that changes a block. Will be deprecated for BLOCK_CHANGE. * @const */ Blockly.Events.CHANGE = 'change'; /** * Name of event that changes a block. * @const */ Blockly.Events.BLOCK_CHANGE = Blockly.Events.CHANGE; /** * Name of event that moves a block. Will be deprecated for BLOCK_MOVE. * @const */ Blockly.Events.MOVE = 'move'; /** * Name of event that moves a block. * @const */ Blockly.Events.BLOCK_MOVE = Blockly.Events.MOVE; /** * Name of event that creates a variable. * @const */ Blockly.Events.VAR_CREATE = 'var_create'; /** * Name of event that deletes a variable. * @const */ Blockly.Events.VAR_DELETE = 'var_delete'; /** * Name of event that renames a variable. * @const */ Blockly.Events.VAR_RENAME = 'var_rename'; /** * Name of event that records a UI change. * @const */ Blockly.Events.UI = 'ui'; /** * Name of event that creates a comment. * @const */ Blockly.Events.COMMENT_CREATE = 'comment_create'; /** * Name of event that deletes a comment. * @const */ Blockly.Events.COMMENT_DELETE = 'comment_delete'; /** * Name of event that changes a comment. * @const */ Blockly.Events.COMMENT_CHANGE = 'comment_change'; /** * Name of event that moves a comment. * @const */ Blockly.Events.COMMENT_MOVE = 'comment_move'; /** * List of events queued for firing. * @private */ Blockly.Events.FIRE_QUEUE_ = []; /** * Create a custom event and fire it. * @param {!Blockly.Events.Abstract} event Custom data for event. */ Blockly.Events.fire = function(event) { if (!Blockly.Events.isEnabled()) { return; } if (!Blockly.Events.FIRE_QUEUE_.length) { // First event added; schedule a firing of the event queue. setTimeout(Blockly.Events.fireNow_, 0); } Blockly.Events.FIRE_QUEUE_.push(event); }; /** * Fire all queued events. * @private */ Blockly.Events.fireNow_ = function() { var queue = Blockly.Events.filter(Blockly.Events.FIRE_QUEUE_, true); Blockly.Events.FIRE_QUEUE_.length = 0; for (var i = 0, event; event = queue[i]; i++) { var workspace = Blockly.Workspace.getById(event.workspaceId); if (workspace) { workspace.fireChangeListener(event); } } }; /** * Filter the queued events and merge duplicates. * @param {!Array.<!Blockly.Events.Abstract>} queueIn Array of events. * @param {boolean} forward True if forward (redo), false if backward (undo). * @return {!Array.<!Blockly.Events.Abstract>} Array of filtered events. */ Blockly.Events.filter = function(queueIn, forward) { var queue = queueIn.slice(); // Shallow copy of queue. if (!forward) { // Undo is merged in reverse order. queue.reverse(); } var mergedQueue = []; var hash = Object.create(null); // Merge duplicates. for (var i = 0, event; event = queue[i]; i++) { if (!event.isNull()) { var key = [event.type, event.blockId, event.workspaceId].join(' '); var lastEntry = hash[key]; var lastEvent = lastEntry ? lastEntry.event : null; if (!lastEntry) { // Each item in the hash table has the event and the index of that event // in the input array. This lets us make sure we only merge adjacent // move events. hash[key] = { event: event, index: i}; mergedQueue.push(event); } else if (event.type == Blockly.Events.MOVE && lastEntry.index == i - 1) { // Merge move events. lastEvent.newParentId = event.newParentId; lastEvent.newInputName = event.newInputName; lastEvent.newCoordinate = event.newCoordinate; lastEntry.index = i; } else if (event.type == Blockly.Events.CHANGE && event.element == lastEvent.element && event.name == lastEvent.name) { // Merge change events. lastEvent.newValue = event.newValue; } else if (event.type == Blockly.Events.UI && event.element == 'click' && (lastEvent.element == 'commentOpen' || lastEvent.element == 'mutatorOpen' || lastEvent.element == 'warningOpen')) { // Merge click events. lastEvent.newValue = event.newValue; } else { // Collision: newer events should merge into this event to maintain order hash[key] = { event: event, index: 1}; mergedQueue.push(event); } } } // Filter out any events that have become null due to merging. queue = mergedQueue.filter(function(e) { return !e.isNull(); }); if (!forward) { // Restore undo order. queue.reverse(); } // Move mutation events to the top of the queue. // Intentionally skip first event. for (var i = 1, event; event = queue[i]; i++) { if (event.type == Blockly.Events.CHANGE && event.element == 'mutation') { queue.unshift(queue.splice(i, 1)[0]); } } return queue; }; /** * Modify pending undo events so that when they are fired they don't land * in the undo stack. Called by Blockly.Workspace.clearUndo. */ Blockly.Events.clearPendingUndo = function() { for (var i = 0, event; event = Blockly.Events.FIRE_QUEUE_[i]; i++) { event.recordUndo = false; } }; /** * Stop sending events. Every call to this function MUST also call enable. */ Blockly.Events.disable = function() { Blockly.Events.disabled_++; }; /** * Start sending events. Unless events were already disabled when the * corresponding call to disable was made. */ Blockly.Events.enable = function() { Blockly.Events.disabled_--; }; /** * Returns whether events may be fired or not. * @return {boolean} True if enabled. */ Blockly.Events.isEnabled = function() { return Blockly.Events.disabled_ == 0; }; /** * Current group. * @return {string} ID string. */ Blockly.Events.getGroup = function() { return Blockly.Events.group_; }; /** * Start or stop a group. * @param {boolean|string} state True to start new group, false to end group. * String to set group explicitly. */ Blockly.Events.setGroup = function(state) { if (typeof state == 'boolean') { Blockly.Events.group_ = state ? Blockly.utils.genUid() : ''; } else { Blockly.Events.group_ = state; } }; /** * Compute a list of the IDs of the specified block and all its descendants. * @param {!Blockly.Block} block The root block. * @return {!Array.<string>} List of block IDs. * @private */ Blockly.Events.getDescendantIds_ = function(block) { var ids = []; var descendants = block.getDescendants(false); for (var i = 0, descendant; descendant = descendants[i]; i++) { ids[i] = descendant.id; } return ids; }; /** * Decode the JSON into an event. * @param {!Object} json JSON representation. * @param {!Blockly.Workspace} workspace Target workspace for event. * @return {!Blockly.Events.Abstract} The event represented by the JSON. */ Blockly.Events.fromJson = function(json, workspace) { // TODO: Should I have a way to register a new event into here? var event; switch (json.type) { case Blockly.Events.CREATE: event = new Blockly.Events.Create(null); break; case Blockly.Events.DELETE: event = new Blockly.Events.Delete(null); break; case Blockly.Events.CHANGE: event = new Blockly.Events.Change(null, '', '', '', ''); break; case Blockly.Events.MOVE: event = new Blockly.Events.Move(null); break; case Blockly.Events.VAR_CREATE: event = new Blockly.Events.VarCreate(null); break; case Blockly.Events.VAR_DELETE: event = new Blockly.Events.VarDelete(null); break; case Blockly.Events.VAR_RENAME: event = new Blockly.Events.VarRename(null, ''); break; case Blockly.Events.UI: event = new Blockly.Events.Ui(null); break; case Blockly.Events.COMMENT_CREATE: event = new Blockly.Events.CommentCreate(null); break; case Blockly.Events.COMMENT_CHANGE: event = new Blockly.Events.CommentChange(null); break; case Blockly.Events.COMMENT_MOVE: event = new Blockly.Events.CommentMove(null); break; case Blockly.Events.COMMENT_DELETE: event = new Blockly.Events.CommentDelete(null); break; default: throw Error('Unknown event type.'); } event.fromJson(json); event.workspaceId = workspace.id; return event; }; /** * Enable/disable a block depending on whether it is properly connected. * Use this on applications where all blocks should be connected to a top block. * Recommend setting the 'disable' option to 'false' in the config so that * users don't try to reenable disabled orphan blocks. * @param {!Blockly.Events.Abstract} event Custom data for event. */ Blockly.Events.disableOrphans = function(event) { if (event.type == Blockly.Events.MOVE || event.type == Blockly.Events.CREATE) { var workspace = Blockly.Workspace.getById(event.workspaceId); var block = workspace.getBlockById(event.blockId); if (block) { if (block.getParent() && !block.getParent().disabled) { var children = block.getDescendants(false); for (var i = 0, child; child = children[i]; i++) { child.setDisabled(false); } } else if ((block.outputConnection || block.previousConnection) && !workspace.isDragging()) { do { block.setDisabled(true); block = block.getNextBlock(); } while (block); } } } };
NTUTVisualScript/Visual_Script
static/javascript/blockly/core/events.js
JavaScript
mit
11,197
var x = require("x-view"); var Raw = x.createClass({ propTypes: { html: x.type.string }, init: function() { x.event.on(this, "updated", this.updateHTML); }, updateHTML: function() { this.root.innerHTML = this.props.html; } }); x.register("x-raw", Raw);
lixiaoyan/x-view
tags/raw.js
JavaScript
mit
279
type SerializeOptions = { domain?: string, encode?: (stringToDecode: string) => string, expires?: Date, httpOnly?: boolean, maxAge?: number, path?: string, sameSite?: boolean | 'lax' | 'strict', secure?: boolean, ... }; type ParseOptions = { // Library itself does not specify output for decode function. // Because of simplicity is output set to string which is default settings and best for working with cookies. decode?: (stringToDecode: string) => string, ... }; declare module 'cookie' { declare module.exports: { serialize(name: string, val: string, options: ?SerializeOptions): string, parse(data: string, options: ?ParseOptions): { [string]: string, ... }, ... }; };
flowtype/flow-typed
definitions/npm/cookie_v0.3.x/flow_v0.104.x-/cookie_v0.3.x.js
JavaScript
mit
711
/** * -------------------------------------------------------------------------- * Bootstrap (v4.3.1): dom/selector-engine.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ import { find as findFn, findOne, matches, closest } from './polyfill' import { makeArray } from '../util/index' /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ const NODE_TEXT = 3 const SelectorEngine = { matches(element, selector) { return matches.call(element, selector) }, find(selector, element = document.documentElement) { if (typeof selector !== 'string') { return null } return findFn.call(element, selector) }, findOne(selector, element = document.documentElement) { if (typeof selector !== 'string') { return null } return findOne.call(element, selector) }, children(element, selector) { if (typeof selector !== 'string') { return null } const children = makeArray(element.children) return children.filter(child => this.matches(child, selector)) }, parents(element, selector) { if (typeof selector !== 'string') { return null } const parents = [] let ancestor = element.parentNode while (ancestor && ancestor.nodeType === Node.ELEMENT_NODE && ancestor.nodeType !== NODE_TEXT) { if (this.matches(ancestor, selector)) { parents.push(ancestor) } ancestor = ancestor.parentNode } return parents }, closest(element, selector) { if (typeof selector !== 'string') { return null } return closest.call(element, selector) }, prev(element, selector) { if (typeof selector !== 'string') { return null } const siblings = [] let previous = element.previousSibling while (previous && previous.nodeType === Node.ELEMENT_NODE && previous.nodeType !== NODE_TEXT) { if (this.matches(previous, selector)) { siblings.push(previous) } previous = previous.previousSibling } return siblings } } export default SelectorEngine
stanwmusic/bootstrap
js/src/dom/selector-engine.js
JavaScript
mit
2,277
version https://git-lfs.github.com/spec/v1 oid sha256:9e5db06495724b6fedb3e06776242c7ddb55da8532eb678a5a5b88757b8108df size 1211
yogeshsaroya/new-cdnjs
ajax/libs/mathjax/1.1a/jax/output/HTML-CSS/fonts/STIX/General/Italic/GeneralPunctuation.js
JavaScript
mit
129
var spawn = require('child_process').spawn, Promise = require('bluebird'), uuid = require('node-uuid'), path = require('path'), fs = require('fs'), mkdirp = require('mkdirp'), _ = require('underscore'), fs = require('fs'), Sftp = require('sftp-upload'); var rosettaExecutable = path.join(__dirname, '../../sip-generator-2/SIP_Generator/'); var depositExecutable = path.join(__dirname, '../../sip-generator-2/rosetta-connector/dps-sdk-deposit'); var Rosetta = module.exports = function() {}; Rosetta.prototype.deposit = function(sourceDir) { var rosetta = this; console.log('[Rosetta::deposit] configuration: ' + sourceDir); var subDir = sourceDir.replace('/', ''); console.log('[Rosetta::deposit] subdir: ' + subDir); return new Promise(function(resolve, reject) { var cwd = process.cwd(); process.chdir(depositExecutable); var executable = path.join(depositExecutable, 'deposit.jar'); var executable = spawn('java', ['-jar', executable, subDir]); executable.stdout.on('data', function(data) { console.log(data.toString()); }); executable.stderr.on('data', function(data) { console.log('[Rosetta::deposit] Error during programm execution: ' + data.toString()); reject(data.toString()); }); executable.on('close', function(code) { if (code !== 0) { console.log('[Rosetta::deposit] child process exited with code ' + code); return reject('[Rosetta::deposit] child process exited with code ' + code); } console.log('[Rosetta::deposit] Successfully deposit ' + subDir); resolve(code); }); }); }; Rosetta.prototype.upload = function(sourceDir) { return new Promise(function(resolve, reject) { var uuid = sourceDir.split('/').pop(), privateKey = null; try { // FIXXME: add possibility to upload key! privateKey = fs.readFileSync('/home/hecher/.ssh/id_rsa-larissa'); } catch (err) { return reject('Private key for Rosetta upload could not be read.'); } var options = { host: 'exchange.tib.eu', username: 'duraark', path: sourceDir, remoteDir: '/tib_extern_deposit_duraark/tmp/' + uuid, privateKey: privateKey }, sftp = new Sftp(options); try { sftp.on('error', function(err) { console.log('Error connecting to SFTP: ' + err); reject('Error connecting to SFTP: ' + err); }) .on('uploading', function(pgs) { console.log('Uploading', pgs.file); console.log(pgs.percent + '% completed'); }) .on('completed', function() { console.log('Upload Completed'); resolve(sourceDir); }) .upload(); } catch (err) { console.log('Error creating connection to SFTP: ' + err); reject('Error creating connection to SFTP: ' + err); } }); }; Rosetta.prototype.start = function(sourceDir, output) { var rosetta = this; console.log('[Rosetta::start] configuration: ' + sourceDir + " --> " + output); return new Promise(function(resolve, reject) { console.log('[Rosetta::start] creating output Dir'); mkdirp(output, function(err) { if (err) return reject(err); var cwd = process.cwd(); process.chdir(rosettaExecutable); //JAVA -jar SIP _Generator.jar D:\input D:\output /exlibris1/transfer/tib_duraark // var args = [sourceDir, output, '/exlibris1/transfer/tib_duraark'], var executable = path.join(rosettaExecutable, 'SIP_Generator.jar'), args = ['-jar', executable, sourceDir, output, '/exlibris1/transfer/tib_extern_deposit_duraark']; console.log('[Rosetta::start] about to execute: java ' + args.join(' ')); var executable = spawn('java', args); executable.stdout.on('data', function(data) { console.log(data.toString()); }); executable.stderr.on('data', function(data) { console.log('[Rosetta::start] Error during programm execution: ' + data.toString()); }); executable.on('close', function(code) { if (code !== 0) { console.log('[Rosetta::start] child process exited with code ' + code); return reject('[Rosetta::start] child process exited with code ' + code); } console.log('[Rosetta::start] child process exited with code ' + code); rosetta.upload(output).then(function(sourceDir) { var deposits = []; var entities = getDirectories(sourceDir); for (var idx = 0; idx < entities.length; idx++) { var entity = entities[idx]; // var subDir = 'session_physicalasset_fa3a93318f644fe9bc97f781cdc1d501'; // var subDir = 'fa3a93318f644fe9bc97f781cdc1d501'; var subDir = path.join(sourceDir, entity); // var subDir = entity; deposits.push(rosetta.deposit(subDir)); } Promise.all(deposits).then(function() { console.log('deposit finished for all intellectual entities'); return resolve(output); }).catch(function(err) { return reject(err); }); }).catch(function(err) { console.log('Rosetta upload error: ' + err); return reject(err); }); }); }); }); }; function getDirectories(srcpath) { return fs.readdirSync(srcpath).filter(function(file) { return fs.statSync(path.join(srcpath, file)).isDirectory(); }); }
DURAARK/microservice-sipgenerator
bindings/rosetta/app.js
JavaScript
mit
5,477
import elem from "./_elem.js"; import clrPckr from "./_color-picker.js"; var s, x, y, z, colorNum = 0, arrMap = [], c = document.getElementById("canvasGrid"), ctx = c.getContext("2d"); var grid = { //create grid and create boxes createGridIllustrator: () => { //module for creating a grid for(var r = 0; r < elem.s.columnCount; r++) { for(var i = 0; i < elem.s.rowCount; i++) { ctx.strokeStyle = "#262626"; ctx.strokeRect(r * elem.s.pixSize, i * elem.s.pixSize, elem.s.pixSize, elem.s.pixSize); ctx.fillStyle = elem.el.backgroundHexColor.value; ctx.fillRect(r * elem.s.pixSize + 1, i * elem.s.pixSize + 1, elem.s.pixSize - 2, elem.s.pixSize - 2); } } }, //allow individual boxes to be clicked // handleClick is still in prototyping phase handleClick: (e) => { clrPckr.pickBackgroundHexColor(); e = e || window.event; var xVal = Math.floor(e.offsetX === undefined ? e.layerX : e.offsetX / elem.s.pixSize) * elem.s.pixSize; var yVal = Math.floor(e.offsetY === undefined ? e.layerY : e.offsetY / elem.s.pixSize) * elem.s.pixSize; ctx.fillStyle = elem.el.hexColor.value; //get the color for the box clicked on var imgData = ctx.getImageData(Math.floor(e.offsetX / elem.s.pixSize) * elem.s.pixSize + 1, Math.floor(e.offsetY / elem.s.pixSize) * elem.s.pixSize + 1, elem.s.pixSize - 2, elem.s.pixSize - 2); //if it is the background grey/gray remove it //currently does not work with color change if(imgData.data[0] !== parseFloat(elem.el.backgroundRed.value) && imgData.data[1] !== parseFloat(elem.el.backgroundGreen.value) && imgData.data[2] !== parseFloat(elem.el.backgroundBlue.value)){ ctx.fillStyle = `rgba(${elem.el.backgroundRed.value}, ${elem.el.backgroundGreen.value}, ${elem.el.backgroundBlue.value}, 1)`; ctx.clearRect(Math.floor(e.offsetX / elem.s.pixSize) * elem.s.pixSize + 1, Math.floor(e.offsetY / elem.s.pixSize) * elem.s.pixSize + 1, elem.s.pixSize - 2, elem.s.pixSize - 2); ctx.fillRect(Math.floor(e.offsetX / elem.s.pixSize) * elem.s.pixSize + 1, Math.floor(e.offsetY / elem.s.pixSize) * elem.s.pixSize + 1, //accomodate for 2 px border //need to put in a variable down the line elem.s.pixSize - 2, elem.s.pixSize - 2); //elem.s.storeValues.indexOf([xVal, yVal, elem.el.hexColor.value]).pop(); //this return false is causing wonky behavior, should look into it return false; } ctx.fillRect(Math.floor(e.offsetX / elem.s.pixSize) * elem.s.pixSize + 1, Math.floor(e.offsetY / elem.s.pixSize) * elem.s.pixSize + 1, //accomodate for 2 px border //need to put in a variable down the line elem.s.pixSize - 2, elem.s.pixSize - 2); }, updateGridColor: () => { for(let x = 0; x < elem.s.columnCount; x++) { for(let y = 0; y < elem.s.rowCount; y++) { ctx.strokeStyle = `${elem.el.backgroundRed.value + 44}. ${elem.el.backgroundGreen.value + 44}. ${elem.el.backgroundBlue.value + 44}`; ctx.strokeRect(x * elem.s.pixSize, y * elem.s.pixSize, elem.s.pixSize, elem.s.pixSize); ctx.fillStyle = elem.el.backgroundHexColor.value; ctx.fillRect(x * elem.s.pixSize + 1, y * elem.s.pixSize + 1, elem.s.pixSize - 2, elem.s.pixSize - 2); } } for(let x = 0; x < elem.s.storeValues.length; x++){ ctx.fillStyle = elem.s.storeValues[x][2]; ctx.fillRect(parseFloat(elem.s.storeValues[x][0]) + 1, parseFloat(elem.s.storeValues[x][1]) + 1, elem.s.pixSize - 2, elem.s.pixSize - 2); } } }; export default grid;
CharlieGreenman/pixelatorV2_with_react
app/js/_grid.js
JavaScript
mit
3,948
'use strict'; //https://gist.github.com/yannickcr/6129327b31b27b14efc5 const instrumenter = require('isparta').Instrumenter; module.exports = function (gulp, $, {src, testSrc, requires, coverageDir, disableCoverage}) { const runTest = function runTest() { return gulp.src(testSrc, {read: false}) .pipe($.mocha({ reporter: 'spec', ui: 'bdd', harmony: true, timeout: 2000000, require: requires })); }; const handleErrEnd = function handleErrEnd(pipe, cb) { return pipe .on('error', (err) => { $.gutil.log(`[test:cov]${err}`); }) .on('end', () => { cb(); const ct = setTimeout(() => { clearTimeout(ct); process.exit();//https://github.com/sindresorhus/gulp-mocha/issues/1 }, 5 * 1000);//let other tasks complete!, hopefully that will complete in 30s }); }; const gatherCoverage = function gatherCoverage(cb) { return gulp.src(src) .pipe($.istanbul({instrumenter})) .pipe($.istanbul.hookRequire()) .once('finish', () => { handleErrEnd(runTest() .pipe($.istanbul.writeReports({ dir: coverageDir, reporters: ['lcov', 'html', 'text', 'text-summary'], reportOpts: {dir: coverageDir} })), cb); }); }; return function test(cb) { disableCoverage ? handleErrEnd(runTest(), cb) : gatherCoverage(cb); }; };
k-sheth/hapi-getting-started
tasks/test.js
JavaScript
mit
1,713
"use strict"; /* * ooiui/static/js/views/science/HighChartsStreamingDataView.js */ var HighchartsStreamingContainerView = Backbone.View.extend({ subviews : [], showControls: true, initialize: function(options) { if (options && 'showControls' in options){ this.showControls = options.showControls; } _.bindAll(this, "render", "add","remove"); this.render(); }, render: function() { this.$el.html("<div class='streaming-plot-container-header'><div class='streaming-plot-container-contents'></div></div>"); }, add: function(streamModel) { var self = this; if (self.subviews.length >= 5){ return false; } var refExists = false; var streamPlotAdded = false; _.each(self.subviews,function(currentView){ var currentRef = currentView.model.get('reference_designator'); var currentStream = currentView.model.get('stream_name'); if (currentRef == streamModel.get('reference_designator') && currentStream == streamModel.get('stream_name') ){ //check to see if the reference designator already exists refExists= true; } }); if (!refExists){ var subview = new HighchartsStreamingDataOptionsView({ model: streamModel, showControls: self.showControls }); subview.render(); this.subviews.push(subview); this.$el.find('.streaming-plot-container-contents').append(subview.el); streamPlotAdded = true; } return streamPlotAdded }, getSelectedStreams : function(){ var self = this; var selectedStreamModelCollection = new StreamCollection(); _.each(self.subviews,function(currentView,i){ selectedStreamModelCollection.add(currentView.model); }); return selectedStreamModelCollection; }, remove: function(streamModel) { var self = this; var streamPlotRemoved = false; _.each(self.subviews,function(currentView,i){ var currentRef = currentView.model.get('reference_designator'); var currentStream = currentView.model.get('stream_name'); if (currentRef == streamModel.get('reference_designator') && currentStream == streamModel.get('stream_name')){ //check to see if the reference designator already exists if (i > -1) { //de render and remove for the list currentView.derender(); self.subviews.splice(i, 1); streamPlotRemoved= true; } } }); return streamPlotRemoved; }, }); var HighchartsStreamingDataOptionsView = Backbone.View.extend({ showControls: true, initialize: function(options) { if (options && options.model){ this.model = options.model; } if (options && 'showControls' in options){ this.showControls = options.showControls; } _.bindAll(this,'render','onPlayClick','onRemoveClick','onPauseClick','onHideChart'); }, events:{ 'click #streamingClose': 'onRemoveClick', 'click #playStream': 'onPlayClick', 'click #pauseStream': 'onPauseClick', 'click #download-plot' : 'plotDownloads', 'click #streamingHide' : 'onHideChart' }, onHideChart:function(){ if (this.$el.find("#streamingHide").hasClass('fa-chevron-circle-down')){ this.$el.find("#streamingHide").removeClass('fa-chevron-circle-down').addClass('fa-chevron-circle-up'); }else{ this.$el.find("#streamingHide").removeClass('fa-chevron-circle-up').addClass('fa-chevron-circle-down'); } this.$el.find('#streamingDataPlot').toggle( "slow"); }, onRemoveClick:function(){ ooi.trigger('streamPlot:removeStream',this.model); }, plotDownloads: function(e) { event.preventDefault(); var self = this; self.onPauseClick(); if ( self.streamingDataView ){ var chart = self.streamingDataView.chart; var fileName = chart.title.textStr + '_' + chart.subtitle.textStr; chart.exportChart({type: 'image/png', filename: fileName}); } }, onPlayClick:function(){ var self = this; if (self.getVariableList().length>0){ this.$el.find('#playStream').prop('disabled', true); if (self.streamingDataView.isRendered){ self.streamingDataView.chart.showLoading(); self.streamingDataView.chart.isLoading=true; self.streamingDataView.updateVariable(self.getVariableList()); self.streamingDataView.resume(); }else{ self.streamingDataView.updateVariable(self.getVariableList()); self.streamingDataView.render(); } this.$el.find('#pauseStream').prop('disabled', false); this.$el.find('#paramSelection').attr('disabled',true); this.$el.find('.selectpicker').selectpicker('refresh'); } }, onPauseClick:function(){ var self = this this.$el.find('#pauseStream').prop('disabled', true); self.streamingDataView.abort(); this.$el.find('#playStream').prop('disabled', false); this.$el.find('#paramSelection').attr('disabled',false); this.$el.find('.selectpicker').selectpicker('refresh'); }, template: JST['ooiui/static/js/partials/HighChartsStreamingDataOptionsView.html'], initialRender: function() { this.$el.html('<i class="fa fa-spinner fa-spin" style="margin-top:80px;margin-left:50%;font-size:90px;"> </i>'); return this; }, getVariableList:function(){ var self = this; var selectedItem = self.$el.find("#paramSelection option:selected"); var selected = []; $(selectedItem).each(function(index){ selected.push({'variable':$(this).data('params'),'prettyname':$(this).text()}); }); return selected; }, render: function() { var self = this; this.$el.html(this.template({streamModel:self.model,showControls:self.showControls})); var param_list = [], parameterhtml = "", shape = self.model.get('variables_shape'), autoPlot = false; var paramCount = 0; parameterhtml += "<optgroup label='Derived'>" for (var i = 0; i < _.uniq(self.model.get('variables')).length; i++) { if (param_list.indexOf(self.model.get('variables')) == -1){ if (shape[i] === "function"){ var parameterId = self.model.get('parameter_id')[i]; var units = self.model.get('units')[i]; var variable = self.model.get('variables')[i]; var displayName; try{ displayName = self.model.get('parameter_display_name')[i]; } catch(err){ displayName = variable; } //for the case when we have "sal"inity in the variable nanem but we want to remove units of "1" var validUnits = false; var validUnitsClass = "class=invalidParam" if (units.toLowerCase() != "s" && units.toLowerCase() != "1" && units.toLowerCase() != "counts" && units.toLowerCase().indexOf("seconds since") == -1 && units.toLowerCase() != "bytes"){ validUnits = true } if (variable.toLowerCase().indexOf("sal") > -1){ validUnits = true; } if (validUnits){ validUnitsClass = 'class=validParam' } if (variable.indexOf("_timestamp") == -1){ if (variable.toLowerCase() != "time"){ if ( paramCount < 4 && validUnits && (variable.indexOf('oxygen') > -1 || variable.indexOf('temperature') > -1 || variable.indexOf('velocity') > -1 || variable.indexOf('conductivity') > -1 || variable.indexOf('current') > -1 || variable.indexOf('voltage') > -1 || variable.indexOf('pressure') > -1 || variable.indexOf('ang_rate') > -1 || variable.indexOf('coefficient') > -1 || variable.indexOf('chlorophyll') > -1 || variable.indexOf('par') > -1 || variable.indexOf('heat') > -1 )){ parameterhtml+= "<option "+validUnitsClass+" selected pid='"+ parameterId +"'data-params='" + variable + "' data-subtext='"+ units +"' >"+ displayName +"</option>"; paramCount++; } else { parameterhtml+= "<option "+validUnitsClass+" pid='"+ parameterId +"'data-params='" + variable + "' data-subtext='"+ units +"' >"+ displayName +"</option>"; } param_list.push(variable); } } } } } parameterhtml += "</optgroup>" //Now get non derived parameters parameterhtml += "<optgroup label='Non Derived'>" for (var i = 0; i < _.uniq(self.model.get('variables')).length; i++) { if (param_list.indexOf(self.model.get('variables')) == -1){ if (shape[i] != "function"){ var parameterId = self.model.get('parameter_id')[i]; var units = self.model.get('units')[i]; var variable = self.model.get('variables')[i]; var displayName; try{ displayName = self.model.get('parameter_display_name')[i]; } catch(err){ displayName = variable; } //for the case when we have "sal"inity in the variable nanem but we want to remove units of "1" var validUnits = false; var validUnitsClass = "class=invalidParam"; if (units.toLowerCase() != "s" && units.toLowerCase() != "1" && units.toLowerCase() != "counts" && units.toLowerCase().indexOf("seconds since") == -1 && units.toLowerCase() != "bytes"){ validUnits = true } if (variable.toLowerCase().indexOf("sal") > -1){ validUnits = true; } if (validUnits){ validUnitsClass = 'class=validParam' } if (variable.toLowerCase() != "time"){ if ( paramCount < 4 && ( parameterhtml.indexOf("<optgroup label='Derived'></optgroup>") > -1 ) && validUnits && (variable.indexOf('oxygen') > -1 || variable.indexOf('temperature') > -1 || variable.indexOf('velocity') > -1 || variable.indexOf('conductivity') > -1 || variable.indexOf('current') > -1 || variable.indexOf('voltage') > -1 || variable.indexOf('pressure') > -1 || variable.indexOf('ang_rate') > -1 || variable.indexOf('coefficient') > -1 || variable.indexOf('chlorophyll') > -1 || variable.indexOf('par') > -1) ) { parameterhtml+= "<option "+validUnitsClass+" selected pid='"+ parameterId +"'data-params='" + variable + "' data-subtext='"+ units +"' >"+ displayName +"</option>"; paramCount++; } else { parameterhtml+= "<option "+validUnitsClass+" pid='"+ parameterId +"'data-params='" + variable + "' data-subtext='"+ units +"' >"+ displayName +"</option>"; } param_list.push(variable); } } } } parameterhtml += "</optgroup>" self.$el.find('#paramSelection').html(parameterhtml) self.$el.find('#paramSelection .invalidParam').attr('disabled','disabled'); self.$el.find('#paramSelection').selectpicker('refresh'); this.streamingDataView = new HighchartsStreamingDataView({ model: self.model, el: self.$el.find('#streamingDataPlot'), variable: self.getVariableList() }); this.$el.find('#playStream').click(); setTimeout(function (){ $(document).resize() }, 100); }, derender: function() { this.streamingDataView.abort(); this.streamingDataView.remove(); this.streamingDataView.unbind(); this.streamingDataView.chart = null; this.streamingDataView.$el.remove(); this.streamingDataView = null; this.remove(); this.unbind(); if (this.model) this.model.off(); } }); var HighchartsStreamingDataView = Backbone.View.extend({ multiRequest: true, isRendered:false, initialize: function(options) { var self = this; this.title = options && options.title || "Chart"; this.title_style = options && options.title_style || { }; this.subtitle = options && options.subtitle || ""; _.bindAll(this, "onClick",'requestData','abort','updateDateTimes','getUrl','updateVariable','resume'); var dt = moment().utc(); var dt2Str = self.getEndDate(dt,0); var dt1Str = self.getStartDate(dt,300); self.variable = options.variable; self.variable_list = []; _.each(self.variable,function(data_variable,vv){ self.variable_list.push(data_variable['variable']); }); this.ds = new DataSeriesCollection([],{'stream':this.model.get('stream_name'),'ref_des':this.model.get('ref_des'), 'xparameters':['time'],'yparameters':self.variable_list, 'startdate':dt1Str,'enddate':dt2Str}); }, getStartDate:function(dt,rm_seconds){ //start date return dt.subtract(rm_seconds, 'seconds').format("YYYY-MM-DDTHH:mm:ss.000")+"Z" }, getEndDate:function(dt,rm_seconds){ //needs to be first, previous 10 seconds return dt.subtract(rm_seconds, 'seconds').format("YYYY-MM-DDTHH:mm:ss.000")+"Z" }, updateVariable:function(variable){ var self = this; self.variable = variable; self.variable_list = []; _.each(self.variable,function(data_variable,vv){ self.variable_list.push(data_variable['variable']); }); self.ds.yparameters = [self.variable_list]; self.resetAxis = true; }, updateDateTimes:function(){ var self = this; //update datetime using new moment dates var dt = moment().utc(); var dt2Str = self.getEndDate(dt,0); if (self.overrideStDate){ //override start date if data points exceed 0 var dt1Str = self.getStartDate(dt,300); this.ds.startdate = dt1Str; } this.ds.enddate = dt2Str; }, onClick: function(e, point) { //this.trigger('onClick', e, point); }, abort:function(){ //kill the request, if its availble this.multiRequest = false; try{ this.xhr.onreadystatechange = null; this.xhr.abort() }catch(e){ } }, resume:function(){ //kill the request this.multiRequest = true; this.overrideStDate = true; this.requestData(); }, getUrl:function(){ var self = this; self.updateDateTimes(); return this.ds.url(); }, requestData: function() { var self = this; self.xhr = $.ajax({ url: self.getUrl(), cache: false, error: function(XMLHttpRequest, textStatus, errorThrown) { // if (errorThrown!="abort"){ self.$el.parent().parent().parent().find('#pauseStream').click(); self.$el.find('.highcharts-container .highcharts-loading span').text('Error Loading...'); bootbox.dialog({ title: "Error Getting Data From Stream", message: "There was an error obtaining the stream data from uframe", }); } }, success: function(points) { if (self.multiRequest){ if (self.isLoading){ self.chart.hideLoading(); } var point = null; if (self.resetAxis){ for (var i = 0; i < 4; i++) { var series = self.chart.series[i]; self.chart.yAxis[i].update({ labels: {enabled: false}, title: {text: null} }); self.chart.series[i].setData([]); self.chart.series[i].hide(); self.chart.series[i].options.showInLegend = false; self.chart.series[i].legendItem = null; self.chart.legend.destroyItem(self.chart.series[i]); } } self.chart.legend.render(); _.each(self.variable,function(data_variable,vv){ var series = self.chart.series[vv]; var shift = false; var shift = self.chart.series[vv].data.length > 200; if (self.resetAxis){ //reset the axis and some of the contents series.name = data_variable['prettyname']; //self.chart.legend.allItems[vv].update({name:series.name}); series.options.showInLegend = true; self.chart.yAxis[vv].update({ labels: {enabled: true}, title: {text:points['units'][self.variable_list[vv]]} }); series.options.units = points['units'][self.variable_list[vv]]; self.chart.series[vv].show(); self.chart.redraw(); self.chart.legend.renderItem(series); self.chart.legend.render(); } //only override the data if their are points available self.overrideStDate = true; if (points['data'].length > 0){ var dx= null; self.overrideStDate = false; for (var i = 0; i < points['data'].length; i++) { var x = points['data'][i]['time']; var y = points['data'][i][self.variable_list[vv]]; x -= 2208988800; x = x*1000; dx= moment.utc(x); point = [dx._i,y] if (i < points['data'].length-1){ self.chart.series[vv].addPoint(point, false, shift); }else{ self.chart.series[vv].addPoint(point, true, shift); } } //fix start date self.ds.startdate = moment.utc(x).format("YYYY-MM-DDTHH:mm:ss.000")+"Z" } }); if (self.resetAxis){ self.chart.redraw(); self.resetAxis = false; } if (self.multiRequest){ // call it again after (X) seconds setTimeout(self.requestData, 2000); } } }, cache: false }); }, render: function() { var self = this; self.isRendered = true; self.resetAxis = true; self.isLoading = true; var formatter = d3.format(".2f"); var yAxisList = []; var seriesList = []; for (var i = 0; i < 4; i++) { var op = !((i+1) % 2); var gridWidth = 1; if (i>0){ gridWidth = 0; } yAxisList.push({ gridLineWidth:gridWidth, labels: { format: '{value:.2f}', style: { color: Highcharts.getOptions().colors[i] } }, minPadding: 0.2, maxPadding: 0.2, title: { text: null, margin: 80, style: { color: Highcharts.getOptions().colors[i] } }, opposite: op }) seriesList.push({ yAxis: i, name: "unknown", data: [] }); } self.chart = new Highcharts.Chart({ chart: { renderTo: self.el, defaultSeriesType: 'line', events: { load: self.requestData } }, credits: { enabled: false }, loading: { labelStyle: { //color: 'black' }, style: { //backgroundColor: 'lightblue', //opacity: 0.4, }, hideDuration: 500, showDuration: 1000, }, plotOptions: { line: { marker: { enabled: false, } } }, title: { text: self.model.get('display_name') }, subtitle: { text: self.model.get('stream_name') }, legend: { align: 'left' }, exporting: { //Enable exporting images enabled: true, scale: 1, enableImages: true, legend:{ enabled:true }, chartOptions: { chart: { width: 1400, height: 400, events: { load: function () { var chart = this; $.each(chart.series,function(i,series) { series.name = self.chart.series[i].name chart.legend.renderItem(series); }); chart.legend.render(); } } }, } }, xAxis: [{ type: 'datetime', tickPixelInterval: 150, maxZoom: 20 * 1000, title: { text: 'Date (UTC)' } }], tooltip: { useHTML: true, formatter: function() { var x = this.x; var s = ''; s+='<p><b>Time: '+Highcharts.dateFormat('%Y-%m-%d %H:%M:%S UTC', this.x) +'</b></p><p>'; _.each(self.chart.series,function(series) { if (series.visible) { // Assume the data is ordered by time. Find the 1st value that is >= x. var xy = _.find(series.data,function(o){return o.x >= x}); if (xy) { s += '<span style="color: ' + series.color + ';">' + series.name + '</span>' + ': ' + formatter(xy.y)+ '</p>'; } } }); return s; }, shared: true, crosshairs : [true,false] }, yAxis: yAxisList, series: seriesList }); self.chart.showLoading(); } });
FBRTMaka/ooi-ui
ooiui/static/js/views/science/HighChartsStreamingDataView.js
JavaScript
mit
23,076
/* * homeController.js * Jami Boy Mohammad */ var homeController = angular.module('homeController', []); homeController.controller('homeController', function($scope) { });
jamiboy16/bearded-ninja
public/app/components/home/homeController.js
JavaScript
mit
179
'use strict'; /**@type {{[k: string]: string}} */ let BattleAliases = { // formats "randbats": "[Gen 8] Random Battle", "uber": "[Gen 8] Ubers", "ag": "[Gen 8] Anything Goes", "mono": "[Gen 8] Monotype", "randdubs": "[Gen 8] Random Doubles Battle", "doubles": "[Gen 8] Doubles OU", "dubs": "[Gen 8] Doubles OU", "dou": "[Gen 8] Doubles OU", "duu": "[Gen 8] Doubles UU", "vgc17": "[Gen 7] VGC 2017", "vgc18": "[Gen 7] VGC 2018", "vgc19": "[Gen 7] VGC 2019 Ultra Series", "bss": "[Gen 8] Battle Stadium Singles", "bsd": "[Gen 8] Battle Stadium Doubles", "bsdoubles": "[Gen 8] Battle Stadium Doubles", "2v2": "[Gen 8] 2v2 Doubles", "natdex": "[Gen 8] National Dex", "natdexag": "[Gen 8] National Dex AG", "bh": "[Gen 8] Balanced Hackmons", "mnm": "[Gen 8] Mix and Mega", "aaa": "[Gen 8] Almost Any Ability", "gen7bh": "[Gen 7] Balanced Hackmons", "cc1v1": "[Gen 8] Challenge Cup 1v1", "cc2v2": "[Gen 8] Challenge Cup 2v2", "hc": "[Gen 8] Hackmons Cup", "monorandom": "[Gen 8] Monotype Random Battle", "bf": "[Gen 7] Battle Factory", "bssf": "[Gen 7] BSS Factory", "ssb": "[Gen 7] Super Staff Bros Brawl", "lgrandom": "[Gen 7] Let's Go Random Battle", "gen6bf": "[Gen 6] Battle Factory", "gen7mono": "[Gen 7] Monotype", "gen7ag": "[Gen 7] Anything Goes", "gen7bss": "[Gen 7] Battle Spot Singles", "gen7bsd": "[Gen 7] Battle Spot Doubles", "gen6mono": "[Gen 6] Monotype", "gen6ag": "[Gen 6] Anything Goes", "petmod": "[Gen 7 Pet Mod] Clean Slate: Micro", "cleanslatemicro": "[Gen 7 Pet Mod] Clean Slate: Micro", "csm": "[Gen 7 Pet Mod] Clean Slate: Micro", // mega evos "fabio": "Ampharos-Mega", "maero": "Aerodactyl-Mega", "megabunny": "Lopunny-Mega", "megabro": "Slowbro-Mega", "megacharizard": "Charizard-Mega-Y", "megacharizardx": "Charizard-Mega-X", "megacharizardy": "Charizard-Mega-Y", "megadoom": "Houndoom-Mega", "megadrill": "Beedrill-Mega", "megagard": "Gardevoir-Mega", "megacross": "Heracross-Mega", "megakhan": "Kangaskhan-Mega", "megalop": "Lopunny-Mega", "megaluc": "Lucario-Mega", "megamaw": "Mawile-Mega", "megamedi": "Medicham-Mega", "megamewtwo": "Mewtwo-Mega-Y", "megamewtwox": "Mewtwo-Mega-X", "megamewtwoy": "Mewtwo-Mega-Y", "megasnow": "Abomasnow-Mega", "megashark": "Sharpedo-Mega", "megasaur": "Venusaur-Mega", "mmx": "Mewtwo-Mega-X", "mmy": "Mewtwo-Mega-Y", "zardx": "Charizard-Mega-X", "zardy": "Charizard-Mega-y", // Pokéstar Studios "blackdoor": "Pokestar Black-Door", "brycen": "Brycen-Man", "brycenman": "Pokestar Brycen-Man", "f00": "Pokestar F00", "f002": "Pokestar F002", "giant": "Pokestar Giant", "mt": "Pokestar MT", "mt2": "Pokestar MT2", "majin": "Spirit", "mechatyranitar": "MT", "mechatyranitar2": "MT2", "monica": "Giant", "spirit": "Pokestar Spirit", "transport": "Pokestar Transport", "ufo": "Pokestar UFO", "ufo2": "Pokestar UFO-2", "whitedoor": "Pokestar White-Door", // formes "bugceus": "Arceus-Bug", "darkceus": "Arceus-Dark", "dragonceus": "Arceus-Dragon", "eleceus": "Arceus-Electric", "fairyceus": "Arceus-Fairy", "fightceus": "Arceus-Fighting", "fireceus": "Arceus-Fire", "flyceus": "Arceus-Flying", "ghostceus": "Arceus-Ghost", "grassceus": "Arceus-Grass", "groundceus": "Arceus-Ground", "iceceus": "Arceus-Ice", "poisonceus": "Arceus-Poison", "psyceus": "Arceus-Psychic", "rockceus": "Arceus-Rock", "steelceus": "Arceus-Steel", "waterceus": "Arceus-Water", "arcbug": "Arceus-Bug", "arcdark": "Arceus-Dark", "arcdragon": "Arceus-Dragon", "arcelectric": "Arceus-Electric", "arcfairy": "Arceus-Fairy", "arcfighting": "Arceus-Fighting", "arcfire": "Arceus-Fire", "arcflying": "Arceus-Flying", "arcghost": "Arceus-Ghost", "arcgrass": "Arceus-Grass", "arcground": "Arceus-Ground", "arcice": "Arceus-Ice", "arcpoison": "Arceus-Poison", "arcpsychic": "Arceus-Psychic", "arcrock": "Arceus-Rock", "arcsteel": "Arceus-Steel", "arcwater": "Arceus-Water", "basculinb": "Basculin-Blue-Striped", "basculinblue": "Basculin-Blue-Striped", "basculinbluestripe": "Basculin-Blue-Striped", "castformh": "Castform-Snowy", "castformice": "Castform-Snowy", "castformr": "Castform-Rainy", "castformwater": "Castform-Rainy", "castforms": "Castform-Sunny", "castformfire": "Castform-Sunny", "cherrims": "Cherrim-Sunshine", "cherrimsunny": "Cherrim-Sunshine", "darmanitanz": "Darmanitan-Zen", "darmanitanzenmode": "Darmanitan-Zen", "darmanitanzengalar": "Darmanitan-Galar-Zen", "deoxysnormal": "Deoxys", "deon": "Deoxys", "deoxysa": "Deoxys-Attack", "deoa": "Deoxys-Attack", "deoxysd": "Deoxys-Defense", "deoxysdefence": "Deoxys-Defense", "deod": "Deoxys-Defense", "deoxyss": "Deoxys-Speed", "deos": "Deoxys-Speed", "eiscuen": "Eiscue-Noice", "eternalfloette": "Floette-Eternal", "eternamax": "Eternatus-Eternamax", "girao": "Giratina-Origin", "giratinao": "Giratina-Origin", "gourgeists": "Gourgeist-Small", "gourgeistl": "Gourgeist-Large", "gourgeistxl": "Gourgeist-Super", "gourgeisth": "Gourgeist-Super", "gourgeisthuge": "Gourgeist-Super", "hoopau": "Hoopa-Unbound", "keldeor": "Keldeo-Resolute", "keldeoresolution": "Keldeo-Resolute", "kyuremb": "Kyurem-Black", "kyuremw": "Kyurem-White", "landorust": "Landorus-Therian", "meloettap": "Meloetta-Pirouette", "meloettas": "Meloetta-Pirouette", "meloettastep": "Meloetta-Pirouette", "meowsticfemale": "Meowstic-F", "morpekoh": "Morpeko-Hangry", "pumpkaboohuge": "Pumpkaboo-Super", "rotomc": "Rotom-Mow", "rotomcut": "Rotom-Mow", "rotomf": "Rotom-Frost", "rotomh": "Rotom-Heat", "rotoms": "Rotom-Fan", "rotomspin": "Rotom-Fan", "rotomw": "Rotom-Wash", "shaymins": "Shaymin-Sky", "skymin": "Shaymin-Sky", "thundurust": "Thundurus-Therian", "thundyt": "Thundurus-Therian", "tornadust": "Tornadus-Therian", "tornt": "Tornadus-Therian", "toxtricityl": "Toxtricity-Low-Key", "toxtricitylk": "Toxtricity-Low-Key", "wormadamg": "Wormadam-Sandy", "wormadamground": "Wormadam-Sandy", "wormadamsandycloak": "Wormadam-Sandy", "wormadams": "Wormadam-Trash", "wormadamsteel": "Wormadam-Trash", "wormadamtrashcloak": "Wormadam-Trash", "floettee": "Floette-Eternal", "floetteeternalflower": "Floette-Eternal", "ashgreninja": "Greninja-Ash", "zydog": "Zygarde-10%", "zydoge": "Zygarde-10%", "zygardedog": "Zygarde-10%", "zygarde50": "Zygarde", "zyc": "Zygarde-Complete", "zygarde100": "Zygarde-Complete", "zygardec": "Zygarde-Complete", "zygardefull": "Zygarde-Complete", "zygod": "Zygarde-Complete", "perfectzygarde": "Zygarde-Complete", "oricoriob": "Oricorio", "oricoriobaile": "Oricorio", "oricoriof": "Oricorio", "oricoriofire": "Oricorio", "oricorioe": "Oricorio-Pom-Pom", "oricorioelectric": "Oricorio-Pom-Pom", "oricoriog": "Oricorio-Sensu", "oricorioghost": "Oricorio-Sensu", "oricorios": "Oricorio-Sensu", "oricoriop": "Oricorio-Pa'u", "oricoriopsychic": "Oricorio-Pa'u", "lycanrocmidday": "Lycanroc", "lycanrocday": "Lycanroc", "lycanrocn": "Lycanroc-Midnight", "lycanrocnight": "Lycanroc-Midnight", "lycanrocd": "Lycanroc-Dusk", "ndm": "Necrozma-Dusk-Mane", "ndw": "Necrozma-Dawn-Wings", "necrozmadm": "Necrozma-Dusk-Mane", "necrozmadusk": "Necrozma-Dusk-Mane", "duskmane": "Necrozma-Dusk-Mane", "duskmanenecrozma": "Necrozma-Dusk-Mane", "necrozmadw": "Necrozma-Dawn-Wings", "necrozmadawn": "Necrozma-Dawn-Wings", "dawnwings": "Necrozma-Dawn-Wings", "dawnwingsnecrozma": "Necrozma-Dawn-Wings", "necrozmau": "Necrozma-Ultra", "ultranecrozma": "Necrozma-Ultra", "unecro": "Necrozma-Ultra", "ufop": "Pokestar UFO-2", "ufopsychic": "Pokestar UFO-2", "zacianc": "Zacian-Crowned", "zamazentac": "Zamazenta-Crowned", // base formes "nidoranfemale": "Nidoran-F", "nidoranmale": "Nidoran-M", "wormadamgrass": "Wormadam", "wormadamp": "Wormadam", "wormadamplant": "Wormadam", "wormadamplantcloak": "Wormadam", "cherrimo": "Cherrim", "cherrimovercast": "Cherrim", "giratinaa": "Giratina", "giratinaaltered": "Giratina", "shayminl": "Shaymin", "shayminland": "Shaymin", "basculinr": "Basculin", "basculinred": "Basculin", "basculinredstripe": "Basculin", "basculinredstriped": "Basculin", "darmanitans": "Darmanitan", "darmanitanstandard": "Darmanitan", "darmanitanstandardmode": "Darmanitan", "tornadusi": "Tornadus", "tornadusincarnate": "Tornadus", "tornadusincarnation": "Tornadus", "thundurusi": "Thundurus", "thundurusincarnate": "Thundurus", "thundurusincarnation": "Thundurus", "landorusi": "Landorus", "landorusincarnate": "Landorus", "landorusincarnation": "Landorus", "keldeoo": "Keldeo", "keldeoordinary": "Keldeo", "meloettaa": "Meloetta", "meloettaaria": "Meloetta", "meloettavoice": "Meloetta", "meowsticm": "Meowstic", "meowsticmale": "Meowstic", "aegislashs": "Aegislash", "aegislashshield": "Aegislash", "pumpkabooaverage": "Pumpkaboo", "gourgeistaverage": "Gourgeist", "hoopac": "Hoopa", "hoopaconfined": "Hoopa", "wishiwashisolo": "Wishiwashi", "pokestarufof": "Pokestar UFO", "pokestarufoflying": "Pokestar UFO", "toxtricitya": "Toxtricity", "toxtricityamped": "Toxtricity", "ufof": "Pokestar UFO", "ufoflying": "Pokestar UFO", // event formes "rockruffdusk": "Rockruff", // totem formes "raticatet": "Raticate-Alola-Totem", "totemalolanraticate": "Raticate-Alola-Totem", "totemraticate": "Raticate-Alola-Totem", "totemraticatea": "Raticate-Alola-Totem", "totemraticatealola": "Raticate-Alola-Totem", "marowakt": "Marowak-Alola-Totem", "totemalolanmarowak": "Marowak-Alola-Totem", "totemmarowak": "Marowak-Alola-Totem", "totemmarowaka": "Marowak-Alola-Totem", "totemmarowakalola": "Marowak-Alola-Totem", "gumshoost": "Gumshoos-Totem", "totemgumshoos": "Gumshoos-Totem", "totemvikavolt": "Vikavolt-Totem", "vikavoltt": "Vikavolt-Totem", "ribombeet": "Ribombee-Totem", "totemribombee": "Ribombee-Totem", "araquanidt": "Araquanid-Totem", "totemaraquanid": "Araquanid-Totem", "lurantist": "Lurantis-Totem", "totemlurantis": "Lurantis-Totem", "salazzlet": "Salazzle-Totem", "totemsalazzle": "Salazzle-Totem", "mimikyut": "Mimikyu-Totem", "totemmimikyu": "Mimikyu-Totem", "kommoot": "Kommo-o-Totem", "totemkommoo": "Kommo-o-Totem", // cosmetic formes "alcremierubycream": "Alcremie", "alcremiematcha": "Alcremie", "alcremiemint": "Alcremie", "alcremielemon": "Alcremie", "alcremiesalted": "Alcremie", "alcremierubyswirl": "Alcremie", "alcremiecaramel": "Alcremie", "alcremierainbow": "Alcremie", "burmygrass": "Burmy", "burmyplant": "Burmy", "burmysandy": "Burmy", "burmytrash": "Burmy", "shelloseast": "Shellos", "shelloswest": "Shellos", "gastrodone": "Gastrodon", "gastrodoneast": "Gastrodon", "gastrodoneastsea": "Gastrodon", "gastrodonw": "Gastrodon", "gastrodonwest": "Gastrodon", "gastrodonwestsea": "Gastrodon", "deerlingspring": "Deerling", "deerlingsummer": "Deerling", "deerlingautumn": "Deerling", "deerlingwinter": "Deerling", "sawsbuckspring": "Sawsbuck", "sawsbucksummer": "Sawsbuck", "sawsbuckautumn": "Sawsbuck", "sawsbuckwinter": "Sawsbuck", "vivillonarchipelago": "Vivillon", "vivilloncontinental": "Vivillon", "vivillonelegant": "Vivillon", "vivillongarden": "Vivillon", "vivillonhighplains": "Vivillon", "vivillonicysnow": "Vivillon", "vivillonjungle": "Vivillon", "vivillonmarine": "Vivillon", "vivillonmodern": "Vivillon", "vivillonmonsoon": "Vivillon", "vivillonocean": "Vivillon", "vivillonpolar": "Vivillon", "vivillonriver": "Vivillon", "vivillonsandstorm": "Vivillon", "vivillonsavanna": "Vivillon", "vivillonsun": "Vivillon", "vivillontundra": "Vivillon", "flabb": "Flabebe", "flabebered": "Flabebe", "flabebeblue": "Flabebe", "flabebeorange": "Flabebe", "flabebewhite": "Flabebe", "flabebeyellow": "Flabebe", "flabbred": "Flabebe", "flabbblue": "Flabebe", "flabborange": "Flabebe", "flabbwhite": "Flabebe", "flabbyellow": "Flabebe", "floettered": "Floette", "floetteblue": "Floette", "floetteorange": "Floette", "floettewhite": "Floette", "floetteyellow": "Floette", "florgesred": "Florges", "florgesblue": "Florges", "florgesorange": "Florges", "florgeswhite": "Florges", "florgesyellow": "Florges", "furfroudandy": "Furfrou", "furfroudebutante": "Furfrou", "furfroudiamond": "Furfrou", "furfrouheart": "Furfrou", "furfroukabuki": "Furfrou", "furfroulareine": "Furfrou", "furfroumatron": "Furfrou", "furfroupharaoh": "Furfrou", "furfroustar": "Furfrou", "miniorred": "Minior", "miniororange": "Minior", "minioryellow": "Minior", "miniorgreen": "Minior", "miniorblue": "Minior", "miniorindigo": "Minior", "miniorviolet": "Minior", "pokestargiant2": "Pokestar Giant", "pokestarmonica2": "Pokestar Giant", "pokestarufopropu1": "Pokestar UFO", "pokestarpropu1": "Pokestar UFO", "pokestarpropu2": "Pokestar UFO-2", "pokestarbrycenmanprop": "Pokestar Brycen-Man", "pokestarproph1": "Pokestar Brycen-Man", "pokestarmtprop": "Pokestar MT", "pokestarpropm1": "Pokestar MT", "pokestarmt2prop": "Pokestar MT2", "pokestarpropm2": "Pokestar MT2", "pokestartransportprop": "Pokestar Transport", "pokestarpropt1": "Pokestar Transport", "pokestargiantpropo1": "Pokestar Giant", "pokestarpropo1": "Pokestar Giant", "pokestargiantpropo2": "Pokestar Giant", "pokestarpropo2": "Pokestar Giant", "pokestarhumanoidprop": "Pokestar Humanoid", "pokestarpropc1": "Pokestar Humanoid", "pokestarmonsterprop": "Pokestar Monster", "pokestarpropc2": "Pokestar Monster", "pokestarspiritprop": "Pokestar Spirit", "pokestarpropg1": "Pokestar Spirit", "pokestarblackdoorprop": "Pokestar Black Door", "pokestarpropw1": "Pokestar Black Door", "pokestarwhitedoorprop": "Pokestar White Door", "pokestarpropw2": "Pokestar White Door", "pokestarf00prop": "Pokestar F00", "pokestarpropr1": "Pokestar F00", "pokestarf002prop": "Pokestar F002", "pokestarpropr2": "Pokestar F002", "pokestarblackbeltprop": "Pokestar Black Belt", "pokestarpropk1": "Pokestar Black Belt", "giant2": "Pokestar Giant", "monica2": "Pokestar Giant", "ufopropu1": "Pokestar UFO", "propu1": "Pokestar UFO", "ufopropu2": "Pokestar UFO-2", "propu2": "Pokestar UFO-2", "brycenmanprop": "Pokestar Brycen-Man", "proph1": "Pokestar Brycen-Man", "mtprop": "Pokestar MT", "propm1": "Pokestar MT", "mt2prop": "Pokestar MT2", "propm2": "Pokestar MT2", "transportprop": "Pokestar Transport", "propt1": "Pokestar Transport", "giantpropo1": "Pokestar Giant", "propo1": "Pokestar Giant", "giantpropo2": "Pokestar Giant", "propo2": "Pokestar Giant", "humanoidprop": "Pokestar Humanoid", "propc1": "Pokestar Humanoid", "monsterprop": "Pokestar Monster", "propc2": "Pokestar Monster", "spiritprop": "Pokestar Spirit", "propg1": "Pokestar Spirit", "blackdoorprop": "Pokestar Black Door", "propw1": "Pokestar Black Door", "whitedoorprop": "Pokestar White Door", "propw2": "Pokestar White Door", "f00prop": "Pokestar F00", "propr1": "Pokestar F00", "f002prop": "Pokestar F002", "propr2": "Pokestar F002", "blackbeltprop": "Pokestar Black Belt", "propk1": "Pokestar Black Belt", // abilities "ph": "Poison Heal", "regen": "Regenerator", "stag": "Shadow Tag", // items "assvest": "Assault Vest", "av": "Assault Vest", "balloon": "Air Balloon", "band": "Choice Band", "cb": "Choice Band", "ebelt": "Expert Belt", "fightgem": "Fighting Gem", "flightgem": "Flying Gem", "goggles": "Safety Goggles", "helmet": "Rocky Helmet", "lefties": "Leftovers", "lo": "Life Orb", "lorb": "Life Orb", "sash": "Focus Sash", "scarf": "Choice Scarf", "specs": "Choice Specs", "wp": "Weakness Policy", // pokemon "aboma": "Abomasnow", "aegi": "Aegislash", "aegiblade": "Aegislash-Blade", "aegis": "Aegislash", "aero": "Aerodactyl", "amph": "Ampharos", "arc": "Arceus", "arceusnormal": "Arceus", "ashgren": "Greninja-Ash", "azu": "Azumarill", "bdrill": "Beedrill", "bee": "Beedrill", "birdjesus": "Pidgeot", "bish": "Bisharp", "blace": "Blacephalon", "bliss": "Blissey", "bulu": "Tapu Bulu", "camel": "Camerupt", "cathy": "Trevenant", "chandy": "Chandelure", "chomp": "Garchomp", "clef": "Clefable", "coba": "Cobalion", "cofag": "Cofagrigus", "conk": "Conkeldurr", "cress": "Cresselia", "cube": "Kyurem-Black", "cune": "Suicune", "darm": "Darmanitan", "dnite": "Dragonite", "dogars": "Koffing", "don": "Groudon", "drill": "Excadrill", "driller": "Excadrill", "dug": "Dugtrio", "duggy": "Dugtrio", "ekiller": "Arceus", "esca": "Escavalier", "ferro": "Ferrothorn", "fini": "Tapu Fini", "forry": "Forretress", "fug": "Rayquaza", "gar": "Gengar", "garde": "Gardevoir", "gatr": "Feraligatr", "gene": "Genesect", "gira": "Giratina", "gren": "Greninja", "gross": "Metagross", "gyara": "Gyarados", "hera": "Heracross", "hippo": "Hippowdon", "honch": "Honchkrow", "kanga": "Kangaskhan", "karp": "Magikarp", "kart": "Kartana", "keld": "Keldeo", "klef": "Klefki", "koko": "Tapu Koko", "kou": "Raikou", "krook": "Krookodile", "kyub": "Kyurem-Black", "kyuw": "Kyurem-White", "lando": "Landorus", "landoi": "Landorus", "landot": "Landorus-Therian", "lego": "Nihilego", "lele": "Tapu Lele", "linda": "Fletchinder", "luke": "Lucario", "lurk": "Golurk", "mage": "Magearna", "mamo": "Mamoswine", "mandi": "Mandibuzz", "mence": "Salamence", "milo": "Milotic", "morfentshusbando": "Gengar", "naga": "Naganadel", "nape": "Infernape", "nebby": "Cosmog", "neckboy": "Exeggutor-Alola", "nidok": "Nidoking", "nidoq": "Nidoqueen", "obama": "Abomasnow", "ogre": "Kyogre", "ohmagod": "Plasmanta", "p2": "Porygon2", "pert": "Swampert", "pex": "Toxapex", "phero": "Pheromosa", "pika": "Pikachu", "pory2": "Porygon2", "poryz": "Porygon-Z", "pyuku": "Pyukumuku", "pz": "Porygon-Z", "queen": "Nidoqueen", "rachi": "Jirachi", "rank": "Reuniclus", "ray": "Rayquaza", "reuni": "Reuniclus", "sab": "Sableye", "sable": "Sableye", "scept": "Sceptile", "scoli": "Scolipede", "serp": "Serperior", "shao": "Mienshao", "skarm": "Skarmory", "smogon": "Koffing", "smogonbird": "Talonflame", "snips": "Drapion", "staka": "Stakataka", "steela": "Celesteela", "sui": "Suicune", "swole": "Buzzwole", "talon": "Talonflame", "tang": "Tangrowth", "terra": "Terrakion", "tflame": "Talonflame", "thundy": "Thundurus", "toed": "Politoed", "torn": "Tornadus", "tran": "Heatran", "ttar": "Tyranitar", "venu": "Venusaur", "viriz": "Virizion", "whimsi": "Whimsicott", "xern": "Xerneas", "xurk": "Xurkitree", "ygod": "Yveltal", "zam": "Alakazam", "zard": "Charizard", "zong": "Bronzong", "zor": "Scizor", "zyg": "Zygarde", // ultra beast codenames "ub01": "Nihilego", "ub02a": "Buzzwole", "ub02b": "Pheromosa", "ub03": "Xurkitree", "ub04blade": "Kartana", "ub04blaster": "Celesteela", "ub05": "Guzzlord", "ubburst": "Blacephalon", "ubassembly": "Stakataka", "ubadhesive": "Poipole", // moves "bb": "Brave Bird", "bd": "Belly Drum", "bpass": "Baton Pass", "bp": "Baton Pass", "cc": "Close Combat", "cm": "Calm Mind", "dbond": "Destiny Bond", "dd": "Dragon Dance", "dv": "Dark Void", "eq": "Earthquake", "espeed": "ExtremeSpeed", "eterrain": "Electric Terrain", "faintattack": "Feint Attack", "glowpunch": "Power-up Punch", "gterrain": "Grassy Terrain", "hp": "Hidden Power", "hpbug": "Hidden Power Bug", "hpdark": "Hidden Power Dark", "hpdragon": "Hidden Power Dragon", "hpelectric": "Hidden Power electric", "hpfighting": "Hidden Power Fighting", "hpfire": "Hidden Power Fire", "hpflying": "Hidden Power Flying", "hpghost": "Hidden Power Ghost", "hpgrass": "Hidden Power Grass", "hpground": "Hidden Power Ground", "hpice": "Hidden Power Ice", "hppoison": "Hidden Power Poison", "hppsychic": "Hidden Power Psychic", "hprock": "Hidden Power Rock", "hpsteel": "Hidden Power Steel", "hpwater": "Hidden Power Water", "hjk": "High Jump Kick", "hijumpkick": "High Jump Kick", "mterrain": "Misty Terrain", "np": "Nasty Plot", "pfists": "Plasma Fists", "playaround": "Play Rough", "pterrain": "Psychic Terrain", "pup": "Power-up Punch", "qd": "Quiver Dance", "rocks": "Stealth Rock", "sd": "Swords Dance", "se": "Stone Edge", "spin": "Rapid Spin", "sr": "Stealth Rock", "sub": "Substitute", "tr": "Trick Room", "troom": "Trick Room", "tbolt": "Thunderbolt", "tspikes": "Toxic Spikes", "twave": "Thunder Wave", "vicegrip": "Vise Grip", "web": "Sticky Web", "wow": "Will-O-Wisp", // z-moves "10mv": "10,000,000 Volt Thunderbolt", "10mvt": "10,000,000 Volt Thunderbolt", "clangorous": "Clangorous Soulblaze", "cs": "Clangorous Soulblaze", "ee": "Extreme Evoboost", "extreme": "Extreme Evoboost", "genesis": "Genesis Supernova", "goa": "Guardian of Alola", "gs": "Genesis Supernova", "guardian": "Guardian of Alola", "lets": "Let's Snuggle Forever", "light": "Light That Burns the Sky", "lsf": "Let's Snuggle Forever", "ltbts": "Light That Burns the Sky", "malicious": "Malicious Moonsault", "menacing": "Menacing Moonraze Maelstrom", "mmm": "Menacing Moonraze Maelstrom", "moonsault": "Malicious Moonsault", "oceanic": "Oceanic Operetta", "oo": "Oceanic Operetta", "pp": "Pulverizing Pancake", "pulverizing": "Pulverizing Pancake", "sar": "Sinister Arrow Raid", "searing": "Searing Sunraze Smash", "sinister": "Sinister Arrow Raid", "ss": "Stoked Sparksurfer", "sss": "Searing Sunraze Smash", "sssss": "Soul-Stealing 7-Star Strike", "ss7ss": "Soul-Stealing 7-Star Strike", "soul": "Soul-Stealing 7-Star Strike", "soulstealingsevenstarstrike": "Soul-Stealing 7-Star Strike", "splintered": "Splintered Stormshards", "stoked": "Stoked Sparksurfer", "stormshards": "Splintered Stormshards", "zbug": "Savage Spin-Out", "zclangingscales": "Clangorous Soulblaze", "zdark": "Black Hole Eclipse", "zdarkestlariat": "Malicious Moonsault", "zdawnwingsnecrozma": "Menacing Moonraze Maelstrom", "zdecidueye": "Sinister Arrow Raid", "zdragon": "Devastating Drake", "zduskmanenecrozma": "Searing Sunraze Smash", "zelectric": "Gigavolt Havoc", "zeevee": "Extreme Evoboost", "zevo": "Extreme Evoboost", "zfairy": "Twinkle Tackle", "zflying": "Supersonic Skystrike", "zfighting": "All-Out Pummeling", "zfire": "Inferno Overdrive", "zghost": "Never-Ending Nightmare", "zgigaimpact": "Pulverizing Pancake", "zgrass": "Bloom Doom", "zground": "Tectonic Rage", "zice": "Subzero Slammer", "zincineroar": "Malicious Moonsault", "zkommoo": "Clangorous Soulblaze", "zlastresort": "Extreme Evoboost", "zlunala": "Menacing Moonraze Maelstrom", "zlycanroc": "Splintered Stormshards", "znaturesmadness": "Guardian of Alola", "zmarshadow": "Soul-Stealing 7-Star Strike", "zmew": "Genesis Supernova", "zmimikyu": "Let's Snuggle Forever", "zmoongeistbeam": "Menacing Moonraze Maelstrom", "znecrozma": "Light That Burns the Sky", "znormal": "Breakneck Blitz", "zrock": "Continental Crush", "zphotongeyser": "Light That Burns the Sky", "zpikachu": "Catastropika", "zpikachucap": "10,000,000 Volt Thunderbolt", "zplayrough": "Let's Snuggle Forever", "zpoison": "Acid Downpour", "zprimarina": "Oceanic Operetta", "zpsychic": "Shattered Psyche", "zraichu": "Stoked Sparksurfer", "zsnorlax": "Pulverizing Pancake", "zsolgaleo": "Searing Sunraze Smash", "zsparklingaria": "Oceanic Operetta", "zspectralthief": "Soul-Stealing 7-Star Strike", "zspiritshackle": "Sinister Arrow Raid", "zsunsteelstrike": "Searing Sunraze Smash", "zsteel": "Corkscrew Crash", "zstoneedge": "Splintered Stormshards", "ztapu": "Guardian of Alola", "zthunderbolt": "10,000,000 Volt Thunderbolt", "zultranecrozma": "Light That Burns the Sky", "zvolttackle": "Catastropika", "zwater": "Hydro Vortex", // Max moves "maxbug": "Max Flutterby", "maxdark": "Max Darkness", "maxdragon": "Max Wyrmwind", "maxelectric": "Max Lightning", "maxfairy": "Max Starfall", "maxfighting": "Max Knuckle", "maxfire": "Max Flare", "maxflying": "Max Airstream", "maxghost": "Max Phantasm", "maxgrass": "Max Overgrowth", "maxground": "Max Quake", "maxice": "Max Hailstorm", "maxnormal": "Max Strike", "maxpoison": "Max Ooze", "maxpsychic": "Max Mindstorm", "maxrock": "Max Rockfall", "maxsteel": "Max Steelspike", "maxwater": "Max Geyser", "maxstatus": "Max Guard", "maxprotect": "Max Guard", // Japanese names "fushigidane": "Bulbasaur", "fushigisou": "Ivysaur", "fushigibana": "Venusaur", "hitokage": "Charmander", "rizaado": "Charmeleon", "rizaadon": "Charizard", "zenigame": "Squirtle", "kameeru": "Wartortle", "kamekkusu": "Blastoise", "kyatapii": "Caterpie", "toranseru": "Metapod", "batafurii": "Butterfree", "biidoru": "Weedle", "kokuun": "Kakuna", "supiaa": "Beedrill", "poppo": "Pidgey", "pijon": "Pidgeotto", "pijotto": "Pidgeot", "koratta": "Rattata", "ratta": "Raticate", "onisuzume": "Spearow", "onidoriru": "Fearow", "aabo": "Ekans", "aabokku": "Arbok", "pikachuu": "Pikachu", "raichuu": "Raichu", "sando": "Sandshrew", "sandopan": "Sandslash", "nidoranmesu": "Nidoran-F", "nidoriina": "Nidorina", "nidokuin": "Nidoqueen", "nidoranosu": "Nidoran-M", "nidoriino": "Nidorino", "nidokingu": "Nidoking", "pippi": "Clefairy", "pikushii": "Clefable", "rokon": "Vulpix", "kyuukon": "Ninetales", "purin": "Jigglypuff", "pukurin": "Wigglytuff", "zubatto": "Zubat", "gorubatto": "Golbat", "nazonokusa": "Oddish", "kusaihana": "Gloom", "rafureshia": "Vileplume", "parasu": "Paras", "parasekuto": "Parasect", "konpan": "Venonat", "morufon": "Venomoth", "diguda": "Diglett", "dagutorio": "Dugtrio", "nyaasu": "Meowth", "perushian": "Persian", "kodakku": "Psyduck", "gorudakku": "Golduck", "mankii": "Mankey", "okorizaru": "Primeape", "gaadi": "Growlithe", "uindi": "Arcanine", "nyoromo": "Poliwag", "nyorozo": "Poliwhirl", "nyorobon": "Poliwrath", "keeshy": "Abra", "yungeraa": "Kadabra", "fuudin": "Alakazam", "wanrikii": "Machop", "goorikii": "Machoke", "kairikii": "Machamp", "madatsubomi": "Bellsprout", "utsudon": "Weepinbell", "utsubotto": "Victreebel", "menokurage": "Tentacool", "dokukurage": "Tentacruel", "ishitsubute": "Geodude", "goroon": "Graveler", "goroonya": "Golem", "poniita": "Ponyta", "gyaroppu": "Rapidash", "yadon": "Slowpoke", "yadoran": "Slowbro", "koiru": "Magnemite", "reakoiru": "Magneton", "kamonegi": "Farfetch'd", "doodoo": "Doduo", "doodorio": "Dodrio", "pauwau": "Seel", "jugon": "Dewgong", "betobetaa": "Grimer", "betobeton": "Muk", "sherudaa": "Shellder", "parushen": "Cloyster", "goosu": "Gastly", "goosuto": "Haunter", "gengaa": "Gengar", "iwaaku": "Onix", "suriipu": "Drowzee", "suriipaa": "Hypno", "kurabu": "Krabby", "kinguraa": "Kingler", "biriridama": "Voltorb", "marumain": "Electrode", "tamatama": "Exeggcute", "nasshii": "Exeggutor", "karakara": "Cubone", "garagara": "Marowak", "sawamuraa": "Hitmonlee", "ebiwaraa": "Hitmonchan", "beroringa": "Lickitung", "dogaasu": "Koffing", "matadogasu": "Weezing", "saihoon": "Rhyhorn", "saidon": "Rhydon", "rakkii": "Chansey", "monjara": "Tangela", "garuura": "Kangaskhan", "tattsuu": "Horsea", "shiidora": "Seadra", "tosakinto": "Goldeen", "azumaou": "Seaking", "hitodeman": "Staryu", "sutaamii": "Starmie", "bariyaado": "Mr. Mime", "sutoraiku": "Scyther", "ruujura": "Jynx", "erebuu": "Electabuzz", "buubaa": "Magmar", "kairosu": "Pinsir", "kentarosu": "Tauros", "koikingu": "Magikarp", "gyaradosu": "Gyarados", "rapurasu": "Lapras", "metamon": "Ditto", "iibui": "Eevee", "shawaazu": "Vaporeon", "sandaasu": "Jolteon", "buusutaa": "Flareon", "porigon": "Porygon", "omunaito": "Omanyte", "omusutaa": "Omastar", "kabutopusu": "Kabutops", "putera": "Aerodactyl", "kabigon": "Snorlax", "furiizaa": "Articuno", "sandaa": "Zapdos", "faiyaa": "Moltres", "miniryuu": "Dratini", "hakuryuu": "Dragonair", "kairyuu": "Dragonite", "myuutsuu": "Mewtwo", "myuu": "Mew", "chikoriita": "Chikorita", "beiriifu": "Bayleef", "meganiumu": "Meganium", "hinoarashi": "Cyndaquil", "magumarashi": "Quilava", "bakufuun": "Typhlosion", "waninoko": "Totodile", "arigeitsu": "Croconaw", "oodairu": "Feraligatr", "otachi": "Sentret", "ootachi": "Furret", "hoohoo": "Hoothoot", "yorunozuku": "Noctowl", "rediba": "Ledyba", "redian": "Ledian", "itomaru": "Spinarak", "ariadosu": "Ariados", "kurobatto": "Crobat", "chonchii": "Chinchou", "rantaan": "Lanturn", "pichuu": "Pichu", "py": "Cleffa", "pupurin": "Igglybuff", "togepii": "Togepi", "togechikku": "Togetic", "neitei": "Natu", "neiteio": "Xatu", "meriipu": "Mareep", "mokoko": "Flaaffy", "denryuu": "Ampharos", "kireihana": "Bellossom", "mariru": "Marill", "mariruri": "Azumarill", "usokkii": "Sudowoodo", "nyorotono": "Politoed", "hanekko": "Hoppip", "popokko": "Skiploom", "watakko": "Jumpluff", "eipamu": "Aipom", "himanattsu": "Sunkern", "kimawari": "Sunflora", "yanyanma": "Yanma", "upaa": "Wooper", "nuoo": "Quagsire", "eefi": "Espeon", "burakkii": "Umbreon", "yamikarasu": "Murkrow", "yadokingu": "Slowking", "muuma": "Misdreavus", "annoon": "Unown", "soonansu": "Wobbuffet", "kirinriki": "Girafarig", "kunugidama": "Pineco", "foretosu": "Forretress", "nokotchi": "Dunsparce", "guraigaa": "Gligar", "haganeeru": "Steelix", "buruu": "Snubbull", "guranburu": "Granbull", "hariisen": "Qwilfish", "hassamu": "Scizor", "tsubotsubo": "Shuckle", "herakurosu": "Heracross", "nyuura": "Sneasel", "himeguma": "Teddiursa", "ringuma": "Ursaring", "magumaggu": "Slugma", "magukarugo": "Magcargo", "urimuu": "Swinub", "inomuu": "Piloswine", "saniigo": "Corsola", "teppouo": "Remoraid", "okutan": "Octillery", "deribaado": "Delibird", "mantain": "Mantine", "eaamudo": "Skarmory", "derubiru": "Houndour", "herugaa": "Houndoom", "kingudora": "Kingdra", "gomazou": "Phanpy", "donfan": "Donphan", "porigon2": "Porygon2", "odoshishi": "Stantler", "dooburu": "Smeargle", "barukii": "Tyrogue", "kapoeraa": "Hitmontop", "muchuuru": "Smoochum", "erekiddo": "Elekid", "buby": "Magby", "mirutanku": "Miltank", "hapinasu": "Blissey", "suikun": "Suicune", "yoogirasu": "Larvitar", "sanagirasu": "Pupitar", "bangirasu": "Tyranitar", "rugia": "Lugia", "houou": "Ho-Oh", "sereby": "Celebi", "kimori": "Treecko", "juputoru": "Grovyle", "jukain": "Sceptile", "achamo": "Torchic", "wakashamo": "Combusken", "bashaamo": "Blaziken", "mizugorou": "Mudkip", "numakuroo": "Marshtomp", "raguraaji": "Swampert", "pochiena": "Poochyena", "guraena": "Mightyena", "jiguzaguma": "Zigzagoon", "massuguma": "Linoone", "kemusso": "Wurmple", "karasarisu": "Silcoon", "agehanto": "Beautifly", "mayurudo": "Cascoon", "dokukeiru": "Dustox", "hasuboo": "Lotad", "hasuburero": "Lombre", "runpappa": "Ludicolo", "taneboo": "Seedot", "konohana": "Nuzleaf", "daatengu": "Shiftry", "subame": "Taillow", "oosubame": "Swellow", "kyamome": "Wingull", "perippaa": "Pelipper", "rarutosu": "Ralts", "kiruria": "Kirlia", "saanaito": "Gardevoir", "ametama": "Surskit", "amemoosu": "Masquerain", "kinokoko": "Shroomish", "kinogassa": "Breloom", "namakero": "Slakoth", "yarukimono": "Vigoroth", "kekkingu": "Slaking", "tsuchinin": "Nincada", "tekkanin": "Ninjask", "nukenin": "Shedinja", "gonyonyo": "Whismur", "dogoomu": "Loudred", "bakuongu": "Exploud", "makunoshita": "Makuhita", "hariteyama": "Hariyama", "ruriri": "Azurill", "nozupasu": "Nosepass", "eneko": "Skitty", "enekororo": "Delcatty", "yamirami": "Sableye", "kuchiito": "Mawile", "kokodora": "Aron", "kodora": "Lairon", "bosugodora": "Aggron", "asanan": "Meditite", "chaaremu": "Medicham", "rakurai": "Electrike", "raiboruto": "Manectric", "purasuru": "Plusle", "mainan": "Minun", "barubiito": "Volbeat", "irumiize": "Illumise", "rozeria": "Roselia", "gokurin": "Gulpin", "marunoomu": "Swalot", "kibania": "Carvanha", "samehadaa": "Sharpedo", "hoeruko": "Wailmer", "hoeruoo": "Wailord", "donmeru": "Numel", "bakuuda": "Camerupt", "kootasu": "Torkoal", "banebuu": "Spoink", "buupiggu": "Grumpig", "patchiiru": "Spinda", "nakkuraa": "Trapinch", "biburaaba": "Vibrava", "furaigon": "Flygon", "sabonea": "Cacnea", "nokutasu": "Cacturne", "chirutto": "Swablu", "chirutarisu": "Altaria", "zanguusu": "Zangoose", "habuneeku": "Seviper", "runatoon": "Lunatone", "sorurokku": "Solrock", "dojotchi": "Barboach", "namazun": "Whiscash", "heigani": "Corphish", "shizarigaa": "Crawdaunt", "yajiron": "Baltoy", "nendooru": "Claydol", "ririira": "Lileep", "yureidoru": "Cradily", "anopusu": "Anorith", "aamarudo": "Armaldo", "hinbasu": "Feebas", "mirokarosu": "Milotic", "powarun": "Castform", "kakureon": "Kecleon", "kagebouzu": "Shuppet", "jupetta": "Banette", "yomawaru": "Duskull", "samayooru": "Dusclops", "toropiusu": "Tropius", "chiriin": "Chimecho", "abusoru": "Absol", "soonano": "Wynaut", "yukiwarashi": "Snorunt", "onigoori": "Glalie", "tamazarashi": "Spheal", "todoguraa": "Sealeo", "todozeruga": "Walrein", "paaruru": "Clamperl", "hanteeru": "Huntail", "sakurabisu": "Gorebyss", "jiiransu": "Relicanth", "rabukasu": "Luvdisc", "tatsubei": "Bagon", "komoruu": "Shelgon", "boomanda": "Salamence", "danbaru": "Beldum", "metangu": "Metang", "metagurosu": "Metagross", "rejirokku": "Regirock", "rejiaisu": "Regice", "rejisuchiru": "Registeel", "rateiasu": "Latias", "rateiosu": "Latios", "kaiooga": "Kyogre", "guraadon": "Groudon", "rekkuuza": "Rayquaza", "jiraachi": "Jirachi", "deokishisu": "Deoxys", "naetoru": "Turtwig", "hayashigame": "Grotle", "dodaitosu": "Torterra", "hikozaru": "Chimchar", "moukazaru": "Monferno", "goukazaru": "Infernape", "potchama": "Piplup", "pottaishi": "Prinplup", "enperuto": "Empoleon", "mukkuru": "Starly", "mukubaado": "Staravia", "mukuhooku": "Staraptor", "bippa": "Bidoof", "biidaru": "Bibarel", "korobooshi": "Kricketot", "korotokku": "Kricketune", "korinku": "Shinx", "rukushio": "Luxio", "rentoraa": "Luxray", "subomii": "Budew", "rozureido": "Roserade", "zugaidosu": "Cranidos", "ramuparudo": "Rampardos", "tatetopusu": "Shieldon", "toridepusu": "Bastiodon", "minomutchi": "Burmy", "minomadamu": "Wormadam", "gaameiru": "Mothim", "mitsuhanii": "Combee", "biikuin": "Vespiquen", "buizeru": "Buizel", "furoozeru": "Floatzel", "cherinbo": "Cherubi", "cherimu": "Cherrim", "karanakushi": "Shellos", "toritodon": "Gastrodon", "eteboosu": "Ambipom", "fuwante": "Drifloon", "fuwaraido": "Drifblim", "mimiroru": "Buneary", "mimiroppu": "Lopunny", "muumaaji": "Mismagius", "donkarasu": "Honchkrow", "nyarumaa": "Glameow", "bunyatto": "Purugly", "riishan": "Chingling", "sukanpuu": "Stunky", "sukatanku": "Skuntank", "doomiraa": "Bronzor", "dootakun": "Bronzong", "usohachi": "Bonsly", "manene": "Mime Jr.", "pinpuku": "Happiny", "perappu": "Chatot", "mikaruge": "Spiritomb", "fukamaru": "Gible", "gabaito": "Gabite", "gaburiasu": "Garchomp", "gonbe": "Munchlax", "rioru": "Riolu", "rukario": "Lucario", "hipopotasu": "Hippopotas", "kabarudon": "Hippowdon", "sukorupi": "Skorupi", "dorapion": "Drapion", "guregguru": "Croagunk", "dokuroggu": "Toxicroak", "masukippa": "Carnivine", "keikouo": "Finneon", "neoranto": "Lumineon", "tamanta": "Mantyke", "yukikaburi": "Snover", "yukinooo": "Abomasnow", "manyuura": "Weavile", "jibakoiru": "Magnezone", "beroberuto": "Lickilicky", "dosaidon": "Rhyperior", "mojanbo": "Tangrowth", "erekiburu": "Electivire", "buubaan": "Magmortar", "togekissu": "Togekiss", "megayanma": "Yanmega", "riifia": "Leafeon", "gureishia": "Glaceon", "guraion": "Gliscor", "manmuu": "Mamoswine", "porigonz": "Porygon-Z", "erureido": "Gallade", "dainoozu": "Probopass", "yonowaaru": "Dusknoir", "yukimenoko": "Froslass", "rotomu": "Rotom", "yukushii": "Uxie", "emuritto": "Mesprit", "agunomu": "Azelf", "diaruga": "Dialga", "parukia": "Palkia", "hiidoran": "Heatran", "rejigigasu": "Regigigas", "girateina": "Giratina", "kureseria": "Cresselia", "fione": "Phione", "manafi": "Manaphy", "daakurai": "Darkrai", "sheimi": "Shaymin", "aruseusu": "Arceus", "bikuteini": "Victini", "tsutaaja": "Snivy", "janobii": "Servine", "jarooda": "Serperior", "pokabu": "Tepig", "chaobuu": "Pignite", "enbuoo": "Emboar", "mijumaru": "Oshawott", "futachimaru": "Dewott", "daikenki": "Samurott", "minezumi": "Patrat", "miruhoggu": "Watchog", "yooterii": "Lillipup", "haaderia": "Herdier", "muurando": "Stoutland", "choroneko": "Purrloin", "reparudasu": "Liepard", "yanappu": "Pansage", "yanakkii": "Simisage", "baoppu": "Pansear", "baokkii": "Simisear", "hiyappu": "Panpour", "hiyakkii": "Simipour", "mushaana": "Musharna", "mamepato": "Pidove", "hatooboo": "Tranquill", "kenhorou": "Unfezant", "shimama": "Blitzle", "zeburaika": "Zebstrika", "dangoro": "Roggenrola", "gantoru": "Boldore", "gigaiasu": "Gigalith", "koromori": "Woobat", "kokoromori": "Swoobat", "moguryuu": "Drilbur", "doryuuzu": "Excadrill", "tabunne": "Audino", "dokkoraa": "Timburr", "dotekkotsu": "Gurdurr", "roobushin": "Conkeldurr", "otamaro": "Tympole", "gamagaru": "Palpitoad", "gamageroge": "Seismitoad", "nageki": "Throh", "dageki": "Sawk", "kurumiru": "Sewaddle", "kurumayu": "Swadloon", "hahakomori": "Leavanny", "fushide": "Venipede", "hoiiga": "Whirlipede", "pendoraa": "Scolipede", "monmen": "Cottonee", "erufuun": "Whimsicott", "churine": "Petilil", "doredia": "Lilligant", "basurao": "Basculin", "meguroko": "Sandile", "warubiru": "Krokorok", "warubiaru": "Krookodile", "darumakka": "Darumaka", "hihidaruma": "Darmanitan", "marakatchi": "Maractus", "ishizumai": "Dwebble", "iwaparesu": "Crustle", "zuruggu": "Scraggy", "zuruzukin": "Scrafty", "shinboraa": "Sigilyph", "desumasu": "Yamask", "desukaan": "Cofagrigus", "purotooga": "Tirtouga", "abagoora": "Carracosta", "aaken": "Archen", "aakeosu": "Archeops", "yabukuron": "Trubbish", "dasutodasu": "Garbodor", "zoroa": "Zorua", "zoroaaku": "Zoroark", "chiraamy": "Minccino", "chirachiino": "Cinccino", "gochimu": "Gothita", "gochimiru": "Gothorita", "gochiruzeru": "Gothitelle", "yuniran": "Solosis", "daburan": "Duosion", "rankurusu": "Reuniclus", "koaruhii": "Ducklett", "suwanna": "Swanna", "baniputchi": "Vanillite", "baniritchi": "Vanillish", "baibanira": "Vanilluxe", "shikijika": "Deerling", "mebukijika": "Sawsbuck", "emonga": "Emolga", "kaburumo": "Karrablast", "shubarugo": "Escavalier", "tamagetake": "Foongus", "morobareru": "Amoonguss", "pururiru": "Frillish", "burungeru": "Jellicent", "mamanbou": "Alomomola", "bachuru": "Joltik", "denchura": "Galvantula", "tesshiido": "Ferroseed", "nattorei": "Ferrothorn", "giaru": "Klink", "gigiaru": "Klang", "gigigiaru": "Klinklang", "shibishirasu": "Tynamo", "shibibiiru": "Eelektrik", "shibirudon": "Eelektross", "riguree": "Elgyem", "oobemu": "Beheeyem", "hitomoshi": "Litwick", "ranpuraa": "Lampent", "shandera": "Chandelure", "kibago": "Axew", "onondo": "Fraxure", "ononokusu": "Haxorus", "kumashun": "Cubchoo", "tsunbeaa": "Beartic", "furiijio": "Cryogonal", "chobomaki": "Shelmet", "agirudaa": "Accelgor", "maggyo": "Stunfisk", "kojofuu": "Mienfoo", "kojondo": "Mienshao", "kurimugan": "Druddigon", "gobitto": "Golett", "goruugu": "Golurk", "komatana": "Pawniard", "kirikizan": "Bisharp", "baffuron": "Bouffalant", "washibon": "Rufflet", "uooguru": "Braviary", "baruchai": "Vullaby", "barujiina": "Mandibuzz", "kuitaran": "Heatmor", "aianto": "Durant", "monozu": "Deino", "jiheddo": "Zweilous", "sazandora": "Hydreigon", "meraruba": "Larvesta", "urugamosu": "Volcarona", "kobaruon": "Cobalion", "terakion": "Terrakion", "birijion": "Virizion", "torunerosu": "Tornadus", "borutorosu": "Thundurus", "reshiramu": "Reshiram", "zekuromu": "Zekrom", "randorosu": "Landorus", "kyuremu": "Kyurem", "kerudio": "Keldeo", "meroetta": "Meloetta", "genosekuto": "Genesect", "harimaron": "Chespin", "hariboogu": "Quilladin", "burigaron": "Chesnaught", "fokko": "Fennekin", "teerunaa": "Braixen", "mafokushii": "Delphox", "keromatsu": "Froakie", "gekogashira": "Frogadier", "gekkouga": "Greninja", "gekkougasatoshi": "Greninja-Ash", "satoshigekkouga": "Greninja-Ash", "horubii": "Bunnelby", "horuudo": "Diggersby", "yayakoma": "Fletchling", "hinoyakoma": "Fletchinder", "faiaroo": "Talonflame", "kofukimushi": "Scatterbug", "kofuurai": "Spewpa", "bibiyon": "Vivillon", "shishiko": "Litleo", "kaenjishi": "Pyroar", "furabebe": "Flabébé", "furaette": "Floette", "furaajesu": "Florges", "meeekuru": "Skiddo", "googooto": "Gogoat", "yanchamu": "Pancham", "goronda": "Pangoro", "torimian": "Furfrou", "nyasupaa": "Espurr", "nyaonikusu": "Meowstic", "hitotsuki": "Honedge", "nidangiru": "Doublade", "girugarudo": "Aegislash", "shushupu": "Spritzee", "furefuwan": "Aromatisse", "peroppafu": "Swirlix", "peroriimu": "Slurpuff", "maaiika": "Inkay", "karamanero": "Malamar", "kametete": "Binacle", "gamenodesu": "Barbaracle", "kuzumoo": "Skrelp", "doramidoro": "Dragalge", "udeppou": "Clauncher", "burosutaa": "Clawitzer", "erikiteru": "Helioptile", "erezaado": "Heliolisk", "chigorasu": "Tyrunt", "gachigorasu": "Tyrantrum", "amarusu": "Amaura", "amaruruga": "Aurorus", "ninfia": "Sylveon", "ruchaburu": "Hawlucha", "mereshii": "Carbink", "numera": "Goomy", "numeiru": "Sliggoo", "numerugon": "Goodra", "kureffi": "Klefki", "bokuree": "Phantump", "oorotto": "Trevenant", "baketcha": "Pumpkaboo", "panpujin": "Gourgeist", "kachikooru": "Bergmite", "kurebeesu": "Avalugg", "onbatto": "Noibat", "onbaan": "Noivern", "zeruneasu": "Xerneas", "iberutaru": "Yveltal", "jigarude": "Zygarde", "dianshii": "Diancie", "fuupa": "Hoopa", "borukenion": "Volcanion", "mokuroo": "Rowlet", "fukusuroo": "Dartrix", "junaipaa": "Decidueye", "nyabii": "Litten", "nyahiito": "Torracat", "gaogaen": "Incineroar", "ashimari": "Popplio", "oshamari": "Brionne", "ashireenu": "Primarina", "tsutsukera": "Pikipek", "kerarappa": "Trumbeak", "dodekabashi": "Toucannon", "yanguusu": "Yungoos", "dekaguusu": "Gumshoos", "agojimushi": "Grubbin", "denjimushi": "Charjabug", "kuwaganon": "Vikavolt", "makenkani": "Crabrawler", "kekenkani": "Crabominable", "odoridori": "Oricorio", "aburii": "Cutiefly", "aburibon": "Ribombee", "iwanko": "Rockruff", "rugarugan": "Lycanroc", "yowashi": "Wishiwashi", "hidoide": "Mareanie", "dohidoide": "Toxapex", "dorobanko": "Mudbray", "banbadoro": "Mudsdale", "shizukumo": "Dewpider", "onishizukumo": "Araquanid", "karikiri": "Fomantis", "rarantesu": "Lurantis", "nemashu": "Morelull", "masheedo": "Shiinotic", "yatoumori": "Salandit", "ennyuuto": "Salazzle", "nuikoguma": "Stufful", "kiteruguma": "Bewear", "amakaji": "Bounsweet", "amamaiko": "Steenee", "amaajo": "Tsareena", "kyuwawaa": "Comfey", "yareyuutan": "Oranguru", "nagetsukesaru": "Passimian", "kosokumushi": "Wimpod", "gusokumusha": "Golisopod", "sunabaa": "Sandygast", "shirodesuna": "Palossand", "namakobushi": "Pyukumuku", "taipunuru": "Type: Null", "shiruvuadi": "Silvally", "meteno": "Minior", "nekkoara": "Komala", "bakugamesu": "Turtonator", "mimikkyu": "Mimikyu", "hagigishiri": "Bruxish", "jijiiron": "Drampa", "dadarin": "Dhelmise", "jarako": "Jangmo-o", "jarango": "Hakamo-o", "jararanga": "Kommo-o", "kapukokeko": "Tapu Koko", "kaputetefu": "Tapu Lele", "kapubururu": "Tapu Bulu", "kapurehire": "Tapu Fini", "kosumoggu": "Cosmog", "kosumoumu": "Cosmoem", "sorugareo": "Solgaleo", "runaaara": "Lunala", "utsuroido": "Nihilego", "masshibuun": "Buzzwole", "fierooche": "Pheromosa", "denjumoku": "Xurkitree", "tekkaguya": "Celesteela", "kamitsurugi": "Kartana", "akujikingu": "Guzzlord", "nekurozuma": "Necrozma", "magiana": "Magearna", "maashadoo": "Marshadow", "bebenomu": "Poipole", "aagoyon": "Naganadel", "tsundetsunde": "Stakataka", "zugadoon": "Blacephalon", "merutan": "Meltan", "merumetaru": "Melmetal", }; exports.BattleAliases = BattleAliases;
QuiteQuiet/Pokemon-Showdown
data/aliases.js
JavaScript
mit
43,883
import { moduleForComponent, test } from 'ember-qunit'; import wait from 'ember-test-helpers/wait'; import hbs from 'htmlbars-inline-precompile'; import startMirage from '../../helpers/setup-mirage'; moduleForComponent('data-table', 'Integration | Component | data table', { integration: true, setup: function() { startMirage(this.container); } }); test('it renders', function(assert) { assert.expect(1); this.set('columns', [{label: 'Column'}]); this.render(hbs`{{data-table 'user' columns=columns}}`); return wait().then(() => { assert.ok(this.$('table').length); }); });
quantosobra/ember-data-table-light
tests/integration/components/data-table-test.js
JavaScript
mit
602
import {useEntryStateConfig} from "./EntryStateProvider"; /** * Returns an object containing theme asset paths. * * @example * * const theme = useTheme(); * theme // => * { * assets: { * logoDesktop: 'path/to/logoDesktop.svg', * logoMobile: 'path/to/logoMobile.svg' * }, * options: { * // options passed to `themes.register` in `pageflow.rb` initializer * // with camleized keys. * } * } */ export function useTheme() { const config = useEntryStateConfig(); return config.theme; }
tf/pageflow
entry_types/scrolled/package/src/entryState/theme.js
JavaScript
mit
548
// this exports a "masked" version of the WrapUp class. var WrapUp = require("./wrapup") module.exports = function(x){ return new WrapUp(x) }
kentaromiura/sugo
node_modules/wrapup/node_modules/prime/cov/node_modules/wrapup/lib/main.js
JavaScript
mit
145
import * as React from 'react'; import PropTypes from 'prop-types'; import debounce from '../utils/debounce'; import useForkRef from '../utils/useForkRef'; import useEnhancedEffect from '../utils/useEnhancedEffect'; import ownerWindow from '../utils/ownerWindow'; function getStyleValue(computedStyle, property) { return parseInt(computedStyle[property], 10) || 0; } const styles = { /* Styles applied to the shadow textarea element. */ shadow: { // Visibility needed to hide the extra text area on iPads visibility: 'hidden', // Remove from the content flow position: 'absolute', // Ignore the scrollbar width overflow: 'hidden', height: 0, top: 0, left: 0, // Create a new layer, increase the isolation of the computed values transform: 'translateZ(0)', }, }; const TextareaAutosize = React.forwardRef(function TextareaAutosize(props, ref) { const { onChange, maxRows, minRows = 1, style, value, ...other } = props; const { current: isControlled } = React.useRef(value != null); const inputRef = React.useRef(null); const handleRef = useForkRef(ref, inputRef); const shadowRef = React.useRef(null); const renders = React.useRef(0); const [state, setState] = React.useState({}); const syncHeight = React.useCallback(() => { const input = inputRef.current; const containerWindow = ownerWindow(input); const computedStyle = containerWindow.getComputedStyle(input); // If input's width is shrunk and it's not visible, don't sync height. if (computedStyle.width === '0px') { return; } const inputShallow = shadowRef.current; inputShallow.style.width = computedStyle.width; inputShallow.value = input.value || props.placeholder || 'x'; if (inputShallow.value.slice(-1) === '\n') { // Certain fonts which overflow the line height will cause the textarea // to report a different scrollHeight depending on whether the last line // is empty. Make it non-empty to avoid this issue. inputShallow.value += ' '; } const boxSizing = computedStyle['box-sizing']; const padding = getStyleValue(computedStyle, 'padding-bottom') + getStyleValue(computedStyle, 'padding-top'); const border = getStyleValue(computedStyle, 'border-bottom-width') + getStyleValue(computedStyle, 'border-top-width'); // The height of the inner content const innerHeight = inputShallow.scrollHeight; // Measure height of a textarea with a single row inputShallow.value = 'x'; const singleRowHeight = inputShallow.scrollHeight; // The height of the outer content let outerHeight = innerHeight; if (minRows) { outerHeight = Math.max(Number(minRows) * singleRowHeight, outerHeight); } if (maxRows) { outerHeight = Math.min(Number(maxRows) * singleRowHeight, outerHeight); } outerHeight = Math.max(outerHeight, singleRowHeight); // Take the box sizing into account for applying this value as a style. const outerHeightStyle = outerHeight + (boxSizing === 'border-box' ? padding + border : 0); const overflow = Math.abs(outerHeight - innerHeight) <= 1; setState((prevState) => { // Need a large enough difference to update the height. // This prevents infinite rendering loop. if ( renders.current < 20 && ((outerHeightStyle > 0 && Math.abs((prevState.outerHeightStyle || 0) - outerHeightStyle) > 1) || prevState.overflow !== overflow) ) { renders.current += 1; return { overflow, outerHeightStyle, }; } if (process.env.NODE_ENV !== 'production') { if (renders.current === 20) { console.error( [ 'Material-UI: Too many re-renders. The layout is unstable.', 'TextareaAutosize limits the number of renders to prevent an infinite loop.', ].join('\n'), ); } } return prevState; }); }, [maxRows, minRows, props.placeholder]); React.useEffect(() => { const handleResize = debounce(() => { renders.current = 0; syncHeight(); }); const containerWindow = ownerWindow(inputRef.current); containerWindow.addEventListener('resize', handleResize); return () => { handleResize.clear(); containerWindow.removeEventListener('resize', handleResize); }; }, [syncHeight]); useEnhancedEffect(() => { syncHeight(); }); React.useEffect(() => { renders.current = 0; }, [value]); const handleChange = (event) => { renders.current = 0; if (!isControlled) { syncHeight(); } if (onChange) { onChange(event); } }; return ( <React.Fragment> <textarea value={value} onChange={handleChange} ref={handleRef} // Apply the rows prop to get a "correct" first SSR paint rows={minRows} style={{ height: state.outerHeightStyle, // Need a large enough difference to allow scrolling. // This prevents infinite rendering loop. overflow: state.overflow ? 'hidden' : null, ...style, }} {...other} /> <textarea aria-hidden className={props.className} readOnly ref={shadowRef} tabIndex={-1} style={{ ...styles.shadow, ...style, padding: 0, }} /> </React.Fragment> ); }); TextareaAutosize.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * @ignore */ className: PropTypes.string, /** * Maximum number of rows to display. */ maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * Minimum number of rows to display. * @default 1 */ minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * @ignore */ onChange: PropTypes.func, /** * @ignore */ placeholder: PropTypes.string, /** * @ignore */ style: PropTypes.object, /** * @ignore */ value: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.string), PropTypes.number, PropTypes.string, ]), }; export default TextareaAutosize;
callemall/material-ui
packages/material-ui/src/TextareaAutosize/TextareaAutosize.js
JavaScript
mit
6,538
version https://git-lfs.github.com/spec/v1 oid sha256:ec9603f026a2a1295d751178e7e48bf8b945506e9b05818112c5166e1e950a67 size 9557
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.8.0/calendarnavigator/calendarnavigator.js
JavaScript
mit
129
/** * Converts an RGB color value to HSL. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes r, g, and b are contained in the set [0, 255] and * returns h, s, and l in the set [0, 1]. * * @param Number r The red color value * @param Number g The green color value * @param Number b The blue color value * @return Array The HSL representation */ function rgbToHsl(r, g, b) { r /= 255, g /= 255, b /= 255; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; if (max == min) { h = s = 0; // achromatic } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } //alert(h*360+","+ s*100+","+ l*100 ); return [ h*360, s*100, l*100 ]; } /** * Converts an HSL color value to RGB. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes h, s, and l are contained in the set [0, 1] (CHANGED, they get divided in function so that they are within 0,1)and * returns r, g, and b in the set [0, 255]. * * @param Number h The hue * @param Number s The saturation * @param Number l The lightness * @return Array The RGB representation */ function hslToRgb(h, s, l) { h=h/360,s=s/100,l=l/100; var r, g, b; if (s == 0) { r = g = b = l; // achromatic } else { function hue2rgb(p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1/6) return p + (q - p) * 6 * t; if (t < 1/2) return q; if (t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; } var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1/3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1/3); } //alert(r * 255+","+ g * 255+","+ b * 255); return [ r * 255, g * 255, b * 255 ]; } /** * Converts an RGB color value to HSV. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSV_color_space. * Assumes r, g, and b are contained in the set [0, 255] and * returns h, s, and v in the set [0, 1]. * * @param Number r The red color value * @param Number g The green color value * @param Number b The blue color value * @return Array The HSV representation */ function rgbToHsv(r, g, b) { r /= 255, g /= 255, b /= 255; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, v = max; var d = max - min; s = max == 0 ? 0 : d / max; if (max == min) { h = 0; // achromatic } else { switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return [ h*360, s*100, v*100 ]; } /** * Converts an HSV color value to RGB. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSV_color_space. * Assumes h, s, and v are contained in the set [0, 1] and * returns r, g, and b in the set [0, 255]. * * @param Number h The hue * @param Number s The saturation * @param Number v The value * @return Array The RGB representation */ function hsvToRgb(h, s, v) { h=h/360,s=s/100,v=v/100; var r, g, b; var i = Math.floor(h * 6); var f = h * 6 - i; var p = v * (1 - s); var q = v * (1 - f * s); var t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } return [ r * 255, g * 255, b * 255 ]; }
ericoporto/Pixel.Tools
color_conversion.js
JavaScript
mit
3,896
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M10.08 10.86c.05-.33.16-.62.3-.87s.34-.46.59-.62c.24-.15.54-.22.91-.23.23.01.44.05.63.13.2.09.38.21.52.36s.25.33.34.53.13.42.14.64h1.79c-.02-.47-.11-.9-.28-1.29s-.4-.73-.7-1.01-.66-.5-1.08-.66-.88-.23-1.39-.23c-.65 0-1.22.11-1.7.34s-.88.53-1.2.92-.56.84-.71 1.36S8 11.29 8 11.87v.27c0 .58.08 1.12.23 1.64s.39.97.71 1.35.72.69 1.2.91c.48.22 1.05.34 1.7.34.47 0 .91-.08 1.32-.23s.77-.36 1.08-.63.56-.58.74-.94.29-.74.3-1.15h-1.79c-.01.21-.06.4-.15.58s-.21.33-.36.46-.32.23-.52.3c-.19.07-.39.09-.6.1-.36-.01-.66-.08-.89-.23-.25-.16-.45-.37-.59-.62s-.25-.55-.3-.88-.08-.67-.08-1v-.27c0-.35.03-.68.08-1.01zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" }), 'CopyrightRounded');
oliviertassinari/material-ui
packages/mui-icons-material/lib/esm/CopyrightRounded.js
JavaScript
mit
915
/** * ELASTICSEARCH CONFIDENTIAL * _____________________________ * * [2014] Elasticsearch Incorporated All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Elasticsearch Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Elasticsearch Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Elasticsearch Incorporated. */ // The ui had different columns in different order depending on the // $scope.pane.view variable. This provides a lookup for the column headers // labels are linked to view from public/directives/shard_allocation/lib/changeData.js export default { index: ['Nodes'], // "index detail" page shows nodes on which index shards are allocated node: ['Indices'], // "node detail" page shows the indexes that have shards on this node indexWithUnassigned: ['Unassigned', 'Nodes'] // NOTE: is this unused or is there even an indexWithUnassigned view? };
ashnewport/elasticsearch
kibana-5.0.2-linux-x86_64/plugins/x-pack/plugins/monitoring/public/directives/shard_allocation/lib/labels.js
JavaScript
mit
1,250
/** * OnFire * Copyright (c) 2013 - 2015 Itzy Sabo * Licensed under the MIT License: https://github.com/isabo/onfire/blob/master/LICENSE */ var onfire = {}; /** * An analogue of a Firebase reference. * @see https://www.firebase.com/docs/web/api/firebase/constructor.html * * @param {string|!Firebase} urlOrRef A Firebase URL or a Firebase reference instance. * @constructor * @final */ onfire.Ref = function(urlOrRef) {}; /** * Firebase.authAnonymously() wrapped in a promise. * @see https://www.firebase.com/docs/web/api/firebase/authanonymously.html * * @param {!Object=} opt_options * @return { !Promise<!Firebase.AuthCallbackData,!Error> | !goog.Promise<!Firebase.AuthCallbackData,!Error> } A promise which resolves to the authData, or is rejected with an error. */ onfire.Ref.prototype.authAnonymously = function(opt_options) {}; /** * Firebase.authWithCustomToken() wrapped in a promise. * @see https://www.firebase.com/docs/web/api/firebase/authwithcustomtoken.html * * @param {string} authToken * @param {!Object=} opt_options * @return { !Promise<!Firebase.AuthCallbackData,!Error> | !goog.Promise<!Firebase.AuthCallbackData,!Error> } A promise which resolves to the authData, or is rejected with an error. */ onfire.Ref.prototype.authWithCustomToken = function(authToken, opt_options) {}; /** * Firebase.authWithOAuthPopup() wrapped in a promise. * @see https://www.firebase.com/docs/web/api/firebase/authwithoauthpopup.html * * @param {string} provider * @param {!Object=} opt_options * @return { !Promise<!Firebase.AuthCallbackData,!Error> | !goog.Promise<!Firebase.AuthCallbackData,!Error> } A promise which resolves to the authData, or is rejected with an error. */ onfire.Ref.prototype.authWithOAuthPopup = function(provider, opt_options) {}; /** * Firebase.authWithOAuthRedirect() wrapped in a promise. * @see https://www.firebase.com/docs/web/api/firebase/authwithoauthredirect.html * * @param {string} provider * @param {!Object=} opt_options * @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise which is rejected with an * error if the authentication fails. */ onfire.Ref.prototype.authWithOAuthRedirect = function(provider, opt_options) {}; /** * Firebase.authWithOAuthToken() wrapped in a promise. * @see https://www.firebase.com/docs/web/api/firebase/authwithoauthtoken.html * * @param {string} provider * @param {string|!Object} credentials * @param {!Object=} opt_options * @return { !Promise<!Firebase.AuthCallbackData,!Error> | !goog.Promise<!Firebase.AuthCallbackData,!Error> } A promise which resolves to the authData, or is rejected with an error. */ onfire.Ref.prototype.authWithOAuthToken = function(provider, credentials, opt_options) {}; /** * Firebase.authWithPassword() wrapped in a promise. * @see https://www.firebase.com/docs/web/api/firebase/authwithpassword.html * * @param {!Firebase.AuthPasswordCredentials} credentials * @param {!Object=} opt_options * @return { !Promise<!Firebase.AuthCallbackData,!Error> | !goog.Promise<!Firebase.AuthCallbackData,!Error> } A promise which resolves to the authData, or is rejected with an error. */ onfire.Ref.prototype.authWithPassword = function(credentials, opt_options) {}; /** * Firebase.changeEmail() wrapped in a promise. * @see https://www.firebase.com/docs/web/api/firebase/changeemail.html * * @param {!{oldEmail:string, password:string, newEmail:string}} credentials * @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise which resolves when the * operation is complete, or is rejected with an error. */ onfire.Ref.prototype.changeEmail = function(credentials) {}; /** * Firebase.changePassword() wrapped in a promise. * @see https://www.firebase.com/docs/web/api/firebase/changepassword.html * * @param {!{email:string, oldPassword:string, newPassword:string}} credentials * @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise which resolves when the * operation is complete, or is rejected with an error. */ onfire.Ref.prototype.changePassword = function(credentials) {}; /** * Firebase.createUser() wrapped in a promise. * @see https://www.firebase.com/docs/web/api/firebase/createuser.html * * @param {!Firebase.AuthPasswordCredentials} credentials * @return {!Promise<!{uid:string},!Error>|!goog.Promise<!{uid:string},!Error>} A promise which * resolves to a userData object, or is rejected with an error. */ onfire.Ref.prototype.createUser = function (credentials) {}; /** * Returns a reference that is relative to the current location. * @see https://www.firebase.com/docs/web/api/firebase/child.html * * @param {string} childPath * @return {!onfire.Ref} A reference that is relative to the current location. * @nosideeffects */ onfire.Ref.prototype.child = function(childPath) {}; /** * Generates a push ID. This takes the place of .push() when all we want is a unique ID, via a * synchronous method instead of a promise, which is what .push() returns. * * @return {string} A unique ID. */ onfire.Ref.prototype.generateId = function() {}; /** * A proxy for Firebase.getAuth(). * @see https://www.firebase.com/docs/web/api/firebase/getauth.html * * @return {Firebase.AuthCallbackData} * @nosideeffects */ onfire.Ref.prototype.getAuth = function() {}; /** * A proxy for Firebase.goOnline(). * @see https://www.firebase.com/docs/web/api/firebase/goonline.html */ onfire.Ref.prototype.goOnline = function() {}; /** * A proxy for Firebase.goOffline(). * @see https://www.firebase.com/docs/web/api/firebase/gooffline.html */ onfire.Ref.prototype.goOffline = function() {}; /** * Returns the key of the current location. * @see https://www.firebase.com/docs/web/api/firebase/key.html * * @return {string} The key of the current location. * @nosideeffects */ onfire.Ref.prototype.key = function() {}; /** * Deregisters a previously registered callback. * @see https://www.firebase.com/docs/web/api/query/off.html * * @param {string=} opt_eventType * @param {!Firebase.EventCallback=} opt_callback If provided, this MUST be the *wrapped* callback * returned by the .on() method. * @param {!Object=} opt_context */ onfire.Ref.prototype.off = function(opt_eventType, opt_callback, opt_context) {}; /** * A proxy for Firebase.offAuth(). * @see https://www.firebase.com/docs/web/api/firebase/offauth.html * * @param {!function(Firebase.AuthCallbackData)} onComplete * @param {!Object=} opt_context */ onfire.Ref.prototype.offAuth = function(onComplete, opt_context) {}; /** * Deregisters a previously registered .onValue() callback. * * @param {!function(Firebase.Value)} callback This MUST be the *wrapped* callback returned * by .onValue(). * @param {!Object=} context */ onfire.Ref.prototype.offValue = function(callback, context) {}; /** * Registers a callback for an event of a specified type at the current location. Make sure to keep * the return value for use when turning this off -- see the off() method. * @see https://www.firebase.com/docs/web/api/query/on.html * * @param {string} eventType * @param {!Firebase.EventCallback} callback * @param {function(!Error)=} cancelCallback * @param {Object=} context * @return {!function(!Firebase.DataSnapshot, ?string=)} A handler function that may be needed when * deregistering the callback. */ onfire.Ref.prototype.on = function(eventType, callback, cancelCallback, context) {}; /** * A proxy for Firebase.onAuth(). * @see https://www.firebase.com/docs/web/api/firebase/onauth.html * * @param {!function(Firebase.AuthCallbackData)} onComplete * @param {!Object=} opt_context */ onfire.Ref.prototype.onAuth = function(onComplete, opt_context) {}; /** * Waits for the first event of a specified type at the current location. A promisified analogue * of Firebase's .once() method. * @see https://www.firebase.com/docs/web/api/query/once.html * * @param {string} eventType * @return {!Promise<!Firebase.DataSnapshot,!Error>|!goog.Promise<!Firebase.DataSnapshot,!Error>} A * promise that resolves to a Firebase snapshot, or is rejected with an error. */ onfire.Ref.prototype.once = function(eventType) {}; /** * Retrieves the value that is stored at the current location. This is shorthand for calling .once() * for the 'value' event and then extracting the value of the returned snapshot. * * @return {!Promise<Firebase.Value,!Error>|!goog.Promise<Firebase.Value,!Error>} A promise that * resolves to the value stored at the current location, or is rejected with an error. */ onfire.Ref.prototype.onceValue = function() {}; /** * Registers a callback for value changes at the current location. This is shorthand for calling * .on() for the 'value' event and then extracting the value of each returned snapshot. Make sure to * keep the return value for when you want to turn this off. See the .offValue() method. * * @param {!function(Firebase.Value)} callback * @param {!function(!Error)=} cancelCallback * @param {!Object=} context * @return {!function(!Firebase.DataSnapshot)} */ onfire.Ref.prototype.onValue = function(callback, cancelCallback, context) {}; /** * Returns a reference to the parent of the current location. * @see https://www.firebase.com/docs/web/api/firebase/parent.html * * @return {onfire.Ref} A reference to the parent of the current location. * @nosideeffects */ onfire.Ref.prototype.parent = function() {}; /** * Returns the path of this reference relative to the root, i.e. not including the firebaseio.com * domain. * * @return {string} The path of this reference relative to the root. * @nosideeffects */ onfire.Ref.prototype.path = function() {}; /** * Pushes a value under the current location. A promisified analogue of Firebase's .push() method. * @see https://www.firebase.com/docs/web/api/firebase/push.html * * @param {Firebase.Value=} opt_value * @return {!Promise<!onfire.Ref,!Error>|!goog.Promise<!onfire.Ref,!Error>} A promise that resolves * to the Ref of the newly pushed child. */ onfire.Ref.prototype.push = function(opt_value) {}; /** * Returns an unwrapped Firebase reference to the current location. * * @return {!Firebase} An unwrapped Firebase reference to the current location. * @nosideeffects */ onfire.Ref.prototype.ref = function() {}; /** * Removes the data that is stored at the current location. A promisified analogue of Firebase's * .remove() method. * @see https://www.firebase.com/docs/web/api/firebase/remove.html * * @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise that resolves when the * operation is complete, or is rejected with an error. */ onfire.Ref.prototype.remove = function() {}; /** * Firebase.removeUser() wrapped in a promise. * @see https://www.firebase.com/docs/web/api/firebase/removeuser.html * * @param {!Firebase.AuthPasswordCredentials} credentials * @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise which resolves when the * operation is complete, or is rejected with an error. */ onfire.Ref.prototype.removeUser = function(credentials) {}; /** * Firebase.resetPassword() wrapped in a promise. * @see https://www.firebase.com/docs/web/api/firebase/resetpassword.html * * @param {!{email:string}} credentials * @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise which resolves when the * operation is complete, or is rejected with an error. */ onfire.Ref.prototype.resetPassword = function(credentials) {}; /** * Returns a reference that represents the root of the tree. * @see https://www.firebase.com/docs/web/api/firebase/root.html * * @return {!onfire.Ref} A reference that represents the root of the tree. * @nosideeffects */ onfire.Ref.prototype.root = function() {}; /** * Stores a value at the current location. A promisified analogue of Firebase's .set() method. * @see https://www.firebase.com/docs/web/api/firebase/set.html * * @param {Firebase.Value} value * @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise that resolves when the * operation is complete, or is rejected with an error. */ onfire.Ref.prototype.set = function(value) {}; /** * Sets a the values stored at the current location, atomically. A promisified analogue of * Firebase's .transaction() method. * @see https://www.firebase.com/docs/web/api/firebase/transaction.html * * @param {Firebase.TransactionUpdateFunction} updateFn * @return { !Promise<!{{isCommitted:boolean,snapshot:Firebase.DataSnapshot}},!Error> | !goog.Promise<!{{isCommitted:boolean,snapshot:Firebase.DataSnapshot}},!Error> } A promise that resolves when the operation is complete, or is rejected with an error. The value provided when the promise resolves is an object with two properties: isCommitted: whether the operation actually committed a value to the database. snapshot: a snapshot of the current data. */ onfire.Ref.prototype.transaction = function(updateFn) {}; /** * A proxy for Firebase.unauth(). * @see https://www.firebase.com/docs/web/api/firebase/unauth.html */ onfire.Ref.prototype.unauth = function() {}; /** * Updates multiple key/value pairs stored at the current location. A promisified analogue of * Firebase's .update() method. * @see https://www.firebase.com/docs/web/api/firebase/update.html * * @param {!Object<string,Firebase.Value>} values An object containing the key/value pairs. * @return {!Promise<null,!Error>|goog.Promise<null,!Error>} A promise that resolves when the * operation is complete, or is rejected with an error. */ onfire.Ref.prototype.update = function(values) {}; /** * Generates a subclass of onfire.model.Model or onfire.model.Collection with a baked in schema. * * @param {!Object} schema A schema object. * @return {!function(new:onfire.model.Model, !onfire.Ref)} A model constructor. * @throws {Error} */ onfire.defineModel = function(schema) {}; onfire.model = {}; /** * Base class to represent objects that live in Firebase. * * @param {!onfire.Ref} ref The reference of the current object. * @constructor */ onfire.model.Model = function(ref) {}; /** * Releases resources used by the model. Call this when you no longer need the instance. */ onfire.model.Model.prototype.dispose = function() {}; /** * Determines whether the underlying data exists. We may have retrieved a non-existent object, or * it may have subsequently been deleted. * * @return {boolean} Whether the underlying data actually exists. * @throws {Error} */ onfire.model.Model.prototype.exists = function() {}; /** * Synchronously retrieves the value associated with a key. If the value is not a primitive, a model * instance will be returned, in which case .whenLoaded() should be called on the returned model in * order to know when it is ready to use. If the key is already known to represent a model, it is * better to obtain it via the asynchronous .fetch() method. * If the key is specified in the schema, its value, or a model representing its value, will be * returned. If the key represents a primitive but missing value, the return value will be null. * If the key is not specified in the schema, but does have a value in the underlying data, that * value will be returned. Otherwise, an exception will be thrown. * * @param {string} key * @return {Firebase.Value|onfire.model.Model} A primitive value or a model instance. * @throws {Error} */ onfire.model.Model.prototype.get = function(key) {}; /** * Synchronously retrieves the primitive value associated with a key. If the value is an object, it * is returned unwrapped, i.e. not as a model instance. * If the key is specified in the schema, its value will be returned. If the key does not have a * value the return value will be null. * If the key is not specified in the schema, but does have a value in the underlying data, that * value will be returned. Otherwise, an exception will be thrown. * * @param {string} key The key under which the value is stored. * @return {Firebase.Value} The value or unwrapped object associated with the key. * @throws {Error} */ onfire.model.Model.prototype.getBasicValue = function(key) {}; /** * Synchronously retrieves the model instance that represents a non-primitive value that is * associated with a key. Make sure to call .whenLoaded() on the returned model in order to know when * it is ready to use. In many cases it may be more convenient to call the asynchronous .fetch() * method instead. * If the key is not specified in the schema, an exception will be thrown. * * @param {string} key * @return {!onfire.model.Model} * @throws {Error} */ onfire.model.Model.prototype.getModel = function(key) {}; /** * Determines whether there are any unsaved changes on this model. * * @return {boolean} Whether there are any unsaved changes on this model. */ onfire.model.Model.prototype.hasChanges = function() {}; /** * Returns the key of the model's reference. * * @return {string} The key of the model's reference */ onfire.model.Model.prototype.key = function() {}; /** * Register the callback function that will be called whenever the model is updated. To deregister * an existing callback, just pass null as the callback argument. * * @param {function()|null} callback */ onfire.model.Model.prototype.onValueChanged = function(callback) {}; /** * Asynchronously commits the outstanding changes. * * @return {!Promise<!onfire.model.Model,!Error>|!goog.Promise<!onfire.model.Model,!Error>} A * promise that resolves to this model instance when the operation completes successfully, or * is rejected with an error. * @throws {Error} if called when model is not yet loaded. */ onfire.model.Model.prototype.save = function() {}; /** * Registers the desire to change the primitive value associated with a key. The value will be * committed only when .save() is called. Returns a reference to the current model to allow * chaining, e.g., * person.set('firstName', 'John').set('lastName', 'Smith').save() * Throws an error if the key is not specified in the schema and does not already have a value in * the underlying data. * * @param {string} key The name of a property. * @param {Firebase.Value} value The primitive value to assign to the property. * @return {!onfire.model.Model} This model instance, in order to make the method chainable. * @throws {Error} */ onfire.model.Model.prototype.set = function(key, value) {}; /** * Returns a promise that is resolved to this instance when the data has been loaded. * * @return {!Promise<!onfire.model.Model,!Error>|!goog.Promise<!onfire.model.Model,!Error>} A * promise resolves to this instance when the data has been loaded. */ onfire.model.Model.prototype.whenLoaded = function() {}; /** * Exposes the schema. This is only exposed on generated models, and is included here for * documentation purposes only. * * @return {!Object} */ onfire.model.Model.getSchema = function() {}; /** * Base class for collections that live in Firebase. If collection members are not primitives, they * are lazily loaded -- only when requested. * * @param {!onfire.Ref} ref The reference of the current object. * @param {!function(new:onfire.model.Model, !onfire.Ref, number=)=} opt_memberCtor The model * constructor to use for instances of collection members. If the members are primitives, * this should not be supplied. * @constructor * @extends {onfire.model.Model} */ onfire.model.Collection = function(ref, opt_memberCtor) {}; /** * Determines whether the collection already has an entry for the provided key. * * @param {string} key * @return {boolean} * @throws {Error} */ onfire.model.Collection.prototype.containsKey = function(key) {}; /** * Returns the number of values in the collection. * * @return {number} The number of values in the collection. * @throws {Error} */ onfire.model.Collection.prototype.count = function() {}; /** * Asynchronously creates a model instance and adds it as a member of the collection, with an * automatically generated key. * * @param {!Object<string,Firebase.Value>=} opt_values An object containing the property/value pairs * to initialize the new object with. * @return {!Promise<!onfire.model.Model,!Error>|!goog.Promise<!onfire.model.Model,!Error>} A * promise that resolves to a model instance, or is rejected with an error. * @throws {Error} */ onfire.model.Collection.prototype.create = function(opt_values) {}; /** * Asynchronously retrieves a model instance that represents a member of the collection. Throws an * exception if the key does not exist. * * @param {string} key The key of the member. * @return {!Promise<!onfire.model.Model,!Error>|!goog.Promise<!onfire.model.Model,!Error>} A * promise that resolves to a model instance, or is rejected with an error. * @throws {Error} */ onfire.model.Collection.prototype.fetch = function(key) {}; /** * Asynchronously retrieves an existing item by its key, or creates it if it does not yet exist, and * adds it to the collection. * * @param {string} key * @param {!Object<string,Firebase.Value>=} values A set of property/value pairs to assign if * created. If null, don't set any values. The object will come into existence only when a * value is set and committed to the database. * @return {!Promise<!onfire.model.Model,!Error>|!goog.Promise<!onfire.model.Model,!Error>} A * promise that resolves to a model instance, or is rejected with an error. * @throws {Error} */ onfire.model.Collection.prototype.fetchOrCreate = function(key, values) {}; /** * Calls a callback for each member of the collection. Returns a promise that is resolved once all * the callbacks have been invoked, and any promises returned by callbacks have themselves been * resolved. * The callback function should accept a primitive value or a model instance, according to the type * of members in the collection. It does not need to return anything, but if it returns a promise, * the main return value of this method (a promise) will depend on it. * * @param { !function((!onfire.model.Model|Firebase.Value), string=):(!Promise|!goog.Promise|undefined) } callback * @return {(!Promise|!goog.Promise)} A promise that in resolved when all callbacks have completed. * @throws {Error} */ onfire.model.Collection.prototype.forEach = function(callback) {}; /** * Synchronously retrieves the value associated with a key. If the collection members are not * primitive values, a model instance will be returned, in which case .whenLoaded() should be called * on the returned model in order to know when it is ready to use. Consider using the asynchronous * .fetch() method instead. * Throws an exception if the key does not have a value in the underlying data. * * @override * @param {string} key An key of an item in the collection. * @return {Firebase.Value|onfire.model.Model} A primitive value or a model instance. * @throws {Error} */ onfire.model.Collection.prototype.get = function(key) {}; /** * Synchronously retrieves the primitive value associated with a key. If the value is an object, it * is returned unwrapped, i.e. not as a model instance. * Throws an exception if the key does not have a value in the underlying data. * * @param {string} key The key of the desired value. * @return {Firebase.Value} * @throws {Error} */ onfire.model.Collection.prototype.getBasicValue = function(key) {}; /** * Synchronously retrieves the value associated with a key and wraps it in a model instance. Make * sure to call .whenLoaded() on the returned model in order to know when it is ready to use. * Consider using the asynchronous .fetch() method instead. * Throws an exception if the key does not have a value in the underlying data. * * @param {string} key The key of the desired item. * @return {!onfire.model.Model} A model instance. * @throws {Error} */ onfire.model.Collection.prototype.getModel = function(key) {}; /** * Returns an array of the keys of members in the collection. * * @return {!Array<string>} An array of the keys of members in the collection. * @throws {Error} */ onfire.model.Collection.prototype.keys = function() {}; /** * Register the callback function that will be called whenever a child is added. To deregister * an existing callback, just pass null as the callback argument. * * @param {function(string)|null} callback A function that will be called with the key of the new * child. */ onfire.model.Collection.prototype.onChildAdded = function(callback) {}; /** * Register the callback function that will be called whenever a child is removed. To deregister * an existing callback, just pass null as the callback argument. * * @param {function(string)|null} callback A function that will be called with the key of the * removed child. */ onfire.model.Collection.prototype.onChildRemoved = function(callback) {}; /** * Asynchronously removes the specified member of the collection. The promise is not rejected if the * member is not present. * * @param {string} key The key of the member. * @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise that resolves when the * operation is complete, or is rejected with an error. * @throws {Error} */ onfire.model.Collection.prototype.remove = function(key) {}; /** * Registers the desire to change the primitive value associated with a key. The value will be * committed only when .save() is called. Returns a reference to the current model to allow * chaining, e.g., * person.set('firstName', 'John').set('lastName', 'Smith').save() * Throws an error if the key is not specified in the schema and does not already have a value in * the underlying data. * * @override return type. * @param {string} key The name of a property. * @param {Firebase.Value} value The primitive value to assign to the property. * @return {!onfire.model.Collection} * @throws {Error} */ onfire.model.Collection.prototype.set = function(key, value) {}; /** * @override the return type. * @return {!Promise<!onfire.model.Collection,!Error>|!goog.Promise<!onfire.model.Collection,!Error>} */ onfire.model.Collection.prototype.save; /** * @override the return type. * @return {!Promise<!onfire.model.Collection,!Error>|!goog.Promise<!onfire.model.Collection,!Error>} */ onfire.model.Collection.prototype.whenLoaded; /** * Exposes the type of members in the collection. This is only exposed on generated models, and is * dincluded here for ocumentation purposes only. * * @return {function(new:onfire.model.Model, !onfire.Ref)|undefined} */ onfire.model.Collection.getMemberCtor = function() {}; /** * Error messages that are thrown. * * @enum {string} */ onfire.model.Error = {}; /** * Thrown when the argument provided to the model constructor is not an onfire.Ref instance. * * @type {string} */ onfire.model.Error.INVALID_REF; /** * Thrown when a property or method is accessed before the model has finished loading, and the * result would be incorrect or unavailable. * * @type {string} */ onfire.model.Error.NOT_LOADED; /** * Thrown when an attempt is made to get or set the value of a key that is not specified in the * schema and does not exist in the underlying data. * * @type {string} */ onfire.model.Error.NO_SUCH_KEY; /** * Thrown when an attempt is made to obtain a model to represent a primitive value, e.g. calling * .getModel('abc') when .abc has an integer value according to the schema or in reality. * Another example is calling a collection's .create(), .fetch() or fetchOrCreate() methods * when the collection is a colection of primitive values and not models. * * @type {string} */ onfire.model.Error.NOT_A_MODEL; /** * Thrown when an attempt is made to assign a value to a key that represents a model. Any * changes need to be assigned via the model itself. In order to add a model instance to a * collection use .create() or .fetchOrCreate() instead of .set(). * * @type {string} */ onfire.model.Error.NOT_A_PRIMITIVE;
isabo/onfire
src/externs/outgoing/onfire-externs.js
JavaScript
mit
28,432
// ========================================================================== // Project: SproutCore Metal // Copyright: ©2011 Strobe Inc. and contributors. // License: Licensed under MIT license (see license.js) // ========================================================================== /*globals sc_assert */ require('sproutcore-metal/core'); require('sproutcore-metal/platform'); require('sproutcore-metal/utils'); require('sproutcore-metal/accessors'); var AFTER_OBSERVERS = ':change'; var BEFORE_OBSERVERS = ':before'; var guidFor = SC.guidFor; var normalizePath = SC.normalizePath; var suspended = 0; var array_Slice = Array.prototype.slice; var ObserverSet = function(iterateable) { this.set = {}; if (iterateable) { this.array = []; } } ObserverSet.prototype.add = function(target, name) { var set = this.set, guid = SC.guidFor(target), array; if (!set[guid]) { set[guid] = {}; } set[guid][name] = true; if (array = this.array) { array.push([target, name]); } }; ObserverSet.prototype.contains = function(target, name) { var set = this.set, guid = SC.guidFor(target), nameSet = set[guid]; return nameSet && nameSet[name]; }; ObserverSet.prototype.empty = function() { this.set = {}; this.array = []; }; ObserverSet.prototype.forEach = function(fn) { var q = this.array; this.empty(); q.forEach(function(item) { fn(item[0], item[1]); }); }; var queue = new ObserverSet(true), beforeObserverSet = new ObserverSet(); function notifyObservers(obj, eventName, forceNotification) { if (suspended && !forceNotification) { // if suspended add to the queue to send event later - but only send // event once. if (!queue.contains(obj, eventName)) { queue.add(obj, eventName); } } else { SC.sendEvent(obj, eventName); } } function flushObserverQueue() { beforeObserverSet.empty(); if (!queue || queue.array.length===0) return ; queue.forEach(function(target, event){ SC.sendEvent(target, event); }); } SC.beginPropertyChanges = function() { suspended++; return this; }; SC.endPropertyChanges = function() { suspended--; if (suspended<=0) flushObserverQueue(); }; function changeEvent(keyName) { return keyName+AFTER_OBSERVERS; } function beforeEvent(keyName) { return keyName+BEFORE_OBSERVERS; } function changeKey(eventName) { return eventName.slice(0, -7); } function beforeKey(eventName) { return eventName.slice(0, -7); } function xformForArgs(args) { return function (target, method, params) { var obj = params[0], keyName = changeKey(params[1]), val; if (method.length>2) val = SC.getPath(obj, keyName); args.unshift(obj, keyName, val); method.apply(target, args); } } var xformChange = xformForArgs([]); function xformBefore(target, method, params) { var obj = params[0], keyName = beforeKey(params[1]), val; if (method.length>2) val = SC.getPath(obj, keyName); method.call(target, obj, keyName, val); } SC.addObserver = function(obj, path, target, method) { path = normalizePath(path); var xform; if (arguments.length > 4) { var args = array_Slice.call(arguments, 4); xform = xformForArgs(args); } else { xform = xformChange; } SC.addListener(obj, changeEvent(path), target, method, xform); SC.watch(obj, path); return this; }; /** @private */ SC.observersFor = function(obj, path) { return SC.listenersFor(obj, changeEvent(path)); }; SC.removeObserver = function(obj, path, target, method) { path = normalizePath(path); SC.unwatch(obj, path); SC.removeListener(obj, changeEvent(path), target, method); return this; }; SC.addBeforeObserver = function(obj, path, target, method) { path = normalizePath(path); SC.addListener(obj, beforeEvent(path), target, method, xformBefore); SC.watch(obj, path); return this; }; /** @private */ SC.beforeObserversFor = function(obj, path) { return SC.listenersFor(obj, beforeEvent(path)); }; SC.removeBeforeObserver = function(obj, path, target, method) { path = normalizePath(path); SC.unwatch(obj, path); SC.removeListener(obj, beforeEvent(path), target, method); return this; }; /** @private */ SC.notifyObservers = function(obj, keyName) { notifyObservers(obj, changeEvent(keyName)); }; /** @private */ SC.notifyBeforeObservers = function(obj, keyName) { var guid, set, forceNotification = false; if (suspended) { if (!beforeObserverSet.contains(obj, keyName)) { beforeObserverSet.add(obj, keyName); forceNotification = true; } else { return; } } notifyObservers(obj, beforeEvent(keyName), forceNotification); };
crofty/sensor_js_message_parsing
vendor/sproutcore-metal/lib/observer.js
JavaScript
mit
4,614
'use strict'; System.register('flarum/akismet/components/AkismetSettingsModal', ['flarum/components/SettingsModal'], function (_export, _context) { var SettingsModal, AkismetSettingsModal; return { setters: [function (_flarumComponentsSettingsModal) { SettingsModal = _flarumComponentsSettingsModal.default; }], execute: function () { AkismetSettingsModal = function (_SettingsModal) { babelHelpers.inherits(AkismetSettingsModal, _SettingsModal); function AkismetSettingsModal() { babelHelpers.classCallCheck(this, AkismetSettingsModal); return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(AkismetSettingsModal).apply(this, arguments)); } babelHelpers.createClass(AkismetSettingsModal, [{ key: 'className', value: function className() { return 'AkismetSettingsModal Modal--small'; } }, { key: 'title', value: function title() { return app.translator.trans('flarum-akismet.admin.akismet_settings.title'); } }, { key: 'form', value: function form() { return [m( 'div', { className: 'Form-group' }, m( 'label', null, app.translator.trans('flarum-akismet.admin.akismet_settings.api_key_label') ), m('input', { className: 'FormControl', bidi: this.setting('flarum-akismet.api_key') }) )]; } }]); return AkismetSettingsModal; }(SettingsModal); _export('default', AkismetSettingsModal); } }; });; 'use strict'; System.register('flarum/akismet/main', ['flarum/app', 'flarum/akismet/components/AkismetSettingsModal'], function (_export, _context) { var app, AkismetSettingsModal; return { setters: [function (_flarumApp) { app = _flarumApp.default; }, function (_flarumAkismetComponentsAkismetSettingsModal) { AkismetSettingsModal = _flarumAkismetComponentsAkismetSettingsModal.default; }], execute: function () { app.initializers.add('flarum-akismet', function () { app.extensionSettings['flarum-akismet'] = function () { return app.modal.show(new AkismetSettingsModal()); }; }); } }; });
namjoker/flarumfull
vendor/flarum/flarum-ext-akismet/js/admin/dist/extension.js
JavaScript
mit
2,370
module.exports = function createItemTweet (url, user, callback) { var fs = require("fs"); var https = require('https'); var models = require('../../models'); var itemTypes = require('../../models/item/itemTypes.json'); var tweetUrl = url; var options = { host: 'publish.twitter.com', path: '/oembed?format=json&url='+ encodeURI(tweetUrl) }; var twCallback = function(response) { var str = ''; response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { var response = JSON.parse(str); var itemTweet = new models.ItemTweet(); itemTweet.url = response.url; itemTweet.html = response.html; itemTweet.author_name = response.author_name; itemTweet.author_url = response.author_url; itemTweet.width = response.width; itemTweet.height = response.height; itemTweet.type = response.type; itemTweet.provider_name = response.provider_name; itemTweet.version = response.version; itemTweet._user = user._id; itemTweet.save(function(err){ if(err)callback(err) callback(null, itemTypes.TWEET, itemTweet) }) }); response.on('error', function () { callback(JSON.parse(str)); }); }; https.request(options, twCallback).end(); }
OlivierCoue/invow
server/helpers/item-content/createItemTweet.js
JavaScript
mit
1,490
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("a11yhelp","cs",{title:"Instrukce pro přístupnost",contents:"Obsah nápovědy. Pro uzavření tohoto dialogu stiskněte klávesu ESC.",legend:[{name:"Obecné",items:[{name:"Panel nástrojů editoru",legend:"Stiskněte${toolbarFocus} k procházení panelu nástrojů. Přejděte na další a předchozí skupiny pomocí TAB a SHIFT+TAB. Přechod na další a předchozí tlačítko panelu nástrojů je pomocí ŠIPKA VPRAVO nebo ŠIPKA VLEVO. Stisknutím mezerníku nebo klávesy ENTER tlačítko aktivujete."},{name:"Dialogové okno editoru", legend:"Uvnitř dialogového okna stiskněte TAB pro přesunutí na další prvek okna, stiskněte SHIFT+TAB pro přesun na předchozí prvek okna, stiskněte ENTER pro odeslání dialogu, stiskněte ESC pro jeho zrušení. Pro dialogová okna, která mají mnoho karet stiskněte ALT+F10 pro zaměření seznamu karet, nebo TAB, pro posun podle pořadí karet.Při zaměření seznamu karet se můžete jimi posouvat pomocí ŠIPKY VPRAVO a VLEVO."},{name:"Kontextové menu editoru",legend:"Stiskněte ${contextMenu} nebo klávesu APPLICATION k otevření kontextového menu. Pak se přesuňte na další možnost menu pomocí TAB nebo ŠIPKY DOLŮ. Přesuňte se na předchozí možnost pomocí SHIFT+TAB nebo ŠIPKY NAHORU. Stiskněte MEZERNÍK nebo ENTER pro zvolení možnosti menu. Podmenu současné možnosti otevřete pomocí MEZERNÍKU nebo ENTER či ŠIPKY DOLEVA. Kontextové menu uzavřete stiskem ESC."}, {name:"Rámeček seznamu editoru",legend:"Uvnitř rámečku seznamu se přesunete na další položku menu pomocí TAB nebo ŠIPKA DOLŮ. Na předchozí položku se přesunete SHIFT+TAB nebo ŠIPKA NAHORU. Stiskněte MEZERNÍK nebo ENTER pro zvolení možnosti seznamu. Stiskněte ESC pro uzavření seznamu."},{name:"Lišta cesty prvku v editoru",legend:"Stiskněte ${elementsPathFocus} pro procházení lišty cesty prvku. Na další tlačítko prvku se přesunete pomocí TAB nebo ŠIPKA VPRAVO. Na předchozí tlačítko se přesunete pomocí SHIFT+TAB nebo ŠIPKA VLEVO. Stiskněte MEZERNÍK nebo ENTER pro vybrání prvku v editoru."}]}, {name:"Příkazy",items:[{name:" Příkaz Zpět",legend:"Stiskněte ${undo}"},{name:" Příkaz Znovu",legend:"Stiskněte ${redo}"},{name:" Příkaz Tučné",legend:"Stiskněte ${bold}"},{name:" Příkaz Kurzíva",legend:"Stiskněte ${italic}"},{name:" Příkaz Podtržení",legend:"Stiskněte ${underline}"},{name:" Příkaz Odkaz",legend:"Stiskněte ${link}"},{name:" Příkaz Skrýt panel nástrojů",legend:"Stiskněte ${toolbarCollapse}"},{name:"Příkaz pro přístup k předchozímu prostoru zaměření",legend:"Stiskněte ${accessPreviousSpace} pro přístup k nejbližšímu nedosažitelnému prostoru zaměření před stříškou, například: dva přilehlé prvky HR. Pro dosažení vzdálených prostorů zaměření tuto kombinaci kláves opakujte."}, {name:"Příkaz pro přístup k dalšímu prostoru zaměření",legend:"Stiskněte ${accessNextSpace} pro přístup k nejbližšímu nedosažitelnému prostoru zaměření po stříšce, například: dva přilehlé prvky HR. Pro dosažení vzdálených prostorů zaměření tuto kombinaci kláves opakujte."},{name:" Nápověda přístupnosti",legend:"Stiskněte ${a11yHelp}"},{name:"Vložit jako čistý text",legend:"Stiskněte ${pastetext}",legendEdge:"Stiskněte ${pastetext} a pak ${paste}"}]}],tab:"Tabulátor",pause:"Pauza",capslock:"Caps lock", escape:"Escape",pageUp:"Stránka nahoru",pageDown:"Stránka dolů",leftArrow:"Šipka vlevo",upArrow:"Šipka nahoru",rightArrow:"Šipka vpravo",downArrow:"Šipka dolů",insert:"Vložit",leftWindowKey:"Levá klávesa Windows",rightWindowKey:"Pravá klávesa Windows",selectKey:"Vyberte klávesu",numpad0:"Numerická klávesa 0",numpad1:"Numerická klávesa 1",numpad2:"Numerická klávesa 2",numpad3:"Numerická klávesa 3",numpad4:"Numerická klávesa 4",numpad5:"Numerická klávesa 5",numpad6:"Numerická klávesa 6",numpad7:"Numerická klávesa 7", numpad8:"Numerická klávesa 8",numpad9:"Numerická klávesa 9",multiply:"Numerická klávesa násobení",add:"Přidat",subtract:"Numerická klávesa odečítání",decimalPoint:"Desetinná tečka",divide:"Numerická klávesa dělení",f1:"F1",f2:"F2",f3:"F3",f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Num lock",scrollLock:"Scroll lock",semiColon:"Středník",equalSign:"Rovnítko",comma:"Čárka",dash:"Pomlčka",period:"Tečka",forwardSlash:"Lomítko",graveAccent:"Přízvuk",openBracket:"Otevřená hranatá závorka", backSlash:"Obrácené lomítko",closeBracket:"Uzavřená hranatá závorka",singleQuote:"Jednoduchá uvozovka"});
rikzuiderlicht/concrete5
concrete/js/ckeditor4/vendor/plugins/a11yhelp/dialogs/lang/cs.js
JavaScript
mit
4,851
/** * Context Object * * @author Zongmin Lei<[email protected]> */ var utils = require('./utils'); var parser = require('./parser'); var filters = require('./filters'); var vm = require('./vm'); var OPCODE = require('./opcode'); var debug = utils.debug('Context'); var merge = utils.merge; /** * Context * * @param {Object} options * - {Object} filters * - {Object} asyncFilters * - {Object} locals * - {Object} syncLocals * - {Object} asyncLocals * - {Object} blocks * - {Boolean} isLayout default:false * - {Integer} timeout unit:ms, default:120000 * - {Object} parent */ var Context = module.exports = exports = function (options) { options = options || {}; this._locals = {}; this._syncLocals = {}; this._asyncLocals = {}; this._asyncLocals2 = []; this._filters = merge(filters, options.filters); this._asyncFilters = {}; this._cycles = {}; this._buffer = ''; this._forloops = []; this._isInForloop = false; this._tablerowloops = []; this._isInTablerowloop = false; this._includeFileHandler = null; this._position = {line: 0, column: 0}; this._astCache = {}; this._filenameStack = []; this._filterCache = {}; this._blocks = {}; this._isLayout = !!options.isLayout; // default configuration options = merge({ timeout: 120000 }, options); this.options = options; // parent this._parent = options.parent || null; // initialize the configuration var me = this; var set = function (name) { if (options[name] && typeof(options[name]) === 'object') { Object.keys(options[name]).forEach(function (i) { me['_' + name][i] = options[name][i]; }); } }; set('locals'); set('syncLocals'); set('asyncLocals'); set('asyncLocals2'); set('filters'); set('blocks'); if (options.asyncFilters && typeof options.asyncFilters === 'object') { Object.keys(options.asyncFilters).forEach(function (i) { me.setAsyncFilter(i, options.asyncFilters[i]); }); } }; /** * Copy the configuration from other context object * * @param {Object} from * @return {Object} */ Context.prototype.from = function (from) { var me = this; var set = function (name) { if (from[name] && typeof(from[name]) === 'object') { for (var i in from[name]) { if (i in me[name]) continue; me[name][i] = from[name][i]; } } else if (typeof(from[name] === 'function')) { if (!me[name]) { me[name] = from[name]; } } } set('_locals'); set('_syncLocals'); set('_asyncLocals'); set('_asyncLocals2'); set('_filters'); set('_asyncFilters'); set('options'); set('_onErrorHandler'); set('_includeFileHandler'); set('_filterCache'); set('_blocks'); if (Array.isArray(from._filenameStack)) { me._filenameStack = from._filenameStack.slice(); } for (var i in from) { if (i in me) continue; me[i] = from[i]; } me._isInForloop = from._isInForloop; me._forloops = from._forloops.slice(); me._isInTablerowloop = from._isInTablerowloop; me._tablerowloops = from._tablerowloops; me._isLayout = from._isLayout; return this; }; /* constants */ Context.prototype.STATIC_LOCALS = 0; // normal locals Context.prototype.SYNC_LOCALS = 1; // get value from a sync function Context.prototype.ASYNC_LOCALS = 2; // get value from a async function Context.prototype.SYNC_FILTER = 0; // normal filter Context.prototype.ASYNC_FILTER = 1; // async filter /** * Set Timeout * * @param {Integer} ms */ Context.prototype.setTimeout = function (ms) { ms = parseInt(ms, 10); if (ms > 0) this.options.timeout = ms; }; /** * Run AST * * @param {Array} astList * @param {Function} callback */ Context.prototype.run = function (astList, callback) { return vm.run(astList, this, callback); }; /** * Register normal locals * * @param {String} name * @param {Function} val */ Context.prototype.setLocals = function (name, val) { this._locals[name] = val; if (this._parent) { this._parent.setLocals(name, val); } }; /** * Register sync locals * * @param {String} name * @param {Function} val */ Context.prototype.setSyncLocals = function (name, fn) { this._syncLocals[name] = fn; }; /** * Register async locals * * @param {String} name * @param {Function} fn */ Context.prototype.setAsyncLocals = function (name, fn) { if (name instanceof RegExp) { var name2 = name.toString(); // remove the same name for (var i = 0, len = this._asyncLocals2; i < len; i++) { var item = this._asyncLocals2[i]; if (item[0].toString() === name2) { this._asyncLocals2.splice(i, 1); break; } } this._asyncLocals2.push([name, fn]); } else { this._asyncLocals[name] = fn; } }; /** * Register normal filter * * @param {String} name * @param {Function} fn */ Context.prototype.setFilter = function (name, fn) { this._filters[name.trim()] = fn; }; /** * Register async filter * * @param {String} name * @param {Function} fn */ Context.prototype.setAsyncFilter = function (name, fn) { if (fn.enableCache) fn = utils.wrapFilterCache(name, fn); this._asyncFilters[name.trim()] = fn; }; /** * Set layout file * * @param {String} filename */ Context.prototype.setLayout = function (filename) { this._layout = filename; }; /** * Set block * * @param {String} name * @param {String} buf */ Context.prototype.setBlock = function (name, buf) { this._blocks[name] = buf; if (this._parent) { this._parent.setBlock(name, buf); } }; /** * Set block if empty * * @param {String} name * @param {String} buf */ Context.prototype.setBlockIfEmpty = function (name, buf) { if (!(name in this._blocks)) { this._blocks[name] = buf; } }; /** * Get block * * @param {String} name * @return {String} */ Context.prototype.getBlock = function (name) { return this._blocks[name] || null; }; /** * Get locals * * @param {String} name * @return {Array} [type, value, isAllowCache] return null if the locals not found */ Context.prototype.getLocals = function (name) { if (name in this._locals) return [this.STATIC_LOCALS, this._locals[name]]; if (name in this._syncLocals) return [this.SYNC_LOCALS, this._syncLocals[name], true]; if (name in this._asyncLocals) return [this.ASYNC_LOCALS, this._asyncLocals[name], true]; for (var i = 0, len = this._asyncLocals2.length; i < len; i++) { var item = this._asyncLocals2[i]; if (item[0].test(name)) { return [this.ASYNC_LOCALS, item[1], true]; } } return null; }; /** * Fetch Single Locals * * @param {String} name * @param {Function} callback */ Context.prototype.fetchSingleLocals = function (name, callback) { var me = this; var info = me.getLocals(name); if (!info) return callback(null, info); switch (info[0]) { case me.STATIC_LOCALS: callback(null, info[1]); break; case me.SYNC_LOCALS: var v = info[1](name, me); if (info[2]) me.setLocals(name, v); callback(null, v); break; case me.ASYNC_LOCALS: info[1](name, function (err, v) { if (err) return callback(err); if (info[2]) me.setLocals(name, v); callback(null, v); }, me); break; default: callback(me.throwLocalsUndefinedError(name)); } }; /** * Fetch locals * * @param {Array|String} list * @param {Function} callback */ Context.prototype.fetchLocals = function (list, callback) { var me = this; if (Array.isArray(list)) { var values = []; utils.asyncEach(list, function (name, i, done) { me.fetchSingleLocals(name, function (err, val) { if (err) { values[i] = err; } else { values[i] = val; } done(); }); }, callback, null, values); } else { me.fetchSingleLocals(list, callback); } }; /** * Get filter * * @param {String} name * @return {Array} [type, function] return null if the filter not found */ Context.prototype.getFilter = function (name) { name = name.trim(); if (name in this._filters) return [this.SYNC_FILTER, this._filters[name]]; if (name in this._asyncFilters) return [this.ASYNC_FILTER, this._asyncFilters[name]]; return null; }; /** * Call filter * * @param {String} method * @param {Array} args * @param {Function} callback */ Context.prototype.callFilter = function (method, args, callback) { if (arguments.length < 3) { callback = args; args = []; } var info = this.getFilter(method); if (!info) return callback(this.throwFilterUndefinedError(method)); if (info[0] === this.ASYNC_FILTER) { args.push(callback); args.push(this); info[1].apply(null, args); } else { args.push(this); callback(null, info[1].apply(null, args)); } }; /** * Print HTML * * @param {Object} str */ Context.prototype.print = function (str) { this._buffer += (str === null || typeof(str) === 'undefined') ? '' : str; }; /** * Set buffer * * @param {String} buf */ Context.prototype.setBuffer = function (buf) { this._buffer = buf; }; /** * Get buffer * * @return {String} */ Context.prototype.getBuffer = function () { return this._buffer; }; /** * Clear buffer * * @return {String} */ Context.prototype.clearBuffer = function () { var buf = this.getBuffer(); this.setBuffer(''); return buf; }; /** * Set cycle * * @param {String} name * @param {Array} list */ Context.prototype.setCycle = function (name, list) { this._cycles[name] = {index: 0, length: list.length, list: list}; }; /** * Get the index of the cycle * * @param {String} name * @return {Integer} */ Context.prototype.getCycleIndex = function (name) { var cycle = this._cycles[name]; if (cycle) { cycle.index++; if (cycle.index >= cycle.length) cycle.index = 0; return cycle.index; } else { return null; } }; /** * Enter a forloop * * @param {Integer} length * @param {String} itemName */ Context.prototype.forloopEnter = function (length, itemName) { this._forloops.push({ length: length, itemName: itemName }); this._isInForloop = true; }; /** * Set the forloop item value * * @param {Object} item * @param {Integer} index */ Context.prototype.forloopItem = function (item, index) { var loop = this._forloops[this._forloops.length - 1]; loop.item = item; loop.index = index; }; /** * Set the forloop information * * @return {Object} */ Context.prototype.forloopInfo = function () { return this._forloops[this._forloops.length - 1]; }; /** * Exit the current forloop */ Context.prototype.forloopEnd = function () { this._forloops.pop(); if (this._forloops.length < 1) { this._isInForloop = false; } }; /** * Enter a tablerowloop * * @param {Integer} length * @param {String} itemName * @param {Integer} columns */ Context.prototype.tablerowloopEnter = function (length, itemName, columns) { this._tablerowloops.push({ length: length, itemName: itemName, columns: columns }); this._isInTablerowloop = true; }; /** * Set the tablerowloop item value * * @param {Object} item * @param {Integer} index * @param {Integer} colIndex */ Context.prototype.tablerowloopItem = function (item, index, colIndex) { var loop = this._tablerowloops[this._tablerowloops.length - 1]; loop.item = item; loop.index = index; loop.colIndex = colIndex; }; /** * Get the tablerow information * * @return {Object} */ Context.prototype.tablerowloopInfo = function () { return this._tablerowloops[this._tablerowloops.length - 1]; }; /** * Exit the current tablerowloop */ Context.prototype.tablerowloopEnd = function () { this._tablerowloops.pop(); if (this._tablerowloops.length < 1) { this._isInTablerowloop = false; } }; /** * Include a template file * * @param {String} name * @param {Array} localsAst * @param {Array} headerAst * @param {Function} callback */ Context.prototype.include = function (name, localsAst, headerAst, callback) { if (typeof headerAst === 'function') { callback = headerAst; headerAst = null; } var me = this; if (typeof(this._includeFileHandler) === 'function') { this._includeFileHandler(name, function (err, astList) { if (err) return callback(err); // all include files run on new context var c = new Context({parent: me}); c.from(me); function start () { c.run(astList, function (err) { //console.log(err, c.getBuffer(), headerAst); me.print(c.clearBuffer()); callback(err); }); } if (headerAst && headerAst.length > 0) { astList = [me._position.line, me._position.column,OPCODE.LIST, headerAst, astList]; } if (localsAst) { me.run(localsAst, function (err, locals) { if (err) locals = {}; Object.keys(locals).forEach(function (n) { c._locals[n] = locals[n]; }); start(); }); } else { start(); } }); } else { return callback(new Error('please set an include file handler')); } }; /** * Extends layout * * @param {String} name * @param {Function} callback */ Context.prototype.extends = function (name, callback) { if (typeof(this._includeFileHandler) === 'function') { this._includeFileHandler(name, callback); } else { return callback(new Error('please set an include file handler')); } }; /** * Set the include file handler * * @param {Function} fn format: function (name, callback) * callback format: function (err, astList) */ Context.prototype.onInclude = function (fn) { this._includeFileHandler = fn; }; /** * Throw locals undefined error * * @param {String} name * @return {Object} */ Context.prototype.throwLocalsUndefinedError = function (name) { debug('Locals ' + name + ' is undefined'); return null; }; /** * Throw loop item undefined error * * @param {String} name * @return {Object} */ Context.prototype.throwLoopItemUndefinedError = function (name) { debug('Loop item ' + name + ' is undefined'); return null; }; /** * Throw forloop/tablerow locals undefined error * * @param {String} name * @return {Object} */ Context.prototype.throwLoopLocalsUndefinedError = function (name) { debug('Loop locals ' + name + ' is undefined'); return null; }; /** * Throw filter undefined error * * @param {String} name * @return {Object} */ Context.prototype.throwFilterUndefinedError = function (name) { var err = new Error('Filter ' + name + ' is undefined ' + this.getCurrentPosition(true)); err.code = 'UNDEFINED_FILTER'; err = this.wrapCurrentPosition(err); return err; } /** * Throw unknown opcode error * * @param {String} code * @return {Object} */ Context.prototype.throwUnknownOpcodeError = function (code) { var err = new Error('Unknown opcode ' + code + ' ' + this.getCurrentPosition(true)); err.code = 'UNKNOWN_OPCODE'; err = this.wrapCurrentPosition(err); return err; }; /** * Throw unknown tag error * * @param {String} name * @param {String} body * @return {Object} */ Context.prototype.throwUnknownTagError = function (name, body) { var err = new Error('Unknown tag "' + (name + ' ' + body).trim() + '" ' + this.getCurrentPosition(true)); err.code = 'UNKNOWN_TAG'; err = this.wrapCurrentPosition(err); return err; }; /** * Set current position * * @param {Integer} line * @param {Integer} column */ Context.prototype.setCurrentPosition = function (line, column) { this._position.line = line; this._position.column = column; }; /** * Get current position * * @param {Boolean} getString * @return {Object} */ Context.prototype.getCurrentPosition = function (getString) { if (getString) { return 'at line ' + this._position.line + ', column ' + this._position.column; } else { return this._position; } }; /** * Wrap current position on a error object * * @param {Object} err * @return {Object} */ Context.prototype.wrapCurrentPosition = function (err) { err = err || {}; err.line = this._position.line; err.column = this._position.column; return err; }; /** * Push Filename * * @param {String} filename * @return {String} */ Context.prototype.pushFilename = function (filename) { this._filenameStack.push(filename); return filename; }; /** * Pop Filename * * @return {String} */ Context.prototype.popFilename = function () { return this._filenameStack.pop(); }; /** * Get filename * * @return {String} */ Context.prototype.getFilename = function () { return this._filenameStack[this._filenameStack.length - 1]; };
jddeeds/jddeeds.github.io
node_modules/tinyliquid/lib/context.js
JavaScript
mit
16,661
const { assign } = require('lodash') const proxyquire = require('proxyquire') const contact = require('../../../../../test/unit/data/contacts/contact.json') describe('Contact controller', () => { beforeEach(() => { this.getContactStub = sinon.stub().resolves(contact) this.getDitCompanyStub = sinon.stub().resolves(contact.company) this.transformerStub = sinon.stub() this.contactController = proxyquire('../details', { '../repos': { getContact: this.getContactStub, }, '../../companies/repos': { getDitCompany: this.getDitCompanyStub, }, '../transformers': { transformContactToView: this.transformerStub, }, }) this.req = { session: { token: 'abcd', }, params: { contactId: '12651151-2149-465e-871b-ac45bc568a62', }, } this.res = { locals: {}, breadcrumb: sinon.stub().returnsThis(), render: sinon.spy(), } this.next = sinon.spy() }) describe('#getCommon', () => { it('should get the contact ID', async () => { await this.contactController.getCommon(this.req, this.res, this.next) expect(this.res.locals.id).to.equal(this.req.params.contactId) expect(this.next).to.have.been.calledOnce }) it('should get the reason for archive options', async () => { await this.contactController.getCommon(this.req, this.res, this.next) const expected = [ 'Left the company', 'Does not want to be contacted', 'Changed role/responsibility', ] expect(this.res.locals.reasonForArchiveOptions).to.deep.equal(expected) expect(this.next).to.have.been.calledOnce }) it('should get the reason for archive options prefix', async () => { await this.contactController.getCommon(this.req, this.res, this.next) expect(this.res.locals.reasonForArchiveOptionsPrefix).to.equal( 'This contact has:' ) expect(this.next).to.have.been.calledOnce }) it('should handle an error', async () => { const error = Error('error') this.getContactStub.rejects(error) await this.contactController.getCommon(this.req, this.res, this.next) expect(this.next).to.be.calledWith( sinon.match({ message: error.message }) ) expect(this.next).to.have.been.calledOnce }) }) describe('#getDetails', () => { context('when called with a contact', () => { beforeEach(() => { this.res.locals = assign({}, this.res.locals, { contact }) this.res.locals.features = assign({}, this.res.locals.features) this.contactController.getDetails(this.req, this.res, this.next) }) it('should return the contact details', () => { const options = this.res.render.firstCall.args[1] expect(options).to.have.property('contactDetails') }) it('should call the details transformer', () => { expect(this.transformerStub).to.be.calledWith(contact) }) it('should render the contact details view', () => { expect(this.res.render).to.be.calledWith('contacts/views/details') }) }) }) })
uktrade/data-hub-fe-beta2
src/apps/contacts/controllers/__test__/details.test.js
JavaScript
mit
3,180
const inherits = require('util').inherits const async = require('async') const ethUtil = require('ethereumjs-util') const Account = require('ethereumjs-account') const FakeMerklePatriciaTree = require('fake-merkle-patricia-tree') const VM = require('./index.js') const ZERO_BUFFER = new Buffer('0000000000000000000000000000000000000000000000000000000000000000', 'hex') module.exports = createHookedVm module.exports.fromWeb3Provider = fromWeb3Provider /* This is a helper for creating a vm with modified state lookups this should be made obsolete by a better public API for StateManager ```js var vm = createHookedVm({ enableHomestead: true, }, { fetchAccountBalance: function(addressHex, cb){ ... }, fetchAccountNonce: function(addressHex, cb){ ... }, fetchAccountCode: function(addressHex, cb){ ... }, fetchAccountStorage: function(addressHex, keyHex, cb){ ... }, }) vm.runTx(txParams, cb) ``` */ function createHookedVm (opts, hooks) { var codeStore = new FallbackAsyncStore(hooks.fetchAccountCode.bind(hooks)) var vm = new VM(opts) vm.stateManager._lookupStorageTrie = createAccountStorageTrie vm.stateManager.cache._lookupAccount = loadAccount vm.stateManager.getContractCode = codeStore.get.bind(codeStore) vm.stateManager.setContractCode = codeStore.set.bind(codeStore) return vm function createAccountStorageTrie (address, cb) { var addressHex = ethUtil.addHexPrefix(address.toString('hex')) var storageTrie = new FallbackStorageTrie({ fetchStorage: function (key, cb) { hooks.fetchAccountStorage(addressHex, ethUtil.addHexPrefix(key), cb) } }) cb(null, storageTrie) } function loadAccount (address, cb) { var addressHex = ethUtil.addHexPrefix(address.toString('hex')) async.parallel({ nonce: hooks.fetchAccountNonce.bind(hooks, addressHex), balance: hooks.fetchAccountBalance.bind(hooks, addressHex) }, function (err, results) { if (err) return cb(err) results._exists = results.nonce !== '0x0' || results.balance !== '0x0' || results._code !== '0x' // console.log('fetch account results:', results) var account = new Account(results) // not used but needs to be anything but the default (ethUtil.SHA3_NULL) // code lookups are handled by `codeStore` account.codeHash = ZERO_BUFFER.slice() cb(null, account) }) } } /* Additional helper for creating a vm with rpc state lookups blockNumber to query against is fixed */ function fromWeb3Provider (provider, blockNumber, opts) { return createHookedVm(opts, { fetchAccountBalance: createRpcFunction(provider, 'eth_getBalance', blockNumber), fetchAccountNonce: createRpcFunction(provider, 'eth_getTransactionCount', blockNumber), fetchAccountCode: createRpcFunction(provider, 'eth_getCode', blockNumber), fetchAccountStorage: createRpcFunction(provider, 'eth_getStorageAt', blockNumber) }) function createRpcFunction (provider, method, blockNumber) { return function sendRpcRequest () { // prepare arguments var args = [].slice.call(arguments) var cb = args.pop() args.push(blockNumber) // send rpc payload provider.sendAsync({ id: 1, jsonrpc: '2.0', method: method, params: args }, function (err, res) { if (err) return cb(err) cb(null, res.result) }) } } } // // FallbackStorageTrie // // is a FakeMerklePatriciaTree that will let lookups // fallback to the fetchStorage fn. writes shadow the underlying fetchStorage value. // doesn't bother with a stateRoot // inherits(FallbackStorageTrie, FakeMerklePatriciaTree) function FallbackStorageTrie (opts) { const self = this FakeMerklePatriciaTree.call(self) self._fetchStorage = opts.fetchStorage } FallbackStorageTrie.prototype.get = function (key, cb) { const self = this var _super = FakeMerklePatriciaTree.prototype.get.bind(self) _super(key, function (err, value) { if (err) return cb(err) if (value) return cb(null, value) // if value not in tree, try network var keyHex = key.toString('hex') self._fetchStorage(keyHex, function (err, rawValue) { if (err) return cb(err) var value = ethUtil.toBuffer(rawValue) value = ethUtil.unpad(value) var encodedValue = ethUtil.rlp.encode(value) cb(null, encodedValue) }) }) } // // FallbackAsyncStore // // is an async key-value store that will let lookups // fallback to the network. puts are not sent. // function FallbackAsyncStore (fetchFn) { // console.log('FallbackAsyncStore - new') const self = this self.fetch = fetchFn self.cache = {} } FallbackAsyncStore.prototype.get = function (address, cb) { // console.log('FallbackAsyncStore - get', arguments) const self = this var addressHex = '0x' + address.toString('hex') var code = self.cache[addressHex] if (code !== undefined) { cb(null, code) } else { // console.log('FallbackAsyncStore - fetch init') self.fetch(addressHex, function (err, value) { // console.log('FallbackAsyncStore - fetch return', arguments) if (err) return cb(err) value = ethUtil.toBuffer(value) self.cache[addressHex] = value cb(null, value) }) } } FallbackAsyncStore.prototype.set = function (address, code, cb) { // console.log('FallbackAsyncStore - set', arguments) const self = this var addressHex = '0x' + address.toString('hex') self.cache[addressHex] = code cb() }
giulidb/ticket_dapp
node_modules/ethereumjs-vm/lib/hooked.js
JavaScript
mit
5,536
title('Entity-relationship diagram.'); description('Make your database structure visible.'); dimension(800, 250); var erd = Joint.dia.erd; Joint.paper("world", 800, 250); var e1 = erd.Entity.create({ rect: { x: 220, y: 70, width: 100, height: 60 }, label: "Entity" }); var e2 = erd.Entity.create({ rect: { x: 520, y: 70, width: 100, height: 60 }, label: "Weak Entity", weak: true }); var r1 = erd.Relationship.create({ rect: { x: 400, y: 72, width: 55, height: 55 }, label: "Relationship" }); var a1 = erd.Attribute.create({ ellipse: { x: 90, y: 30, rx: 50, ry: 20 }, label: "primary", primaryKey: true }); var a2 = erd.Attribute.create({ ellipse: { x: 90, y: 80, rx: 50, ry: 20 }, label: "multivalued", multivalued: true }); var a3 = erd.Attribute.create({ ellipse: { x: 90, y: 130, rx: 50, ry: 20 }, label: "derived", derived: true }); var a4 = erd.Attribute.create({ ellipse: { x: 90, y: 180, rx: 50, ry: 20 }, label: "normal" }); a1.joint(e1, erd.arrow); a2.joint(e1, erd.arrow); a3.joint(e1, erd.arrow); a4.joint(e1, erd.arrow); e1.joint(r1, erd.toMany); r1.joint(e2, erd.oneTo);
dee-bee/decisionz
decisionz/lib/JointJS/www/demos/erd.js
JavaScript
mit
1,130
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM7.07 18.28c.43-.9 3.05-1.78 4.93-1.78s4.51.88 4.93 1.78C15.57 19.36 13.86 20 12 20s-3.57-.64-4.93-1.72zm11.29-1.45c-1.43-1.74-4.9-2.33-6.36-2.33s-4.93.59-6.36 2.33C4.62 15.49 4 13.82 4 12c0-4.41 3.59-8 8-8s8 3.59 8 8c0 1.82-.62 3.49-1.64 4.83zM12 6c-1.94 0-3.5 1.56-3.5 3.5S10.06 13 12 13s3.5-1.56 3.5-3.5S13.94 6 12 6zm0 5c-.83 0-1.5-.67-1.5-1.5S11.17 8 12 8s1.5.67 1.5 1.5S12.83 11 12 11z" }), 'AccountCircleOutlined'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/AccountCircleOutlined.js
JavaScript
mit
934
/* Ratings and how they work: -2: Extremely detrimental The sort of ability that relegates Pokemon with Uber-level BSTs into NU. ex. Slow Start, Truant -1: Detrimental An ability that does more harm than good. ex. Defeatist, Normalize 0: Useless An ability with no net effect on a Pokemon during a battle. ex. Pickup, Illuminate 1: Ineffective An ability that has a minimal effect. Should never be chosen over any other ability. ex. Damp, Shell Armor 2: Situationally useful An ability that can be useful in certain situations. ex. Blaze, Insomnia 3: Useful An ability that is generally useful. ex. Volt Absorb, Iron Fist 4: Very useful One of the most popular abilities. The difference between 3 and 4 can be ambiguous. ex. Technician, Protean 5: Essential The sort of ability that defines metagames. ex. Drizzle, Shadow Tag */ exports.BattleAbilities = { "adaptability": { desc: "This Pokemon's attacks that receive STAB (Same Type Attack Bonus) are increased from 50% to 100%.", shortDesc: "This Pokemon's same-type attack bonus (STAB) is increased from 1.5x to 2x.", onModifyMove: function (move) { move.stab = 2; }, id: "adaptability", name: "Adaptability", rating: 3.5, num: 91 }, "aftermath": { desc: "If a contact move knocks out this Pokemon, the opponent receives damage equal to one-fourth of its max HP.", shortDesc: "If this Pokemon is KOed with a contact move, that move's user loses 1/4 its max HP.", id: "aftermath", name: "Aftermath", onAfterDamageOrder: 1, onAfterDamage: function (damage, target, source, move) { if (source && source !== target && move && move.isContact && !target.hp) { this.damage(source.maxhp / 4, source, target, null, true); } }, rating: 3, num: 106 }, "aerilate": { desc: "Turns all of this Pokemon's Normal-typed attacks into Flying-type and deal 1.3x damage. Does not affect Hidden Power.", shortDesc: "This Pokemon's Normal moves become Flying-type and do 1.3x damage.", onModifyMove: function (move, pokemon) { if (move.type === 'Normal' && move.id !== 'hiddenpower') { move.type = 'Flying'; if (move.category !== 'Status') pokemon.addVolatile('aerilate'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower, pokemon, target, move) { return this.chainModify([0x14CD, 0x1000]); } }, id: "aerilate", name: "Aerilate", rating: 3, num: 185 }, "airlock": { desc: "While this Pokemon is active, all weather conditions and their effects are disabled.", shortDesc: "While this Pokemon is active, all weather conditions and their effects are disabled.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Air Lock'); }, onAnyModifyPokemon: function (pokemon) { pokemon.ignore['WeatherTarget'] = true; }, onAnyTryWeather: false, id: "airlock", name: "Air Lock", rating: 3, num: 76 }, "analytic": { desc: "This Pokemon's attacks do 1.3x damage if it is the last to move in a turn.", shortDesc: "If the user moves last, the power of that move is increased by 30%.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (!this.willMove(defender)) { this.debug('Analytic boost'); return this.chainModify([0x14CD, 0x1000]); // The Analytic modifier is slightly higher than the normal 1.3 (0x14CC) } }, id: "analytic", name: "Analytic", rating: 1, num: 148 }, "angerpoint": { desc: "If this Pokemon, and not its Substitute, is struck by a Critical Hit, its Attack is boosted to six stages.", shortDesc: "If this Pokemon is hit by a critical hit, its Attack is boosted by 12.", onCriticalHit: function (target) { if (!target.volatiles['substitute']) { target.setBoost({atk: 6}); this.add('-setboost', target, 'atk', 12, '[from] ability: Anger Point'); } }, id: "angerpoint", name: "Anger Point", rating: 2, num: 83 }, "anticipation": { desc: "A warning is displayed if an opposing Pokemon has the moves Fissure, Guillotine, Horn Drill, Sheer Cold, or any attacking move from a type that is considered super effective against this Pokemon (including Counter, Mirror Coat, and Metal Burst). Hidden Power, Judgment, Natural Gift and Weather Ball are considered Normal-type moves. Flying Press is considered a Fighting-type move.", shortDesc: "On switch-in, this Pokemon shudders if any foe has a super effective or OHKO move.", onStart: function (pokemon) { var targets = pokemon.side.foe.active; for (var i = 0; i < targets.length; i++) { if (!targets[i] || targets[i].fainted) continue; for (var j = 0; j < targets[i].moveset.length; j++) { var move = this.getMove(targets[i].moveset[j].move); if (move.category !== 'Status' && (this.getImmunity(move.type, pokemon) && this.getEffectiveness(move.type, pokemon) > 0 || move.ohko)) { this.add('-activate', pokemon, 'ability: Anticipation'); return; } } } }, id: "anticipation", name: "Anticipation", rating: 1, num: 107 }, "arenatrap": { desc: "When this Pokemon enters the field, its opponents cannot switch or flee the battle unless they are part Flying-type, have the Levitate ability, are holding Shed Shell, or they use the moves Baton Pass or U-Turn. Flying-type and Levitate Pokemon cannot escape if they are holding Iron Ball or Gravity is in effect. Levitate Pokemon also cannot escape if their ability is disabled through other means, such as Skill Swap or Gastro Acid.", shortDesc: "Prevents foes from switching out normally unless they have immunity to Ground.", onFoeModifyPokemon: function (pokemon) { if (!this.isAdjacent(pokemon, this.effectData.target)) return; if (!pokemon.runImmunity('Ground', false)) return; if (!pokemon.hasType('Flying') || pokemon.hasType('ironball') || this.getPseudoWeather('gravity') || pokemon.volatiles['ingrain']) { pokemon.tryTrap(true); } }, onFoeMaybeTrapPokemon: function (pokemon, source) { if (!source) source = this.effectData.target; if (!this.isAdjacent(pokemon, source)) return; if (!pokemon.runImmunity('Ground', false)) return; if (!pokemon.hasType('Flying') || pokemon.hasType('ironball') || this.getPseudoWeather('gravity') || pokemon.volatiles['ingrain']) { pokemon.maybeTrapped = true; } }, id: "arenatrap", name: "Arena Trap", rating: 5, num: 71 }, "aromaveil": { desc: "Protects this Pokemon and its allies from Attract, Disable, Encore, Heal Block, Taunt, and Torment.", shortDesc: "Protects from Attract, Disable, Encore, Heal Block, Taunt, and Torment.", onAllyTryHit: function (target, source, move) { if (move && move.id in {attract:1, disable:1, encore:1, healblock:1, taunt:1, torment:1}) { return false; } }, id: "aromaveil", name: "Aroma Veil", rating: 3, num: 165 }, "aurabreak": { desc: "Reverses the effect of Dark Aura and Fairy Aura.", shortDesc: "Reverses the effect of Aura abilities.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Aura Break'); }, onAnyTryPrimaryHit: function (target, source, move) { if (target === source || move.category === 'Status') return; source.addVolatile('aurabreak'); }, effect: { duration: 1 }, id: "aurabreak", name: "Aura Break", rating: 2, num: 188 }, "baddreams": { desc: "If asleep, each of this Pokemon's opponents receives damage equal to one-eighth of its max HP.", shortDesc: "Causes sleeping adjacent foes to lose 1/8 of their max HP at the end of each turn.", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { if (!pokemon.hp) return; for (var i = 0; i < pokemon.side.foe.active.length; i++) { var target = pokemon.side.foe.active[i]; if (!target || !target.hp) continue; if (target.status === 'slp') { this.damage(target.maxhp / 8, target); } } }, id: "baddreams", name: "Bad Dreams", rating: 2, num: 123 }, "battlearmor": { desc: "This Pokemon cannot be struck by a critical hit.", shortDesc: "Critical Hits cannot strike this Pokemon.", onCriticalHit: false, id: "battlearmor", name: "Battle Armor", rating: 1, num: 4 }, "bigpecks": { desc: "Prevents other Pokemon from lowering this Pokemon's Defense.", shortDesc: "Prevents the Pokemon's Defense stat from being reduced.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; if (boost['def'] && boost['def'] < 0) { boost['def'] = 0; if (!effect.secondaries) this.add("-fail", target, "unboost", "Defense", "[from] ability: Big Pecks", "[of] " + target); } }, id: "bigpecks", name: "Big Pecks", rating: 1, num: 145 }, "blaze": { desc: "When its health reaches one-third or less of its max HP, this Pokemon's Fire-type attacks receive a 50% boost in power.", shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Fire attacks do 1.5x damage.", onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Fire' && attacker.hp <= attacker.maxhp / 3) { this.debug('Blaze boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Fire' && attacker.hp <= attacker.maxhp / 3) { this.debug('Blaze boost'); return this.chainModify(1.5); } }, id: "blaze", name: "Blaze", rating: 2, num: 66 }, "bulletproof": { desc: "This Pokemon is protected from some Ball and Bomb moves.", shortDesc: "This Pokemon is protected from ball and bomb moves.", onTryHit: function (pokemon, target, move) { if (move.flags && move.flags['bullet']) { this.add('-immune', pokemon, '[msg]', '[from] Bulletproof'); return null; } }, id: "bulletproof", name: "Bulletproof", rating: 3, num: 171 }, "cheekpouch": { desc: "Restores HP when this Pokemon consumes a berry.", shortDesc: "Restores HP when this Pokemon consumes a berry.", onEatItem: function (item, pokemon) { this.heal(pokemon.maxhp / 3); }, id: "cheekpouch", name: "Cheek Pouch", rating: 2, num: 167 }, "chlorophyll": { desc: "If this Pokemon is active while Sunny Day is in effect, its speed is temporarily doubled.", shortDesc: "If Sunny Day is active, this Pokemon's Speed is doubled.", onModifySpe: function (speMod) { if (this.isWeather(['sunnyday', 'desolateland'])) { return this.chain(speMod, 2); } }, id: "chlorophyll", name: "Chlorophyll", rating: 2, num: 34 }, "clearbody": { desc: "Opponents cannot reduce this Pokemon's stats; they can, however, modify stat changes with Power Swap, Guard Swap and Heart Swap and inflict stat boosts with Swagger and Flatter. This ability does not prevent self-inflicted stat reductions.", shortDesc: "Prevents other Pokemon from lowering this Pokemon's stat stages.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; var showMsg = false; for (var i in boost) { if (boost[i] < 0) { delete boost[i]; showMsg = true; } } if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: Clear Body", "[of] " + target); }, id: "clearbody", name: "Clear Body", rating: 2, num: 29 }, "cloudnine": { desc: "While this Pokemon is active, all weather conditions and their effects are disabled.", shortDesc: "While this Pokemon is active, all weather conditions and their effects are disabled.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Cloud Nine'); }, onAnyModifyPokemon: function (pokemon) { pokemon.ignore['WeatherTarget'] = true; }, onAnyTryWeather: false, id: "cloudnine", name: "Cloud Nine", rating: 3, num: 13 }, "colorchange": { desc: "This Pokemon's type changes according to the type of the last move that hit this Pokemon.", shortDesc: "This Pokemon's type changes to match the type of the last move that hit it.", onAfterMoveSecondary: function (target, source, move) { if (target.isActive && move && move.effectType === 'Move' && move.category !== 'Status') { if (!target.hasType(move.type)) { if (!target.setType(move.type)) return false; this.add('-start', target, 'typechange', move.type, '[from] Color Change'); target.update(); } } }, id: "colorchange", name: "Color Change", rating: 2, num: 16 }, "competitive": { desc: "Raises the user's Special Attack stat by two stages when a stat is lowered, including the Special Attack stat. This does not include self-induced stat drops like those from Close Combat.", shortDesc: "This Pokemon's SpAtk is boosted by 2 for each of its stats that is lowered by a foe.", onAfterEachBoost: function (boost, target, source) { if (!source || target.side === source.side) { return; } var statsLowered = false; for (var i in boost) { if (boost[i] < 0) { statsLowered = true; } } if (statsLowered) { this.boost({spa: 2}); } }, id: "competitive", name: "Competitive", rating: 2, num: 172 }, "compoundeyes": { desc: "The accuracy of this Pokemon's moves receives a 30% increase; for example, a 75% accurate move becomes 97.5% accurate.", shortDesc: "This Pokemon's moves have their accuracy boosted to 1.3x.", onSourceAccuracy: function (accuracy) { if (typeof accuracy !== 'number') return; this.debug('compoundeyes - enhancing accuracy'); return accuracy * 1.3; }, id: "compoundeyes", name: "Compound Eyes", rating: 3.5, num: 14 }, "contrary": { desc: "If this Pokemon has a stat boosted it is lowered instead, and vice versa.", shortDesc: "Stat changes are inverted.", onBoost: function (boost) { for (var i in boost) { boost[i] *= -1; } }, id: "contrary", name: "Contrary", rating: 4, num: 126 }, "cursedbody": { desc: "30% chance of disabling one of the opponent's moves when attacked. This works even if the attacker is behind a Substitute, but will not activate if the Pokemon with Cursed Body is behind a Substitute.", shortDesc: "If this Pokemon is hit by an attack, there is a 30% chance that move gets Disabled.", onAfterDamage: function (damage, target, source, move) { if (!source || source.volatiles['disable']) return; if (source !== target && move && move.effectType === 'Move') { if (this.random(10) < 3) { source.addVolatile('disable'); } } }, id: "cursedbody", name: "Cursed Body", rating: 2, num: 130 }, "cutecharm": { desc: "If an opponent of the opposite gender directly attacks this Pokemon, there is a 30% chance that the opponent will become Attracted to this Pokemon.", shortDesc: "30% chance of infatuating Pokemon of the opposite gender if they make contact.", onAfterDamage: function (damage, target, source, move) { if (move && move.isContact) { if (this.random(10) < 3) { source.addVolatile('attract', target); } } }, id: "cutecharm", name: "Cute Charm", rating: 1, num: 56 }, "damp": { desc: "While this Pokemon is active, no Pokemon on the field can use Selfdestruct or Explosion.", shortDesc: "While this Pokemon is active, Selfdestruct, Explosion, and Aftermath do not work.", id: "damp", onAnyTryMove: function (target, source, effect) { if (effect.id === 'selfdestruct' || effect.id === 'explosion') { this.attrLastMove('[still]'); this.add('-activate', this.effectData.target, 'ability: Damp'); return false; } }, onAnyDamage: function (damage, target, source, effect) { if (effect && effect.id === 'aftermath') { return false; } }, name: "Damp", rating: 0.5, num: 6 }, "darkaura": { desc: "Increases the power of all Dark-type moves in battle to 1.33x.", shortDesc: "Increases the power of all Dark-type moves in battle to 1.33x.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Dark Aura'); }, onAnyTryPrimaryHit: function (target, source, move) { if (target === source || move.category === 'Status') return; if (move.type === 'Dark') { source.addVolatile('aura'); } }, id: "darkaura", name: "Dark Aura", rating: 3, num: 186 }, "defeatist": { desc: "When this Pokemon has 1/2 or less of its max HP, its Attack and Sp. Atk are halved.", shortDesc: "Attack and Special Attack are halved when HP is less than half.", onModifyAtkPriority: 5, onModifyAtk: function (atk, pokemon) { if (pokemon.hp < pokemon.maxhp / 2) { return this.chainModify(0.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, pokemon) { if (pokemon.hp < pokemon.maxhp / 2) { return this.chainModify(0.5); } }, onResidual: function (pokemon) { pokemon.update(); }, id: "defeatist", name: "Defeatist", rating: -1, num: 129 }, "defiant": { desc: "Raises the user's Attack stat by two stages when a stat is lowered, including the Attack stat. This does not include self-induced stat drops like those from Close Combat.", shortDesc: "This Pokemon's Attack is boosted by 2 for each of its stats that is lowered by a foe.", onAfterEachBoost: function (boost, target, source) { if (!source || target.side === source.side) { return; } var statsLowered = false; for (var i in boost) { if (boost[i] < 0) { statsLowered = true; } } if (statsLowered) { this.boost({atk: 2}); } }, id: "defiant", name: "Defiant", rating: 2, num: 128 }, "deltastream": { desc: "When this Pokemon enters the battlefield, the weather becomes strong winds for as long as this Pokemon remains on the battlefield with Delta Stream.", shortDesc: "The weather becomes strong winds until this Pokemon leaves battle.", onStart: function (source) { this.setWeather('deltastream'); }, onEnd: function (pokemon) { if (this.weatherData.source !== pokemon) return; for (var i = 0; i < this.sides.length; i++) { for (var j = 0; j < this.sides[i].active.length; j++) { var target = this.sides[i].active[j]; if (target === pokemon) continue; if (target && target.hp && target.ability === 'deltastream' && target.ignore['Ability'] !== true) { this.weatherData.source = target; return; } } } this.clearWeather(); }, id: "deltastream", name: "Delta Stream", rating: 5, num: 191 }, "desolateland": { desc: "When this Pokemon enters the battlefield, the weather becomes harsh sun for as long as this Pokemon remains on the battlefield with Desolate Land.", shortDesc: "The weather becomes harsh sun until this Pokemon leaves battle.", onStart: function (source) { this.setWeather('desolateland'); }, onEnd: function (pokemon) { if (this.weatherData.source !== pokemon) return; for (var i = 0; i < this.sides.length; i++) { for (var j = 0; j < this.sides[i].active.length; j++) { var target = this.sides[i].active[j]; if (target === pokemon) continue; if (target && target.hp && target.ability === 'desolateland' && target.ignore['Ability'] !== true) { this.weatherData.source = target; return; } } } this.clearWeather(); }, id: "desolateland", name: "Desolate Land", rating: 5, num: 190 }, "download": { desc: "If this Pokemon switches into an opponent with equal Defenses or higher Defense than Special Defense, this Pokemon's Special Attack receives a 50% boost. If this Pokemon switches into an opponent with higher Special Defense than Defense, this Pokemon's Attack receive a 50% boost.", shortDesc: "On switch-in, Attack or Sp. Atk is boosted by 1 based on the foes' weaker Defense.", onStart: function (pokemon) { var foeactive = pokemon.side.foe.active; var totaldef = 0; var totalspd = 0; for (var i = 0; i < foeactive.length; i++) { if (!foeactive[i] || foeactive[i].fainted) continue; totaldef += foeactive[i].getStat('def', false, true); totalspd += foeactive[i].getStat('spd', false, true); } if (totaldef && totaldef >= totalspd) { this.boost({spa:1}); } else if (totalspd) { this.boost({atk:1}); } }, id: "download", name: "Download", rating: 4, num: 88 }, "drizzle": { desc: "When this Pokemon enters the battlefield, the weather becomes Rain Dance (for 5 turns normally, or 8 turns while holding Damp Rock).", shortDesc: "On switch-in, the weather becomes Rain Dance.", onStart: function (source) { if (this.isWeather(['desolateland', 'primordialsea', 'deltastream'])) { this.add('-ability', source, 'Drizzle', '[from] ' + this.effectiveWeather(), '[fail]'); return null; } this.setWeather('raindance'); }, id: "drizzle", name: "Drizzle", rating: 5, num: 2 }, "drought": { desc: "When this Pokemon enters the battlefield, the weather becomes Sunny Day (for 5 turns normally, or 8 turns while holding Heat Rock).", shortDesc: "On switch-in, the weather becomes Sunny Day.", onStart: function (source) { if (this.isWeather(['desolateland', 'primordialsea', 'deltastream'])) { this.add('-ability', source, 'Drought', '[from] ' + this.effectiveWeather(), '[fail]'); return null; } this.setWeather('sunnyday'); }, id: "drought", name: "Drought", rating: 5, num: 70 }, "dryskin": { desc: "This Pokemon absorbs Water attacks and gains a weakness to Fire attacks. If Sunny Day is in effect, this Pokemon takes damage. If Rain Dance is in effect, this Pokemon recovers health.", shortDesc: "This Pokemon is healed 1/4 by Water, 1/8 by Rain; is hurt 1.25x by Fire, 1/8 by Sun.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Water') { if (!this.heal(target.maxhp / 4)) { this.add('-immune', target, '[msg]'); } return null; } }, onBasePowerPriority: 7, onFoeBasePower: function (basePower, attacker, defender, move) { if (this.effectData.target !== defender) return; if (move.type === 'Fire') { return this.chainModify(1.25); } }, onWeather: function (target, source, effect) { if (effect.id === 'raindance' || effect.id === 'primordialsea') { this.heal(target.maxhp / 8); } else if (effect.id === 'sunnyday' || effect.id === 'desolateland') { this.damage(target.maxhp / 8); } }, id: "dryskin", name: "Dry Skin", rating: 3.5, num: 87 }, "earlybird": { desc: "This Pokemon will remain asleep for half as long as it normally would; this includes both opponent-induced sleep and user-induced sleep via Rest.", shortDesc: "This Pokemon's sleep status lasts half as long as usual, self-induced or not.", id: "earlybird", name: "Early Bird", isHalfSleep: true, rating: 2.5, num: 48 }, "effectspore": { desc: "If an opponent directly attacks this Pokemon, there is a 30% chance that the opponent will become either poisoned, paralyzed or put to sleep. There is an equal chance to inflict each status.", shortDesc: "30% chance of poisoning, paralyzing, or causing sleep on Pokemon making contact.", onAfterDamage: function (damage, target, source, move) { if (move && move.isContact && !source.status && source.runImmunity('powder')) { var r = this.random(100); if (r < 11) { source.setStatus('slp', target); } else if (r < 21) { source.setStatus('par', target); } else if (r < 30) { source.setStatus('psn', target); } } }, id: "effectspore", name: "Effect Spore", rating: 2, num: 27 }, "fairyaura": { desc: "Increases the power of all Fairy-type moves in battle to 1.33x.", shortDesc: "Increases the power of all Fairy-type moves in battle to 1.33x.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Fairy Aura'); }, onAnyTryPrimaryHit: function (target, source, move) { if (target === source || move.category === 'Status') return; if (move.type === 'Fairy') { source.addVolatile('aura'); } }, id: "fairyaura", name: "Fairy Aura", rating: 3, num: 187 }, "filter": { desc: "This Pokemon receives one-fourth reduced damage from Super Effective attacks.", shortDesc: "This Pokemon receives 3/4 damage from super effective attacks.", onSourceModifyDamage: function (damage, source, target, move) { if (target.runEffectiveness(move) > 0) { this.debug('Filter neutralize'); return this.chainModify(0.75); } }, id: "filter", name: "Filter", rating: 3, num: 111 }, "flamebody": { desc: "If an opponent directly attacks this Pokemon, there is a 30% chance that the opponent will become burned.", shortDesc: "30% chance of burning a Pokemon making contact with this Pokemon.", onAfterDamage: function (damage, target, source, move) { if (move && move.isContact) { if (this.random(10) < 3) { source.trySetStatus('brn', target, move); } } }, id: "flamebody", name: "Flame Body", rating: 2, num: 49 }, "flareboost": { desc: "When the user with this ability is burned, its Special Attack is raised by 50%.", shortDesc: "When this Pokemon is burned, its special attacks do 1.5x damage.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (attacker.status === 'brn' && move.category === 'Special') { return this.chainModify(1.5); } }, id: "flareboost", name: "Flare Boost", rating: 3, num: 138 }, "flashfire": { desc: "This Pokemon is immune to all Fire-type attacks; additionally, its own Fire-type attacks receive a 50% boost if a Fire-type move hits this Pokemon. Multiple boosts do not occur if this Pokemon is hit with multiple Fire-type attacks.", shortDesc: "This Pokemon's Fire attacks do 1.5x damage if hit by one Fire move; Fire immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Fire') { move.accuracy = true; if (!target.addVolatile('flashfire')) { this.add('-immune', target, '[msg]'); } return null; } }, effect: { noCopy: true, // doesn't get copied by Baton Pass onStart: function (target) { this.add('-start', target, 'ability: Flash Fire'); }, onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Fire') { this.debug('Flash Fire boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Fire') { this.debug('Flash Fire boost'); return this.chainModify(1.5); } } }, id: "flashfire", name: "Flash Fire", rating: 3, num: 18 }, "flowergift": { desc: "If this Pokemon is active while Sunny Day is in effect, its Attack and Special Defense stats (as well as its partner's stats in double battles) receive a 50% boost.", shortDesc: "If user is Cherrim and Sunny Day is active, it and allies' Attack and Sp. Def are 1.5x.", onStart: function (pokemon) { delete this.effectData.forme; }, onUpdate: function (pokemon) { if (!pokemon.isActive || pokemon.speciesid !== 'cherrim') return; if (this.isWeather(['sunnyday', 'desolateland'])) { if (this.effectData.forme !== 'Sunshine') { this.effectData.forme = 'Sunshine'; this.add('-formechange', pokemon, 'Cherrim-Sunshine', '[msg]'); } } else { if (this.effectData.forme) { delete this.effectData.forme; this.add('-formechange', pokemon, 'Cherrim', '[msg]'); } } }, onModifyAtkPriority: 3, onAllyModifyAtk: function (atk) { if (this.effectData.target.template.speciesid !== 'cherrim') return; if (this.isWeather(['sunnyday', 'desolateland'])) { return this.chainModify(1.5); } }, onModifySpDPriority: 4, onAllyModifySpD: function (spd) { if (this.effectData.target.template.speciesid !== 'cherrim') return; if (this.isWeather(['sunnyday', 'desolateland'])) { return this.chainModify(1.5); } }, id: "flowergift", name: "Flower Gift", rating: 3, num: 122 }, "flowerveil": { desc: "Prevents ally Grass-type Pokemon from being statused or having their stats lowered.", shortDesc: "Prevents lowering of ally Grass-type Pokemon's stats.", onAllyBoost: function (boost, target, source, effect) { if ((source && target === source) || !target.hasType('Grass')) return; var showMsg = false; for (var i in boost) { if (boost[i] < 0) { delete boost[i]; showMsg = true; } } if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: Flower Veil", "[of] " + target); }, onAllySetStatus: function (status, target) { if (target.hasType('Grass')) return false; }, id: "flowerveil", name: "Flower Veil", rating: 0, num: 166 }, "forecast": { desc: "This Pokemon's type changes according to the current weather conditions: it becomes Fire-type during Sunny Day, Water-type during Rain Dance, Ice-type during Hail and remains its regular type otherwise.", shortDesc: "Castform's type changes to the current weather condition's type, except Sandstorm.", onUpdate: function (pokemon) { if (pokemon.baseTemplate.species !== 'Castform' || pokemon.transformed) return; var forme = null; switch (this.effectiveWeather()) { case 'sunnyday': case 'desolateland': if (pokemon.template.speciesid !== 'castformsunny') forme = 'Castform-Sunny'; break; case 'raindance': case 'primordialsea': if (pokemon.template.speciesid !== 'castformrainy') forme = 'Castform-Rainy'; break; case 'hail': if (pokemon.template.speciesid !== 'castformsnowy') forme = 'Castform-Snowy'; break; default: if (pokemon.template.speciesid !== 'castform') forme = 'Castform'; break; } if (pokemon.isActive && forme) { pokemon.formeChange(forme); this.add('-formechange', pokemon, forme, '[msg]'); } }, id: "forecast", name: "Forecast", rating: 4, num: 59 }, "forewarn": { desc: "On switch-in, this Pokemon is alerted to the foes' move with the highest Base Power.", shortDesc: "The move with the highest Base Power in the opponent's moveset is revealed.", onStart: function (pokemon) { var targets = pokemon.side.foe.active; var warnMoves = []; var warnBp = 1; for (var i = 0; i < targets.length; i++) { if (targets[i].fainted) continue; for (var j = 0; j < targets[i].moveset.length; j++) { var move = this.getMove(targets[i].moveset[j].move); var bp = move.basePower; if (move.ohko) bp = 160; if (move.id === 'counter' || move.id === 'metalburst' || move.id === 'mirrorcoat') bp = 120; if (!bp && move.category !== 'Status') bp = 80; if (bp > warnBp) { warnMoves = [[move, targets[i]]]; warnBp = bp; } else if (bp === warnBp) { warnMoves.push([move, targets[i]]); } } } if (!warnMoves.length) return; var warnMove = warnMoves[this.random(warnMoves.length)]; this.add('-activate', pokemon, 'ability: Forewarn', warnMove[0], warnMove[1]); }, id: "forewarn", name: "Forewarn", rating: 1, num: 108 }, "friendguard": { desc: "Reduces the damage received from an ally in a double or triple battle.", shortDesc: "This Pokemon's allies receive 3/4 damage from other Pokemon's attacks.", id: "friendguard", name: "Friend Guard", onAnyModifyDamage: function (damage, source, target, move) { if (target !== this.effectData.target && target.side === this.effectData.target.side) { this.debug('Friend Guard weaken'); return this.chainModify(0.75); } }, rating: 0, num: 132 }, "frisk": { desc: "When this Pokemon enters the field, it identifies all the opponent's held items.", shortDesc: "On switch-in, this Pokemon identifies the foe's held items.", onStart: function (pokemon) { var foeactive = pokemon.side.foe.active; for (var i = 0; i < foeactive.length; i++) { if (!foeactive[i] || foeactive[i].fainted) continue; if (foeactive[i].item) { this.add('-item', foeactive[i], foeactive[i].getItem().name, '[from] ability: Frisk', '[of] ' + pokemon, '[identify]'); } } }, id: "frisk", name: "Frisk", rating: 1.5, num: 119 }, "furcoat": { desc: "This Pokemon's Defense is doubled.", shortDesc: "This Pokemon's Defense is doubled.", onModifyDefPriority: 6, onModifyDef: function (def) { return this.chainModify(2); }, id: "furcoat", name: "Fur Coat", rating: 3.5, num: 169 }, "galewings": { desc: "This Pokemon's Flying-type moves have their priority increased by 1.", shortDesc: "Gives priority to Flying-type moves.", onModifyPriority: function (priority, pokemon, target, move) { if (move && move.type === 'Flying') return priority + 1; }, id: "galewings", name: "Gale Wings", rating: 4.5, num: 177 }, "gluttony": { desc: "This Pokemon consumes its held berry when its health reaches 50% max HP or lower.", shortDesc: "When this Pokemon has 1/2 or less of its max HP, it uses certain Berries early.", id: "gluttony", name: "Gluttony", rating: 1.5, num: 82 }, "gooey": { desc: "Contact with this Pokemon lowers the attacker's Speed stat by 1.", shortDesc: "Contact with this Pokemon lowers the attacker's Speed.", onAfterDamage: function (damage, target, source, effect) { if (effect && effect.isContact) this.boost({spe: -1}, source, target); }, id: "gooey", name: "Gooey", rating: 3, num: 183 }, "grasspelt": { desc: "This Pokemon's Defense is boosted in Grassy Terrain.", shortDesc: "This Pokemon's Defense is boosted in Grassy Terrain.", onModifyDefPriority: 6, onModifyDef: function (pokemon) { if (this.isTerrain('grassyterrain')) return this.chainModify(1.5); }, id: "grasspelt", name: "Grass Pelt", rating: 2, num: 179 }, "guts": { desc: "When this Pokemon is poisoned (including Toxic), burned, paralyzed or asleep (including self-induced Rest), its Attack stat receives a 50% boost; the burn status' Attack drop is also ignored.", shortDesc: "If this Pokemon is statused, its Attack is 1.5x; burn's Attack drop is ignored.", onModifyAtkPriority: 5, onModifyAtk: function (atk, pokemon) { if (pokemon.status) { return this.chainModify(1.5); } }, id: "guts", name: "Guts", rating: 3, num: 62 }, "harvest": { desc: "When the user uses a held Berry, it has a 50% chance of having it restored at the end of the turn. This chance becomes 100% during Sunny Day.", shortDesc: "50% chance this Pokemon's Berry is restored at the end of each turn. 100% in Sun.", id: "harvest", name: "Harvest", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { if (this.isWeather(['sunnyday', 'desolateland']) || this.random(2) === 0) { if (pokemon.hp && !pokemon.item && this.getItem(pokemon.lastItem).isBerry) { pokemon.setItem(pokemon.lastItem); this.add('-item', pokemon, pokemon.getItem(), '[from] ability: Harvest'); } } }, rating: 2, num: 139 }, "healer": { desc: "Has a 30% chance of curing an adjacent ally's status ailment at the end of each turn in Double and Triple Battles.", shortDesc: "30% chance of curing an adjacent ally's status at the end of each turn.", id: "healer", name: "Healer", onResidualOrder: 5, onResidualSubOrder: 1, onResidual: function (pokemon) { var allyActive = pokemon.side.active; if (allyActive.length === 1) { return; } for (var i = 0; i < allyActive.length; i++) { if (allyActive[i] && this.isAdjacent(pokemon, allyActive[i]) && allyActive[i].status && this.random(10) < 3) { allyActive[i].cureStatus(); } } }, rating: 0, num: 131 }, "heatproof": { desc: "This Pokemon receives half damage from both Fire-type attacks and residual burn damage.", shortDesc: "This Pokemon receives half damage from Fire-type attacks and burn damage.", onBasePowerPriority: 7, onSourceBasePower: function (basePower, attacker, defender, move) { if (move.type === 'Fire') { return this.chainModify(0.5); } }, onDamage: function (damage, target, source, effect) { if (effect && effect.id === 'brn') { return damage / 2; } }, id: "heatproof", name: "Heatproof", rating: 2.5, num: 85 }, "heavymetal": { desc: "The user's weight is doubled. This increases user's base power of Heavy Slam and Heat Crash, as well as damage taken from the opponent's Low Kick and Grass Knot, due to these moves being calculated by the target's weight.", shortDesc: "This Pokemon's weight is doubled.", onModifyPokemon: function (pokemon) { pokemon.weightkg *= 2; }, id: "heavymetal", name: "Heavy Metal", rating: -1, num: 134 }, "honeygather": { desc: "If it is not already holding an item, this Pokemon may find and be holding Honey after a battle.", shortDesc: "No competitive use.", id: "honeygather", name: "Honey Gather", rating: 0, num: 118 }, "hugepower": { desc: "This Pokemon's Attack stat is doubled. Therefore, if this Pokemon's Attack stat on the status screen is 200, it effectively has an Attack stat of 400; which is then subject to the full range of stat boosts and reductions.", shortDesc: "This Pokemon's Attack is doubled.", onModifyAtkPriority: 5, onModifyAtk: function (atk) { return this.chainModify(2); }, id: "hugepower", name: "Huge Power", rating: 5, num: 37 }, "hustle": { desc: "This Pokemon's Attack receives a 50% boost but its Physical attacks receive a 20% drop in Accuracy. For example, a 100% accurate move would become an 80% accurate move. The accuracy of moves that never miss, such as Aerial Ace, remains unaffected.", shortDesc: "This Pokemon's Attack is 1.5x and accuracy of its physical attacks is 0.8x.", // This should be applied directly to the stat as opposed to chaining witht he others onModifyAtkPriority: 5, onModifyAtk: function (atk) { return this.modify(atk, 1.5); }, onModifyMove: function (move) { if (move.category === 'Physical' && typeof move.accuracy === 'number') { move.accuracy *= 0.8; } }, id: "hustle", name: "Hustle", rating: 3, num: 55 }, "hydration": { desc: "If this Pokemon is active while Rain Dance is in effect, it recovers from poison, paralysis, burn, sleep and freeze at the end of the turn.", shortDesc: "This Pokemon has its status cured at the end of each turn if Rain Dance is active.", onResidualOrder: 5, onResidualSubOrder: 1, onResidual: function (pokemon) { if (pokemon.status && this.isWeather(['raindance', 'primordialsea'])) { this.debug('hydration'); pokemon.cureStatus(); } }, id: "hydration", name: "Hydration", rating: 2, num: 93 }, "hypercutter": { desc: "Opponents cannot reduce this Pokemon's Attack stat; they can, however, modify stat changes with Power Swap or Heart Swap and inflict a stat boost with Swagger. This ability does not prevent self-inflicted stat reductions.", shortDesc: "Prevents other Pokemon from lowering this Pokemon's Attack.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; if (boost['atk'] && boost['atk'] < 0) { boost['atk'] = 0; if (!effect.secondaries) this.add("-fail", target, "unboost", "Attack", "[from] ability: Hyper Cutter", "[of] " + target); } }, id: "hypercutter", name: "Hyper Cutter", rating: 1.5, num: 52 }, "icebody": { desc: "If active while Hail is in effect, this Pokemon recovers one-sixteenth of its max HP after each turn. If a non-Ice-type Pokemon receives this ability through Skill Swap, Role Play or the Trace ability, it will not take damage from Hail.", shortDesc: "If Hail is active, this Pokemon heals 1/16 of its max HP each turn; immunity to Hail.", onWeather: function (target, source, effect) { if (effect.id === 'hail') { this.heal(target.maxhp / 16); } }, onImmunity: function (type, pokemon) { if (type === 'hail') return false; }, id: "icebody", name: "Ice Body", rating: 3, num: 115 }, "illuminate": { desc: "When this Pokemon is in the first slot of the player's party, it doubles the rate of wild encounters.", shortDesc: "No competitive use.", id: "illuminate", name: "Illuminate", rating: 0, num: 35 }, "illusion": { desc: "Illusion will change the appearance of the Pokemon to a different species. This is dependent on the last Pokemon in the player's party. Along with the species itself, Illusion is broken when the user is damaged, but is not broken by Substitute, weather conditions, status ailments, or entry hazards. Illusion will replicate the type of Poke Ball, the species name, and the gender of the Pokemon it is masquerading as.", shortDesc: "This Pokemon appears as the last Pokemon in the party until it takes direct damage.", onBeforeSwitchIn: function (pokemon) { pokemon.illusion = null; var i; for (i = pokemon.side.pokemon.length - 1; i > pokemon.position; i--) { if (!pokemon.side.pokemon[i]) continue; if (!pokemon.side.pokemon[i].fainted) break; } if (!pokemon.side.pokemon[i]) return; if (pokemon === pokemon.side.pokemon[i]) return; pokemon.illusion = pokemon.side.pokemon[i]; }, // illusion clearing is hardcoded in the damage function id: "illusion", name: "Illusion", rating: 4.5, num: 149 }, "immunity": { desc: "This Pokemon cannot be poisoned. Gaining this Ability while poisoned cures it.", shortDesc: "This Pokemon cannot become poisoned nor Toxic poisoned.", onUpdate: function (pokemon) { if (pokemon.status === 'psn' || pokemon.status === 'tox') { pokemon.cureStatus(); } }, onImmunity: function (type) { if (type === 'psn') return false; }, id: "immunity", name: "Immunity", rating: 1, num: 17 }, "imposter": { desc: "As soon as the user comes into battle, it Transforms into its opponent, copying the opponent's stats exactly, with the exception of HP. Imposter copies all stat changes on the target originating from moves and abilities such as Swords Dance and Intimidate, but not from items such as Choice Specs. Imposter will not Transform the user if the opponent is an Illusion or if the opponent is behind a Substitute.", shortDesc: "On switch-in, this Pokemon copies the foe it's facing; stats, moves, types, Ability.", onStart: function (pokemon) { var target = pokemon.side.foe.active[pokemon.side.foe.active.length - 1 - pokemon.position]; if (target) { pokemon.transformInto(target, pokemon); } }, id: "imposter", name: "Imposter", rating: 5, num: 150 }, "infiltrator": { desc: "This Pokemon's moves ignore the target's Light Screen, Mist, Reflect, Safeguard, and Substitute.", shortDesc: "Ignores Light Screen, Mist, Reflect, Safeguard, and Substitute.", onModifyMove: function (move) { move.notSubBlocked = true; move.ignoreScreens = true; }, id: "infiltrator", name: "Infiltrator", rating: 2.5, num: 151 }, "innerfocus": { desc: "This Pokemon cannot be made to flinch.", shortDesc: "This Pokemon cannot be made to flinch.", onFlinch: false, id: "innerfocus", name: "Inner Focus", rating: 1, num: 39 }, "insomnia": { desc: "This Pokemon cannot be put to sleep; this includes both opponent-induced sleep as well as user-induced sleep via Rest.", shortDesc: "This Pokemon cannot fall asleep. Gaining this Ability while asleep cures it.", onUpdate: function (pokemon) { if (pokemon.status === 'slp') { pokemon.cureStatus(); } }, onImmunity: function (type, pokemon) { if (type === 'slp') return false; }, id: "insomnia", name: "Insomnia", rating: 2, num: 15 }, "intimidate": { desc: "When this Pokemon enters the field, the Attack stat of each of its opponents lowers by one stage.", shortDesc: "On switch-in, this Pokemon lowers adjacent foes' Attack by 1.", onStart: function (pokemon) { var foeactive = pokemon.side.foe.active; for (var i = 0; i < foeactive.length; i++) { if (!foeactive[i] || !this.isAdjacent(foeactive[i], pokemon)) continue; if (foeactive[i].volatiles['substitute']) { // does it give a message? this.add('-activate', foeactive[i], 'Substitute', 'ability: Intimidate', '[of] ' + pokemon); } else { this.add('-ability', pokemon, 'Intimidate', '[of] ' + foeactive[i]); this.boost({atk: -1}, foeactive[i], pokemon); } } }, id: "intimidate", name: "Intimidate", rating: 3.5, num: 22 }, "ironbarbs": { desc: "All moves that make contact with the Pokemon with Iron Barbs will damage the user by 1/8 of their maximum HP after damage is dealt.", shortDesc: "This Pokemon causes other Pokemon making contact to lose 1/8 of their max HP.", onAfterDamageOrder: 1, onAfterDamage: function (damage, target, source, move) { if (source && source !== target && move && move.isContact) { this.damage(source.maxhp / 8, source, target, null, true); } }, id: "ironbarbs", name: "Iron Barbs", rating: 3, num: 160 }, "ironfist": { desc: "This Pokemon receives a 20% power boost for the following attacks: Bullet Punch, Comet Punch, Dizzy Punch, Drain Punch, Dynamicpunch, Fire Punch, Focus Punch, Hammer Arm, Ice Punch, Mach Punch, Mega Punch, Meteor Mash, Shadow Punch, Sky Uppercut, and Thunderpunch. Sucker Punch, which is known Ambush in Japan, is not boosted.", shortDesc: "This Pokemon's punch-based attacks do 1.2x damage. Sucker Punch is not boosted.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.isPunchAttack) { this.debug('Iron Fist boost'); return this.chainModify(1.2); } }, id: "ironfist", name: "Iron Fist", rating: 3, num: 89 }, "justified": { desc: "Will raise the user's Attack stat one level when hit by any Dark-type moves. Unlike other abilities with immunity to certain typed moves, the user will still receive damage from the attack. Justified will raise Attack one level for each hit of a multi-hit move like Beat Up.", shortDesc: "This Pokemon's Attack is boosted by 1 after it is damaged by a Dark-type attack.", onAfterDamage: function (damage, target, source, effect) { if (effect && effect.type === 'Dark') { this.boost({atk:1}); } }, id: "justified", name: "Justified", rating: 2, num: 154 }, "keeneye": { desc: "Prevents other Pokemon from lowering this Pokemon's accuracy.", shortDesc: "This Pokemon's Accuracy cannot be lowered.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; if (boost['accuracy'] && boost['accuracy'] < 0) { boost['accuracy'] = 0; if (!effect.secondaries) this.add("-fail", target, "unboost", "accuracy", "[from] ability: Keen Eye", "[of] " + target); } }, onModifyMove: function (move) { move.ignoreEvasion = true; }, id: "keeneye", name: "Keen Eye", rating: 1, num: 51 }, "klutz": { desc: "This Pokemon ignores both the positive and negative effects of its held item, other than the speed-halving and EV-enhancing effects of Macho Brace, Power Anklet, Power Band, Power Belt, Power Bracer, Power Lens, and Power Weight. Fling cannot be used.", shortDesc: "This Pokemon's held item has no effect, except Macho Brace. Fling cannot be used.", onModifyPokemonPriority: 1, onModifyPokemon: function (pokemon) { if (pokemon.getItem().megaEvolves) return; pokemon.ignore['Item'] = true; }, id: "klutz", name: "Klutz", rating: 0, num: 103 }, "leafguard": { desc: "If this Pokemon is active while Sunny Day is in effect, it cannot become poisoned, burned, paralyzed or put to sleep (other than user-induced Rest). Leaf Guard does not heal status effects that existed before Sunny Day came into effect.", shortDesc: "If Sunny Day is active, this Pokemon cannot be statused and Rest will fail for it.", onSetStatus: function (pokemon) { if (this.isWeather(['sunnyday', 'desolateland'])) { return false; } }, onTryHit: function (target, source, move) { if (move && move.id === 'yawn' && this.isWeather(['sunnyday', 'desolateland'])) { return false; } }, id: "leafguard", name: "Leaf Guard", rating: 1, num: 102 }, "levitate": { desc: "This Pokemon is immune to Ground-type attacks, Spikes, Toxic Spikes and the Arena Trap ability; it loses these immunities while holding Iron Ball, after using Ingrain or if Gravity is in effect.", shortDesc: "This Pokemon is immune to Ground; Gravity, Ingrain, Smack Down, Iron Ball nullify it.", onImmunity: function (type) { if (type === 'Ground') return false; }, id: "levitate", name: "Levitate", rating: 3.5, num: 26 }, "lightmetal": { desc: "The user's weight is halved. This decreases the damage taken from Low Kick and Grass Knot, and also lowers user's base power of Heavy Slam and Heat Crash, due these moves being calculated by the target and user's weight.", shortDesc: "This Pokemon's weight is halved.", onModifyPokemon: function (pokemon) { pokemon.weightkg /= 2; }, id: "lightmetal", name: "Light Metal", rating: 1, num: 135 }, "lightningrod": { desc: "During double battles, this Pokemon draws any single-target Electric-type attack to itself. If an opponent uses an Electric-type attack that affects multiple Pokemon, those targets will be hit. This ability does not affect Electric Hidden Power or Judgment. The user is immune to Electric and its Special Attack is increased one stage when hit by one.", shortDesc: "This Pokemon draws Electric moves to itself to boost Sp. Atk by 1; Electric immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Electric') { if (!this.boost({spa:1})) { this.add('-immune', target, '[msg]'); } return null; } }, onAnyRedirectTargetPriority: 1, onAnyRedirectTarget: function (target, source, source2, move) { if (move.type !== 'Electric') return; if (this.validTarget(this.effectData.target, source, move.target)) { return this.effectData.target; } }, id: "lightningrod", name: "Lightning Rod", rating: 3.5, num: 32 }, "limber": { desc: "This Pokemon cannot be paralyzed. Gaining this Ability while paralyzed cures it.", shortDesc: "This Pokemon cannot become paralyzed.", onUpdate: function (pokemon) { if (pokemon.status === 'par') { pokemon.cureStatus(); } }, onImmunity: function (type, pokemon) { if (type === 'par') return false; }, id: "limber", name: "Limber", rating: 2, num: 7 }, "liquidooze": { desc: "When another Pokemon uses Absorb, Drain Punch, Dream Eater, Giga Drain, Leech Life, Leech Seed or Mega Drain against this Pokemon, the attacking Pokemon loses the amount of health that it would have gained.", shortDesc: "This Pokemon damages those draining HP from it for as much as they would heal.", id: "liquidooze", onSourceTryHeal: function (damage, target, source, effect) { this.debug("Heal is occurring: " + target + " <- " + source + " :: " + effect.id); var canOoze = {drain: 1, leechseed: 1}; if (canOoze[effect.id]) { this.damage(damage, null, null, null, true); return 0; } }, name: "Liquid Ooze", rating: 1, num: 64 }, "magicbounce": { desc: "This Pokemon blocks certain status moves and uses the move itself.", shortDesc: "Non-damaging moves are reflected back at the user.", id: "magicbounce", name: "Magic Bounce", onTryHitPriority: 1, onTryHit: function (target, source, move) { if (target === source) return; if (move.hasBounced) return; if (typeof move.isBounceable === 'undefined') { move.isBounceable = !!(move.category === 'Status' && (move.status || move.boosts || move.volatileStatus === 'confusion' || move.forceSwitch)); } if (move.isBounceable) { var newMove = this.getMoveCopy(move.id); newMove.hasBounced = true; this.useMove(newMove, target, source); return null; } }, onAllyTryHitSide: function (target, source, move) { if (target.side === source.side) return; if (move.hasBounced) return; if (typeof move.isBounceable === 'undefined') { move.isBounceable = !!(move.category === 'Status' && (move.status || move.boosts || move.volatileStatus === 'confusion' || move.forceSwitch)); } if (move.isBounceable) { var newMove = this.getMoveCopy(move.id); newMove.hasBounced = true; this.useMove(newMove, target, source); return null; } }, effect: { duration: 1 }, rating: 5, num: 156 }, "magicguard": { desc: "This Pokemon can only be damaged by direct attacks.", shortDesc: "Prevents all damage except from direct attacks.", onDamage: function (damage, target, source, effect) { if (effect.effectType !== 'Move') { return false; } }, id: "magicguard", name: "Magic Guard", rating: 4.5, num: 98 }, "magician": { desc: "If this Pokemon is not holding an item, it steals the held item of a target it hits with a move.", shortDesc: "This Pokemon steals the held item of a target it hits with a move.", onSourceHit: function (target, source, move) { if (!move || !target) return; if (target !== source && move.category !== 'Status') { if (source.item) return; var yourItem = target.takeItem(source); if (!yourItem) return; if (!source.setItem(yourItem)) { target.item = yourItem.id; // bypass setItem so we don't break choicelock or anything return; } this.add('-item', source, yourItem, '[from] ability: Magician', '[of] ' + target); } }, id: "magician", name: "Magician", rating: 2, num: 170 }, "magmaarmor": { desc: "This Pokemon cannot be frozen. Gaining this Ability while frozen cures it.", shortDesc: "This Pokemon cannot become frozen.", onUpdate: function (pokemon) { if (pokemon.status === 'frz') { pokemon.cureStatus(); } }, onImmunity: function (type, pokemon) { if (type === 'frz') return false; }, id: "magmaarmor", name: "Magma Armor", rating: 0.5, num: 40 }, "magnetpull": { desc: "When this Pokemon enters the field, Steel-type opponents cannot switch out nor flee the battle unless they are holding Shed Shell or use attacks like U-Turn or Baton Pass.", shortDesc: "Prevents Steel-type foes from switching out normally.", onFoeModifyPokemon: function (pokemon) { if (pokemon.hasType('Steel') && this.isAdjacent(pokemon, this.effectData.target)) { pokemon.tryTrap(true); } }, onFoeMaybeTrapPokemon: function (pokemon, source) { if (!source) source = this.effectData.target; if (pokemon.hasType('Steel') && this.isAdjacent(pokemon, source)) { pokemon.maybeTrapped = true; } }, id: "magnetpull", name: "Magnet Pull", rating: 4.5, num: 42 }, "marvelscale": { desc: "When this Pokemon becomes burned, poisoned (including Toxic), paralyzed, frozen or put to sleep (including self-induced sleep via Rest), its Defense receives a 50% boost.", shortDesc: "If this Pokemon is statused, its Defense is 1.5x.", onModifyDefPriority: 6, onModifyDef: function (def, pokemon) { if (pokemon.status) { return this.chainModify(1.5); } }, id: "marvelscale", name: "Marvel Scale", rating: 3, num: 63 }, "megalauncher": { desc: "Boosts the power of Aura and Pulse moves, such as Aura Sphere and Dark Pulse, by 50%.", shortDesc: "Boosts the power of Aura/Pulse moves by 50%.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.flags && move.flags['pulse']) { return this.chainModify(1.5); } }, id: "megalauncher", name: "Mega Launcher", rating: 3, num: 178 }, "minus": { desc: "This Pokemon's Special Attack receives a 50% boost in double battles if a partner has the Plus or Minus ability.", shortDesc: "If an ally has the Ability Plus or Minus, this Pokemon's Sp. Atk is 1.5x.", onModifySpAPriority: 5, onModifySpA: function (spa, pokemon) { var allyActive = pokemon.side.active; if (allyActive.length === 1) { return; } for (var i = 0; i < allyActive.length; i++) { if (allyActive[i] && allyActive[i].position !== pokemon.position && !allyActive[i].fainted && allyActive[i].hasAbility(['minus', 'plus'])) { return this.chainModify(1.5); } } }, id: "minus", name: "Minus", rating: 0, num: 58 }, "moldbreaker": { desc: "When this Pokemon uses any move, it nullifies the Ability of any active Pokemon that hinder or empower this Pokemon's attacks. These abilities include Battle Armor, Clear Body, Damp, Dry Skin, Filter, Flash Fire, Flower Gift, Heatproof, Herbivore, Hyper Cutter, Immunity, Inner Focus, Insomnia, Keen Eye, Leaf Guard, Levitate, Lightningrod, Limber, Magma Armor, Marvel Scale, Motor Drive, Oblivious, Own Tempo, Sand Veil, Shell Armor, Shield Dust, Simple, Snow Cloak, Solid Rock, Soundproof, Sticky Hold, Storm Drain, Sturdy, Suction Cups, Tangled Feet, Thick Fat, Unaware, Vital Spirit, Volt Absorb, Water Absorb, Water Veil, White Smoke and Wonder Guard.", shortDesc: "This Pokemon's moves ignore any Ability that could modify the effectiveness.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Mold Breaker'); }, onAllyModifyPokemonPriority: 100, onAllyModifyPokemon: function (pokemon) { if (this.activePokemon === this.effectData.target && pokemon !== this.activePokemon) { pokemon.ignore['Ability'] = 'A'; } }, onFoeModifyPokemonPriority: 100, onFoeModifyPokemon: function (pokemon) { if (this.activePokemon === this.effectData.target) { pokemon.ignore['Ability'] = 'A'; } }, id: "moldbreaker", name: "Mold Breaker", rating: 3, num: 104 }, "moody": { desc: "At the end of each turn, the Pokemon raises a random stat that isn't already +6 by two stages, and lowers a random stat that isn't already -6 by one stage. These stats include accuracy and evasion.", shortDesc: "Boosts a random stat by 2 and lowers another stat by 1 at the end of each turn.", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { var stats = [], i = ''; var boost = {}; for (var i in pokemon.boosts) { if (pokemon.boosts[i] < 6) { stats.push(i); } } if (stats.length) { i = stats[this.random(stats.length)]; boost[i] = 2; } stats = []; for (var j in pokemon.boosts) { if (pokemon.boosts[j] > -6 && j !== i) { stats.push(j); } } if (stats.length) { i = stats[this.random(stats.length)]; boost[i] = -1; } this.boost(boost); }, id: "moody", name: "Moody", rating: 5, num: 141 }, "motordrive": { desc: "This Pokemon is immune to all Electric-type moves (including Status moves). If hit by an Electric-type attack, its Speed increases by one stage.", shortDesc: "This Pokemon's Speed is boosted by 1 if hit by an Electric move; Electric immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Electric') { if (!this.boost({spe:1})) { this.add('-immune', target, '[msg]'); } return null; } }, id: "motordrive", name: "Motor Drive", rating: 3, num: 78 }, "moxie": { desc: "If this Pokemon knocks out another Pokemon with a damaging attack, its Attack is raised by one stage.", shortDesc: "This Pokemon's Attack is boosted by 1 if it attacks and faints another Pokemon.", onSourceFaint: function (target, source, effect) { if (effect && effect.effectType === 'Move') { this.boost({atk:1}, source); } }, id: "moxie", name: "Moxie", rating: 4, num: 153 }, "multiscale": { desc: "If this Pokemon is at full HP, it takes half damage from attacks.", shortDesc: "If this Pokemon is at full HP, it takes half damage from attacks.", onSourceModifyDamage: function (damage, source, target, move) { if (target.hp >= target.maxhp) { this.debug('Multiscale weaken'); return this.chainModify(0.5); } }, id: "multiscale", name: "Multiscale", rating: 4, num: 136 }, "multitype": { desc: "If this Pokemon is Arceus, its type and sprite change to match its held Plate. Either way, this Pokemon is holding a Plate, the Plate cannot be taken (such as by Trick or Thief). This ability cannot be Skill Swapped, Role Played or Traced.", shortDesc: "If this Pokemon is Arceus, its type changes to match its held Plate.", // Multitype's type-changing itself is implemented in statuses.js id: "multitype", name: "Multitype", rating: 4, num: 121 }, "mummy": { desc: "When the user is attacked by a contact move, the opposing Pokemon's ability is turned into Mummy as well. Multitype, Wonder Guard and Mummy itself are the only abilities not affected by Mummy. The effect of Mummy is not removed by Mold Breaker, Turboblaze, or Teravolt.", shortDesc: "Pokemon making contact with this Pokemon have their Ability changed to Mummy.", id: "mummy", name: "Mummy", onAfterDamage: function (damage, target, source, move) { if (source && source !== target && move && move.isContact) { var oldAbility = source.setAbility('mummy', source, 'mummy', true); if (oldAbility) { this.add('-endability', source, oldAbility, '[from] Mummy'); this.add('-ability', source, 'Mummy', '[from] Mummy'); this.runEvent('EndAbility', source, oldAbility, 'mummy'); } } }, rating: 1, num: 152 }, "naturalcure": { desc: "When this Pokemon switches out of battle, it is cured of poison (including Toxic), paralysis, burn, freeze and sleep (including self-induced Rest).", shortDesc: "This Pokemon has its status cured when it switches out.", onSwitchOut: function (pokemon) { pokemon.setStatus(''); }, id: "naturalcure", name: "Natural Cure", rating: 4, num: 30 }, "noguard": { desc: "Every attack used by or against this Pokemon will always hit, even during evasive two-turn moves such as Fly and Dig.", shortDesc: "Every move used by or against this Pokemon will always hit.", onAnyAccuracy: function (accuracy, target, source, move) { if (move && (source === this.effectData.target || target === this.effectData.target)) { return true; } return accuracy; }, id: "noguard", name: "No Guard", rating: 4, num: 99 }, "normalize": { desc: "Makes all of this Pokemon's attacks Normal-typed.", shortDesc: "This Pokemon's moves all become Normal-typed.", onModifyMove: function (move) { if (move.id !== 'struggle') { move.type = 'Normal'; } }, id: "normalize", name: "Normalize", rating: -1, num: 96 }, "oblivious": { desc: "This Pokemon cannot be infatuated (by Attract or Cute Charm) or taunted. Gaining this Ability while afflicted by either condition cures it.", shortDesc: "This Pokemon cannot be infatuated or taunted. Gaining this Ability cures it.", onUpdate: function (pokemon) { if (pokemon.volatiles['attract']) { pokemon.removeVolatile('attract'); this.add('-end', pokemon, 'move: Attract'); } if (pokemon.volatiles['taunt']) { pokemon.removeVolatile('taunt'); // Taunt's volatile already sends the -end message when removed } }, onImmunity: function (type, pokemon) { if (type === 'attract') { this.add('-immune', pokemon, '[from] Oblivious'); return false; } }, onTryHit: function (pokemon, target, move) { if (move.id === 'captivate' || move.id === 'taunt') { this.add('-immune', pokemon, '[msg]', '[from] Oblivious'); return null; } }, id: "oblivious", name: "Oblivious", rating: 0.5, num: 12 }, "overcoat": { desc: "In battle, the Pokemon does not take damage from weather conditions like Sandstorm or Hail. It is also immune to powder moves.", shortDesc: "This Pokemon is immune to residual weather damage, and powder moves.", onImmunity: function (type, pokemon) { if (type === 'sandstorm' || type === 'hail' || type === 'powder') return false; }, id: "overcoat", name: "Overcoat", rating: 2, num: 142 }, "overgrow": { desc: "When its health reaches one-third or less of its max HP, this Pokemon's Grass-type attacks receive a 50% boost in power.", shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Grass attacks do 1.5x damage.", onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Grass' && attacker.hp <= attacker.maxhp / 3) { this.debug('Overgrow boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Grass' && attacker.hp <= attacker.maxhp / 3) { this.debug('Overgrow boost'); return this.chainModify(1.5); } }, id: "overgrow", name: "Overgrow", rating: 2, num: 65 }, "owntempo": { desc: "This Pokemon cannot be confused. Gaining this Ability while confused cures it.", shortDesc: "This Pokemon cannot be confused. Gaining this Ability while confused cures it.", onUpdate: function (pokemon) { if (pokemon.volatiles['confusion']) { pokemon.removeVolatile('confusion'); } }, onImmunity: function (type, pokemon) { if (type === 'confusion') { this.add('-immune', pokemon, 'confusion'); return false; } }, id: "owntempo", name: "Own Tempo", rating: 1, num: 20 }, "parentalbond": { desc: "Allows the Pokemon to hit twice with the same move in one turn. Second hit has 0.5x base power. Does not affect Status, multihit, or spread moves (in doubles).", shortDesc: "Hits twice in one turn. Second hit has 0.5x base power.", onModifyMove: function (move, pokemon, target) { if (move.category !== 'Status' && !move.selfdestruct && !move.multihit && ((target.side && target.side.active.length < 2) || move.target in {any:1, normal:1, randomNormal:1})) { move.multihit = 2; pokemon.addVolatile('parentalbond'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower) { if (this.effectData.hit) { return this.chainModify(0.5); } else { this.effectData.hit = true; } } }, id: "parentalbond", name: "Parental Bond", rating: 4.5, num: 184 }, "pickup": { desc: "If an opponent uses a consumable item, Pickup will give the Pokemon the item used, if it is not holding an item. If multiple Pickup Pokemon are in play, one will pick up a copy of the used Berry, and may or may not use it immediately. Works on Berries, Gems, Absorb Bulb, Focus Sash, Herbs, Cell Battery, Red Card, and anything that is thrown with Fling.", shortDesc: "If this Pokemon has no item, it finds one used by an adjacent Pokemon this turn.", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { var foe = pokemon.side.foe.randomActive(); if (!foe) return; if (!pokemon.item && foe.lastItem && foe.usedItemThisTurn && foe.lastItem !== 'airballoon' && foe.lastItem !== 'ejectbutton') { pokemon.setItem(foe.lastItem); foe.lastItem = ''; var item = pokemon.getItem(); this.add('-item', pokemon, item, '[from] Pickup'); if (item.isBerry) pokemon.update(); } }, id: "pickup", name: "Pickup", rating: 0, num: 53 }, "pickpocket": { desc: "If this Pokemon has no item, it steals an item off an attacking Pokemon making contact.", shortDesc: "If this Pokemon has no item, it steals an item off a Pokemon making contact.", onAfterDamage: function (damage, target, source, move) { if (source && source !== target && move && move.isContact) { if (target.item) { return; } var yourItem = source.takeItem(target); if (!yourItem) { return; } if (!target.setItem(yourItem)) { source.item = yourItem.id; return; } this.add('-item', target, yourItem, '[from] ability: Pickpocket'); } }, id: "pickpocket", name: "Pickpocket", rating: 1, num: 124 }, "pixilate": { desc: "Turns all of this Pokemon's Normal-typed attacks into Fairy-type and deal 1.3x damage. Does not affect Hidden Power.", shortDesc: "This Pokemon's Normal moves become Fairy-type and do 1.3x damage.", onModifyMove: function (move, pokemon) { if (move.type === 'Normal' && move.id !== 'hiddenpower') { move.type = 'Fairy'; if (move.category !== 'Status') pokemon.addVolatile('pixilate'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower, pokemon, target, move) { return this.chainModify([0x14CD, 0x1000]); } }, id: "pixilate", name: "Pixilate", rating: 3, num: 182 }, "plus": { desc: "This Pokemon's Special Attack receives a 50% boost in double battles if a partner has the Plus or Minus ability.", shortDesc: "If an ally has the Ability Plus or Minus, this Pokemon's Sp. Atk is 1.5x.", onModifySpAPriority: 5, onModifySpA: function (spa, pokemon) { var allyActive = pokemon.side.active; if (allyActive.length === 1) { return; } for (var i = 0; i < allyActive.length; i++) { if (allyActive[i] && allyActive[i].position !== pokemon.position && !allyActive[i].fainted && allyActive[i].hasAbility(['minus', 'plus'])) { return this.chainModify(1.5); } } }, id: "plus", name: "Plus", rating: 0, num: 57 }, "poisonheal": { desc: "If this Pokemon becomes poisoned (including Toxic), it will recover 1/8 of its max HP after each turn.", shortDesc: "This Pokemon is healed by 1/8 of its max HP each turn when poisoned; no HP loss.", onDamage: function (damage, target, source, effect) { if (effect.id === 'psn' || effect.id === 'tox') { this.heal(target.maxhp / 8); return false; } }, id: "poisonheal", name: "Poison Heal", rating: 4, num: 90 }, "poisonpoint": { desc: "If an opponent contact attacks this Pokemon, there is a 30% chance that the opponent will become poisoned.", shortDesc: "30% chance of poisoning a Pokemon making contact with this Pokemon.", onAfterDamage: function (damage, target, source, move) { if (move && move.isContact) { if (this.random(10) < 3) { source.trySetStatus('psn', target, move); } } }, id: "poisonpoint", name: "Poison Point", rating: 2, num: 38 }, "poisontouch": { desc: "This Pokemon's contact attacks have a 30% chance of poisoning the target.", shortDesc: "This Pokemon's contact moves have a 30% chance of poisoning.", // upokecenter says this is implemented as an added secondary effect onModifyMove: function (move) { if (!move || !move.isContact) return; if (!move.secondaries) { move.secondaries = []; } move.secondaries.push({ chance: 30, status: 'psn' }); }, id: "poisontouch", name: "Poison Touch", rating: 2, num: 143 }, "prankster": { desc: "This Pokemon's Status moves have their priority increased by 1 stage.", shortDesc: "This Pokemon's Status moves have their priority increased by 1.", onModifyPriority: function (priority, pokemon, target, move) { if (move && move.category === 'Status') { return priority + 1; } }, id: "prankster", name: "Prankster", rating: 4.5, num: 158 }, "pressure": { desc: "If this Pokemon is the target of a foe's move, that move loses one additional PP.", shortDesc: "If this Pokemon is the target of a foe's move, that move loses one additional PP.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Pressure'); }, onSourceDeductPP: function (pp, target, source) { if (target.side === source.side) return; return pp + 1; }, id: "pressure", name: "Pressure", rating: 1.5, num: 46 }, "primordialsea": { desc: "When this Pokemon enters the battlefield, the weather becomes heavy rain for as long as this Pokemon remains on the battlefield with Primordial Sea.", shortDesc: "The weather becomes heavy rain until this Pokemon leaves battle.", onStart: function (source) { this.setWeather('primordialsea'); }, onEnd: function (pokemon) { if (this.weatherData.source !== pokemon) return; for (var i = 0; i < this.sides.length; i++) { for (var j = 0; j < this.sides[i].active.length; j++) { var target = this.sides[i].active[j]; if (target === pokemon) continue; if (target && target.hp && target.ability === 'primordialsea' && target.ignore['Ability'] !== true) { this.weatherData.source = target; return; } } } this.clearWeather(); }, id: "primordialsea", name: "Primordial Sea", rating: 5, num: 189 }, "protean": { desc: "Right before this Pokemon uses a move, it changes its type to match that move. Hidden Power is interpreted as its Hidden Power type, rather than Normal.", shortDesc: "Right before this Pokemon uses a move, it changes its type to match that move.", onPrepareHit: function (source, target, move) { var type = move.type; if (type && type !== '???' && source.getTypes().join() !== type) { if (!source.setType(type)) return; this.add('-start', source, 'typechange', type, '[from] Protean'); } }, id: "protean", name: "Protean", rating: 4, num: 168 }, "purepower": { desc: "This Pokemon's Attack stat is doubled. Note that this is the Attack stat itself, not the base Attack stat of its species.", shortDesc: "This Pokemon's Attack is doubled.", onModifyAtkPriority: 5, onModifyAtk: function (atk) { return this.chainModify(2); }, id: "purepower", name: "Pure Power", rating: 5, num: 74 }, "quickfeet": { desc: "When this Pokemon is poisoned (including Toxic), burned, paralyzed, asleep (including self-induced Rest) or frozen, its Speed stat receives a 50% boost; the paralysis status' Speed drop is also ignored.", shortDesc: "If this Pokemon is statused, its Speed is 1.5x; paralysis' Speed drop is ignored.", onModifySpe: function (speMod, pokemon) { if (pokemon.status) { return this.chain(speMod, 1.5); } }, id: "quickfeet", name: "Quick Feet", rating: 3, num: 95 }, "raindish": { desc: "If the weather is Rain Dance, this Pokemon recovers 1/16 of its max HP after each turn.", shortDesc: "If the weather is Rain Dance, this Pokemon heals 1/16 of its max HP each turn.", onWeather: function (target, source, effect) { if (effect.id === 'raindance' || effect.id === 'primordialsea') { this.heal(target.maxhp / 16); } }, id: "raindish", name: "Rain Dish", rating: 1.5, num: 44 }, "rattled": { desc: "Raises the user's Speed one stage when hit by a Dark-, Bug-, or Ghost-type move.", shortDesc: "This Pokemon gets +1 Speed if hit by a Dark-, Bug-, or Ghost-type attack.", onAfterDamage: function (damage, target, source, effect) { if (effect && (effect.type === 'Dark' || effect.type === 'Bug' || effect.type === 'Ghost')) { this.boost({spe:1}); } }, id: "rattled", name: "Rattled", rating: 2, num: 155 }, "reckless": { desc: "When this Pokemon uses an attack that causes recoil damage, or an attack that has a chance to cause recoil damage such as Jump Kick and High Jump Kick, the attacks's power receives a 20% boost.", shortDesc: "This Pokemon's attacks with recoil or crash damage do 1.2x damage; not Struggle.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.recoil || move.hasCustomRecoil) { this.debug('Reckless boost'); return this.chainModify(1.2); } }, id: "reckless", name: "Reckless", rating: 3, num: 120 }, "refrigerate": { desc: "Turns all of this Pokemon's Normal-typed attacks into Ice-typed and deal 1.3x damage. Does not affect Hidden Power.", shortDesc: "This Pokemon's Normal moves become Ice-type and do 1.3x damage.", onModifyMove: function (move, pokemon) { if (move.type === 'Normal' && move.id !== 'hiddenpower') { move.type = 'Ice'; if (move.category !== 'Status') pokemon.addVolatile('refrigerate'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower, pokemon, target, move) { return this.chainModify([0x14CD, 0x1000]); } }, id: "refrigerate", name: "Refrigerate", rating: 3, num: 174 }, "regenerator": { desc: "This Pokemon heals 1/3 of its max HP when it switches out.", shortDesc: "This Pokemon heals 1/3 of its max HP when it switches out.", onSwitchOut: function (pokemon) { pokemon.heal(pokemon.maxhp / 3); }, id: "regenerator", name: "Regenerator", rating: 4, num: 144 }, "rivalry": { desc: "This Pokemon's attacks do 1.25x damage if their target is the same gender, but 0.75x if their target is the opposite gender.", shortDesc: "This Pokemon's attacks do 1.25x on same gender targets; 0.75x on opposite gender.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (attacker.gender && defender.gender) { if (attacker.gender === defender.gender) { this.debug('Rivalry boost'); return this.chainModify(1.25); } else { this.debug('Rivalry weaken'); return this.chainModify(0.75); } } }, id: "rivalry", name: "Rivalry", rating: 0.5, num: 79 }, "rockhead": { desc: "This Pokemon does not receive recoil damage except from Struggle, Life Orb, or crash damage from Jump Kick or High Jump Kick.", shortDesc: "This Pokemon does not take recoil damage besides Struggle, Life Orb, crash damage.", onModifyMove: function (move) { delete move.recoil; }, id: "rockhead", name: "Rock Head", rating: 3, num: 69 }, "roughskin": { desc: "Causes recoil damage equal to 1/8 of the opponent's max HP if an opponent makes contact.", shortDesc: "This Pokemon causes other Pokemon making contact to lose 1/8 of their max HP.", onAfterDamageOrder: 1, onAfterDamage: function (damage, target, source, move) { if (source && source !== target && move && move.isContact) { this.damage(source.maxhp / 8, source, target, null, true); } }, id: "roughskin", name: "Rough Skin", rating: 3, num: 24 }, "runaway": { desc: "Unless this Pokemon is under the effects of a trapping move or ability, such as Mean Look or Shadow Tag, it will escape from wild Pokemon battles without fail.", shortDesc: "No competitive use.", id: "runaway", name: "Run Away", rating: 0, num: 50 }, "sandforce": { desc: "Raises the power of this Pokemon's Rock, Ground, and Steel-type moves by 1.3x if the weather is Sandstorm. This Pokemon is also immune to residual Sandstorm damage.", shortDesc: "This Pokemon's Rock/Ground/Steel attacks do 1.3x in Sandstorm; immunity to it.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (this.isWeather('sandstorm')) { if (move.type === 'Rock' || move.type === 'Ground' || move.type === 'Steel') { this.debug('Sand Force boost'); return this.chainModify([0x14CD, 0x1000]); // The Sand Force modifier is slightly higher than the normal 1.3 (0x14CC) } } }, onImmunity: function (type, pokemon) { if (type === 'sandstorm') return false; }, id: "sandforce", name: "Sand Force", rating: 2, num: 159 }, "sandrush": { desc: "This Pokemon's Speed is doubled if the weather is Sandstorm. This Pokemon is also immune to residual Sandstorm damage.", shortDesc: "If Sandstorm is active, this Pokemon's Speed is doubled; immunity to Sandstorm.", onModifySpe: function (speMod, pokemon) { if (this.isWeather('sandstorm')) { return this.chain(speMod, 2); } }, onImmunity: function (type, pokemon) { if (type === 'sandstorm') return false; }, id: "sandrush", name: "Sand Rush", rating: 2, num: 146 }, "sandstream": { desc: "When this Pokemon enters the battlefield, the weather becomes Sandstorm (for 5 turns normally, or 8 turns while holding Smooth Rock).", shortDesc: "On switch-in, the weather becomes Sandstorm.", onStart: function (source) { if (this.isWeather(['desolateland', 'primordialsea', 'deltastream'])) { this.add('-ability', source, 'Sand Stream', '[from] ' + this.effectiveWeather(), '[fail]'); return null; } this.setWeather('sandstorm'); }, id: "sandstream", name: "Sand Stream", rating: 4.5, num: 45 }, "sandveil": { desc: "This Pokemon's Evasion is boosted by 1.25x if the weather is Sandstorm. This Pokemon is also immune to residual Sandstorm damage.", shortDesc: "If Sandstorm is active, this Pokemon's evasion is 1.25x; immunity to Sandstorm.", onImmunity: function (type, pokemon) { if (type === 'sandstorm') return false; }, onAccuracy: function (accuracy) { if (typeof accuracy !== 'number') return; if (this.isWeather('sandstorm')) { this.debug('Sand Veil - decreasing accuracy'); return accuracy * 0.8; } }, id: "sandveil", name: "Sand Veil", rating: 1.5, num: 8 }, "sapsipper": { desc: "This Pokemon is immune to Grass moves. If hit by a Grass move, its Attack is increased by one stage (once for each hit of Bullet Seed). Does not affect Aromatherapy, but the move will still trigger an Attack increase.", shortDesc: "This Pokemon's Attack is boosted by 1 if hit by any Grass move; Grass immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Grass') { if (!this.boost({atk:1})) { this.add('-immune', target, '[msg]'); } return null; } }, onAllyTryHitSide: function (target, source, move) { if (target.side !== source.side) return; if (move.type === 'Grass') { this.boost({atk:1}, this.effectData.target); } }, id: "sapsipper", name: "Sap Sipper", rating: 3.5, num: 157 }, "scrappy": { desc: "This Pokemon has the ability to hit Ghost-type Pokemon with Normal-type and Fighting-type moves. Effectiveness of these moves takes into account the Ghost-type Pokemon's other weaknesses and resistances.", shortDesc: "This Pokemon can hit Ghost-types with Normal- and Fighting-type moves.", onModifyMovePriority: -5, onModifyMove: function (move) { if (move.type in {'Fighting':1, 'Normal':1}) { move.affectedByImmunities = false; } }, id: "scrappy", name: "Scrappy", rating: 3, num: 113 }, "serenegrace": { desc: "This Pokemon's moves have their secondary effect chance doubled. For example, if this Pokemon uses Ice Beam, it will have a 20% chance to freeze its target.", shortDesc: "This Pokemon's moves have their secondary effect chance doubled.", onModifyMove: function (move) { if (move.secondaries && move.id !== 'secretpower') { this.debug('doubling secondary chance'); for (var i = 0; i < move.secondaries.length; i++) { move.secondaries[i].chance *= 2; } } }, id: "serenegrace", name: "Serene Grace", rating: 4, num: 32 }, "shadowtag": { desc: "When this Pokemon enters the field, its non-Ghost-type opponents cannot switch or flee the battle unless they have the same ability, are holding Shed Shell, or they use the moves Baton Pass or U-Turn.", shortDesc: "Prevents foes from switching out normally unless they also have this Ability.", onFoeModifyPokemon: function (pokemon) { if (!pokemon.hasAbility('shadowtag') && this.isAdjacent(pokemon, this.effectData.target)) { pokemon.tryTrap(true); } }, onFoeMaybeTrapPokemon: function (pokemon, source) { if (!source) source = this.effectData.target; if (!pokemon.hasAbility('shadowtag') && this.isAdjacent(pokemon, source)) { pokemon.maybeTrapped = true; } }, id: "shadowtag", name: "Shadow Tag", rating: 5, num: 23 }, "shedskin": { desc: "At the end of each turn, this Pokemon has a 33% chance to heal itself from poison (including Toxic), paralysis, burn, freeze or sleep (including self-induced Rest).", shortDesc: "This Pokemon has a 33% chance to have its status cured at the end of each turn.", onResidualOrder: 5, onResidualSubOrder: 1, onResidual: function (pokemon) { if (pokemon.hp && pokemon.status && this.random(3) === 0) { this.debug('shed skin'); this.add('-activate', pokemon, 'ability: Shed Skin'); pokemon.cureStatus(); } }, id: "shedskin", name: "Shed Skin", rating: 4, num: 61 }, "sheerforce": { desc: "Raises the base power of all moves that have any secondary effects by 30%, but the secondary effects are ignored. Some side effects of moves, such as recoil, draining, stat reduction, and switching out usually aren't considered secondary effects. If a Pokemon with Sheer Force is holding a Life Orb and uses an attack that would be boosted by Sheer Force, then the move gains both boosts and the user receives no Life Orb recoil (only if the attack is boosted by Sheer Force).", shortDesc: "This Pokemon's attacks with secondary effects do 1.3x damage; nullifies the effects.", onModifyMove: function (move, pokemon) { if (move.secondaries) { delete move.secondaries; move.negateSecondary = true; pokemon.addVolatile('sheerforce'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower, pokemon, target, move) { return this.chainModify([0x14CD, 0x1000]); // The Sheer Force modifier is slightly higher than the normal 1.3 (0x14CC) } }, id: "sheerforce", name: "Sheer Force", rating: 4, num: 125 }, "shellarmor": { desc: "Attacks targeting this Pokemon can't be critical hits.", shortDesc: "This Pokemon cannot be struck by a critical hit.", onCriticalHit: false, id: "shellarmor", name: "Shell Armor", rating: 1, num: 75 }, "shielddust": { desc: "If the opponent uses a move that has secondary effects that affect this Pokemon in addition to damage, the move's secondary effects will not trigger (For example, Ice Beam loses its 10% freeze chance).", shortDesc: "This Pokemon is not affected by the secondary effect of another Pokemon's attack.", onTrySecondaryHit: function () { this.debug('Shield Dust prevent secondary'); return null; }, id: "shielddust", name: "Shield Dust", rating: 2, num: 19 }, "simple": { desc: "This Pokemon doubles all of its positive and negative stat modifiers. For example, if this Pokemon uses Curse, its Attack and Defense stats increase by two stages and its Speed stat decreases by two stages.", shortDesc: "This Pokemon has its own stat boosts and drops doubled as they happen.", onBoost: function (boost) { for (var i in boost) { boost[i] *= 2; } }, id: "simple", name: "Simple", rating: 4, num: 86 }, "skilllink": { desc: "When this Pokemon uses an attack that strikes multiple times in one turn, such as Fury Attack or Spike Cannon, such attacks will always strike for the maximum number of hits.", shortDesc: "This Pokemon's multi-hit attacks always hit the maximum number of times.", onModifyMove: function (move) { if (move.multihit && move.multihit.length) { move.multihit = move.multihit[1]; } }, id: "skilllink", name: "Skill Link", rating: 4, num: 92 }, "slowstart": { desc: "After this Pokemon switches into the battle, its Attack and Speed stats are halved for five turns. For example, if this Pokemon has an Attack stat of 400, its Attack will be 200 until the effects of Slow Start wear off.", shortDesc: "On switch-in, this Pokemon's Attack and Speed are halved for 5 turns.", onStart: function (pokemon) { pokemon.addVolatile('slowstart'); }, effect: { duration: 5, onStart: function (target) { this.add('-start', target, 'Slow Start'); }, onModifyAtkPriority: 5, onModifyAtk: function (atk, pokemon) { if (pokemon.ignore['Ability'] === true || pokemon.ability !== 'slowstart') { pokemon.removeVolatile('slowstart'); return; } return this.chainModify(0.5); }, onModifySpe: function (speMod, pokemon) { if (pokemon.ignore['Ability'] === true || pokemon.ability !== 'slowstart') { pokemon.removeVolatile('slowstart'); return; } return this.chain(speMod, 0.5); }, onEnd: function (target) { this.add('-end', target, 'Slow Start'); } }, id: "slowstart", name: "Slow Start", rating: -2, num: 112 }, "sniper": { desc: "When this Pokemon lands a Critical Hit, the damage is increased to another 1.5x.", shortDesc: "If this Pokemon strikes with a critical hit, the damage is increased by 50%.", onModifyDamage: function (damage, source, target, move) { if (move.crit) { this.debug('Sniper boost'); return this.chainModify(1.5); } }, id: "sniper", name: "Sniper", rating: 1, num: 97 }, "snowcloak": { desc: "This Pokemon's Evasion is boosted by 1.25x if the weather is Hail. This Pokemon is also immune to residual Hail damage.", shortDesc: "If Hail is active, this Pokemon's evasion is 1.25x; immunity to Hail.", onImmunity: function (type, pokemon) { if (type === 'hail') return false; }, onAccuracy: function (accuracy) { if (typeof accuracy !== 'number') return; if (this.isWeather('hail')) { this.debug('Snow Cloak - decreasing accuracy'); return accuracy * 0.8; } }, id: "snowcloak", name: "Snow Cloak", rating: 1, num: 81 }, "snowwarning": { desc: "When this Pokemon enters the battlefield, the weather becomes Hail (for 5 turns normally, or 8 turns while holding Icy Rock).", shortDesc: "On switch-in, the weather becomes Hail.", onStart: function (source) { if (this.isWeather(['desolateland', 'primordialsea', 'deltastream'])) { this.add('-ability', source, 'Snow Warning', '[from] ' + this.effectiveWeather(), '[fail]'); return null; } this.setWeather('hail'); }, id: "snowwarning", name: "Snow Warning", rating: 4, num: 117 }, "solarpower": { desc: "If the weather is Sunny Day, this Pokemon's Special Attack is 1.5x, but it loses 1/8 of its max HP at the end of every turn.", shortDesc: "If Sunny Day is active, this Pokemon's Sp. Atk is 1.5x and loses 1/8 max HP per turn.", onModifySpAPriority: 5, onModifySpA: function (spa, pokemon) { if (this.isWeather(['sunnyday', 'desolateland'])) { return this.chainModify(1.5); } }, onWeather: function (target, source, effect) { if (effect.id === 'sunnyday' || effect.id === 'desolateland') { this.damage(target.maxhp / 8); } }, id: "solarpower", name: "Solar Power", rating: 1.5, num: 94 }, "solidrock": { desc: "Super-effective attacks only deal 3/4 their usual damage against this Pokemon.", shortDesc: "This Pokemon receives 3/4 damage from super effective attacks.", onSourceModifyDamage: function (damage, source, target, move) { if (target.runEffectiveness(move) > 0) { this.debug('Solid Rock neutralize'); return this.chainModify(0.75); } }, id: "solidrock", name: "Solid Rock", rating: 3, num: 116 }, "soundproof": { desc: "This Pokemon is immune to the effects of sound-based moves, which are: Bug Buzz, Chatter, Echoed Voice, Grasswhistle, Growl, Heal Bell, Hyper Voice, Metal Sound, Perish Song, Relic Song, Roar, Round, Screech, Sing, Snarl, Snore, Supersonic, and Uproar. This ability doesn't affect Heal Bell.", shortDesc: "This Pokemon is immune to sound-based moves, except Heal Bell.", onTryHit: function (target, source, move) { if (target !== source && move.isSoundBased) { this.add('-immune', target, '[msg]'); return null; } }, id: "soundproof", name: "Soundproof", rating: 2, num: 43 }, "speedboost": { desc: "At the end of every turn, this Pokemon's Speed increases by one stage (except the turn it switched in).", shortDesc: "This Pokemon's Speed is boosted by 1 at the end of each full turn on the field.", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { if (pokemon.activeTurns) { this.boost({spe:1}); } }, id: "speedboost", name: "Speed Boost", rating: 4.5, num: 3 }, "stall": { desc: "This Pokemon moves last among Pokemon using the same or greater priority moves.", shortDesc: "This Pokemon moves last among Pokemon using the same or greater priority moves.", onModifyPriority: function (priority) { return priority - 0.1; }, id: "stall", name: "Stall", rating: -1, num: 100 }, "stancechange": { desc: "Only affects Aegislash. If this Pokemon uses a Physical or Special move, it changes to Blade forme. If this Pokemon uses King's Shield, it changes to Shield forme.", shortDesc: "The Pokemon changes form depending on how it battles.", onBeforeMovePriority: 11, onBeforeMove: function (attacker, defender, move) { if (attacker.template.baseSpecies !== 'Aegislash') return; if (move.category === 'Status' && move.id !== 'kingsshield') return; var targetSpecies = (move.id === 'kingsshield' ? 'Aegislash' : 'Aegislash-Blade'); if (attacker.template.species !== targetSpecies && attacker.formeChange(targetSpecies)) { this.add('-formechange', attacker, targetSpecies); } }, id: "stancechange", name: "Stance Change", rating: 4.5, num: 176 }, "static": { desc: "If an opponent contact attacks this Pokemon, there is a 30% chance that the opponent will become paralyzed.", shortDesc: "30% chance of paralyzing a Pokemon making contact with this Pokemon.", onAfterDamage: function (damage, target, source, effect) { if (effect && effect.isContact) { if (this.random(10) < 3) { source.trySetStatus('par', target, effect); } } }, id: "static", name: "Static", rating: 2, num: 9 }, "steadfast": { desc: "If this Pokemon flinches, its Speed increases by one stage.", shortDesc: "If this Pokemon flinches, its Speed is boosted by 1.", onFlinch: function (pokemon) { this.boost({spe: 1}); }, id: "steadfast", name: "Steadfast", rating: 1, num: 80 }, "stench": { desc: "This Pokemon's damaging moves that don't already have a flinch chance gain a 10% chance to cause flinch.", shortDesc: "This Pokemon's attacks without a chance to flinch have a 10% chance to flinch.", onModifyMove: function (move) { if (move.category !== "Status") { this.debug('Adding Stench flinch'); if (!move.secondaries) move.secondaries = []; for (var i = 0; i < move.secondaries.length; i++) { if (move.secondaries[i].volatileStatus === 'flinch') return; } move.secondaries.push({ chance: 10, volatileStatus: 'flinch' }); } }, id: "stench", name: "Stench", rating: 0, num: 1 }, "stickyhold": { desc: "This Pokemon cannot lose its held item due to another Pokemon's attack.", shortDesc: "This Pokemon cannot lose its held item due to another Pokemon's attack.", onTakeItem: function (item, pokemon, source) { if (source && source !== pokemon) return false; }, id: "stickyhold", name: "Sticky Hold", rating: 1, num: 60 }, "stormdrain": { desc: "During double battles, this Pokemon draws any single-target Water-type attack to itself. If an opponent uses an Water-type attack that affects multiple Pokemon, those targets will be hit. This ability does not affect Water Hidden Power, Judgment or Weather Ball. The user is immune to Water and its Special Attack is increased one stage when hit by one.", shortDesc: "This Pokemon draws Water moves to itself to boost Sp. Atk by 1; Water immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Water') { if (!this.boost({spa:1})) { this.add('-immune', target, '[msg]'); } return null; } }, onAnyRedirectTargetPriority: 1, onAnyRedirectTarget: function (target, source, source2, move) { if (move.type !== 'Water') return; if (this.validTarget(this.effectData.target, source, move.target)) { move.accuracy = true; return this.effectData.target; } }, id: "stormdrain", name: "Storm Drain", rating: 3.5, num: 114 }, "strongjaw": { desc: "This Pokemon receives a 50% power boost for jaw attacks such as Bite and Crunch.", shortDesc: "This Pokemon's bite-based attacks do 1.5x damage.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.flags && move.flags['bite']) { return this.chainModify(1.5); } }, id: "strongjaw", name: "Strong Jaw", rating: 3, num: 173 }, "sturdy": { desc: "This Pokemon is immune to OHKO moves, and will survive with 1 HP if hit by an attack which would KO it while at full health.", shortDesc: "If this Pokemon is at full HP, it lives one hit with at least 1HP. OHKO moves fail on it.", onDamagePriority: -100, onDamage: function (damage, target, source, effect) { if (effect && effect.ohko) { this.add('-activate', target, 'Sturdy'); return 0; } if (target.hp === target.maxhp && damage >= target.hp && effect && effect.effectType === 'Move') { this.add('-activate', target, 'Sturdy'); return target.hp - 1; } }, id: "sturdy", name: "Sturdy", rating: 3, num: 5 }, "suctioncups": { desc: "This Pokemon cannot be forced to switch out by another Pokemon's attack or item.", shortDesc: "This Pokemon cannot be forced to switch out by another Pokemon's attack or item.", onDragOutPriority: 1, onDragOut: function (pokemon) { this.add('-activate', pokemon, 'ability: Suction Cups'); return null; }, id: "suctioncups", name: "Suction Cups", rating: 2.5, num: 21 }, "superluck": { desc: "This Pokemon's critical hit ratio is boosted by 1.", shortDesc: "This Pokemon's critical hit ratio is boosted by 1.", onModifyMove: function (move) { move.critRatio++; }, id: "superluck", name: "Super Luck", rating: 1, num: 105 }, "swarm": { desc: "When its health reaches 1/3 or less of its max HP, this Pokemon's Bug-type attacks do 1.5x damage.", shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Bug attacks do 1.5x damage.", onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Bug' && attacker.hp <= attacker.maxhp / 3) { this.debug('Swarm boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Bug' && attacker.hp <= attacker.maxhp / 3) { this.debug('Swarm boost'); return this.chainModify(1.5); } }, id: "swarm", name: "Swarm", rating: 2, num: 68 }, "sweetveil": { desc: "Prevents allies from being put to Sleep.", shortDesc: "Prevents allies from being put to Sleep.", id: "sweetveil", name: "Sweet Veil", onAllySetStatus: function (status, target, source, effect) { if (status.id === 'slp') { this.debug('Sweet Veil interrupts sleep'); return false; } }, onAllyTryHit: function (target, source, move) { if (move && move.id === 'yawn') { this.debug('Sweet Veil blocking yawn'); return false; } }, rating: 0, num: 175 }, "swiftswim": { desc: "If the weather is Rain Dance, this Pokemon's Speed is doubled.", shortDesc: "If the weather is Rain Dance, this Pokemon's Speed is doubled.", onModifySpe: function (speMod, pokemon) { if (this.isWeather(['raindance', 'primordialsea'])) { return this.chain(speMod, 2); } }, id: "swiftswim", name: "Swift Swim", rating: 2, num: 33 }, "symbiosis": { desc: "This Pokemon immediately passes its item to an ally after their item is consumed.", shortDesc: "This Pokemon passes its item to an ally after their item is consumed.", onAllyAfterUseItem: function (item, pokemon) { var sourceItem = this.effectData.target.getItem(); var noSharing = sourceItem.onTakeItem && sourceItem.onTakeItem(sourceItem, pokemon) === false; if (!sourceItem || noSharing) { return; } sourceItem = this.effectData.target.takeItem(); if (!sourceItem) { return; } if (pokemon.setItem(sourceItem)) { this.add('-activate', pokemon, 'ability: Symbiosis', sourceItem, '[of] ' + this.effectData.target); } }, id: "symbiosis", name: "Symbiosis", rating: 0, num: 180 }, "synchronize": { desc: "If an opponent burns, poisons or paralyzes this Pokemon, it receives the same condition.", shortDesc: "If another Pokemon burns/poisons/paralyzes this Pokemon, it also gets that status.", onAfterSetStatus: function (status, target, source) { if (!source || source === target) return; if (status.id === 'slp' || status.id === 'frz') return; source.trySetStatus(status, target); }, id: "synchronize", name: "Synchronize", rating: 3, num: 28 }, "tangledfeet": { desc: "When this Pokemon is confused, attacks targeting it have a 50% chance of missing.", shortDesc: "This Pokemon's evasion is doubled as long as it is confused.", onAccuracy: function (accuracy, target) { if (typeof accuracy !== 'number') return; if (target && target.volatiles['confusion']) { this.debug('Tangled Feet - decreasing accuracy'); return accuracy * 0.5; } }, id: "tangledfeet", name: "Tangled Feet", rating: 1, num: 77 }, "technician": { desc: "When this Pokemon uses an attack that has 60 Base Power or less (including Struggle), the move's Base Power receives a 50% boost. For example, a move with 60 Base Power effectively becomes a move with 90 Base Power.", shortDesc: "This Pokemon's attacks of 60 Base Power or less do 1.5x damage. Includes Struggle.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (basePower <= 60) { this.debug('Technician boost'); return this.chainModify(1.5); } }, id: "technician", name: "Technician", rating: 4, num: 101 }, "telepathy": { desc: "This Pokemon will not take damage from its allies' spread moves in double and triple battles.", shortDesc: "This Pokemon does not take damage from its allies' attacks.", onTryHit: function (target, source, move) { if (target.side === source.side && move.category !== 'Status') { this.add('-activate', target, 'ability: Telepathy'); return null; } }, id: "telepathy", name: "Telepathy", rating: 0, num: 140 }, "teravolt": { desc: "When this Pokemon uses any move, it nullifies the Ability of any active Pokemon that hinder or empower this Pokemon's attacks. These abilities include Battle Armor, Clear Body, Damp, Dry Skin, Filter, Flash Fire, Flower Gift, Heatproof, Herbivore, Hyper Cutter, Immunity, Inner Focus, Insomnia, Keen Eye, Leaf Guard, Levitate, Lightningrod, Limber, Magma Armor, Marvel Scale, Motor Drive, Oblivious, Own Tempo, Sand Veil, Shell Armor, Shield Dust, Simple, Snow Cloak, Solid Rock, Soundproof, Sticky Hold, Storm Drain, Sturdy, Suction Cups, Tangled Feet, Thick Fat, Unaware, Vital Spirit, Volt Absorb, Water Absorb, Water Veil, White Smoke and Wonder Guard.", shortDesc: "This Pokemon's moves ignore any Ability that could modify the effectiveness.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Teravolt'); }, onAllyModifyPokemon: function (pokemon) { if (this.activePokemon === this.effectData.target && pokemon !== this.activePokemon) { pokemon.ignore['Ability'] = 'A'; } }, onFoeModifyPokemon: function (pokemon) { if (this.activePokemon === this.effectData.target) { pokemon.ignore['Ability'] = 'A'; } }, id: "teravolt", name: "Teravolt", rating: 3, num: 164 }, "thickfat": { desc: "This Pokemon receives half damage from Ice-type and Fire-type attacks.", shortDesc: "This Pokemon receives half damage from Fire- and Ice-type attacks.", onModifyAtkPriority: 6, onSourceModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Ice' || move.type === 'Fire') { this.debug('Thick Fat weaken'); return this.chainModify(0.5); } }, onModifySpAPriority: 5, onSourceModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Ice' || move.type === 'Fire') { this.debug('Thick Fat weaken'); return this.chainModify(0.5); } }, id: "thickfat", name: "Thick Fat", rating: 3, num: 47 }, "tintedlens": { desc: "This Pokemon's attacks that are not very effective on a target do double damage.", shortDesc: "This Pokemon's attacks that are not very effective on a target do double damage.", onModifyDamage: function (damage, source, target, move) { if (target.runEffectiveness(move) < 0) { this.debug('Tinted Lens boost'); return this.chainModify(2); } }, id: "tintedlens", name: "Tinted Lens", rating: 4, num: 110 }, "torrent": { desc: "When its health reaches 1/3 or less of its max HP, this Pokemon's Water-type attacks do 1.5x damage.", shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Water attacks do 1.5x damage.", onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Water' && attacker.hp <= attacker.maxhp / 3) { this.debug('Torrent boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Water' && attacker.hp <= attacker.maxhp / 3) { this.debug('Torrent boost'); return this.chainModify(1.5); } }, id: "torrent", name: "Torrent", rating: 2, num: 67 }, "toxicboost": { desc: "When this Pokemon is poisoned, its physical attacks do 1.5x damage.", shortDesc: "When this Pokemon is poisoned, its physical attacks do 1.5x damage.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if ((attacker.status === 'psn' || attacker.status === 'tox') && move.category === 'Physical') { return this.chainModify(1.5); } }, id: "toxicboost", name: "Toxic Boost", rating: 3, num: 137 }, "toughclaws": { desc: "This Pokemon's contact attacks do 33% more damage.", shortDesc: "This Pokemon's contact attacks do 1.33x damage.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.isContact) { return this.chainModify(1.33); } }, id: "toughclaws", name: "Tough Claws", rating: 3, num: 181 }, "trace": { desc: "When this Pokemon enters the field, it temporarily copies an opponent's ability. This ability remains with this Pokemon until it leaves the field.", shortDesc: "On switch-in, or when it can, this Pokemon copies a random adjacent foe's Ability.", onUpdate: function (pokemon) { var possibleTargets = []; for (var i = 0; i < pokemon.side.foe.active.length; i++) { if (pokemon.side.foe.active[i] && !pokemon.side.foe.active[i].fainted) possibleTargets.push(pokemon.side.foe.active[i]); } while (possibleTargets.length) { var rand = 0; if (possibleTargets.length > 1) rand = this.random(possibleTargets.length); var target = possibleTargets[rand]; var ability = this.getAbility(target.ability); var bannedAbilities = {flowergift:1, forecast:1, illusion:1, imposter:1, multitype:1, stancechange:1, trace:1, zenmode:1}; if (bannedAbilities[target.ability]) { possibleTargets.splice(rand, 1); continue; } this.add('-ability', pokemon, ability, '[from] ability: Trace', '[of] ' + target); pokemon.setAbility(ability); return; } }, id: "trace", name: "Trace", rating: 3.5, num: 36 }, "truant": { desc: "After this Pokemon is switched into battle, it skips every other turn.", shortDesc: "This Pokemon skips every other turn instead of using a move.", onBeforeMovePriority: 9, onBeforeMove: function (pokemon, target, move) { if (pokemon.removeVolatile('truant')) { this.add('cant', pokemon, 'ability: Truant', move); return false; } pokemon.addVolatile('truant'); }, effect: { duration: 2 }, id: "truant", name: "Truant", rating: -2, num: 54 }, "turboblaze": { desc: "When this Pokemon uses any move, it nullifies the Ability of any active Pokemon that hinder or empower this Pokemon's attacks. These abilities include Battle Armor, Clear Body, Damp, Dry Skin, Filter, Flash Fire, Flower Gift, Heatproof, Herbivore, Hyper Cutter, Immunity, Inner Focus, Insomnia, Keen Eye, Leaf Guard, Levitate, Lightningrod, Limber, Magma Armor, Marvel Scale, Motor Drive, Oblivious, Own Tempo, Sand Veil, Shell Armor, Shield Dust, Simple, Snow Cloak, Solid Rock, Soundproof, Sticky Hold, Storm Drain, Sturdy, Suction Cups, Tangled Feet, Thick Fat, Unaware, Vital Spirit, Volt Absorb, Water Absorb, Water Veil, White Smoke and Wonder Guard.", shortDesc: "This Pokemon's moves ignore any Ability that could modify the effectiveness.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Turboblaze'); }, onAllyModifyPokemon: function (pokemon) { if (this.activePokemon === this.effectData.target && pokemon !== this.activePokemon) { pokemon.ignore['Ability'] = 'A'; } }, onFoeModifyPokemon: function (pokemon) { if (this.activePokemon === this.effectData.target) { pokemon.ignore['Ability'] = 'A'; } }, id: "turboblaze", name: "Turboblaze", rating: 3, num: 163 }, "unaware": { desc: "This Pokemon ignores an opponent's stat boosts for Attack, Defense, Special Attack and Special Defense. These boosts will still affect Base Power calculation for Punishment and Stored Power.", shortDesc: "This Pokemon ignores other Pokemon's stat changes when taking or doing damage.", id: "unaware", name: "Unaware", onModifyMove: function (move, user, target) { move.ignoreEvasion = true; move.ignoreDefensive = true; }, onSourceModifyMove: function (move, user, target) { if (user.hasAbility(['moldbreaker', 'turboblaze', 'teravolt'])) return; move.ignoreAccuracy = true; move.ignoreOffensive = true; }, rating: 3, num: 109 }, "unburden": { desc: "Doubles this Pokemon's Speed if it loses its held item (such as by eating Berries, using Gems, or via Thief, Knock Off, etc).", shortDesc: "Speed is doubled on held item loss; boost is lost if it switches, gets new item/Ability.", onUseItem: function (item, pokemon) { pokemon.addVolatile('unburden'); }, onTakeItem: function (item, pokemon) { pokemon.addVolatile('unburden'); }, effect: { onModifySpe: function (speMod, pokemon) { if (pokemon.ignore['Ability'] === true || pokemon.ability !== 'unburden') { pokemon.removeVolatile('unburden'); return; } if (!pokemon.item) { return this.chain(speMod, 2); } } }, id: "unburden", name: "Unburden", rating: 3.5, num: 84 }, "unnerve": { desc: "While this Pokemon is active, prevents opposing Pokemon from using their Berries.", shortDesc: "While this Pokemon is active, prevents opposing Pokemon from using their Berries.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Unnerve', pokemon.side.foe); }, onFoeEatItem: false, id: "unnerve", name: "Unnerve", rating: 1, num: 127 }, "victorystar": { desc: "Raises every friendly Pokemon's Accuracy, including this Pokemon's, by 10% (multiplied).", shortDesc: "This Pokemon and its allies' moves have their accuracy boosted to 1.1x.", onAllyModifyMove: function (move) { if (typeof move.accuracy === 'number') { move.accuracy *= 1.1; } }, id: "victorystar", name: "Victory Star", rating: 2, num: 162 }, "vitalspirit": { desc: "This Pokemon cannot fall asleep (Rest will fail if it tries to use it). Gaining this Ability while asleep cures it.", shortDesc: "This Pokemon cannot fall asleep. Gaining this Ability while asleep cures it.", onUpdate: function (pokemon) { if (pokemon.status === 'slp') { pokemon.cureStatus(); } }, onImmunity: function (type) { if (type === 'slp') return false; }, id: "vitalspirit", name: "Vital Spirit", rating: 2, num: 72 }, "voltabsorb": { desc: "This Pokemon is immune to Electric moves. If hit by an Electric move, it recovers 25% of its max HP.", shortDesc: "This Pokemon heals 1/4 of its max HP when hit by Electric moves; Electric immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Electric') { if (!this.heal(target.maxhp / 4)) { this.add('-immune', target, '[msg]'); } return null; } }, id: "voltabsorb", name: "Volt Absorb", rating: 3.5, num: 10 }, "waterabsorb": { desc: "This Pokemon is immune to Water moves. If hit by an Water move, it recovers 25% of its max HP.", shortDesc: "This Pokemon heals 1/4 of its max HP when hit by Water moves; Water immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Water') { if (!this.heal(target.maxhp / 4)) { this.add('-immune', target, '[msg]'); } return null; } }, id: "waterabsorb", name: "Water Absorb", rating: 3.5, num: 11 }, "waterveil": { desc: "This Pokemon cannot become burned. Gaining this Ability while burned cures it.", shortDesc: "This Pokemon cannot be burned. Gaining this Ability while burned cures it.", onUpdate: function (pokemon) { if (pokemon.status === 'brn') { pokemon.cureStatus(); } }, onImmunity: function (type, pokemon) { if (type === 'brn') return false; }, id: "waterveil", name: "Water Veil", rating: 1.5, num: 41 }, "weakarmor": { desc: "Causes physical moves to lower the Pokemon's Defense and increase its Speed stat by one stage.", shortDesc: "If a physical attack hits this Pokemon, Defense is lowered 1 and Speed is boosted 1.", onAfterDamage: function (damage, target, source, move) { if (move.category === 'Physical') { this.boost({spe:1, def:-1}); } }, id: "weakarmor", name: "Weak Armor", rating: 0, num: 133 }, "whitesmoke": { desc: "Opponents cannot reduce this Pokemon's stats; they can, however, modify stat changes with Power Swap, Guard Swap and Heart Swap and inflict stat boosts with Swagger and Flatter. This ability does not prevent self-inflicted stat reductions. [Field Effect]\u00a0If this Pokemon is in the lead spot, the rate of wild Pokemon battles decreases by 50%.", shortDesc: "Prevents other Pokemon from lowering this Pokemon's stat stages.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; var showMsg = false; for (var i in boost) { if (boost[i] < 0) { delete boost[i]; showMsg = true; } } if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: White Smoke", "[of] " + target); }, id: "whitesmoke", name: "White Smoke", rating: 2, num: 73 }, "wonderguard": { desc: "This Pokemon only receives damage from attacks belonging to types that cause Super Effective to this Pokemon. Wonder Guard does not protect a Pokemon from status ailments (burn, freeze, paralysis, poison, sleep, Toxic or any of their side effects or damage), recoil damage nor the moves Beat Up, Bide, Doom Desire, Fire Fang, Future Sight, Hail, Leech Seed, Sandstorm, Spikes, Stealth Rock and Struggle. Wonder Guard cannot be Skill Swapped nor Role Played. Trace, however, does copy Wonder Guard.", shortDesc: "This Pokemon can only be damaged by super effective moves and indirect damage.", onTryHit: function (target, source, move) { if (target === source || move.category === 'Status' || move.type === '???' || move.id === 'struggle' || move.isFutureMove) return; this.debug('Wonder Guard immunity: ' + move.id); if (target.runEffectiveness(move) <= 0) { this.add('-activate', target, 'ability: Wonder Guard'); return null; } }, id: "wonderguard", name: "Wonder Guard", rating: 5, num: 25 }, "wonderskin": { desc: "Causes the chance of a status move working to be halved. It does not affect moves that inflict status as a secondary effect like Thunder's chance to paralyze.", shortDesc: "All status moves with a set % accuracy are 50% accurate if used on this Pokemon.", onAccuracyPriority: 10, onAccuracy: function (accuracy, target, source, move) { if (move.category === 'Status' && typeof move.accuracy === 'number') { this.debug('Wonder Skin - setting accuracy to 50'); return 50; } }, id: "wonderskin", name: "Wonder Skin", rating: 3, num: 147 }, "zenmode": { desc: "When Darmanitan's HP drops to below half, it will enter Zen Mode at the end of the turn. If it loses its ability, or recovers HP to above half while in Zen mode, it will change back. This ability only works on Darmanitan, even if it is copied by Role Play, Entrainment, or swapped with Skill Swap.", shortDesc: "If this Pokemon is Darmanitan, it changes to Zen Mode whenever it is below half HP.", onResidualOrder: 27, onResidual: function (pokemon) { if (pokemon.baseTemplate.species !== 'Darmanitan') { return; } if (pokemon.hp <= pokemon.maxhp / 2 && pokemon.template.speciesid === 'darmanitan') { pokemon.addVolatile('zenmode'); } else if (pokemon.hp > pokemon.maxhp / 2 && pokemon.template.speciesid === 'darmanitanzen') { pokemon.removeVolatile('zenmode'); } }, effect: { onStart: function (pokemon) { if (pokemon.formeChange('Darmanitan-Zen')) { this.add('-formechange', pokemon, 'Darmanitan-Zen'); } else { return false; } }, onEnd: function (pokemon) { if (pokemon.formeChange('Darmanitan')) { this.add('-formechange', pokemon, 'Darmanitan'); } else { return false; } }, onUpdate: function (pokemon) { if (!pokemon.hasAbility('zenmode')) { pokemon.transformed = false; pokemon.removeVolatile('zenmode'); } } }, id: "zenmode", name: "Zen Mode", rating: -1, num: 161 }, // CAP "mountaineer": { desc: "On switch-in, this Pokemon avoids all Rock-type attacks and Stealth Rock.", shortDesc: "This Pokemon avoids all Rock-type attacks and hazards when switching in.", onDamage: function (damage, target, source, effect) { if (effect && effect.id === 'stealthrock') { return false; } }, onImmunity: function (type, target) { if (type === 'Rock' && !target.activeTurns) { return false; } }, id: "mountaineer", isNonstandard: true, name: "Mountaineer", rating: 3.5, num: -2 }, "rebound": { desc: "On switch-in, this Pokemon blocks certain status moves and uses the move itself.", shortDesc: "It can reflect the effect of status moves when switching in.", id: "rebound", isNonstandard: true, name: "Rebound", onTryHitPriority: 1, onTryHit: function (target, source, move) { if (this.effectData.target.activeTurns) return; if (target === source) return; if (move.hasBounced) return; if (typeof move.isBounceable === 'undefined') { move.isBounceable = !!(move.category === 'Status' && (move.status || move.boosts || move.volatileStatus === 'confusion' || move.forceSwitch)); } if (move.isBounceable) { var newMove = this.getMoveCopy(move.id); newMove.hasBounced = true; this.useMove(newMove, target, source); return null; } }, onAllyTryHitSide: function (target, source, move) { if (this.effectData.target.activeTurns) return; if (target.side === source.side) return; if (move.hasBounced) return; if (typeof move.isBounceable === 'undefined') { move.isBounceable = !!(move.category === 'Status' && (move.status || move.boosts || move.volatileStatus === 'confusion' || move.forceSwitch)); } if (move.isBounceable) { var newMove = this.getMoveCopy(move.id); newMove.hasBounced = true; this.useMove(newMove, target, source); return null; } }, effect: { duration: 1 }, rating: 4, num: -3 }, "persistent": { desc: "The duration of certain field effects is increased by 2 turns if used by this Pokemon.", shortDesc: "Increases the duration of many field effects by two turns when used by this Pokemon.", id: "persistent", isNonstandard: true, name: "Persistent", // implemented in the corresponding move rating: 4, num: -4 } };
Raina4uberz/Showdown-light
data/abilities.js
JavaScript
mit
120,010
/* @flow */ import SelectListView from "atom-select-list"; import store from "./store"; import _ from "lodash"; import tildify from "tildify"; import WSKernel from "./ws-kernel"; import { kernelSpecProvidesGrammar } from "./utils"; import type Kernel from "./kernel"; function getName(kernel: Kernel) { const prefix = kernel instanceof WSKernel ? `${kernel.gatewayName}: ` : ""; return ( prefix + kernel.displayName + " - " + store .getFilesForKernel(kernel) .map(tildify) .join(", ") ); } export default class ExistingKernelPicker { kernelSpecs: Array<Kernelspec>; selectListView: SelectListView; panel: ?atom$Panel; previouslyFocusedElement: ?HTMLElement; constructor() { this.selectListView = new SelectListView({ itemsClassList: ["mark-active"], items: [], filterKeyForItem: kernel => getName(kernel), elementForItem: kernel => { const element = document.createElement("li"); element.textContent = getName(kernel); return element; }, didConfirmSelection: kernel => { const { filePath, editor, grammar } = store; if (!filePath || !editor || !grammar) return this.cancel(); store.newKernel(kernel, filePath, editor, grammar); this.cancel(); }, didCancelSelection: () => this.cancel(), emptyMessage: "No running kernels for this language." }); } destroy() { this.cancel(); return this.selectListView.destroy(); } cancel() { if (this.panel != null) { this.panel.destroy(); } this.panel = null; if (this.previouslyFocusedElement) { this.previouslyFocusedElement.focus(); this.previouslyFocusedElement = null; } } attach() { this.previouslyFocusedElement = document.activeElement; if (this.panel == null) this.panel = atom.workspace.addModalPanel({ item: this.selectListView }); this.selectListView.focus(); this.selectListView.reset(); } async toggle() { if (this.panel != null) { this.cancel(); } else if (store.filePath && store.grammar) { await this.selectListView.update({ items: store.runningKernels.filter(kernel => kernelSpecProvidesGrammar(kernel.kernelSpec, store.grammar) ) }); store.markers.clear(); this.attach(); } } }
rgbkrk/hydrogen
lib/existing-kernel-picker.js
JavaScript
mit
2,362