code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
// Copyright IBM Corp. 2013,2016. All Rights Reserved. // Node module: loopback-connector-mongodb // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT var g = require('strong-globalize')(); var DataSource = require('loopback-datasource-juggler').DataSource; var config = require('rc')('loopback', { dev: { mongodb: {}}}).dev.mongodb; var ds = new DataSource(require('../'), config); var Customer = ds.createModel('customer', { seq: { type: Number, id: true }, name: String, emails: [ { label: String, email: String }, ], age: Number }); Customer.destroyAll(function(err) { Customer.create({ seq: 1, name: 'John1', emails: [ { label: 'work', email: '[email protected]' }, { label: 'home', email: '[email protected]' }, ], age: 30, }, function(err, customer1) { console.log(customer1.toObject()); Customer.create({ seq: 2, name: 'John2', emails: [ { label: 'work', email: '[email protected]' }, { label: 'home', email: '[email protected]' }, ], age: 35, }, function(err, customer2) { Customer.find({ where: { 'emails.email': '[email protected]' }}, function(err, customers) { g.log('{{Customers}} matched by {{emails.email}} %s', customers); }); Customer.find({ where: { 'emails.0.label': 'work' }}, function(err, customers) { g.log('{{Customers}} matched by {{emails.0.label}} %s', customers); }); /* customer1.updateAttributes({name: 'John'}, function(err, result) { console.log(err, result); }); customer1.delete(function(err, result) { customer1.updateAttributes({name: 'JohnX'}, function(err, result) { console.log(err, result); }); }); */ Customer.findById(customer1.seq, function(err, customer1) { console.log(customer1.toObject()); customer1.name = 'John'; customer1.save(function(err, customer1) { console.log(customer1.toObject()); ds.disconnect(); }); }); }); }); });
Tuxity/loopback-connector-mongodb
example/model.js
JavaScript
mit
2,094
/* Tests for the Pilotfish recorder plugin */ QUnit.module('Pilotfish Plugin recorder'); QUnit.test('basic events', function () { // Fire two test events Pilotfish('recorder', 'test_event_1'); Pilotfish('recorder', 'test_event_2'); // Check the event log var eventLog = JSON.stringify(Pilotfish('eventLog')); QUnit.ok(eventLog.indexOf('test_event_1') > -1, "test_event_1 in eventLog"); QUnit.ok(eventLog.indexOf('test_event_2') > -1, "test_event_2 in eventLog"); // Check the session data var events = Pilotfish('session').events; QUnit.ok(typeof events, "string", "window.sessionStorage.PilotfishEvents exists"); var eventsFlat = JSON.stringify(events); QUnit.ok(eventsFlat.indexOf('test_event_1') > -1, "test_event_1 in session storage"); QUnit.ok(eventsFlat.indexOf('test_event_2') > -1, "test_event_2 in session storage"); var pageViews = Pilotfish('session').pageViews; QUnit.equal(typeof pageViews, "number", "typeof Pilotfish('session').pageViews"); // Set it in the html so casper can easily get to it jQuery("#pageViews").text(pageViews); });
pilotfish/pilotfish
plugins/recorder/test/qunit-recorder.js
JavaScript
mit
1,124
module.exports = { entry: './main.js', output: { path: './', filename: 'index.js', }, devServer: { inline: true, port: 3333, }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015', 'react'] } } ] } }
claycarpenter/node-sandbox
rx-sandbox/creating-apps-with-observables/webpack.config.js
JavaScript
mit
355
DocsApp.constant('BUILDCONFIG', { "ngVersion": "1.4.6", "version": "0.11.3", "repository": "https://github.com/angular/material", "commit": "3f51bd8633cfc0f1bcfee93d5f0f5650c9a8b01c", "date": "2015-10-12 10:15:32 -0700" });
StephenFluin/code.material.angularjs.org
0.11.3/js/build-config.js
JavaScript
mit
234
{ "name": "espresso.js", "url": "https://github.com/techlayer/espresso.js.git" }
bower/components
packages/espresso.js
JavaScript
mit
85
import React from 'react'; const EmptyStateIcon = props => ( <svg {...props.size || { width: '144px', height: '144px' }} {...props} viewBox="0 0 144 144"> {props.title && <title>{props.title}</title>} <defs> <path d="M76,8 L20,8 C15.6,8 12,11.6 12,16 L12,72 C12,76.4 15.6,80 20,80 L36,80 L48,92 L60,80 L76,80 C80.4,80 84,76.4 84,72 L84,16 C84,11.6 80.4,8 76,8 Z M55.52,51.52 L48,68 L40.48,51.52 L24,44 L40.48,36.48 L48,20 L55.52,36.48 L72,44 L55.52,51.52 Z" id="path-1"></path> </defs> <g id="Task---Insights" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd"> <g id="Insights---Extension-Not-Downloaded" transform="translate(-636.000000, -228.000000)"> <g id="Navigation/Empty-State-Icon" transform="translate(636.000000, 228.000000)"> <circle id="Background" fillOpacity="0.04" fill="#000000" cx="72" cy="72" r="72"></circle> <g id="Icon/Alert/Error" opacity="0.1" transform="translate(24.000000, 24.000000)"> <polygon id="Spacing" points="0 0 96 0 96 96 0 96"></polygon> <g id="Icon"> <mask id="mask-2" fill="white"> <use xlinkHref="#path-1"></use> </mask> <use id="Shape" fillOpacity="0" fill="#FFFFFF" fillRule="nonzero" xlinkHref="#path-1"></use> <g id="Color" mask="url(#mask-2)" fill="#000000"> <rect id="Rectangle" x="0" y="0" width="96" height="96"></rect> </g> </g> </g> </g> </g> </g> </svg> ); export default EmptyStateIcon;
InsideSalesOfficial/insidesales-components
src/components/icons/EmptyStateIcon.js
JavaScript
mit
1,707
'use strict'; var expect = require('expect.js'); var noop = function() { return function() {}; }, task = require('./../tasks/ssh-multi-exec')(require('grunt')); var proceed = function(iteration, maxIterations, cb) { if(++iteration === maxIterations) { cb(); } else { return iteration; } }; describe('multiple targets (restricted parallelism)', function() { it('single command, successful', function(done) { var iteration = 0; task.call({ async: noop, target: 'test', data: { hosts: ['127.0.0.1:2222', '127.0.0.1:2223'], maxDegreeOfParallelism: 1, username: 'test', password: 'test', logFn: noop, commands: [ { hint: 'hint', input: 'echo 1', success: function(data, context, next) { expect(data).to.equal('1\n'); expect(context.host).to.equal('127.0.0.1'); expect(context.port).to.match(/222[2,3]/); iteration = proceed(iteration, 2, done); next(); } } ] } }); }); it('multiple commands, successful', function(done) { var iteration = 0; task.call({ async: noop, target: 'test', data: { hosts: ['127.0.0.1:2222', '127.0.0.1:2223'], maxDegreeOfParallelism: 1, username: 'test', password: 'test', logFn: noop, commands: [ { hint: 'hint 1', input: 'echo 1', success: function(data, context, next) { expect(data).to.equal('1\n'); expect(context.host).to.equal('127.0.0.1'); expect(context.port).to.match(/222[2,3]/); next(); } }, { hint: 'hint 2', input: 'echo 2', success: function(data, context, next) { expect(data).to.equal('2\n'); expect(context.host).to.equal('127.0.0.1'); expect(context.port).to.match(/222[2,3]/); iteration = proceed(iteration, 2, done); next(); } } ] } }); }); it('multiple commands, first failing', function(done) { var iteration = 0; task.call({ async: noop, target: 'test', data: { hosts: ['127.0.0.1:2222', '127.0.0.1:2223'], maxDegreeOfParallelism: 1, username: 'test', password: 'test', logFn: noop, commands: [ { hint: 'hint 1', input: '_test_', error: function(err, context, next) { expect(err).to.equal('bash: _test_: command not found\n'); expect(context.host).to.equal('127.0.0.1'); expect(context.port).to.match(/222[2,3]/); iteration = proceed(iteration, 2, done); next(); } }, { hint: 'hint 2', input: 'echo 2', success: function() { expect().fail('Previous command failed - this should not have been executed!'); } } ] } }); }); it('multiple commands, first failing +force', function(done) { var iteration = 0; task.call({ async: noop, target: 'test', data: { hosts: ['127.0.0.1:2222', '127.0.0.1:2223'], maxDegreeOfParallelism: 1, username: 'test', password: 'test', logFn: noop, commands: [ { hint: 'hint 1', input: '_test_', force: true, error: function(err, context, next) { expect(err).to.equal('bash: _test_: command not found\n'); expect(context.host).to.equal('127.0.0.1'); expect(context.port).to.match(/222[2,3]/); next(); } }, { hint: 'hint 2', input: 'echo 2', success: function(data, context, next) { expect(data).to.equal('2\n'); expect(context.host).to.equal('127.0.0.1'); expect(context.port).to.match(/222[2,3]/); iteration = proceed(iteration, 2, done); next(); } } ] } }); }); it('multiple commands, last failing', function(done) { var iteration = 0; task.call({ async: noop, target: 'test', data: { hosts: ['127.0.0.1:2222', '127.0.0.1:2223'], maxDegreeOfParallelism: 1, username: 'test', password: 'test', logFn: noop, commands: [ { hint: 'hint 1', input: 'echo 1', success: function(data, context, next) { expect(data).to.equal('1\n'); expect(context.host).to.equal('127.0.0.1'); expect(context.port).to.match(/222[2,3]/); next(); } }, { hint: 'hint 2', input: '_test_', error: function(err, context, next) { expect(err).to.equal('bash: _test_: command not found\n'); expect(context.host).to.equal('127.0.0.1'); expect(context.port).to.match(/222[2,3]/); iteration = proceed(iteration, 2, done); next(); } } ] } }); }); });
radzinzki/grunt-ssh-multi-exec
test/multiple targets (restricted parallelism).js
JavaScript
mit
7,099
/* * Copyright (c) 2017. MIT-license for Jari Van Melckebeke * Note that there was a lot of educational work in this project, * this project was (or is) used for an assignment from Realdolmen in Belgium. * Please just don't abuse my work */ //! moment.js locale configuration //! locale : Albanian (sq) //! author : Flakërim Ismani : https://github.com/flakerimi //! author: Menelion Elensúle: https://github.com/Oire (tests) //! author : Oerd Cukalla : https://github.com/oerd (fixes) ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; var sq = moment.defineLocale('sq', { months : 'Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor'.split('_'), monthsShort : 'Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj'.split('_'), weekdays : 'E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë'.split('_'), weekdaysShort : 'Die_Hën_Mar_Mër_Enj_Pre_Sht'.split('_'), weekdaysMin : 'D_H_Ma_Më_E_P_Sh'.split('_'), weekdaysParseExact : true, meridiemParse: /PD|MD/, isPM: function (input) { return input.charAt(0) === 'M'; }, meridiem : function (hours, minutes, isLower) { return hours < 12 ? 'PD' : 'MD'; }, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Sot në] LT', nextDay : '[Nesër në] LT', nextWeek : 'dddd [në] LT', lastDay : '[Dje në] LT', lastWeek : 'dddd [e kaluar në] LT', sameElse : 'L' }, relativeTime : { future : 'në %s', past : '%s më parë', s : 'disa sekonda', m : 'një minutë', mm : '%d minuta', h : 'një orë', hh : '%d orë', d : 'një ditë', dd : '%d ditë', M : 'një muaj', MM : '%d muaj', y : 'një vit', yy : '%d vite' }, ordinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); return sq; }));
N00bface/Real-Dolmen-Stage-Opdrachten
stageopdracht/src/main/resources/static/vendors/moment/locale/sq.js
JavaScript
mit
2,726
// (c) 2012 Guilherme Oenning var hCharts=[];function setIntervalAndExecute(func,time){func();return(setInterval(func,time));} Highcharts.Chart.prototype.clearSeries=function(){while(this.series.length>0) this.series[0].remove(true);};function loadChartAjax(options){var chart=hCharts[options.chartId];var url=options.url;var animation=options.animation;var interval=options.interval;var fn=function(){if("GET"===options.method){$.getJSON(url,function(data){parseAjaxResult(chart,data,animation)});}else{$.post(url,null,function(data){parseAjaxResult(chart,data,animation)},"json");}} if(typeof(interval)!='undefined') setIntervalAndExecute(fn,interval);else fn();} function parseAjaxResult(chart,data,animation){$.each(data,function(key,value){if(chart.series.length>key){var serie=chart.series[key];for(var i=0;i<serie.data.length;i++){serie.data[i].update(value.Values[i],false,false);}} else{chart.addSeries({name:value.Name,data:value.Values},false,false);}});chart.redraw(animation);}
oenning/highcharts-mvc
src/Highcharts.Mvc/highcharts-mvc.min.js
JavaScript
mit
994
/* MIT License http://www.opensource.org/licenses/mit-license.php */ "use strict"; const RuntimeGlobals = require("../RuntimeGlobals"); const RuntimeModule = require("../RuntimeModule"); /** @typedef {import("../MainTemplate")} MainTemplate */ class CompatRuntimePlugin extends RuntimeModule { constructor() { super("compat", 10); } /** * @returns {string} runtime code */ generate() { const { chunk, compilation } = this; const { chunkGraph, runtimeTemplate, mainTemplate, moduleTemplates, dependencyTemplates } = compilation; const bootstrap = mainTemplate.hooks.bootstrap.call( "", chunk, compilation.hash || "XXXX", moduleTemplates.javascript, dependencyTemplates ); const localVars = mainTemplate.hooks.localVars.call( "", chunk, compilation.hash || "XXXX" ); const requireExtensions = mainTemplate.hooks.requireExtensions.call( "", chunk, compilation.hash || "XXXX" ); const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); let requireEnsure = ""; if (runtimeRequirements.has(RuntimeGlobals.ensureChunk)) { const requireEnsureHandler = mainTemplate.hooks.requireEnsure.call( "", chunk, compilation.hash || "XXXX", "chunkId" ); if (requireEnsureHandler) { requireEnsure = `${ RuntimeGlobals.ensureChunkHandlers }.compat = ${runtimeTemplate.basicFunction( "chunkId, promises", requireEnsureHandler )};`; } } return [bootstrap, localVars, requireEnsure, requireExtensions] .filter(Boolean) .join("\n"); } } module.exports = CompatRuntimePlugin;
EliteScientist/webpack
lib/runtime/CompatRuntimePlugin.js
JavaScript
mit
1,622
(function () { var defs = {}; // id -> {dependencies, definition, instance (possibly undefined)} // Used when there is no 'main' module. // The name is probably (hopefully) unique so minification removes for releases. var register_3795 = function (id) { var module = dem(id); var fragments = id.split('.'); var target = Function('return this;')(); for (var i = 0; i < fragments.length - 1; ++i) { if (target[fragments[i]] === undefined) target[fragments[i]] = {}; target = target[fragments[i]]; } target[fragments[fragments.length - 1]] = module; }; var instantiate = function (id) { var actual = defs[id]; var dependencies = actual.deps; var definition = actual.defn; var len = dependencies.length; var instances = new Array(len); for (var i = 0; i < len; ++i) instances[i] = dem(dependencies[i]); var defResult = definition.apply(null, instances); if (defResult === undefined) throw 'module [' + id + '] returned undefined'; actual.instance = defResult; }; var def = function (id, dependencies, definition) { if (typeof id !== 'string') throw 'module id must be a string'; else if (dependencies === undefined) throw 'no dependencies for ' + id; else if (definition === undefined) throw 'no definition function for ' + id; defs[id] = { deps: dependencies, defn: definition, instance: undefined }; }; var dem = function (id) { var actual = defs[id]; if (actual === undefined) throw 'module [' + id + '] was undefined'; else if (actual.instance === undefined) instantiate(id); return actual.instance; }; var req = function (ids, callback) { var len = ids.length; var instances = new Array(len); for (var i = 0; i < len; ++i) instances.push(dem(ids[i])); callback.apply(null, callback); }; var ephox = {}; ephox.bolt = { module: { api: { define: def, require: req, demand: dem } } }; var define = def; var require = req; var demand = dem; // this helps with minificiation when using a lot of global references var defineGlobal = function (id, ref) { define(id, [], function () { return ref; }); }; /*jsc ["tinymce.themes.modern.Theme","global!window","tinymce.core.AddOnManager","tinymce.core.EditorManager","tinymce.core.Env","tinymce.core.ui.Api","tinymce.themes.modern.modes.Iframe","tinymce.themes.modern.modes.Inline","tinymce.themes.modern.ui.ProgressState","tinymce.themes.modern.ui.Resize","global!tinymce.util.Tools.resolve","tinymce.core.dom.DOMUtils","tinymce.core.ui.Factory","tinymce.core.util.Tools","tinymce.themes.modern.ui.A11y","tinymce.themes.modern.ui.Branding","tinymce.themes.modern.ui.ContextToolbars","tinymce.themes.modern.ui.Menubar","tinymce.themes.modern.ui.Sidebar","tinymce.themes.modern.ui.SkinLoaded","tinymce.themes.modern.ui.Toolbar","tinymce.core.ui.FloatPanel","tinymce.core.ui.Throbber","tinymce.core.util.Delay","tinymce.core.geom.Rect"] jsc*/ defineGlobal("global!window", window); defineGlobal("global!tinymce.util.Tools.resolve", tinymce.util.Tools.resolve); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.AddOnManager', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.AddOnManager'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.EditorManager', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.EditorManager'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.Env', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.Env'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.ui.Api', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.ui.Api'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.dom.DOMUtils', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.dom.DOMUtils'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.ui.Factory', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.ui.Factory'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.util.Tools', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.util.Tools'); } ); /** * A11y.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.A11y', [ ], function () { var focus = function (panel, type) { return function () { var item = panel.find(type)[0]; if (item) { item.focus(true); } }; }; var addKeys = function (editor, panel) { editor.shortcuts.add('Alt+F9', '', focus(panel, 'menubar')); editor.shortcuts.add('Alt+F10,F10', '', focus(panel, 'toolbar')); editor.shortcuts.add('Alt+F11', '', focus(panel, 'elementpath')); panel.on('cancel', function () { editor.focus(); }); }; return { addKeys: addKeys }; } ); /** * Branding.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.Branding', [ 'tinymce.core.dom.DOMUtils' ], function (DOMUtils) { var DOM = DOMUtils.DOM; var reposition = function (editor, poweredByElm) { return function () { var iframeWidth = editor.getContentAreaContainer().querySelector('iframe').offsetWidth; var scrollbarWidth = Math.max(iframeWidth - editor.getDoc().documentElement.offsetWidth, 0); var statusbarElm = editor.getContainer().querySelector('.mce-statusbar'); var statusbarHeight = statusbarElm ? statusbarElm.offsetHeight : 1; DOM.setStyles(poweredByElm, { right: scrollbarWidth + 'px', bottom: statusbarHeight + 'px' }); }; }; var hide = function (poweredByElm) { return function () { DOM.hide(poweredByElm); }; }; var setupEventListeners = function (editor) { editor.on('SkinLoaded', function () { var poweredByElm = DOM.create('div', { 'class': 'mce-branding-powered-by' }); editor.getContainer().appendChild(poweredByElm); DOM.bind(poweredByElm, 'click', hide(poweredByElm)); editor.on('NodeChange ResizeEditor', reposition(editor, poweredByElm)); }); }; var setup = function (editor) { if (editor.settings.branding !== false) { setupEventListeners(editor); } }; return { setup: setup }; } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.util.Delay', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.util.Delay'); } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.geom.Rect', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.geom.Rect'); } ); /** * Toolbar.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.Toolbar', [ 'tinymce.core.util.Tools', 'tinymce.core.ui.Factory' ], function (Tools, Factory) { var defaultToolbar = "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | " + "bullist numlist outdent indent | link image"; var createToolbar = function (editor, items, size) { var toolbarItems = [], buttonGroup; if (!items) { return; } Tools.each(items.split(/[ ,]/), function (item) { var itemName; var bindSelectorChanged = function () { var selection = editor.selection; if (item.settings.stateSelector) { selection.selectorChanged(item.settings.stateSelector, function (state) { item.active(state); }, true); } if (item.settings.disabledStateSelector) { selection.selectorChanged(item.settings.disabledStateSelector, function (state) { item.disabled(state); }); } }; if (item == "|") { buttonGroup = null; } else { if (!buttonGroup) { buttonGroup = { type: 'buttongroup', items: [] }; toolbarItems.push(buttonGroup); } if (editor.buttons[item]) { // TODO: Move control creation to some UI class itemName = item; item = editor.buttons[itemName]; if (typeof item == "function") { item = item(); } item.type = item.type || 'button'; item.size = size; item = Factory.create(item); buttonGroup.items.push(item); if (editor.initialized) { bindSelectorChanged(); } else { editor.on('init', bindSelectorChanged); } } } }); return { type: 'toolbar', layout: 'flow', items: toolbarItems }; }; /** * Creates the toolbars from config and returns a toolbar array. * * @param {String} size Optional toolbar item size. * @return {Array} Array with toolbars. */ var createToolbars = function (editor, size) { var toolbars = [], settings = editor.settings; var addToolbar = function (items) { if (items) { toolbars.push(createToolbar(editor, items, size)); return true; } }; // Convert toolbar array to multiple options if (Tools.isArray(settings.toolbar)) { // Empty toolbar array is the same as a disabled toolbar if (settings.toolbar.length === 0) { return; } Tools.each(settings.toolbar, function (toolbar, i) { settings["toolbar" + (i + 1)] = toolbar; }); delete settings.toolbar; } // Generate toolbar<n> for (var i = 1; i < 10; i++) { if (!addToolbar(settings["toolbar" + i])) { break; } } // Generate toolbar or default toolbar unless it's disabled if (!toolbars.length && settings.toolbar !== false) { addToolbar(settings.toolbar || defaultToolbar); } if (toolbars.length) { return { type: 'panel', layout: 'stack', classes: "toolbar-grp", ariaRoot: true, ariaRemember: true, items: toolbars }; } }; return { createToolbar: createToolbar, createToolbars: createToolbars }; } ); /** * ContextToolbars.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.ContextToolbars', [ 'tinymce.core.dom.DOMUtils', 'tinymce.core.util.Tools', 'tinymce.core.util.Delay', 'tinymce.core.ui.Factory', 'tinymce.core.geom.Rect', 'tinymce.themes.modern.ui.Toolbar' ], function (DOMUtils, Tools, Delay, Factory, Rect, Toolbar) { var DOM = DOMUtils.DOM; var toClientRect = function (geomRect) { return { left: geomRect.x, top: geomRect.y, width: geomRect.w, height: geomRect.h, right: geomRect.x + geomRect.w, bottom: geomRect.y + geomRect.h }; }; var hideAllFloatingPanels = function (editor) { Tools.each(editor.contextToolbars, function (toolbar) { if (toolbar.panel) { toolbar.panel.hide(); } }); }; var movePanelTo = function (panel, pos) { panel.moveTo(pos.left, pos.top); }; var togglePositionClass = function (panel, relPos, predicate) { relPos = relPos ? relPos.substr(0, 2) : ''; Tools.each({ t: 'down', b: 'up' }, function (cls, pos) { panel.classes.toggle('arrow-' + cls, predicate(pos, relPos.substr(0, 1))); }); Tools.each({ l: 'left', r: 'right' }, function (cls, pos) { panel.classes.toggle('arrow-' + cls, predicate(pos, relPos.substr(1, 1))); }); }; var userConstrain = function (handler, x, y, elementRect, contentAreaRect, panelRect) { panelRect = toClientRect({ x: x, y: y, w: panelRect.w, h: panelRect.h }); if (handler) { panelRect = handler({ elementRect: toClientRect(elementRect), contentAreaRect: toClientRect(contentAreaRect), panelRect: panelRect }); } return panelRect; }; var addContextualToolbars = function (editor) { var scrollContainer, settings = editor.settings; var getContextToolbars = function () { return editor.contextToolbars || []; }; var getElementRect = function (elm) { var pos, targetRect, root; pos = DOM.getPos(editor.getContentAreaContainer()); targetRect = editor.dom.getRect(elm); root = editor.dom.getRoot(); // Adjust targetPos for scrolling in the editor if (root.nodeName === 'BODY') { targetRect.x -= root.ownerDocument.documentElement.scrollLeft || root.scrollLeft; targetRect.y -= root.ownerDocument.documentElement.scrollTop || root.scrollTop; } targetRect.x += pos.x; targetRect.y += pos.y; return targetRect; }; var reposition = function (match, shouldShow) { var relPos, panelRect, elementRect, contentAreaRect, panel, relRect, testPositions, smallElementWidthThreshold; var handler = settings.inline_toolbar_position_handler; if (editor.removed) { return; } if (!match || !match.toolbar.panel) { hideAllFloatingPanels(editor); return; } testPositions = [ 'bc-tc', 'tc-bc', 'tl-bl', 'bl-tl', 'tr-br', 'br-tr' ]; panel = match.toolbar.panel; // Only show the panel on some events not for example nodeChange since that fires when context menu is opened if (shouldShow) { panel.show(); } elementRect = getElementRect(match.element); panelRect = DOM.getRect(panel.getEl()); contentAreaRect = DOM.getRect(editor.getContentAreaContainer() || editor.getBody()); smallElementWidthThreshold = 25; if (DOM.getStyle(match.element, 'display', true) !== 'inline') { // We need to use these instead of the rect values since the style // size properites might not be the same as the real size for a table elementRect.w = match.element.clientWidth; elementRect.h = match.element.clientHeight; } if (!editor.inline) { contentAreaRect.w = editor.getDoc().documentElement.offsetWidth; } // Inflate the elementRect so it doesn't get placed above resize handles if (editor.selection.controlSelection.isResizable(match.element) && elementRect.w < smallElementWidthThreshold) { elementRect = Rect.inflate(elementRect, 0, 8); } relPos = Rect.findBestRelativePosition(panelRect, elementRect, contentAreaRect, testPositions); elementRect = Rect.clamp(elementRect, contentAreaRect); if (relPos) { relRect = Rect.relativePosition(panelRect, elementRect, relPos); movePanelTo(panel, userConstrain(handler, relRect.x, relRect.y, elementRect, contentAreaRect, panelRect)); } else { // Allow overflow below the editor to avoid placing toolbars ontop of tables contentAreaRect.h += panelRect.h; elementRect = Rect.intersect(contentAreaRect, elementRect); if (elementRect) { relPos = Rect.findBestRelativePosition(panelRect, elementRect, contentAreaRect, [ 'bc-tc', 'bl-tl', 'br-tr' ]); if (relPos) { relRect = Rect.relativePosition(panelRect, elementRect, relPos); movePanelTo(panel, userConstrain(handler, relRect.x, relRect.y, elementRect, contentAreaRect, panelRect)); } else { movePanelTo(panel, userConstrain(handler, elementRect.x, elementRect.y, elementRect, contentAreaRect, panelRect)); } } else { panel.hide(); } } togglePositionClass(panel, relPos, function (pos1, pos2) { return pos1 === pos2; }); //drawRect(contentAreaRect, 'blue'); //drawRect(elementRect, 'red'); //drawRect(panelRect, 'green'); }; var repositionHandler = function (show) { return function () { var execute = function () { if (editor.selection) { reposition(findFrontMostMatch(editor.selection.getNode()), show); } }; Delay.requestAnimationFrame(execute); }; }; var bindScrollEvent = function () { if (!scrollContainer) { scrollContainer = editor.selection.getScrollContainer() || editor.getWin(); DOM.bind(scrollContainer, 'scroll', repositionHandler(true)); editor.on('remove', function () { DOM.unbind(scrollContainer, 'scroll'); }); } }; var showContextToolbar = function (match) { var panel; if (match.toolbar.panel) { match.toolbar.panel.show(); reposition(match); return; } bindScrollEvent(); panel = Factory.create({ type: 'floatpanel', role: 'dialog', classes: 'tinymce tinymce-inline arrow', ariaLabel: 'Inline toolbar', layout: 'flex', direction: 'column', align: 'stretch', autohide: false, autofix: true, fixed: true, border: 1, items: Toolbar.createToolbar(editor, match.toolbar.items), oncancel: function () { editor.focus(); } }); match.toolbar.panel = panel; panel.renderTo(document.body).reflow(); reposition(match); }; var hideAllContextToolbars = function () { Tools.each(getContextToolbars(), function (toolbar) { if (toolbar.panel) { toolbar.panel.hide(); } }); }; var findFrontMostMatch = function (targetElm) { var i, y, parentsAndSelf, toolbars = getContextToolbars(); parentsAndSelf = editor.$(targetElm).parents().add(targetElm); for (i = parentsAndSelf.length - 1; i >= 0; i--) { for (y = toolbars.length - 1; y >= 0; y--) { if (toolbars[y].predicate(parentsAndSelf[i])) { return { toolbar: toolbars[y], element: parentsAndSelf[i] }; } } } return null; }; editor.on('click keyup setContent ObjectResized', function (e) { // Only act on partial inserts if (e.type === 'setcontent' && !e.selection) { return; } // Needs to be delayed to avoid Chrome img focus out bug Delay.setEditorTimeout(editor, function () { var match; match = findFrontMostMatch(editor.selection.getNode()); if (match) { hideAllContextToolbars(); showContextToolbar(match); } else { hideAllContextToolbars(); } }); }); editor.on('blur hide contextmenu', hideAllContextToolbars); editor.on('ObjectResizeStart', function () { var match = findFrontMostMatch(editor.selection.getNode()); if (match && match.toolbar.panel) { match.toolbar.panel.hide(); } }); editor.on('ResizeEditor ResizeWindow', repositionHandler(true)); editor.on('nodeChange', repositionHandler(false)); editor.on('remove', function () { Tools.each(getContextToolbars(), function (toolbar) { if (toolbar.panel) { toolbar.panel.remove(); } }); editor.contextToolbars = {}; }); editor.shortcuts.add('ctrl+shift+e > ctrl+shift+p', '', function () { var match = findFrontMostMatch(editor.selection.getNode()); if (match && match.toolbar.panel) { match.toolbar.panel.items()[0].focus(); } }); }; return { addContextualToolbars: addContextualToolbars }; } ); /** * Menubar.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.Menubar', [ 'tinymce.core.util.Tools' ], function (Tools) { var defaultMenus = { file: { title: 'File', items: 'newdocument' }, edit: { title: 'Edit', items: 'undo redo | cut copy paste pastetext | selectall' }, insert: { title: 'Insert', items: '|' }, view: { title: 'View', items: 'visualaid |' }, format: { title: 'Format', items: 'bold italic underline strikethrough superscript subscript | formats | removeformat' }, table: { title: 'Table' }, tools: { title: 'Tools' } }; var createMenuItem = function (menuItems, name) { var menuItem; if (name == '|') { return { text: '|' }; } menuItem = menuItems[name]; return menuItem; }; var createMenu = function (editorMenuItems, settings, context) { var menuButton, menu, menuItems, isUserDefined, removedMenuItems; removedMenuItems = Tools.makeMap((settings.removed_menuitems || '').split(/[ ,]/)); // User defined menu if (settings.menu) { menu = settings.menu[context]; isUserDefined = true; } else { menu = defaultMenus[context]; } if (menu) { menuButton = { text: menu.title }; menuItems = []; // Default/user defined items Tools.each((menu.items || '').split(/[ ,]/), function (item) { var menuItem = createMenuItem(editorMenuItems, item); if (menuItem && !removedMenuItems[item]) { menuItems.push(createMenuItem(editorMenuItems, item)); } }); // Added though context if (!isUserDefined) { Tools.each(editorMenuItems, function (menuItem) { if (menuItem.context == context) { if (menuItem.separator == 'before') { menuItems.push({ text: '|' }); } if (menuItem.prependToContext) { menuItems.unshift(menuItem); } else { menuItems.push(menuItem); } if (menuItem.separator == 'after') { menuItems.push({ text: '|' }); } } }); } for (var i = 0; i < menuItems.length; i++) { if (menuItems[i].text == '|') { if (i === 0 || i == menuItems.length - 1) { menuItems.splice(i, 1); } } } menuButton.menu = menuItems; if (!menuButton.menu.length) { return null; } } return menuButton; }; var createMenuButtons = function (editor) { var name, menuButtons = [], settings = editor.settings; var defaultMenuBar = []; if (settings.menu) { for (name in settings.menu) { defaultMenuBar.push(name); } } else { for (name in defaultMenus) { defaultMenuBar.push(name); } } var enabledMenuNames = typeof settings.menubar == "string" ? settings.menubar.split(/[ ,]/) : defaultMenuBar; for (var i = 0; i < enabledMenuNames.length; i++) { var menu = enabledMenuNames[i]; menu = createMenu(editor.menuItems, editor.settings, menu); if (menu) { menuButtons.push(menu); } } return menuButtons; }; return { createMenuButtons: createMenuButtons }; } ); /** * Resize.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.Resize', [ 'tinymce.core.dom.DOMUtils' ], function (DOMUtils) { var DOM = DOMUtils.DOM; var getSize = function (elm) { return { width: elm.clientWidth, height: elm.clientHeight }; }; var resizeTo = function (editor, width, height) { var containerElm, iframeElm, containerSize, iframeSize, settings = editor.settings; containerElm = editor.getContainer(); iframeElm = editor.getContentAreaContainer().firstChild; containerSize = getSize(containerElm); iframeSize = getSize(iframeElm); if (width !== null) { width = Math.max(settings.min_width || 100, width); width = Math.min(settings.max_width || 0xFFFF, width); DOM.setStyle(containerElm, 'width', width + (containerSize.width - iframeSize.width)); DOM.setStyle(iframeElm, 'width', width); } height = Math.max(settings.min_height || 100, height); height = Math.min(settings.max_height || 0xFFFF, height); DOM.setStyle(iframeElm, 'height', height); editor.fire('ResizeEditor'); }; var resizeBy = function (editor, dw, dh) { var elm = editor.getContentAreaContainer(); resizeTo(editor, elm.clientWidth + dw, elm.clientHeight + dh); }; return { resizeTo: resizeTo, resizeBy: resizeBy }; } ); /** * Sidebar.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.Sidebar', [ 'tinymce.core.util.Tools', 'tinymce.core.ui.Factory', 'tinymce.core.Env' ], function (Tools, Factory, Env) { var api = function (elm) { return { element: function () { return elm; } }; }; var trigger = function (sidebar, panel, callbackName) { var callback = sidebar.settings[callbackName]; if (callback) { callback(api(panel.getEl('body'))); } }; var hidePanels = function (name, container, sidebars) { Tools.each(sidebars, function (sidebar) { var panel = container.items().filter('#' + sidebar.name)[0]; if (panel && panel.visible() && sidebar.name !== name) { trigger(sidebar, panel, 'onhide'); panel.visible(false); } }); }; var deactivateButtons = function (toolbar) { toolbar.items().each(function (ctrl) { ctrl.active(false); }); }; var findSidebar = function (sidebars, name) { return Tools.grep(sidebars, function (sidebar) { return sidebar.name === name; })[0]; }; var showPanel = function (editor, name, sidebars) { return function (e) { var btnCtrl = e.control; var container = btnCtrl.parents().filter('panel')[0]; var panel = container.find('#' + name)[0]; var sidebar = findSidebar(sidebars, name); hidePanels(name, container, sidebars); deactivateButtons(btnCtrl.parent()); if (panel && panel.visible()) { trigger(sidebar, panel, 'onhide'); panel.hide(); btnCtrl.active(false); } else { if (panel) { panel.show(); trigger(sidebar, panel, 'onshow'); } else { panel = Factory.create({ type: 'container', name: name, layout: 'stack', classes: 'sidebar-panel', html: '' }); container.prepend(panel); trigger(sidebar, panel, 'onrender'); trigger(sidebar, panel, 'onshow'); } btnCtrl.active(true); } editor.fire('ResizeEditor'); }; }; var isModernBrowser = function () { return !Env.ie || Env.ie >= 11; }; var hasSidebar = function (editor) { return isModernBrowser() && editor.sidebars ? editor.sidebars.length > 0 : false; }; var createSidebar = function (editor) { var buttons = Tools.map(editor.sidebars, function (sidebar) { var settings = sidebar.settings; return { type: 'button', icon: settings.icon, image: settings.image, tooltip: settings.tooltip, onclick: showPanel(editor, sidebar.name, editor.sidebars) }; }); return { type: 'panel', name: 'sidebar', layout: 'stack', classes: 'sidebar', items: [ { type: 'toolbar', layout: 'stack', classes: 'sidebar-toolbar', items: buttons } ] }; }; return { hasSidebar: hasSidebar, createSidebar: createSidebar }; } ); /** * SkinLoaded.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.SkinLoaded', [ ], function () { var fireSkinLoaded = function (editor) { var done = function () { editor._skinLoaded = true; editor.fire('SkinLoaded'); }; return function () { if (editor.initialized) { done(); } else { editor.on('init', done); } }; }; return { fireSkinLoaded: fireSkinLoaded }; } ); /** * Iframe.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.modes.Iframe', [ 'tinymce.core.dom.DOMUtils', 'tinymce.core.ui.Factory', 'tinymce.core.util.Tools', 'tinymce.themes.modern.ui.A11y', 'tinymce.themes.modern.ui.Branding', 'tinymce.themes.modern.ui.ContextToolbars', 'tinymce.themes.modern.ui.Menubar', 'tinymce.themes.modern.ui.Resize', 'tinymce.themes.modern.ui.Sidebar', 'tinymce.themes.modern.ui.SkinLoaded', 'tinymce.themes.modern.ui.Toolbar' ], function (DOMUtils, Factory, Tools, A11y, Branding, ContextToolbars, Menubar, Resize, Sidebar, SkinLoaded, Toolbar) { var DOM = DOMUtils.DOM; var switchMode = function (panel) { return function (e) { panel.find('*').disabled(e.mode === 'readonly'); }; }; var editArea = function (border) { return { type: 'panel', name: 'iframe', layout: 'stack', classes: 'edit-area', border: border, html: '' }; }; var editAreaContainer = function (editor) { return { type: 'panel', layout: 'stack', classes: 'edit-aria-container', border: '1 0 0 0', items: [ editArea('0'), Sidebar.createSidebar(editor) ] }; }; var render = function (editor, theme, args) { var panel, resizeHandleCtrl, startSize, settings = editor.settings; if (args.skinUiCss) { DOM.styleSheetLoader.load(args.skinUiCss, SkinLoaded.fireSkinLoaded(editor)); } panel = theme.panel = Factory.create({ type: 'panel', role: 'application', classes: 'tinymce', style: 'visibility: hidden', layout: 'stack', border: 1, items: [ settings.menubar === false ? null : { type: 'menubar', border: '0 0 1 0', items: Menubar.createMenuButtons(editor) }, Toolbar.createToolbars(editor, settings.toolbar_items_size), Sidebar.hasSidebar(editor) ? editAreaContainer(editor) : editArea('1 0 0 0') ] }); if (settings.resize !== false) { resizeHandleCtrl = { type: 'resizehandle', direction: settings.resize, onResizeStart: function () { var elm = editor.getContentAreaContainer().firstChild; startSize = { width: elm.clientWidth, height: elm.clientHeight }; }, onResize: function (e) { if (settings.resize === 'both') { Resize.resizeTo(editor, startSize.width + e.deltaX, startSize.height + e.deltaY); } else { Resize.resizeTo(editor, null, startSize.height + e.deltaY); } } }; } // Add statusbar if needed if (settings.statusbar !== false) { panel.add({ type: 'panel', name: 'statusbar', classes: 'statusbar', layout: 'flow', border: '1 0 0 0', ariaRoot: true, items: [ { type: 'elementpath', editor: editor }, resizeHandleCtrl ] }); } editor.fire('BeforeRenderUI'); editor.on('SwitchMode', switchMode(panel)); panel.renderBefore(args.targetNode).reflow(); if (settings.readonly) { editor.setMode('readonly'); } if (args.width) { DOM.setStyle(panel.getEl(), 'width', args.width); } // Remove the panel when the editor is removed editor.on('remove', function () { panel.remove(); panel = null; }); // Add accesibility shortcuts A11y.addKeys(editor, panel); ContextToolbars.addContextualToolbars(editor); Branding.setup(editor); return { iframeContainer: panel.find('#iframe')[0].getEl(), editorContainer: panel.getEl() }; }; return { render: render }; } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.ui.FloatPanel', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.ui.FloatPanel'); } ); /** * Inline.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.modes.Inline', [ 'tinymce.core.util.Tools', 'tinymce.core.ui.Factory', 'tinymce.core.dom.DOMUtils', 'tinymce.core.ui.FloatPanel', 'tinymce.themes.modern.ui.Toolbar', 'tinymce.themes.modern.ui.Menubar', 'tinymce.themes.modern.ui.ContextToolbars', 'tinymce.themes.modern.ui.A11y', 'tinymce.themes.modern.ui.SkinLoaded' ], function (Tools, Factory, DOMUtils, FloatPanel, Toolbar, Menubar, ContextToolbars, A11y, SkinLoaded) { var render = function (editor, theme, args) { var panel, inlineToolbarContainer, settings = editor.settings; var DOM = DOMUtils.DOM; if (settings.fixed_toolbar_container) { inlineToolbarContainer = DOM.select(settings.fixed_toolbar_container)[0]; } var reposition = function () { if (panel && panel.moveRel && panel.visible() && !panel._fixed) { // TODO: This is kind of ugly and doesn't handle multiple scrollable elements var scrollContainer = editor.selection.getScrollContainer(), body = editor.getBody(); var deltaX = 0, deltaY = 0; if (scrollContainer) { var bodyPos = DOM.getPos(body), scrollContainerPos = DOM.getPos(scrollContainer); deltaX = Math.max(0, scrollContainerPos.x - bodyPos.x); deltaY = Math.max(0, scrollContainerPos.y - bodyPos.y); } panel.fixed(false).moveRel(body, editor.rtl ? ['tr-br', 'br-tr'] : ['tl-bl', 'bl-tl', 'tr-br']).moveBy(deltaX, deltaY); } }; var show = function () { if (panel) { panel.show(); reposition(); DOM.addClass(editor.getBody(), 'mce-edit-focus'); } }; var hide = function () { if (panel) { // We require two events as the inline float panel based toolbar does not have autohide=true panel.hide(); // All other autohidden float panels will be closed below. FloatPanel.hideAll(); DOM.removeClass(editor.getBody(), 'mce-edit-focus'); } }; var render = function () { if (panel) { if (!panel.visible()) { show(); } return; } // Render a plain panel inside the inlineToolbarContainer if it's defined panel = theme.panel = Factory.create({ type: inlineToolbarContainer ? 'panel' : 'floatpanel', role: 'application', classes: 'tinymce tinymce-inline', layout: 'flex', direction: 'column', align: 'stretch', autohide: false, autofix: true, fixed: !!inlineToolbarContainer, border: 1, items: [ settings.menubar === false ? null : { type: 'menubar', border: '0 0 1 0', items: Menubar.createMenuButtons(editor) }, Toolbar.createToolbars(editor, settings.toolbar_items_size) ] }); // Add statusbar /*if (settings.statusbar !== false) { panel.add({type: 'panel', classes: 'statusbar', layout: 'flow', border: '1 0 0 0', items: [ {type: 'elementpath'} ]}); }*/ editor.fire('BeforeRenderUI'); panel.renderTo(inlineToolbarContainer || document.body).reflow(); A11y.addKeys(editor, panel); show(); ContextToolbars.addContextualToolbars(editor); editor.on('nodeChange', reposition); editor.on('activate', show); editor.on('deactivate', hide); editor.nodeChanged(); }; settings.content_editable = true; editor.on('focus', function () { // Render only when the CSS file has been loaded if (args.skinUiCss) { DOM.styleSheetLoader.load(args.skinUiCss, render, render); } else { render(); } }); editor.on('blur hide', hide); // Remove the panel when the editor is removed editor.on('remove', function () { if (panel) { panel.remove(); panel = null; } }); // Preload skin css if (args.skinUiCss) { DOM.styleSheetLoader.load(args.skinUiCss, SkinLoaded.fireSkinLoaded(editor)); } return {}; }; return { render: render }; } ); /** * ResolveGlobal.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.core.ui.Throbber', [ 'global!tinymce.util.Tools.resolve' ], function (resolve) { return resolve('tinymce.ui.Throbber'); } ); /** * ProgressState.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.ui.ProgressState', [ 'tinymce.core.ui.Throbber' ], function (Throbber) { var setup = function (editor, theme) { var throbber; editor.on('ProgressState', function (e) { throbber = throbber || new Throbber(theme.panel.getEl('body')); if (e.state) { throbber.show(e.time); } else { throbber.hide(); } }); }; return { setup: setup }; } ); /** * Theme.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ define( 'tinymce.themes.modern.Theme', [ 'global!window', 'tinymce.core.AddOnManager', 'tinymce.core.EditorManager', 'tinymce.core.Env', 'tinymce.core.ui.Api', 'tinymce.themes.modern.modes.Iframe', 'tinymce.themes.modern.modes.Inline', 'tinymce.themes.modern.ui.ProgressState', 'tinymce.themes.modern.ui.Resize' ], function (window, AddOnManager, EditorManager, Env, Api, Iframe, Inline, ProgressState, Resize) { var ThemeManager = AddOnManager.ThemeManager; Api.appendTo(window.tinymce ? window.tinymce : {}); var renderUI = function (editor, theme, args) { var settings = editor.settings; var skin = settings.skin !== false ? settings.skin || 'lightgray' : false; if (skin) { var skinUrl = settings.skin_url; if (skinUrl) { skinUrl = editor.documentBaseURI.toAbsolute(skinUrl); } else { skinUrl = EditorManager.baseURL + '/skins/' + skin; } args.skinUiCss = skinUrl + '/skin.min.css'; // Load content.min.css or content.inline.min.css editor.contentCSS.push(skinUrl + '/content' + (editor.inline ? '.inline' : '') + '.min.css'); } ProgressState.setup(editor, theme); if (settings.inline) { return Inline.render(editor, theme, args); } return Iframe.render(editor, theme, args); }; ThemeManager.add('modern', function (editor) { return { renderUI: function (args) { return renderUI(editor, this, args); }, resizeTo: function (w, h) { return Resize.resizeTo(editor, w, h); }, resizeBy: function (dw, dh) { return Resize.resizeBy(editor, dw, dh); } }; }); return function () { }; } ); dem('tinymce.themes.modern.Theme')(); })();
g0otgahp/number-energy
theme/tinymce/tinymce/themes/modern/theme.js
JavaScript
mit
44,251
module.exports = function(sequelize, DataTypes) { var Product = sequelize.define('Product', { ProductId: { type: DataTypes.BIGINT, primaryKey:true, allowNull: false, autoIncrement: true }, ProductTypeId:{ type:DataTypes.BIGINT, allowNull: false, references : 'ProductType', referencesKey:'ProductTypeId', comment: "references对应的是表名" } , productName:{ type:DataTypes.STRING, allowNull: false }, productDesc:{ type:DataTypes.STRING }, mount:{ type:DataTypes.BIGINT }, price:{ type:DataTypes.DECIMAL(10,2) }, isSale:{ type:DataTypes.BOOLEAN }, isVailed:{ type:DataTypes.BOOLEAN } }); return Product; };
coolicer/shopshop
models/Product.js
JavaScript
mit
807
"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: "M17 4h-3V2h-4v2H7v18h10V4z" }), 'BatteryStdSharp'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/BatteryStdSharp.js
JavaScript
mit
497
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createConfig; var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); var _jsYaml = require('js-yaml'); var _jsYaml2 = _interopRequireDefault(_jsYaml); var _stripJsonComments = require('strip-json-comments'); var _stripJsonComments2 = _interopRequireDefault(_stripJsonComments); var _fileExists = require('./utils/fileExists'); var _fileExists2 = _interopRequireDefault(_fileExists); var _selectModules = require('./utils/selectModules'); var _selectModules2 = _interopRequireDefault(_selectModules); var _selectUserModules = require('./utils/selectUserModules'); var _selectUserModules2 = _interopRequireDefault(_selectUserModules); var _getEnvProp = require('./utils/getEnvProp'); var _getEnvProp2 = _interopRequireDefault(_getEnvProp); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* ======= Fetching config */ var DEFAULT_VERSION = 3; var SUPPORTED_VERSIONS = [3, 4]; var CONFIG_FILE = '.bootstraprc'; function resolveDefaultConfigPath(bootstrapVersion) { return _path2.default.resolve(__dirname, '../' + CONFIG_FILE + '-' + bootstrapVersion + '-default'); } function parseConfigFile(configFilePath) { var configContent = (0, _stripJsonComments2.default)(_fs2.default.readFileSync(configFilePath, 'utf8')); try { return _jsYaml2.default.safeLoad(configContent); } catch (YAMLException) { throw new Error('Config file cannot be parsed: ' + configFilePath + '\''); } } function readDefaultConfig() { var configFilePath = resolveDefaultConfigPath(DEFAULT_VERSION); var defaultConfig = parseConfigFile(configFilePath); return { defaultConfig: defaultConfig, configFilePath: configFilePath }; } // default location .bootstraprc function defaultUserConfigPath() { return _path2.default.resolve(__dirname, '../../../' + CONFIG_FILE); } function readUserConfig(customConfigFilePath) { var userConfig = parseConfigFile(customConfigFilePath); var bootstrapVersion = userConfig.bootstrapVersion; if (!bootstrapVersion) { throw new Error('\nBootstrap version not found in your \'.bootstraprc\'.\nMake sure it\'s set to 3 or 4. Like this:\n bootstrapVersion: 4\n '); } if (SUPPORTED_VERSIONS.indexOf(parseInt(bootstrapVersion, 10)) === -1) { throw new Error('\nUnsupported Bootstrap version in your \'.bootstraprc\'.\nMake sure it\'s set to 3 or 4. Like this:\n bootstrapVersion: 4\n '); } var defaultConfigFilePath = resolveDefaultConfigPath(bootstrapVersion); var defaultConfig = parseConfigFile(defaultConfigFilePath); return { userConfig: userConfig, defaultConfig: defaultConfig }; } /* ======= Exports */ function createConfig(_ref) { var extractStyles = _ref.extractStyles, customConfigFilePath = _ref.customConfigFilePath; // .bootstraprc-{3,4}-default, per the DEFAULT_VERSION // otherwise read user provided config file var userConfigFilePath = null; if (customConfigFilePath) { userConfigFilePath = _path2.default.resolve(__dirname, customConfigFilePath); } else { var defaultLocationUserConfigPath = defaultUserConfigPath(); if ((0, _fileExists2.default)(defaultLocationUserConfigPath)) { userConfigFilePath = defaultLocationUserConfigPath; } } if (!userConfigFilePath) { var _readDefaultConfig = readDefaultConfig(), _defaultConfig = _readDefaultConfig.defaultConfig, _configFilePath = _readDefaultConfig.configFilePath; return { bootstrapVersion: parseInt(_defaultConfig.bootstrapVersion, 10), loglevel: _defaultConfig.loglevel, useFlexbox: _defaultConfig.useFlexbox, preBootstrapCustomizations: _defaultConfig.preBootstrapCustomizations, bootstrapCustomizations: _defaultConfig.bootstrapCustomizations, appStyles: _defaultConfig.appStyles, useCustomIconFontPath: _defaultConfig.useCustomIconFontPath, extractStyles: extractStyles || (0, _getEnvProp2.default)('extractStyles', _defaultConfig), styleLoaders: (0, _getEnvProp2.default)('styleLoaders', _defaultConfig), styles: (0, _selectModules2.default)(_defaultConfig.styles), scripts: (0, _selectModules2.default)(_defaultConfig.scripts), configFilePath: _configFilePath }; } var configFilePath = userConfigFilePath; var _readUserConfig = readUserConfig(configFilePath), userConfig = _readUserConfig.userConfig, defaultConfig = _readUserConfig.defaultConfig; var configDir = _path2.default.dirname(configFilePath); var preBootstrapCustomizations = userConfig.preBootstrapCustomizations && _path2.default.resolve(configDir, userConfig.preBootstrapCustomizations); var bootstrapCustomizations = userConfig.bootstrapCustomizations && _path2.default.resolve(configDir, userConfig.bootstrapCustomizations); var appStyles = userConfig.appStyles && _path2.default.resolve(configDir, userConfig.appStyles); return { bootstrapVersion: parseInt(userConfig.bootstrapVersion, 10), loglevel: userConfig.loglevel, preBootstrapCustomizations: preBootstrapCustomizations, bootstrapCustomizations: bootstrapCustomizations, appStyles: appStyles, disableSassSourceMap: userConfig.disableSassSourceMap, disableResolveUrlLoader: userConfig.disableResolveUrlLoader, useFlexbox: userConfig.useFlexbox, useCustomIconFontPath: userConfig.useCustomIconFontPath, extractStyles: extractStyles || (0, _getEnvProp2.default)('extractStyles', userConfig), styleLoaders: (0, _getEnvProp2.default)('styleLoaders', userConfig), styles: (0, _selectUserModules2.default)(userConfig.styles, defaultConfig.styles), scripts: (0, _selectUserModules2.default)(userConfig.scripts, defaultConfig.scripts), configFilePath: configFilePath }; }
Dackng/eh-unmsm-client
node_modules/bootstrap-loader/lib/bootstrap.config.js
JavaScript
mit
5,934
var allTestFiles = []; var TEST_REGEXP = /test\.js$/; var pathToModule = function(path) { return path.replace(/^\/base\//, '').replace(/\.js$/, ''); }; Object.keys(window.__karma__.files).forEach(function(file) { if (TEST_REGEXP.test(file)) { // Normalize paths to RequireJS module names. allTestFiles.push(pathToModule(file)); } }); require.config({ // Karma serves files under /base, which is the basePath from your config file baseUrl: '/base', // example of using shim, to load non AMD libraries (such as underscore and jquery) paths: { 'angular': 'bower_components/angular/angular', 'text': 'bower_components/requirejs-text/text', '_': 'bower_components/underscore/underscore-min' }, shim: { 'angular': { exports: 'angular' }, }, // dynamically load all test files deps: allTestFiles, // we have to kickoff jasmine, as it is asynchronous callback: window.__karma__.start });
Antonio-Lopez/angularjs-requirejs-typescript
app/tests/require-config.js
JavaScript
mit
1,010
/*global blogCategories, $ */ function BlogCategory(blogCategoryElement) { this.element = $vic(blogCategoryElement); if ($vic(blogCategoryElement).data('index')) { this.index = $vic(blogCategoryElement).data('index'); } else { this.index = $vic(blogCategoryElement).children('[data-init="true"]').length; } var lastMaxId = 0; $vic('[data-init=true]').each(function(index, el) { if (!isNaN($vic(el).attr('data-blog-category')) && $vic(el).attr('data-blog-category') > lastMaxId) { lastMaxId = parseInt($vic(el).attr('data-blog-category')); } }); this.id = lastMaxId + 1; this.parentId = $vic(blogCategoryElement).parents('li[role="blogCategory"]').first().data('blog-category'); //get the parent by its id if (this.parentId == null || this.parentId == 0) { this.parent = null; this.parentId = 0; } else { this.parent = blogCategories[this.parentId]; } blogCategories[this.id] = this; } function addBlogCategoryRootItem(el) { var blogCategoryElement = $vic(el).parents('div').first().prev('ul'); // var parentBlogCategory = $vic('#blogCategory-children'); var blogCategory = new BlogCategory(blogCategoryElement); blogCategory.init(); blogCategory.append(); } function addBlogCategoryRow(el) { var blogCategoryElement = $vic(el).parents('span.add_blogCategory_link-container').first().next('ul'); // var parentBlogCategory = $vic(el).parents('[role="blogCategory-item"]').first(); var blogCategory = new BlogCategory(blogCategoryElement); blogCategory.init(); blogCategory.append(); } function deleteBlogCategoryRow(el) { var blogCategory = $vic(el).parents('li[role="blogCategory"]').first(); blogCategories[blogCategory.data('blog-category')] = undefined; blogCategory.remove(); } function initBlogCategories() { var links = $vic('.add_blogCategory_link'); var blogCategory = {id: 0}; //we want the links from the bottom to the top $vic.each(links, function (index, link) { var blogCategoryElement = $vic(link).parents('li[role="blogCategory"]').first(); if (blogCategoryElement.length > 0) { blogCategory = new BlogCategory(blogCategoryElement); blogCategory.update(); } }); //This is exactly the same loop as the one just before //We need to close the previous loop and iterate on a new one because //we operated on the DOM that is updated only when the loop ends. $vic.each(links, function (index, link) { var blogCategoryElement = $vic(link).parents('li[role="blogCategory"]').first(); var blogCategory = blogCategories[blogCategoryElement.attr('data-blog-category')]; var parentBlogCategoryElement = $vic(blogCategoryElement).parents('li[role="blogCategory"]').first(); var parentBlogCategory = blogCategories[parentBlogCategoryElement.attr('data-blog-category')]; if (parentBlogCategory != undefined) { blogCategory.parentId = parentBlogCategory.id; blogCategory.parent = parentBlogCategory; blogCategories[blogCategory.id] = blogCategory; } }); } BlogCategory.prototype.init = function () { var currentBlogCategory = this; var name = '[' + currentBlogCategory.index + ']'; var i = 0; do { i++; if (currentBlogCategory.parent != null) { name = '[' + currentBlogCategory.parent.index + '][children]' + name; } currentBlogCategory = currentBlogCategory.parent; } while (currentBlogCategory != null && i < 10); var newForm = prototype.replace(/\[__name__\]/g, name); var name = name.replace(/\]\[/g, '_'); var name = name.replace(/\]/g, '_'); var name = name.replace(/\[/g, '_'); var newForm = newForm.replace(/__name__/g, name); var newForm = newForm.replace(/__blogCategory_id__/g, this.id); var newForm = newForm.replace(/__blogCategory_index__/g, this.index); this.newForm = $vic.parseHTML(newForm); $vic(this.newForm).attr('data-init', "true"); }; BlogCategory.prototype.update = function () { $vic(this.element).replaceWith(this.element); $vic(this.element).attr('data-blog-category', this.id); $vic(this.element).attr('data-init', "true"); }; BlogCategory.prototype.append = function () { $vic('[data-blog-category="' + this.parentId + '"]').children('[role="blogCategory-container"]').first().append(this.newForm); }; function attachSubmitEventToForm(formSelector, container) { $vic(document).on('submit', formSelector, function(event) { event.preventDefault(); var form = $vic(this); var formData = $vic(form).serializeArray(); formData = $vic.param(formData); if ($vic(form).attr('enctype') == 'multipart/form-data') { var formData = new FormData($vic(form)[0]); var contentType = false; } $vic.ajax({ url : $vic(form).attr('action'), context : document.body, data : formData, type : $vic(form).attr('method'), contentType : 'application/x-www-form-urlencoded; charset=UTF-8', processData : false, async : true, cache : false, success : function(jsonResponse) { if (jsonResponse.hasOwnProperty("url")) { congrat(jsonResponse.message, 10000); window.location.replace(jsonResponse.url); }else{ $vic(container).html(jsonResponse.html); warn(jsonResponse.message, 10000); } } }); }); } attachSubmitEventToForm('#victoire_blog_settings_form', '#victoire-blog-settings'); attachSubmitEventToForm('#victoire_blog_category_form', '#victoire-blog-category');
alexislefebvre/victoire
Bundle/BlogBundle/Resources/public/js/blog.js
JavaScript
mit
5,952
'use strict' const isDirectory = require('is-directory').sync const isFile = require('is-file') function getFarmArgs (args, fileIndex) { const start = 0 const end = fileIndex + 1 return args.slice(start, end) } function getFileArgs (args, fileIndex) { const start = fileIndex + 1 const end = args[args.length] return args.slice(start, end) } function parseArgs (args) { const fileIndex = args.findIndex(arg => isFile(arg) || isDirectory(arg)) return { farm: getFarmArgs(args, fileIndex), file: getFileArgs(args, fileIndex) } } module.exports = parseArgs
Kikobeats/worker-farm-cli
bin/parse-args/index.js
JavaScript
mit
586
(function ($) { $.extend(Backbone.View.prototype, { parse: function(objName) { var self = this, recurse_form = function(object, objName) { $.each(object, function(v,k) { if (k instanceof Object) { object[v] = recurse_form(k, objName + '[' + v + ']'); } else { object[v] = self.$('[name="'+ objName + '[' + v + ']"]').val(); } }); return object; }; this.model.attributes = recurse_form(this.model.attributes, objName); }, populate: function(objName) { var self = this, recurse_obj = function(object, objName) { $.each(object, function (v,k) { if (v instanceof Object) { recurse_obj(v, k); } else if (_.isString(v)) { self.$('[name="'+ objName + '[' + v + ']"]').val(k); } }); }; recurse_obj(this.model.attributes, objName); } }); })(jQuery);
teampl4y4/j2-exchange
web/bundles/j2exchange/js/backbone/form.js
JavaScript
mit
1,175
const getShows = require('./lib/getShows'); module.exports = { getShows };
oliverviljamaa/markus-cinema-client
index.js
JavaScript
mit
76
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("a11yhelp","sv",{title:"Hjälpmedelsinstruktioner",contents:"Hjälpinnehåll. För att stänga denna dialogruta trycker du på ESC.",legend:[{name:"Allmänt",items:[{name:"Editor verktygsfält",legend:"Tryck på ${toolbarFocus} för att navigera till verktygsfältet. Flytta till nästa och föregående verktygsfältsgrupp med TAB och SHIFT+TAB. Flytta till nästa och föregående knapp i verktygsfältet med HÖGERPIL eller VÄNSTERPIL. Tryck SPACE eller ENTER för att aktivera knappen i verktygsfältet."}, {name:"Dialogeditor",legend:"Inuti en dialogruta, tryck TAB för att navigera till nästa fält i dialogrutan, tryck SKIFT+TAB för att flytta till föregående fält, tryck ENTER för att skicka. Du avbryter och stänger dialogen med ESC. För dialogrutor som har flera flikar, tryck ALT+F10 eller TAB för att navigera till fliklistan. med fliklistan vald flytta till nästa och föregående flik med HÖGER- eller VÄNSTERPIL."},{name:"Editor för innehållsmeny",legend:"Tryck på $ {contextMenu} eller PROGRAMTANGENTEN för att öppna snabbmenyn. Flytta sedan till nästa menyalternativ med TAB eller NEDPIL. Flytta till föregående alternativ med SHIFT + TABB eller UPPIL. Tryck Space eller ENTER för att välja menyalternativ. Öppna undermeny av nuvarande alternativ med SPACE eller ENTER eller HÖGERPIL. Gå tillbaka till överordnade menyalternativ med ESC eller VÄNSTERPIL. Stäng snabbmenyn med ESC."}, {name:"Editor för list-box",legend:"Inuti en list-box, gå till nästa listobjekt med TAB eller NEDPIL. Flytta till föregående listobjekt med SHIFT+TAB eller UPPIL. Tryck SPACE eller ENTER för att välja listan alternativet. Tryck ESC för att stänga list-boxen."},{name:"Editor för elementens sökväg",legend:"Tryck på ${elementsPathFocus} för att navigera till verktygsfältet för elementens sökvägar. Flytta till nästa elementknapp med TAB eller HÖGERPIL. Flytta till föregående knapp med SKIFT+TAB eller VÄNSTERPIL. Tryck SPACE eller ENTER för att välja element i redigeraren."}]}, {name:"Kommandon",items:[{name:"Ångra kommando",legend:"Tryck på ${undo}"},{name:"Gör om kommando",legend:"Tryck på ${redo}"},{name:"Kommandot fet stil",legend:"Tryck på ${bold}"},{name:"Kommandot kursiv",legend:"Tryck på ${italic}"},{name:"Kommandot understruken",legend:"Tryck på ${underline}"},{name:"Kommandot länk",legend:"Tryck på ${link}"},{name:"Verktygsfält Dölj kommandot",legend:"Tryck på ${toolbarCollapse}"},{name:"Gå till föregående fokus plats",legend:"Tryck på ${accessPreviousSpace} för att gå till närmast onåbara utrymme före markören, exempel: två intilliggande HR element. Repetera tangentkombinationen för att gå till nästa."}, {name:"Tillgå nästa fokuskommandots utrymme",legend:"Tryck ${accessNextSpace} på för att komma åt den närmaste onåbar fokus utrymme efter cirkumflex, till exempel: två intilliggande HR element. Upprepa tangentkombinationen för att nå avlägsna fokus utrymmen."},{name:"Hjälp om tillgänglighet",legend:"Tryck ${a11yHelp}"},{name:"Klistra in som vanlig text",legend:"Tryck ${pastetext}",legendEdge:"Tryck ${pastetext}, följt av ${paste}"}]}],tab:"Tab",pause:"Paus",capslock:"Caps lock",escape:"Escape",pageUp:"Sida Up", pageDown:"Sida Ned",leftArrow:"Vänsterpil",upArrow:"Uppil",rightArrow:"Högerpil",downArrow:"Nedåtpil",insert:"Infoga",leftWindowKey:"Vänster Windowstangent",rightWindowKey:"Höger Windowstangent",selectKey:"Välj tangent",numpad0:"Nummer 0",numpad1:"Nummer 1",numpad2:"Nummer 2",numpad3:"Nummer 3",numpad4:"Nummer 4",numpad5:"Nummer 5",numpad6:"Nummer 6",numpad7:"Nummer 7",numpad8:"Nummer 8",numpad9:"Nummer 9",multiply:"Multiplicera",add:"Addera",subtract:"Minus",decimalPoint:"Decimalpunkt",divide:"Dividera", 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:"Semikolon",equalSign:"Lika med tecken",comma:"Komma",dash:"Minus",period:"Punkt",forwardSlash:"Snedstreck framåt",graveAccent:"Accent",openBracket:"Öppningsparentes",backSlash:"Snedstreck bakåt",closeBracket:"Slutparentes",singleQuote:"Enkelt Citattecken"});
bgegham/davideluna
public/ckeditor/plugins/a11yhelp/dialogs/lang/sv.js
JavaScript
mit
4,348
// Node.js env expect = require('expect.js'); sha1 = require('../src/sha1.js'); require('./test.js'); delete require.cache[require.resolve('../src/sha1.js')]; delete require.cache[require.resolve('./test.js')]; sha1 = null; // Webpack browser env JS_SHA1_NO_NODE_JS = true; window = global; sha1 = require('../src/sha1.js'); require('./test.js'); delete require.cache[require.resolve('../src/sha1.js')]; delete require.cache[require.resolve('./test.js')]; sha1 = null; // browser env JS_SHA1_NO_NODE_JS = true; JS_SHA1_NO_COMMON_JS = true; window = global; require('../src/sha1.js'); require('./test.js'); delete require.cache[require.resolve('../src/sha1.js')]; delete require.cache[require.resolve('./test.js')]; sha1 = null; // browser AMD JS_SHA1_NO_NODE_JS = true; JS_SHA1_NO_COMMON_JS = true; window = global; define = function (func) { sha1 = func(); require('./test.js'); }; define.amd = true; require('../src/sha1.js');
emn178/js-sha1
tests/node-test.js
JavaScript
mit
940
'use strict'; var expect = require('chai').expect; var stub = require('../../helpers/stub').stub; var commandOptions = require('../../factories/command-options'); var UninstallCommand = require('../../../lib/commands/uninstall-npm'); var Task = require('../../../lib/models/task'); describe('uninstall:npm command', function() { var command, options, tasks, npmInstance; beforeEach(function() { tasks = { NpmUninstall: Task.extend({ init: function() { npmInstance = this; } }) }; options = commandOptions({ settings: {}, project: { name: function() { return 'some-random-name'; }, isEmberCLIProject: function() { return true; } }, tasks: tasks }); stub(tasks.NpmUninstall.prototype, 'run'); command = new UninstallCommand(options); }); afterEach(function() { tasks.NpmUninstall.prototype.run.restore(); }); it('initializes npm task with ui, project and analytics', function() { return command.validateAndRun([]).then(function() { expect(npmInstance.ui, 'ui was set'); expect(npmInstance.project, 'project was set'); expect(npmInstance.analytics, 'analytics was set'); }); }); describe('with no args', function() { it('runs the npm uninstall task with no packages, save-dev true and save-exact true', function() { return command.validateAndRun([]).then(function() { var npmRun = tasks.NpmUninstall.prototype.run; expect(npmRun.called).to.equal(1, 'expected npm uninstall run was called once'); expect(npmRun.calledWith[0][0]).to.deep.equal({ packages: [], 'save-dev': true, 'save-exact': true }, 'expected npm uninstall called with no packages, save-dev true, and save-exact true'); }); }); }); describe('with args', function() { it('runs the npm uninstall task with given packages', function() { return command.validateAndRun(['moment', 'lodash']).then(function() { var npmRun = tasks.NpmUninstall.prototype.run; expect(npmRun.called).to.equal(1, 'expected npm uninstall run was called once'); expect(npmRun.calledWith[0][0]).to.deep.equal({ packages: ['moment', 'lodash'], 'save-dev': true, 'save-exact': true }, 'expected npm uninstall called with given packages, save-dev true, and save-exact true'); }); }); }); });
zanemayo/ember-cli
tests/unit/commands/uninstall-npm-test.js
JavaScript
mit
2,523
(function($) { // Some vars var template = '/field/link'; // Tabs $(document).on('click', '.adminContext .tabs li', function() { // Some vars var $admincontext = $(this).parents('.adminContext'); var $tabs = $admincontext.find('.tabs'); var $panels = $admincontext.find('.panels'); var currentTab = $(this).data('tab'); // Close all tabs & panels $tabs.find('>li').attr('class', 'off'); $panels.find('>div').attr('class', 'off'); // Open the right one $tabs.find('>li[data-tab="'+currentTab+'"]').attr('class', 'on'); $panel = $panels.find('>div[data-panel="'+currentTab+'"]'); $panel.attr('class', 'on'); // Init the panel (cameltoe function initCurrenttab) var function_name = 'init'+currentTab.charAt(0).toUpperCase() + currentTab.slice(1); window[function_name]($panel); }); // Init internal linking initInternal = function(panel) { // restore selection when blur input $('.adminContext').on('blur', 'input[type="search"]', function() { restoreSelection(selRange); // selRange = false; }); // Send Internal link $(document).on('click', '.adminContext[data-template="/field/link"] [data-panel="internal"] [data-item] button', function(e) { if (selRange !== null) { restoreSelection(selRange); var link = $(this).parent().data('item'); // console.log(link) document.execCommand('CreateLink', false, link); closeContext(template); selRange = null; }; }); // Refine item lists $('.adminContext[data-template="/field/link"] [data-panel="internal"] input[type="search"]').each(function() { // Some vars var $input = $(this); var item = $input.data('item'); var $target = $(this).next('ul'); // Search as you type $input.searchasyoutype( { app:'sirtrevor', template:'/field/link.internal', param:'{"item":"'+item+'"}', target:$target, }) // Start with something .trigger('input'); }); } // Init external linking initExternal = function(panel) { // Send external link $(document).on('click', '.adminContext[data-template="/field/link"] [data-panel="external"] button.done', function() { // Get the value from the iframe var link = $(this).parent().find('iframe').contents().find('input').val(); // Good link if(link && link.length > 0) { var link_regex = /(ftp|http|https):\/\/./; if (!link_regex.test(link)) link = "http://" + link; document.execCommand('CreateLink', false, link); closeContext(template); } // Bad link else console.log('That is not a valid URL, buddy'); }); } // Init media linking initMedia = function(panel) { panel.ajx( { app:'media', template:'admin', }, { done:function() { // Override "Edit a media"... $('#mediaLibrary').off('click', 'a.file'); // ...with "send the link" $(document).on('click', '.adminContext[data-template="/field/link"] #mediaLibrary a.file', function() { url = $(this).parent().data('url'); // Send link document.execCommand('CreateLink', false, url); closeContext(template); }); } }); } // Open one by default $('.adminContext .tabs li[data-tab="internal"]').trigger('click'); })(jQuery);
hands-agency/grandcentral
grandcentral/sirtrevor/template/field/js/link.js
JavaScript
mit
3,216
'use strict'; const blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers'); const setupTestHooks = blueprintHelpers.setupTestHooks; const emberNew = blueprintHelpers.emberNew; const emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy; const setupPodConfig = blueprintHelpers.setupPodConfig; const expectError = require('../helpers/expect-error'); const EOL = require('os').EOL; const chai = require('ember-cli-blueprint-test-helpers/chai'); const expect = chai.expect; const setupTestEnvironment = require('../helpers/setup-test-environment'); const enableModuleUnification = setupTestEnvironment.enableModuleUnification; describe('Blueprint: mixin', function() { setupTestHooks(this); describe('in app', function() { beforeEach(function() { return emberNew(); }); it('mixin foo', function() { return emberGenerateDestroy(['mixin', 'foo'], _file => { expect(_file('app/mixins/foo.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo-test.js')).to.contain( "import FooMixin from 'my-app/mixins/foo';" ); }); }); it('mixin foo/bar', function() { return emberGenerateDestroy(['mixin', 'foo/bar'], _file => { expect(_file('app/mixins/foo/bar.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo/bar-test.js')).to.contain( "import FooBarMixin from 'my-app/mixins/foo/bar';" ); }); }); it('mixin foo/bar/baz', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz'], _file => { expect(_file('tests/unit/mixins/foo/bar/baz-test.js')).to.contain( "import FooBarBazMixin from 'my-app/mixins/foo/bar/baz';" ); }); }); it('mixin foo --pod', function() { return emberGenerateDestroy(['mixin', 'foo', '--pod'], _file => { expect(_file('app/mixins/foo.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo-test.js')).to.contain( "import FooMixin from 'my-app/mixins/foo';" ); }); }); it('mixin foo/bar --pod', function() { return emberGenerateDestroy(['mixin', 'foo/bar', '--pod'], _file => { expect(_file('app/mixins/foo/bar.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo/bar-test.js')).to.contain( "import FooBarMixin from 'my-app/mixins/foo/bar';" ); }); }); it('mixin foo/bar/baz --pod', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz', '--pod'], _file => { expect(_file('tests/unit/mixins/foo/bar/baz-test.js')).to.contain( "import FooBarBazMixin from 'my-app/mixins/foo/bar/baz';" ); }); }); describe('with podModulePrefix', function() { beforeEach(function() { setupPodConfig({ podModulePrefix: true }); }); it('mixin foo --pod', function() { return emberGenerateDestroy(['mixin', 'foo', '--pod'], _file => { expect(_file('app/mixins/foo.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo-test.js')).to.contain( "import FooMixin from 'my-app/mixins/foo';" ); }); }); it('mixin foo/bar --pod', function() { return emberGenerateDestroy(['mixin', 'foo/bar', '--pod'], _file => { expect(_file('app/mixins/foo/bar.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo/bar-test.js')).to.contain( "import FooBarMixin from 'my-app/mixins/foo/bar';" ); }); }); }); }); describe('in app - module unification', function() { enableModuleUnification(); beforeEach(function() { return emberNew(); }); it('mixin foo', function() { return emberGenerateDestroy(['mixin', 'foo'], _file => { expect(_file('src/mixins/foo.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('src/mixins/foo-test.js')).to.contain( "import FooMixin from 'my-app/mixins/foo';" ); }); }); it('mixin foo/bar', function() { return emberGenerateDestroy(['mixin', 'foo/bar'], _file => { expect(_file('src/mixins/foo/bar.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('src/mixins/foo/bar-test.js')).to.contain( "import FooBarMixin from 'my-app/mixins/foo/bar';" ); }); }); it('mixin foo/bar/baz', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz'], _file => { expect(_file('src/mixins/foo/bar/baz.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('src/mixins/foo/bar/baz-test.js')).to.contain( "import FooBarBazMixin from 'my-app/mixins/foo/bar/baz';" ); }); }); it('mixin foo --pod', function() { return expectError( emberGenerateDestroy(['service', 'foo', '--pod']), "Pods aren't supported within a module unification app" ); }); }); describe('in addon', function() { beforeEach(function() { return emberNew({ target: 'addon' }); }); it('mixin foo', function() { return emberGenerateDestroy(['mixin', 'foo'], _file => { expect(_file('addon/mixins/foo.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo-test.js')).to.contain( "import FooMixin from 'my-addon/mixins/foo';" ); expect(_file('app/mixins/foo.js')).to.not.exist; }); }); it('mixin foo/bar', function() { return emberGenerateDestroy(['mixin', 'foo/bar'], _file => { expect(_file('addon/mixins/foo/bar.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo/bar-test.js')).to.contain( "import FooBarMixin from 'my-addon/mixins/foo/bar';" ); expect(_file('app/mixins/foo/bar.js')).to.not.exist; }); }); it('mixin foo/bar/baz', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz'], _file => { expect(_file('addon/mixins/foo/bar/baz.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo/bar/baz-test.js')).to.contain( "import FooBarBazMixin from 'my-addon/mixins/foo/bar/baz';" ); expect(_file('app/mixins/foo/bar/baz.js')).to.not.exist; }); }); it('mixin foo/bar/baz --dummy', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz', '--dummy'], _file => { expect(_file('tests/dummy/app/mixins/foo/bar/baz.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('addon/mixins/foo/bar/baz.js')).to.not.exist; }); }); }); describe('in addon - module unification', function() { enableModuleUnification(); beforeEach(function() { return emberNew({ target: 'addon' }); }); it('mixin foo', function() { return emberGenerateDestroy(['mixin', 'foo'], _file => { expect(_file('src/mixins/foo.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('src/mixins/foo-test.js')).to.contain( "import FooMixin from 'my-addon/mixins/foo';" ); }); }); it('mixin foo/bar', function() { return emberGenerateDestroy(['mixin', 'foo/bar'], _file => { expect(_file('src/mixins/foo/bar.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('src/mixins/foo/bar-test.js')).to.contain( "import FooBarMixin from 'my-addon/mixins/foo/bar';" ); }); }); it('mixin foo/bar/baz', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz'], _file => { expect(_file('src/mixins/foo/bar/baz.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('src/mixins/foo/bar/baz-test.js')).to.contain( "import FooBarBazMixin from 'my-addon/mixins/foo/bar/baz';" ); }); }); it('mixin foo/bar/baz --dummy', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz', '--dummy'], _file => { expect(_file('tests/dummy/src/mixins/foo/bar/baz.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('src/mixins/foo/bar/baz.js')).to.not.exist; }); }); }); describe('in in-repo-addon', function() { beforeEach(function() { return emberNew({ target: 'in-repo-addon' }); }); it('mixin foo --in-repo-addon=my-addon', function() { return emberGenerateDestroy(['mixin', 'foo', '--in-repo-addon=my-addon'], _file => { expect(_file('lib/my-addon/addon/mixins/foo.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo-test.js')).to.contain( "import FooMixin from 'my-addon/mixins/foo';" ); }); }); it('mixin foo/bar --in-repo-addon=my-addon', function() { return emberGenerateDestroy(['mixin', 'foo/bar', '--in-repo-addon=my-addon'], _file => { expect(_file('lib/my-addon/addon/mixins/foo/bar.js')) .to.contain("import Mixin from '@ember/object/mixin';") .to.contain(`export default Mixin.create({${EOL}});`); expect(_file('tests/unit/mixins/foo/bar-test.js')).to.contain( "import FooBarMixin from 'my-addon/mixins/foo/bar';" ); }); }); it('mixin foo/bar/baz --in-repo-addon=my-addon', function() { return emberGenerateDestroy(['mixin', 'foo/bar/baz', '--in-repo-addon=my-addon'], _file => { expect(_file('tests/unit/mixins/foo/bar/baz-test.js')).to.contain( "import FooBarBazMixin from 'my-addon/mixins/foo/bar/baz';" ); }); }); }); });
kellyselden/ember.js
node-tests/blueprints/mixin-test.js
JavaScript
mit
11,394
//Controller app.controller('NavbarController', function($scope, $location) { //Set active navigation bar tab $scope.isActive = function (viewLocation) { return viewLocation === $location.path(); }; });
Vmlweb/MEAN-AngularJS-1
client/controller.js
JavaScript
mit
218
{ "name": "editor.js", "url": "https://github.com/ktkaushik/editor.git" }
bower/components
packages/editor.js
JavaScript
mit
78
'use strict'; const dotenv = require('dotenv'); dotenv.load(); const express = require('express'); const debug = require('debug')('ways2go:server'); const morgan = require('morgan'); const cors = require('cors'); const mongoose = require('mongoose'); const Promise = require('bluebird'); const apiRouter = require('./route/api-router.js'); const wayRouter = require('./route/way-router.js'); const userRouter = require('./route/user-router.js'); const profileRouter = require('./route/profile-router.js'); const messageRouter = require('./route/message-router.js'); const reviewRouter = require('./route/review-router.js'); const errors = require('./lib/error-middleware.js'); const PORT = process.env.PORT || 3000; const app = express(); mongoose.Promise = Promise; mongoose.connect(process.env.MONGODB_URI); app.use(cors()); app.use(morgan('dev')); app.use(userRouter); app.use(apiRouter); app.use(wayRouter); app.use(profileRouter); app.use(reviewRouter); app.use(messageRouter); app.use(errors); const server = module.exports = app.listen(PORT, () => { debug(`Server's up on PORT: ${PORT}`); }); server.isRunning = true;
dkulp23/ways2goAPI
server.js
JavaScript
mit
1,137
var conf = require('../config/'); var sha = require('object-hash'); var uuid = require('node-uuid'); var _ = require('underscore'); _.mixin(require('underscore.deep')); var url = require('url'); var db; var env = exports.env = conf.name; var similarFilter = ['type', 'location', 'description.contactnumber']; var readonly = exports.readonly = Number(process.env.KAHA_READONLY) || 0; exports.init = function(dbObj){ db = dbObj; }; /** * Description: mixin for increment * and decrement counter * * @method flagcounter * @param dbQry{Function} query to be performed * @return Function */ var flagcounter = exports.flagcounter = function(dbQry) { return function(req, res, next) { if (enforceReadonly(res)) { return; } var obj = { "uuid": req.params.id, "flag": req.query.flag }; dbQry(req, res, obj); }; }; /** * Description: When the server * needs to enable read-only * mode to stop writing on db * * @method enforceReadonly * @param res{Object} * @return Boolean */ var enforceReadonly = exports.enforceReadonly = function(res) { if (readonly) { res.status(503).send('Service Unavailable'); return true; } return false; }; /** * Description: Standard Callback * To stop duplication across * all page * * @method stdCb * @param err{Boolean}, reply{Array} * @return [Boolean] */ var stdCb = exports.stdCb = function(err, reply) { if (err) { return err; } }; /** * Description: Get Everything * * @method getAllFromDb * @param Function * @return N/A */ exports.getEverything = function(cb) { var results = []; var multi = db.multi(); db.keys('*', function(err, reply) { if (err) { return err; } reply.forEach(function(key) { multi.get(key, stdCb); }); multi.exec(function(err, replies) { if (err) { return err; } var result = _.map(replies, function(rep) { return JSON.parse(rep); }); var keyVals = _.object(reply, result); cb(null, keyVals); }); }); }; /** * Description: DRYing * * @method getAllFromDb * @param cb{Function} * @return n/a */ var getAllFromDb = exports.getAllFromDb = function(cb) { var results = []; var multi = db.multi(); db.keys('*', function(err, reply) { if (err) { return err; } db.keys('*:*', function(err, reply2) { if (err) { return err; } _.each(_.difference(reply, reply2), function(key) { multi.get(key, stdCb); }); multi.exec(function(err, replies) { if (err) { return err; } var result = _.map(replies, function(rep) { return JSON.parse(rep); }); cb(null, result); }); }); }); }; /** * Description: Only for individual * Object * * @method getSha * @param obj{Object}, shaFilters{Array} * @return String */ var getSha = exports.getSha = function(obj, shaFilters) { var key, extract = {}; if (Array.isArray(shaFilters)) { shaFilters.forEach(function(filter) { var selectedObj = _.deepPick(obj, [filter]); _.extend(extract, selectedObj); }); } return sha(extract); }; /** * Description: Similar to getSha * but for array of Objects * * @method getShaAllWithObjs * @param objs{Object} * @return Array */ var getShaAllWithObjs = exports.getShaAllWithObjs = function(objs) { var hashes = []; objs.forEach(function(result) { var tmpObj = {}; tmpObj[getSha(result, similarFilter)] = result; hashes.push(tmpObj); }); return hashes; }; /** * Description: No filter * * @method methodName * @param type * @return type */ var getShaAll = exports.getShaAll = function(objs, similarFilter) { var hashes = []; objs.forEach(function(result) { hashes.push(getSha(result, similarFilter)); }); return hashes; }; /** * Description: * * @method methodName * @param type * @return type */ var getSimilarItems = exports.getSimilarItems = function(arrayObj, shaKey) { return _.map(_.filter(getShaAllWithObjs(arrayObj), function(obj) { return _.keys(obj)[0] === shaKey; }), function(obj) { return _.values(obj)[0]; }); }; var getUniqueUserID = exports.getUniqueUserID = function(req) { var proxies = req.headers['x-forwarded-for'] || ''; var ip = _.last(proxies.split(',')) || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; return ip; }; /** * Description: Does single or bulk post * * @method rootPost * @param req(Object), res(Object), next(Function) * @return n/a */ var rootPost = exports.rootPost = function(req, res, next) { /* give each entry a unique id */ function entry(obj) { var data_uuid = uuid.v4(); obj.uuid = data_uuid; obj = dateEntry(obj); if (typeof obj.verified === 'undefined') { obj.verified = false; } multi.set(data_uuid, JSON.stringify(obj), function(err, reply) { if (err) { return err; } return reply; }); } function dateEntry(obj) { var today = new Date(); if (!(obj.date && obj.date.created)) { obj.date = { 'created': today.toUTCString(), 'modified': today.toUTCString() }; } return obj; } function insertToDb(res) { multi.exec(function(err, replies) { if (err) { console.log(err); res.status(500).send(err); return; } //console.log(JSON.stringify(replies)); if (replies) { res.send(replies); } }); } if (enforceReadonly(res)) { return; } var ref = (req.headers && req.headers.referer) || false; //No POST request allowed from other sources //TODO probably need to fix this for prod docker if (ref) { var u = url.parse(ref); var hostname = u && u.hostname; var environment = env.toLowerCase(); if (hasPostAccess(hostname, environment)) { var okResult = []; var multi = db.multi(); var data = req.body; if (Array.isArray(data)) { data.forEach(function(item, index) { entry(item); insertToDb(res); }); } else { getAllFromDb(function(err, results) { var similarItems = getSimilarItems(results, getSha(data, similarFilter)); var query = req.query.confirm || "no"; if (similarItems.length > 0 && (query.toLowerCase() === "no")) { res.send(similarItems); } else { entry(data); insertToDb(res); } }); } } else { res.status(403).send('Invalid Origin'); } } else { res.status(403).send('Invalid Origin'); } }; function hasPostAccess(currDomain, currEnv){ var allowedDomains= ["kaha.co", "demokaha.herokuapp.com"]; var allowedEnvs = ["dev", "stage"]; return checkDomain(allowedDomains, currDomain) || checkEnvs(allowedEnvs, currEnv); } /** * Description: Checks if it's the right domains * * @method checkDomain * @param {Array}, {String} * @return {Boolean} */ function checkDomain(allowedDomains, currDomain){ //check sub-domains and prefixes like `www` too return allowedDomains.some(function(domain){ return ~currDomain.indexOf(domain); }); } /** * Description: Checks the right environment * for right access * @method checkEnvs * @param {Array}, {String} * @return {Boolean} */ function checkEnvs(allowedEnvs, currEnv){ return ~allowedEnvs.indexOf(currEnv); }
sinkingshriek/kaha
routes/utils.js
JavaScript
mit
7,537
(function () { angular .module('keylistener') .directive('keylistener', keylistener); function keylistener($document, $rootScope, $ionicPopup) { var directive = { restrict: 'A', link: link }; return directive; function link() { var captured = []; $document.bind('keydown', function (e) { $rootScope.$broadcast('keydown', e); $rootScope.$broadcast('keydown:' + e.which, e); // check nerd captured.push(e.which) if (arrayEndsWith(captured, [38, 38, 40, 40, 37, 39, 37, 39, 66, 65])) nerd(); }); } function arrayEndsWith(a, b) { a = a.slice(a.length - b.length, a.length); if (a.length !== b.length) return; for (var i = 0; i < a.length; ++i) { if (a[i] !== b[i]) return false; } return true; } function nerd() { captured = []; document.getElementsByTagName('body')[0].className += ' nerd'; $ionicPopup.alert({title: 'You\'re a nerd 🤓', buttons: [{text: 'I know', type: 'button-positive'}]}); } } })();
dank-meme-dealership/foosey
frontend/www/js/keylistener/keylistener.directive.js
JavaScript
mit
1,086
import { highlight } from "../../../helpers/highlight" import { module, test } from "qunit" module("Unit | Helper | highlight") test("it works", function(assert) { let result result = highlight([], { phrase: "Something", part: "Some" }) assert.equal( result, '<mark class="en-select-option-highlight">Some</mark>thing' ) result = highlight([], { phrase: "No match", part: "Some" }) assert.equal(result, "No match") result = highlight([], { phrase: "John Doe", part: "John D" }) assert.equal( result, '<mark class="en-select-option-highlight">John</mark> <mark class="en-select-option-highlight">D</mark>oe' ) result = highlight([], { phrase: "John Doe", part: "John Doe" }) assert.equal( result, '<mark class="en-select-option-highlight">John</mark> <mark class="en-select-option-highlight">Doe</mark>' ) result = highlight([], { phrase: "John Doe", part: "John Doe" }) assert.equal( result, '<mark class="en-select-option-highlight">John</mark> <mark class="en-select-option-highlight">Doe</mark>' ) result = highlight([], { phrase: "John Doe", part: "John Doe" }) assert.equal( result, '<mark class="en-select-option-highlight">John</mark> <mark class="en-select-option-highlight">Doe</mark>' ) result = highlight([], { phrase: "In a world far away", part: "a" }) assert.equal( result, 'In <mark class="en-select-option-highlight">a</mark> world f<mark class="en-select-option-highlight">a</mark>r <mark class="en-select-option-highlight">a</mark>w<mark class="en-select-option-highlight">a</mark>y' ) result = highlight([], { phrase: "In a world far away", part: "" }) assert.equal( result, 'In a world far away' ) })
swastik/en-select
tests/unit/helpers/highlight-test.js
JavaScript
mit
1,823
var EventUtil = { addHandler: function(element, type, handler){ if (element.addEventListener){ element.addEventListener(type, handler, false); } else if (element.attachEvent){ element.attachEvent("on" + type, handler); } else { element["on" + type] = handler; } }, getButton: function(event){ if (document.implementation.hasFeature("MouseEvents", "2.0")){ return event.button; } else { switch(event.button){ case 0: case 1: case 3: case 5: case 7: return 0; case 2: case 6: return 2; case 4: return 1; } } }, getCharCode: function(event){ if (typeof event.charCode == "number"){ return event.charCode; } else { return event.keyCode; } }, getClipboardText: function(event){ var clipboardData = (event.clipboardData || window.clipboardData); return clipboardData.getData("text"); }, getEvent: function(event){ return event ? event : window.event; }, getRelatedTarget: function(event){ if (event.relatedTarget){ return event.relatedTarget; } else if (event.toElement){ return event.toElement; } else if (event.fromElement){ return event.fromElement; } else { return null; } }, getTarget: function(event){ if (event.target){ return event.target; } else { return event.srcElement; } }, getWheelDelta: function(event){ if (event.wheelDelta){ return (client.opera && client.opera < 9.5 ? -event.wheelDelta : event.wheelDelta); } else { return -event.detail * 40; } }, preventDefault: function(event){ if (event.preventDefault){ event.preventDefault(); } else { event.returnValue = false; } }, removeHandler: function(element, type, handler){ if (element.removeEventListener){ element.removeEventListener(type, handler, false); } else if (element.detachEvent){ element.detachEvent("on" + type, handler); } else { element["on" + type] = null; } }, setClipboardText: function(event, value){ if (event.clipboardData){ event.clipboardData.setData("text/plain", value); } else if (window.clipboardData){ window.clipboardData.setData("text", value); } }, stopPropagation: function(event){ if (event.stopPropagation){ event.stopPropagation(); } else { event.cancelBubble = true; } } }; //back button function goBack() { window.history.back(); } // yes, this does what you think it does! $( document ).ready(function() { window.setInterval(function(){ $('.blink').toggle(); }, 550); }); // this sets the default sprint number if its not changed on the admin page. var defaultSprint = function() { var sprintNow = JSON.parse(localStorage.getItem('sprint-number')); console.log(sprintNow); if (sprintNow == null) { sprintNow = "programmeTen"; localStorage.setItem("sprint-number", JSON.stringify(sprintNow)); } else { } }; defaultSprint(); // This removes the breadcrumbs from sprint 10 (the navigation version). The breadcrumb on earlier versions is broken var breadyCrumb = function() { var whatSprint = JSON.parse(localStorage.getItem('sprint-number')); console.log('what sprint is ' + whatSprint); if (whatSprint == "sprint10") { $('<style>.breadcrumbs ol li a { display:none;}</style>').appendTo('head'); } else {} }; breadyCrumb(); // This sets a default company name if its not been set on the proto admin page var CompanyName = function() { var compName = JSON.parse(localStorage.getItem('company-name-header')); console.log(compName); if (compName == null) { compName = "Acme Ltd"; localStorage.setItem("company-name-header", JSON.stringify(compName)); } else { } }; CompanyName(); /* To determine if the to do list has been done - only dates works for now - this breaks because of the URl change below if it is in the page...it should live in /sprint11/contracts/new-contract/provider-interface/add-apprenticeship */ //$( document ).ready(function() { //var addedOrNor = function() { // var hasDatesAdded = JSON.parse(localStorage.getItem('apprenticeship-dates-added')); // console.log(hasDatesAdded) // if (hasDatesAdded == "yes") { // $( ".datesComplete" ).removeClass( "rj-dont-display" ); // $( ".datesToDo" ).addClass( "rj-dont-display" ); // var hasDatesAdded = 'no'; // localStorage.setItem("apprenticeship-dates-added", JSON.stringify(hasDatesAdded)); // } else { // $( ".datesComplete" ).addClass( "rj-dont-display" ); // } //}; //addedOrNor(); //}); /* To determine if an apprenticeship has been added to the contract - this breaks because of the URl change below if it is in the page...it should live in /sprint11/contracts/new-contract/provider-interface/individual-contract */ // This has moved to javascripts/das/commitment-1.0.js // $( document ).ready(function() { // var whereNow = function() { // var hasAppAdded = JSON.parse(localStorage.getItem('apprenticeship-added')); // // if (hasAppAdded == "yes") { // $( "#no-apprenticeships" ).addClass( "rj-dont-display" ); // var isAddedApp = 'no'; // localStorage.setItem("apprenticeship-added", JSON.stringify(isAddedApp)); // // // } else { // $( "#apprenticeships" ).addClass( "rj-dont-display" ); // // } // }; // whereNow(); // // }); // // $( document ).ready(function() { // var bulkUpload = function() { // var hasBulkUpload = JSON.parse(localStorage.getItem('apprenticeship-added.bulk-upload')); // if (hasBulkUpload == "yes") { // $( "#no-apprenticeships" ).addClass( "rj-dont-display" ); // $( "#no-apprenticeships" ).addClass( "rj-dont-display" ); // $( "#apprenticeships-bulk" ).removeClass( "rj-dont-display" ); // var hasBulkUpload = 'no'; // localStorage.setItem("apprenticeship-added.bulk-upload", JSON.stringify(hasBulkUpload)); // } else { // $( "#apprenticeships-bulk" ).addClass( "rj-dont-display" ); // // } // }; // bulkUpload(); // // }); /* To determine whether the commitments in progress page should show the confirmation or not (i.e. have you just completed something) - this breaks because of the URl change below if it is in the page...it should live in /contracts/provider-in-progress? */ $( document ).ready(function() { var showDoneAlert = function() { var isAlertShowing = JSON.parse(localStorage.getItem('commitments.providerAlert')); if (isAlertShowing == "yes") { $( "#showDoneAlert" ).removeClass( "rj-dont-display" ); var isAlertShowing = 'no'; localStorage.setItem("commitments.providerAlert", JSON.stringify(isAlertShowing)); } else { // $( "#showDoneAlert" ).addClass( "rj-dont-display" ); } }; showDoneAlert(); }); //This swaps out the URL to the sprint chosen in the admin tool. The phrase it is searching for and replacing is in includes/sprint-link.html // Want this to run last as it was breaking other things... $(document).ready(function() { var urlToBeChanged = JSON.parse(localStorage.getItem('sprint-number')); $("body").html($("body").html().replace(/change-me-url/g, urlToBeChanged)); });
SkillsFundingAgency/das-alpha-ui
public/javascripts/custom.js
JavaScript
mit
7,807
export default `flf2a$ 6 5 17 -1 16 "Sub-Zero" font by Sub-Zero ============================== -> Conversion to FigLet font by MEPH. (Part of ASCII Editor Service Pack I) (http://studenten.freepage.de/meph/ascii/ascii/editor/_index.htm) -> Defined: ASCII code alphabet -> Uppercase characters only. ScarecrowsASCIIArtArchive1.0.txt From: "Sub-Zero" <[email protected]> "Here's a font I've been working on lately. Can someone make the V, Q, and X look better? Also, the B, P, and R could use an improvement too. Oh, here it is." $$$@ $$$@ $$$@ $$$@ $$$@ $$$@@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ ______ @ /\\ __ \\ @ \\ \\ __ \\ @ \\ \\_\\ \\_\\ @ \\/_/\\/_/ @ @@ ______ @ /\\ == \\ @ \\ \\ __< @ \\ \\_____\\ @ \\/_____/ @ @@ ______ @ /\\ ___\\ @ \\ \\ \\____ @ \\ \\_____\\ @ \\/_____/ @ @@ _____ @ /\\ __-. @ \\ \\ \\/\\ \\ @ \\ \\____- @ \\/____/ @ @@ ______ @ /\\ ___\\ @ \\ \\ __\\ @ \\ \\_____\\ @ \\/_____/ @ @@ ______ @ /\\ ___\\ @ \\ \\ __\\ @ \\ \\_\\ @ \\/_/ @ @@ ______ @ /\\ ___\\ @ \\ \\ \\__ \\ @ \\ \\_____\\ @ \\/_____/ @ @@ __ __ @ /\\ \\_\\ \\ @ \\ \\ __ \\ @ \\ \\_\\ \\_\\ @ \\/_/\\/_/ @ @@ __ @ /\\ \\ @ \\ \\ \\ @ \\ \\_\\ @ \\/_/ @ @@ __ @ /\\ \\ @ _\\_\\ \\ @ /\\_____\\ @ \\/_____/ @ @@ __ __ @ /\\ \\/ / @ \\ \\ _"-. @ \\ \\_\\ \\_\\ @ \\/_/\\/_/ @ @@ __ @ /\\ \\ @ \\ \\ \\____ @ \\ \\_____\\ @ \\/_____/ @ @@ __ __ @ /\\ "-./ \\ @ \\ \\ \\-./\\ \\ @ \\ \\_\\ \\ \\_\\ @ \\/_/ \\/_/ @ @@ __ __ @ /\\ "-.\\ \\ @ \\ \\ \\-. \\ @ \\ \\_\\\\"\\_\\ @ \\/_/ \\/_/ @ @@ ______ @ /\\ __ \\ @ \\ \\ \\/\\ \\ @ \\ \\_____\\ @ \\/_____/ @ @@ ______ @ /\\ == \\ @ \\ \\ _-/ @ \\ \\_\\ @ \\/_/ @ @@ ______ @ /\\ __ \\ @ \\ \\ \\/\\_\\ @ \\ \\___\\_\\ @ \\/___/_/ @ @@ ______ @ /\\ == \\ @ \\ \\ __< @ \\ \\_\\ \\_\\ @ \\/_/ /_/ @ @@ ______ @ /\\ ___\\ @ \\ \\___ \\ @ \\/\\_____\\ @ \\/_____/ @ @@ ______ @ /\\__ _\\ @ \\/_/\\ \\/ @ \\ \\_\\ @ \\/_/ @ @@ __ __ @ /\\ \\/\\ \\ @ \\ \\ \\_\\ \\ @ \\ \\_____\\ @ \\/_____/ @ @@ __ __ @ /\\ \\ / / @ \\ \\ \\'/ @ \\ \\__| @ \\/_/ @ @@ __ __ @ /\\ \\ _ \\ \\ @ \\ \\ \\/ ".\\ \\ @ \\ \\__/".~\\_\\ @ \\/_/ \\/_/ @ @@ __ __ @ /\\_\\_\\_\\ @ \\/_/\\_\\/_ @ /\\_\\/\\_\\ @ \\/_/\\/_/ @ @@ __ __ @ /\\ \\_\\ \\ @ \\ \\____ \\ @ \\/\\_____\\ @ \\/_____/ @ @@ ______ @ /\\___ \\ @ \\/_/ /__ @ /\\_____\\ @ \\/_____/ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ ______ @ /\\ __ \\ @ \\ \\ __ \\ @ \\ \\_\\ \\_\\ @ \\/_/\\/_/ @ @@ ______ @ /\\ == \\ @ \\ \\ __< @ \\ \\_____\\ @ \\/_____/ @ @@ ______ @ /\\ ___\\ @ \\ \\ \\____ @ \\ \\_____\\ @ \\/_____/ @ @@ _____ @ /\\ __-. @ \\ \\ \\/\\ \\ @ \\ \\____- @ \\/____/ @ @@ ______ @ /\\ ___\\ @ \\ \\ __\\ @ \\ \\_____\\ @ \\/_____/ @ @@ ______ @ /\\ ___\\ @ \\ \\ __\\ @ \\ \\_\\ @ \\/_/ @ @@ ______ @ /\\ ___\\ @ \\ \\ \\__ \\ @ \\ \\_____\\ @ \\/_____/ @ @@ __ __ @ /\\ \\_\\ \\ @ \\ \\ __ \\ @ \\ \\_\\ \\_\\ @ \\/_/\\/_/ @ @@ __ @ /\\ \\ @ \\ \\ \\ @ \\ \\_\\ @ \\/_/ @ @@ __ @ /\\ \\ @ _\\_\\ \\ @ /\\_____\\ @ \\/_____/ @ @@ __ __ @ /\\ \\/ / @ \\ \\ _"-. @ \\ \\_\\ \\_\\ @ \\/_/\\/_/ @ @@ __ @ /\\ \\ @ \\ \\ \\____ @ \\ \\_____\\ @ \\/_____/ @ @@ __ __ @ /\\ "-./ \\ @ \\ \\ \\-./\\ \\ @ \\ \\_\\ \\ \\_\\ @ \\/_/ \\/_/ @ @@ __ __ @ /\\ "-.\\ \\ @ \\ \\ \\-. \\ @ \\ \\_\\\\"\\_\\ @ \\/_/ \\/_/ @ @@ ______ @ /\\ __ \\ @ \\ \\ \\/\\ \\ @ \\ \\_____\\ @ \\/_____/ @ @@ ______ @ /\\ == \\ @ \\ \\ _-/ @ \\ \\_\\ @ \\/_/ @ @@ ______ @ /\\ __ \\ @ \\ \\ \\/\\_\\ @ \\ \\___\\_\\ @ \\/___/_/ @ @@ ______ @ /\\ == \\ @ \\ \\ __< @ \\ \\_\\ \\_\\ @ \\/_/ /_/ @ @@ ______ @ /\\ ___\\ @ \\ \\___ \\ @ \\/\\_____\\ @ \\/_____/ @ @@ ______ @ /\\__ _\\ @ \\/_/\\ \\/ @ \\ \\_\\ @ \\/_/ @ @@ __ __ @ /\\ \\/\\ \\ @ \\ \\ \\_\\ \\ @ \\ \\_____\\ @ \\/_____/ @ @@ __ __ @ /\\ \\ / / @ \\ \\ \\'/ @ \\ \\__| @ \\/_/ @ @@ __ __ @ /\\ \\ _ \\ \\ @ \\ \\ \\/ ".\\ \\ @ \\ \\__/".~\\_\\ @ \\/_/ \\/_/ @ @@ __ __ @ /\\_\\_\\_\\ @ \\/_/\\_\\/_ @ /\\_\\/\\_\\ @ \\/_/\\/_/ @ @@ __ __ @ /\\ \\_\\ \\ @ \\ \\____ \\ @ \\/\\_____\\ @ \\/_____/ @ @@ ______ @ /\\___ \\ @ \\/_/ /__ @ /\\_____\\ @ \\/_____/ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ @ @ @ @ @ @@ `
patorjk/figlet.js
importable-fonts/Sub-Zero.js
JavaScript
mit
6,438
import { readFileSync } from 'fs'; import { createServer } from 'http'; import { parse } from 'url'; import { join } from 'path'; var server = createServer(function(req, res) { let path = parse(req.url, true).query.path; // BAD: This could read any file on the file system res.write(readFileSync(join("public", path))); });
github/codeql
javascript/ql/test/query-tests/Security/CWE-022/TaintedPath/TaintedPath-es6.js
JavaScript
mit
332
var clients = require('./../../data.js').clients; module.exports.getId = function(client) { return client.id; }; module.exports.getRedirectUri = function(client) { return client.redirectUri; }; module.exports.fetchById = function(clientId, cb) { for (var i in clients) { if (clientId == clients[i].id) return cb(null, clients[i]); } cb(); }; module.exports.checkSecret = function(client, secret) { return (client.secret == secret); };
ojengwa/node-oauth20-provider
test/server/model/memory/oauth2/client.js
JavaScript
mit
470
#!/usr/bin/env node /* Logfella Copyright (c) 2015 - 2019 Cédric Ronvel The MIT License (MIT) 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" ; var Logfella = require( '../lib/Logfella.js' ) ; /* Tests */ describe( "NetServer Transport" , function() { it( "simple test" , function( done ) { this.timeout( 10000 ) ; var logger = Logfella.create() ; var count = 0 ; logger.setGlobalConfig( { minLevel: 'trace' , defaultDomain: 'default-domain' } ) ; logger.addTransport( 'console' , { minLevel: 'trace' , output: process.stderr } ) ; logger.addTransport( 'netServer' , { minLevel: 'trace' , listen: 1234 } ) ; logger.logTransports[ 1 ].server.on( 'connection' , function() { count ++ ; if ( count >= 2 ) { logger.warning( 'storage' , 'gloups' , 'We are running out of storage! Only %iMB left' , 139 ) ; logger.info( 'idle' , { some: 'meta' , few: 'data' , somethingElse: 4 } , 'Youpla boum!' ) ; setTimeout( done , 30 ) ; } } ) ; } ) ; } ) ;
cronvel/logger-kit
sample/net-server-test.js
JavaScript
mit
2,053
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor */ WebInspector.Settings = function() { this._eventSupport = new WebInspector.Object(); this._registry = /** @type {!Object.<string, !WebInspector.Setting>} */ ({}); this.colorFormat = this.createSetting("colorFormat", "original"); this.consoleHistory = this.createSetting("consoleHistory", []); this.domWordWrap = this.createSetting("domWordWrap", true); this.eventListenersFilter = this.createSetting("eventListenersFilter", "all"); this.lastViewedScriptFile = this.createSetting("lastViewedScriptFile", "application"); this.monitoringXHREnabled = this.createSetting("monitoringXHREnabled", false); this.preserveConsoleLog = this.createSetting("preserveConsoleLog", false); this.consoleTimestampsEnabled = this.createSetting("consoleTimestampsEnabled", false); this.resourcesLargeRows = this.createSetting("resourcesLargeRows", true); this.resourcesSortOptions = this.createSetting("resourcesSortOptions", {timeOption: "responseTime", sizeOption: "transferSize"}); this.resourceViewTab = this.createSetting("resourceViewTab", "preview"); this.showInheritedComputedStyleProperties = this.createSetting("showInheritedComputedStyleProperties", false); this.showUserAgentStyles = this.createSetting("showUserAgentStyles", true); this.watchExpressions = this.createSetting("watchExpressions", []); this.breakpoints = this.createSetting("breakpoints", []); this.eventListenerBreakpoints = this.createSetting("eventListenerBreakpoints", []); this.domBreakpoints = this.createSetting("domBreakpoints", []); this.xhrBreakpoints = this.createSetting("xhrBreakpoints", []); this.jsSourceMapsEnabled = this.createSetting("sourceMapsEnabled", true); this.cssSourceMapsEnabled = this.createSetting("cssSourceMapsEnabled", true); this.cacheDisabled = this.createSetting("cacheDisabled", false); this.showUAShadowDOM = this.createSetting("showUAShadowDOM", false); this.savedURLs = this.createSetting("savedURLs", {}); this.javaScriptDisabled = this.createSetting("javaScriptDisabled", false); this.showAdvancedHeapSnapshotProperties = this.createSetting("showAdvancedHeapSnapshotProperties", false); this.recordAllocationStacks = this.createSetting("recordAllocationStacks", false); this.highResolutionCpuProfiling = this.createSetting("highResolutionCpuProfiling", false); this.searchInContentScripts = this.createSetting("searchInContentScripts", false); this.textEditorIndent = this.createSetting("textEditorIndent", " "); this.textEditorAutoDetectIndent = this.createSetting("textEditorAutoIndentIndent", true); this.textEditorAutocompletion = this.createSetting("textEditorAutocompletion", true); this.textEditorBracketMatching = this.createSetting("textEditorBracketMatching", true); this.cssReloadEnabled = this.createSetting("cssReloadEnabled", false); this.timelineLiveUpdate = this.createSetting("timelineLiveUpdate", true); this.showMetricsRulers = this.createSetting("showMetricsRulers", false); this.workerInspectorWidth = this.createSetting("workerInspectorWidth", 600); this.workerInspectorHeight = this.createSetting("workerInspectorHeight", 600); this.messageURLFilters = this.createSetting("messageURLFilters", {}); this.networkHideDataURL = this.createSetting("networkHideDataURL", false); this.networkResourceTypeFilters = this.createSetting("networkResourceTypeFilters", {}); this.messageLevelFilters = this.createSetting("messageLevelFilters", {}); this.splitVerticallyWhenDockedToRight = this.createSetting("splitVerticallyWhenDockedToRight", true); this.visiblePanels = this.createSetting("visiblePanels", {}); this.shortcutPanelSwitch = this.createSetting("shortcutPanelSwitch", false); this.showWhitespacesInEditor = this.createSetting("showWhitespacesInEditor", false); this.skipStackFramesPattern = this.createRegExpSetting("skipStackFramesPattern", ""); this.pauseOnExceptionEnabled = this.createSetting("pauseOnExceptionEnabled", false); this.pauseOnCaughtException = this.createSetting("pauseOnCaughtException", false); this.enableAsyncStackTraces = this.createSetting("enableAsyncStackTraces", false); this.showMediaQueryInspector = this.createSetting("showMediaQueryInspector", false); this.disableOverridesWarning = this.createSetting("disableOverridesWarning", false); // Rendering options this.showPaintRects = this.createSetting("showPaintRects", false); this.showDebugBorders = this.createSetting("showDebugBorders", false); this.showFPSCounter = this.createSetting("showFPSCounter", false); this.continuousPainting = this.createSetting("continuousPainting", false); this.showScrollBottleneckRects = this.createSetting("showScrollBottleneckRects", false); } WebInspector.Settings.prototype = { /** * @param {string} key * @param {*} defaultValue * @return {!WebInspector.Setting} */ createSetting: function(key, defaultValue) { if (!this._registry[key]) this._registry[key] = new WebInspector.Setting(key, defaultValue, this._eventSupport, window.localStorage); return this._registry[key]; }, /** * @param {string} key * @param {string} defaultValue * @param {string=} regexFlags * @return {!WebInspector.Setting} */ createRegExpSetting: function(key, defaultValue, regexFlags) { if (!this._registry[key]) this._registry[key] = new WebInspector.RegExpSetting(key, defaultValue, this._eventSupport, window.localStorage, regexFlags); return this._registry[key]; } } /** * @constructor * @param {string} name * @param {V} defaultValue * @param {!WebInspector.Object} eventSupport * @param {?Storage} storage * @template V */ WebInspector.Setting = function(name, defaultValue, eventSupport, storage) { this._name = name; this._defaultValue = defaultValue; this._eventSupport = eventSupport; this._storage = storage; } WebInspector.Setting.prototype = { /** * @param {function(!WebInspector.Event)} listener * @param {!Object=} thisObject */ addChangeListener: function(listener, thisObject) { this._eventSupport.addEventListener(this._name, listener, thisObject); }, /** * @param {function(!WebInspector.Event)} listener * @param {!Object=} thisObject */ removeChangeListener: function(listener, thisObject) { this._eventSupport.removeEventListener(this._name, listener, thisObject); }, get name() { return this._name; }, /** * @return {V} */ get: function() { if (typeof this._value !== "undefined") return this._value; this._value = this._defaultValue; if (this._storage && this._name in this._storage) { try { this._value = JSON.parse(this._storage[this._name]); } catch(e) { delete this._storage[this._name]; } } return this._value; }, /** * @param {V} value */ set: function(value) { this._value = value; if (this._storage) { try { this._storage[this._name] = JSON.stringify(value); } catch(e) { console.error("Error saving setting with name:" + this._name); } } this._eventSupport.dispatchEventToListeners(this._name, value); } } /** * @constructor * @extends {WebInspector.Setting} * @param {string} name * @param {string} defaultValue * @param {!WebInspector.Object} eventSupport * @param {?Storage} storage * @param {string=} regexFlags */ WebInspector.RegExpSetting = function(name, defaultValue, eventSupport, storage, regexFlags) { WebInspector.Setting.call(this, name, defaultValue ? [{ pattern: defaultValue }] : [], eventSupport, storage); this._regexFlags = regexFlags; } WebInspector.RegExpSetting.prototype = { /** * @override * @return {string} */ get: function() { var result = []; var items = this.getAsArray(); for (var i = 0; i < items.length; ++i) { var item = items[i]; if (item.pattern && !item.disabled) result.push(item.pattern); } return result.join("|"); }, /** * @return {!Array.<{pattern: string, disabled: (boolean|undefined)}>} */ getAsArray: function() { return WebInspector.Setting.prototype.get.call(this); }, /** * @override * @param {string} value */ set: function(value) { this.setAsArray([{ pattern: value }]); }, /** * @param {!Array.<{pattern: string, disabled: (boolean|undefined)}>} value */ setAsArray: function(value) { delete this._regex; WebInspector.Setting.prototype.set.call(this, value); }, /** * @return {?RegExp} */ asRegExp: function() { if (typeof this._regex !== "undefined") return this._regex; this._regex = null; try { var pattern = this.get(); if (pattern) this._regex = new RegExp(pattern, this._regexFlags || ""); } catch (e) { } return this._regex; }, __proto__: WebInspector.Setting.prototype } /** * @constructor * @param {boolean} experimentsEnabled */ WebInspector.ExperimentsSettings = function(experimentsEnabled) { this._experimentsEnabled = experimentsEnabled; this._setting = WebInspector.settings.createSetting("experiments", {}); this._experiments = []; this._enabledForTest = {}; // Add currently running experiments here. this.applyCustomStylesheet = this._createExperiment("applyCustomStylesheet", "Allow custom UI themes"); this.canvasInspection = this._createExperiment("canvasInspection ", "Canvas inspection"); this.devicesPanel = this._createExperiment("devicesPanel", "Devices panel"); this.disableAgentsWhenProfile = this._createExperiment("disableAgentsWhenProfile", "Disable other agents and UI when profiler is active", true); this.dockToLeft = this._createExperiment("dockToLeft", "Dock to left", true); this.documentation = this._createExperiment("documentation", "Documentation for JS and CSS", true); this.fileSystemInspection = this._createExperiment("fileSystemInspection", "FileSystem inspection"); this.gpuTimeline = this._createExperiment("gpuTimeline", "GPU data on timeline", true); this.layersPanel = this._createExperiment("layersPanel", "Layers panel"); this.paintProfiler = this._createExperiment("paintProfiler", "Paint profiler"); this.timelineOnTraceEvents = this._createExperiment("timelineOnTraceEvents", "Timeline on trace events"); this.timelinePowerProfiler = this._createExperiment("timelinePowerProfiler", "Timeline power profiler"); this.timelineJSCPUProfile = this._createExperiment("timelineJSCPUProfile", "Timeline with JS sampling"); this._cleanUpSetting(); } WebInspector.ExperimentsSettings.prototype = { /** * @return {!Array.<!WebInspector.Experiment>} */ get experiments() { return this._experiments.slice(); }, /** * @return {boolean} */ get experimentsEnabled() { return this._experimentsEnabled; }, /** * @param {string} experimentName * @param {string} experimentTitle * @param {boolean=} hidden * @return {!WebInspector.Experiment} */ _createExperiment: function(experimentName, experimentTitle, hidden) { var experiment = new WebInspector.Experiment(this, experimentName, experimentTitle, !!hidden); this._experiments.push(experiment); return experiment; }, /** * @param {string} experimentName * @return {boolean} */ isEnabled: function(experimentName) { if (this._enabledForTest[experimentName]) return true; if (!this.experimentsEnabled) return false; var experimentsSetting = this._setting.get(); return experimentsSetting[experimentName]; }, /** * @param {string} experimentName * @param {boolean} enabled */ setEnabled: function(experimentName, enabled) { var experimentsSetting = this._setting.get(); experimentsSetting[experimentName] = enabled; this._setting.set(experimentsSetting); }, /** * @param {string} experimentName */ _enableForTest: function(experimentName) { this._enabledForTest[experimentName] = true; }, _cleanUpSetting: function() { var experimentsSetting = this._setting.get(); var cleanedUpExperimentSetting = {}; for (var i = 0; i < this._experiments.length; ++i) { var experimentName = this._experiments[i].name; if (experimentsSetting[experimentName]) cleanedUpExperimentSetting[experimentName] = true; } this._setting.set(cleanedUpExperimentSetting); } } /** * @constructor * @param {!WebInspector.ExperimentsSettings} experimentsSettings * @param {string} name * @param {string} title * @param {boolean} hidden */ WebInspector.Experiment = function(experimentsSettings, name, title, hidden) { this._name = name; this._title = title; this._hidden = hidden; this._experimentsSettings = experimentsSettings; } WebInspector.Experiment.prototype = { /** * @return {string} */ get name() { return this._name; }, /** * @return {string} */ get title() { return this._title; }, /** * @return {boolean} */ get hidden() { return this._hidden; }, /** * @return {boolean} */ isEnabled: function() { return this._experimentsSettings.isEnabled(this._name); }, /** * @param {boolean} enabled */ setEnabled: function(enabled) { this._experimentsSettings.setEnabled(this._name, enabled); }, enableForTest: function() { this._experimentsSettings._enableForTest(this._name); } } /** * @constructor */ WebInspector.VersionController = function() { } WebInspector.VersionController.currentVersion = 9; WebInspector.VersionController.prototype = { updateVersion: function() { var versionSetting = WebInspector.settings.createSetting("inspectorVersion", 0); var currentVersion = WebInspector.VersionController.currentVersion; var oldVersion = versionSetting.get(); var methodsToRun = this._methodsToRunToUpdateVersion(oldVersion, currentVersion); for (var i = 0; i < methodsToRun.length; ++i) this[methodsToRun[i]].call(this); versionSetting.set(currentVersion); }, /** * @param {number} oldVersion * @param {number} currentVersion */ _methodsToRunToUpdateVersion: function(oldVersion, currentVersion) { var result = []; for (var i = oldVersion; i < currentVersion; ++i) result.push("_updateVersionFrom" + i + "To" + (i + 1)); return result; }, _updateVersionFrom0To1: function() { this._clearBreakpointsWhenTooMany(WebInspector.settings.breakpoints, 500000); }, _updateVersionFrom1To2: function() { var versionSetting = WebInspector.settings.createSetting("previouslyViewedFiles", []); versionSetting.set([]); }, _updateVersionFrom2To3: function() { var fileSystemMappingSetting = WebInspector.settings.createSetting("fileSystemMapping", {}); fileSystemMappingSetting.set({}); if (window.localStorage) delete window.localStorage["fileMappingEntries"]; }, _updateVersionFrom3To4: function() { var advancedMode = WebInspector.settings.createSetting("showHeaSnapshotObjectsHiddenProperties", false).get(); WebInspector.settings.showAdvancedHeapSnapshotProperties.set(advancedMode); }, _updateVersionFrom4To5: function() { if (!window.localStorage) return; var settingNames = { "FileSystemViewSidebarWidth": "fileSystemViewSplitViewState", "canvasProfileViewReplaySplitLocation": "canvasProfileViewReplaySplitViewState", "canvasProfileViewSplitLocation": "canvasProfileViewSplitViewState", "elementsSidebarWidth": "elementsPanelSplitViewState", "StylesPaneSplitRatio": "stylesPaneSplitViewState", "heapSnapshotRetainersViewSize": "heapSnapshotSplitViewState", "InspectorView.splitView": "InspectorView.splitViewState", "InspectorView.screencastSplitView": "InspectorView.screencastSplitViewState", "Inspector.drawerSplitView": "Inspector.drawerSplitViewState", "layerDetailsSplitView": "layerDetailsSplitViewState", "networkSidebarWidth": "networkPanelSplitViewState", "sourcesSidebarWidth": "sourcesPanelSplitViewState", "scriptsPanelNavigatorSidebarWidth": "sourcesPanelNavigatorSplitViewState", "sourcesPanelSplitSidebarRatio": "sourcesPanelDebuggerSidebarSplitViewState", "timeline-details": "timelinePanelDetailsSplitViewState", "timeline-split": "timelinePanelRecorsSplitViewState", "timeline-view": "timelinePanelTimelineStackSplitViewState", "auditsSidebarWidth": "auditsPanelSplitViewState", "layersSidebarWidth": "layersPanelSplitViewState", "profilesSidebarWidth": "profilesPanelSplitViewState", "resourcesSidebarWidth": "resourcesPanelSplitViewState" }; for (var oldName in settingNames) { var newName = settingNames[oldName]; var oldNameH = oldName + "H"; var newValue = null; var oldSetting = WebInspector.settings.createSetting(oldName, undefined).get(); if (oldSetting) { newValue = newValue || {}; newValue.vertical = {}; newValue.vertical.size = oldSetting; delete window.localStorage[oldName]; } var oldSettingH = WebInspector.settings.createSetting(oldNameH, undefined).get(); if (oldSettingH) { newValue = newValue || {}; newValue.horizontal = {}; newValue.horizontal.size = oldSettingH; delete window.localStorage[oldNameH]; } var newSetting = WebInspector.settings.createSetting(newName, {}); if (newValue) newSetting.set(newValue); } }, _updateVersionFrom5To6: function() { if (!window.localStorage) return; var settingNames = { "debuggerSidebarHidden": "sourcesPanelSplitViewState", "navigatorHidden": "sourcesPanelNavigatorSplitViewState", "WebInspector.Drawer.showOnLoad": "Inspector.drawerSplitViewState" }; for (var oldName in settingNames) { var newName = settingNames[oldName]; var oldSetting = WebInspector.settings.createSetting(oldName, undefined).get(); var invert = "WebInspector.Drawer.showOnLoad" === oldName; var hidden = !!oldSetting !== invert; delete window.localStorage[oldName]; var showMode = hidden ? "OnlyMain" : "Both"; var newSetting = WebInspector.settings.createSetting(newName, null); var newValue = newSetting.get() || {}; newValue.vertical = newValue.vertical || {}; newValue.vertical.showMode = showMode; newValue.horizontal = newValue.horizontal || {}; newValue.horizontal.showMode = showMode; newSetting.set(newValue); } }, _updateVersionFrom6To7: function() { if (!window.localStorage) return; var settingNames = { "sourcesPanelNavigatorSplitViewState": "sourcesPanelNavigatorSplitViewState", "elementsPanelSplitViewState": "elementsPanelSplitViewState", "canvasProfileViewReplaySplitViewState": "canvasProfileViewReplaySplitViewState", "stylesPaneSplitViewState": "stylesPaneSplitViewState", "sourcesPanelDebuggerSidebarSplitViewState": "sourcesPanelDebuggerSidebarSplitViewState" }; for (var name in settingNames) { if (!(name in window.localStorage)) continue; var setting = WebInspector.settings.createSetting(name, undefined); var value = setting.get(); if (!value) continue; // Zero out saved percentage sizes, and they will be restored to defaults. if (value.vertical && value.vertical.size && value.vertical.size < 1) value.vertical.size = 0; if (value.horizontal && value.horizontal.size && value.horizontal.size < 1) value.horizontal.size = 0; setting.set(value); } }, _updateVersionFrom7To8: function() { var settingName = "deviceMetrics"; if (!window.localStorage || !(settingName in window.localStorage)) return; var setting = WebInspector.settings.createSetting(settingName, undefined); var value = setting.get(); if (!value) return; var components = value.split("x"); if (components.length >= 3) { var width = parseInt(components[0], 10); var height = parseInt(components[1], 10); var deviceScaleFactor = parseFloat(components[2]); if (deviceScaleFactor) { components[0] = "" + Math.round(width / deviceScaleFactor); components[1] = "" + Math.round(height / deviceScaleFactor); } } value = components.join("x"); setting.set(value); }, _updateVersionFrom8To9: function() { if (!window.localStorage) return; var settingNames = [ "skipStackFramesPattern", "workspaceFolderExcludePattern" ]; for (var i = 0; i < settingNames.length; ++i) { var settingName = settingNames[i]; if (!(settingName in window.localStorage)) continue; try { var value = JSON.parse(window.localStorage[settingName]); if (!value) continue; if (typeof value === "string") value = [value]; for (var j = 0; j < value.length; ++j) { if (typeof value[j] === "string") value[j] = { pattern: value[j] }; } window.localStorage[settingName] = JSON.stringify(value); } catch(e) { } } }, /** * @param {!WebInspector.Setting} breakpointsSetting * @param {number} maxBreakpointsCount */ _clearBreakpointsWhenTooMany: function(breakpointsSetting, maxBreakpointsCount) { // If there are too many breakpoints in a storage, it is likely due to a recent bug that caused // periodical breakpoints duplication leading to inspector slowness. if (breakpointsSetting.get().length > maxBreakpointsCount) breakpointsSetting.set([]); } } /** * @type {!WebInspector.Settings} */ WebInspector.settings; /** * @type {!WebInspector.ExperimentsSettings} */ WebInspector.experimentsSettings; // These methods are added for backwards compatibility with Devtools CodeSchool extension. // DO NOT REMOVE /** * @constructor */ WebInspector.PauseOnExceptionStateSetting = function() { WebInspector.settings.pauseOnExceptionEnabled.addChangeListener(this._enabledChanged, this); WebInspector.settings.pauseOnCaughtException.addChangeListener(this._pauseOnCaughtChanged, this); this._name = "pauseOnExceptionStateString"; this._eventSupport = new WebInspector.Object(); this._value = this._calculateValue(); } WebInspector.PauseOnExceptionStateSetting.prototype = { /** * @param {function(!WebInspector.Event)} listener * @param {!Object=} thisObject */ addChangeListener: function(listener, thisObject) { this._eventSupport.addEventListener(this._name, listener, thisObject); }, /** * @param {function(!WebInspector.Event)} listener * @param {!Object=} thisObject */ removeChangeListener: function(listener, thisObject) { this._eventSupport.removeEventListener(this._name, listener, thisObject); }, /** * @return {string} */ get: function() { return this._value; }, /** * @return {string} */ _calculateValue: function() { if (!WebInspector.settings.pauseOnExceptionEnabled.get()) return "none"; // The correct code here would be // return WebInspector.settings.pauseOnCaughtException.get() ? "all" : "uncaught"; // But the CodeSchool DevTools relies on the fact that we used to enable pausing on ALL extensions by default, so we trick it here. return "all"; }, _enabledChanged: function(event) { this._fireChangedIfNeeded(); }, _pauseOnCaughtChanged: function(event) { this._fireChangedIfNeeded(); }, _fireChangedIfNeeded: function() { var newValue = this._calculateValue(); if (newValue === this._value) return; this._value = newValue; this._eventSupport.dispatchEventToListeners(this._name, this._value); } }
tsiry95/openshift-strongloop-cartridge
strongloop/node_modules/strong-arc/devtools/frontend/common/Settings.js
JavaScript
mit
27,489
var assert = require('assert') var mongoose = require('mongoose') var request = require('request') var sinon = require('sinon') var util = require('util') module.exports = function (createFn, setup, dismantle) { var erm = require('../../lib/express-restify-mongoose') var db = require('./setup')() var testPort = 30023 var testUrl = 'http://localhost:' + testPort var invalidId = 'invalid-id' var randomId = mongoose.Types.ObjectId().toHexString() describe('preMiddleware/Create/Read/Update/Delete - null', function () { var app = createFn() var server var customer beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, { preMiddleware: null, preCreate: null, preRead: null, preUpdate: null, preDelete: null, restify: app.isRestify }) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { dismantle(app, server, done) }) it('POST /Customers 201', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), json: { name: 'John' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 201) done() }) }) it('GET /Customers 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) done() }) }) it('POST /Customers/:id 200', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) done() }) }) it('PUT /Customers/:id 200', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) done() }) }) it('DELETE /Customers/:id 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) done() }) }) }) describe('preMiddleware', function () { var app = createFn() var server var customer var options = { preMiddleware: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { options.preMiddleware.reset() dismantle(app, server, done) }) it('GET /Customers 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preMiddleware) var args = options.preMiddleware.args[0] assert.equal(args.length, 3) assert.equal(typeof args[2], 'function') done() }) }) it('GET /Customers/:id 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preMiddleware) var args = options.preMiddleware.args[0] assert.equal(args.length, 3) assert.equal(typeof args[2], 'function') done() }) }) it('POST /Customers 201', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), json: { name: 'Pre' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 201) sinon.assert.calledOnce(options.preMiddleware) var args = options.preMiddleware.args[0] assert.equal(args.length, 3) assert.equal(typeof args[2], 'function') done() }) }) it('POST /Customers 400 - not called (missing content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl) }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preMiddleware) done() }) }) it('POST /Customers 400 - not called (invalid content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), formData: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preMiddleware) done() }) }) it('POST /Customers/:id 200', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preMiddleware) var args = options.preMiddleware.args[0] assert.equal(args.length, 3) assert.equal(typeof args[2], 'function') done() }) }) it('POST /Customers/:id 400 - not called (missing content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id) }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preMiddleware) done() }) }) it('POST /Customers/:id 400 - not called (invalid content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), formData: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preMiddleware) done() }) }) it('PUT /Customers/:id 200', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preMiddleware) var args = options.preMiddleware.args[0] assert.equal(args.length, 3) assert.equal(typeof args[2], 'function') done() }) }) it('PUT /Customers/:id 400 - not called (missing content type)', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id) }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preMiddleware) done() }) }) it('PUT /Customers/:id 400 - not called (invalid content type)', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), formData: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preMiddleware) done() }) }) it('DELETE /Customers 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) sinon.assert.calledOnce(options.preMiddleware) var args = options.preMiddleware.args[0] assert.equal(args.length, 3) assert.equal(typeof args[2], 'function') done() }) }) it('DELETE /Customers/:id 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) sinon.assert.calledOnce(options.preMiddleware) var args = options.preMiddleware.args[0] assert.equal(args.length, 3) assert.equal(typeof args[2], 'function') done() }) }) }) describe('preCreate', function () { var app = createFn() var server var options = { preCreate: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) server = app.listen(testPort, done) }) }) afterEach(function (done) { options.preCreate.reset() dismantle(app, server, done) }) it('POST /Customers 201', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), json: { name: 'Bob' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 201) sinon.assert.calledOnce(options.preCreate) var args = options.preCreate.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bob') assert.equal(args[0].erm.statusCode, 201) assert.equal(typeof args[2], 'function') done() }) }) }) describe('preRead', function () { var app = createFn() var server var customer var options = { preRead: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { options.preRead.reset() dismantle(app, server, done) }) it('GET /Customers 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preRead) var args = options.preRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result[0].name, 'Bob') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('GET /Customers/count 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers/count', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preRead) var args = options.preRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.count, 1) assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('GET /Customers/:id 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preRead) var args = options.preRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bob') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('GET /Customers/:id/shallow 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers/%s/shallow', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preRead) var args = options.preRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bob') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) }) describe('preUpdate', function () { var app = createFn() var server var customer var options = { preUpdate: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { options.preUpdate.reset() dismantle(app, server, done) }) it('POST /Customers/:id 200', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preUpdate) var args = options.preUpdate.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bobby') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('POST /Customers/:id 400 - not called (missing content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id) }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preUpdate) done() }) }) it('POST /Customers/:id 400 - not called (invalid content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), formData: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preUpdate) done() }) }) it('PUT /Customers/:id 200', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.preUpdate) var args = options.preUpdate.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bobby') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('PUT /Customers/:id 400 - not called (missing content type)', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id) }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preUpdate) done() }) }) it('PUT /Customers/:id 400 - not called (invalid content type)', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), formData: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.preUpdate) done() }) }) }) describe('preDelete', function () { var app = createFn() var server var customer var options = { preDelete: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { options.preDelete.reset() dismantle(app, server, done) }) it('DELETE /Customers 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) sinon.assert.calledOnce(options.preDelete) var args = options.preDelete.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result, undefined) assert.equal(args[0].erm.statusCode, 204) assert.equal(typeof args[2], 'function') done() }) }) it('DELETE /Customers/:id 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) sinon.assert.calledOnce(options.preDelete) var args = options.preDelete.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result, undefined) assert.equal(args[0].erm.statusCode, 204) assert.equal(typeof args[2], 'function') done() }) }) }) describe('postCreate/Read/Update/Delete - null', function () { var app = createFn() var server var customer beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, { postCreate: null, postRead: null, postUpdate: null, postDelete: null, restify: app.isRestify }) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { dismantle(app, server, done) }) it('POST /Customers 201', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), json: { name: 'John' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 201) done() }) }) it('GET /Customers 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) done() }) }) it('POST /Customers/:id 200', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) done() }) }) it('PUT /Customers/:id 200', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) done() }) }) it('DELETE /Customers/:id 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) done() }) }) }) describe('postCreate', function () { var app = createFn() var server var options = { postCreate: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) server = app.listen(testPort, done) }) }) afterEach(function (done) { options.postCreate.reset() dismantle(app, server, done) }) it('POST /Customers 201', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), json: { name: 'Bob' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 201) sinon.assert.calledOnce(options.postCreate) var args = options.postCreate.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bob') assert.equal(args[0].erm.statusCode, 201) assert.equal(typeof args[2], 'function') done() }) }) it('POST /Customers 400 - missing required field', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), json: { comment: 'Bar' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postCreate) done() }) }) }) describe('postRead', function () { var app = createFn() var server var customer var options = { postRead: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { options.postRead.reset() dismantle(app, server, done) }) it('GET /Customers 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.postRead) var args = options.postRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result[0].name, 'Bob') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('GET /Customers/count 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers/count', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.postRead) var args = options.postRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.count, 1) assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('GET /Customers/:id 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.postRead) var args = options.postRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bob') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('GET /Customers/:id 404', function (done) { request.get({ url: util.format('%s/api/v1/Customers/%s', testUrl, randomId), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 404) sinon.assert.notCalled(options.postRead) done() }) }) it('GET /Customers/:id 400', function (done) { request.get({ url: util.format('%s/api/v1/Customers/%s', testUrl, invalidId), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postRead) done() }) }) it('GET /Customers/:id/shallow 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers/%s/shallow', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.postRead) var args = options.postRead.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bob') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) }) describe('postUpdate', function () { var app = createFn() var server var customer var options = { postUpdate: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { options.postUpdate.reset() dismantle(app, server, done) }) it('POST /Customers/:id 200', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.postUpdate) var args = options.postUpdate.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bobby') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('POST /Customers/:id 404 - random id', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, randomId), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 404) sinon.assert.notCalled(options.postUpdate) done() }) }) it('POST /Customers/:id 400 - invalid id', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, invalidId), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postUpdate) done() }) }) it('POST /Customers/:id 400 - not called (missing content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id) }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postUpdate) done() }) }) it('POST /Customers/:id 400 - not called (invalid content type)', function (done) { request.post({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), formData: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postUpdate) done() }) }) it('PUT /Customers/:id 200', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.postUpdate) var args = options.postUpdate.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bobby') assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) it('PUT /Customers/:id 404 - random id', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, randomId), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 404) sinon.assert.notCalled(options.postUpdate) done() }) }) it('PUT /Customers/:id 400 - invalid id', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, invalidId), json: { name: 'Bobby' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postUpdate) done() }) }) it('PUT /Customers/:id 400 - not called (missing content type)', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id) }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postUpdate) done() }) }) it('PUT /Customers/:id 400 - not called (invalid content type)', function (done) { request.put({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), formData: {} }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postUpdate) done() }) }) }) describe('postDelete', function () { var app = createFn() var server var customer var options = { postDelete: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) db.models.Customer.create({ name: 'Bob' }).then(function (createdCustomer) { customer = createdCustomer server = app.listen(testPort, done) }, function (err) { done(err) }) }) }) afterEach(function (done) { options.postDelete.reset() dismantle(app, server, done) }) it('DELETE /Customers 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) sinon.assert.calledOnce(options.postDelete) var args = options.postDelete.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result, undefined) assert.equal(args[0].erm.statusCode, 204) assert.equal(typeof args[2], 'function') done() }) }) it('DELETE /Customers/:id 204', function (done) { request.del({ url: util.format('%s/api/v1/Customers/%s', testUrl, customer._id), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 204) sinon.assert.calledOnce(options.postDelete) var args = options.postDelete.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result, undefined) assert.equal(args[0].erm.statusCode, 204) assert.equal(typeof args[2], 'function') done() }) }) it('DELETE /Customers/:id 404', function (done) { request.del({ url: util.format('%s/api/v1/Customers/%s', testUrl, randomId), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 404) sinon.assert.notCalled(options.postDelete) done() }) }) it('DELETE /Customers/:id 400', function (done) { request.del({ url: util.format('%s/api/v1/Customers/%s', testUrl, invalidId), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.notCalled(options.postDelete) done() }) }) }) describe('postCreate yields an error', function () { var app = createFn() var server var options = { postCreate: sinon.spy(function (req, res, next) { var err = new Error('Something went wrong') err.statusCode = 400 next(err) }), postProcess: sinon.spy(), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) server = app.listen(testPort, done) }) }) afterEach(function (done) { options.postCreate.reset() dismantle(app, server, done) }) it('POST /Customers 201', function (done) { request.post({ url: util.format('%s/api/v1/Customers', testUrl), json: { name: 'Bob' } }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 400) sinon.assert.calledOnce(options.postCreate) var args = options.postCreate.args[0] assert.equal(args.length, 3) assert.equal(args[0].erm.result.name, 'Bob') assert.equal(args[0].erm.statusCode, 201) assert.equal(typeof args[2], 'function') sinon.assert.notCalled(options.postProcess) done() }) }) }) describe('postProcess', function () { var app = createFn() var server var options = { postProcess: sinon.spy(function (req, res, next) { next() }), restify: app.isRestify } beforeEach(function (done) { setup(function (err) { if (err) { return done(err) } erm.serve(app, db.models.Customer, options) server = app.listen(testPort, done) }) }) afterEach(function (done) { options.postProcess.reset() dismantle(app, server, done) }) it('GET /Customers 200', function (done) { request.get({ url: util.format('%s/api/v1/Customers', testUrl), json: true }, function (err, res, body) { assert.ok(!err) assert.equal(res.statusCode, 200) sinon.assert.calledOnce(options.postProcess) var args = options.postProcess.args[0] assert.equal(args.length, 3) assert.deepEqual(args[0].erm.result, []) assert.equal(args[0].erm.statusCode, 200) assert.equal(typeof args[2], 'function') done() }) }) }) }
Ensequence/express-restify-mongoose
test/integration/middleware.js
JavaScript
mit
36,848
'use strict'; var _ = require('lodash'); var util = require('util'); var property = require('corazon/property'); var inflection = require('../util/inflection'); var Mixin = require('corazon/mixin'); /** * A helper function for creating config properties that either reads from a * cached value or calls a function to get a value to cache. * * @function BelongsTo~config * @param {String} name The name of the option/property. * @param {Function} calculate A function to calculate the default value. * @return {Property} A config property */ var config = function(name, calculate) { var attr = '$' + name; return property(function() { if (this[attr] === undefined) { this[attr] = calculate.call(this); } return this[attr]; }); }; /** * BelongsTo mixin for options/configuration. * * This mixin separates some of the logic of {@link BelongsTo} and is only * intended to be mixed into that one class. */ module.exports = Mixin.create(/** @lends BelongsTo# */ { /** * Override of {@link BaseRelation#configure}. * * @protected * @method * @see {@link BaseRelation#configure} */ configure: function() { /* jshint expr: true */ // configure each of the properties that are calculated on a delay by // simply invoking the property once. configure the inverse first as some // other calculations may rely on it. this.inverse; this.primaryKey; this.primaryKeyAttr; this.foreignKey; this.foreignKeyAttr; this.inverseRelation(); // ensure the inverse is configured this._super(); }, /** * Get the inverse of this relation. Access the option that was given or * calculate the value based on the current model class name. * * The resulting value will be locked in after the first call to avoid any * possible changes due to changing state outside of the relation. * * @private * @type {String} */ inverse: config('inverse', function() { var inverse = this._options.inverse || this._inverse(); // add the inverse if it's missing if (inverse && !this._relatedModel[inverse + 'Relation']) { var db = this._modelClass.db; var attr = db.hasMany(this._modelClass, { inverse: this._name, primaryKey: this._options.primaryKey, foreignKey: this._options.foreignKey, implicit: true, }); this._relatedModel.reopen(_.object([[inverse, attr]])); } return inverse; }), /** * Calculate the default value of the inverse for when an option was not * provided for this relation. * * Mixins installed after this one can override {@link HasMany#_inverse} if * they need to change the default. * * @method * @private * @return {String} The default value. */ _inverse: function() { var name = _.camelCase(this._modelClass.__name__); var singularized = inflection.singularize(name); var pluralized = inflection.pluralize(name); var related = this._relatedModel; var inverse; if (related[pluralized + 'Relation']) { inverse = pluralized; } else if (related[singularized + 'Relation']) { inverse = singularized; } else { // find a relation w/ an inverse that points back to this one var match = _.find(related.relations, function(relation) { return relation._options.inverse === this._name; }.bind(this)); inverse = _.get(match, '_name'); } if (!inverse) { inverse = pluralized; } return inverse; }, /** * Get the primary key for this relation. This will access the primary key * value specified on the inverse relation, if an inverse relation exists. If * the inverse exists and the user also provided the `primaryKey` option when * creating this relation, it will ensure that the given value matches the * value from the inverse. * * If an inverse does not exist, this will return the value given for the * `primaryKey` option or `pk` as a default. * * The resulting value will be locked in after the first call to avoid any * possible changes due to changing state outside of the relation. * * @private * @type {String} */ primaryKey: config('primaryKey', function() { var primaryKey = this._options.primaryKey; var inverseRelation = this.inverseRelation(); var inversePrimaryKey = inverseRelation && inverseRelation.primaryKey; if (inverseRelation && primaryKey && primaryKey !== inversePrimaryKey) { throw new Error(util.format('%s.%s primary key must equal %j ' + 'specified by %s.%s relation', this._modelClass.__identity__.__name__, this._name, inverseRelation.primaryKey, inverseRelation._modelClass.__identity__.__name__, inverseRelation._name)); } if (inverseRelation) { primaryKey = inverseRelation.primaryKey; } if (!primaryKey) { // default in case the inverse does not exist primaryKey = 'pk'; } return primaryKey; }), /** * Get the primary key attribute value for this relation. This looks up the * attribute value on the related class. If that value was not defied, it * falls back to the underscored version of {@link BelongsTo#primaryKey}. * * @private * @type {String} */ primaryKeyAttr: config('primaryKeyAttr', function() { // since the related model may not have defined the attribute being used as // the primary key attribute, we need a fallback here, so we snake case the // property name. var relatedClass = this._relatedModel.__class__; var prototype = relatedClass.prototype; var primaryKeyAttr = prototype[this.primaryKey + 'Attr']; return primaryKeyAttr || _.snakeCase(this.primaryKey); }), /** * Get the foreign key for this relation. Access the option that was given or * calculate the value based on the relation name. * * @private * @type {String} */ foreignKey: config('foreignKey', function() { return this._options.foreignKey || _.camelCase(this._name + 'Id'); }), /** * Get the foreign key attribute value for this relation. This looks up the * attribute value on the model class. * * @private * @type {String} */ foreignKeyAttr: config('foreignKeyAttr', function() { // we always try to find the foreign key attribute by looking at the model // class. it's possible that it won't be there, though. belongs-to // relationships that were created implicitly from a has-many won't add the // attribute, so we need to fall back to snake casing the foreign key. var modelClass = this._modelClass; var prototype = modelClass.__class__.prototype; var foreignKeyAttr = prototype[this.foreignKey + 'Attr']; if (!foreignKeyAttr) { foreignKeyAttr = _.snakeCase(this.foreignKey); } return foreignKeyAttr; }), });
tgriesser/azul
lib/relations/belongs_to_config.js
JavaScript
mit
6,858
function foo() { var bar = ''; };
michaelghinrichs/hello-world
scope-chains-closures/scopes.js
JavaScript
mit
37
/*-- 简单测试node.js端使用的air-js -note 所有的模块以模块简称为属性名挂载在air上 */ var air = require('air-js'); var byteLength = air.byteLength; console.log(byteLength('中国人')); // => 6 console.log(byteLength('air')); // => 3 console.log(air.byteLength('air')); // => 3 console.log(air.clip('我是中国人', 8)); // => 我是中国… console.log(air.thousandFloat(78934.25)); // => 78,934.25
erniu/air
test-air.js
JavaScript
mit
442
import forIn from '../core/forIn' import forElements from '../core/forElements' export default function _parseAndApply (parse, apply, elements, options) { forIn(options, parse.bind(null, options)) return forElements(elements, apply.bind(null, options)) }
chirashijs/chirashi
lib/_internals/_parseAndApply.js
JavaScript
mit
261
'use strict'; app.controller('DeleteTripModalCtrl', function($scope, $uibModalInstance, TripFactory, $routeParams, $window, ActivityFactory, MemberFactory){ let tripId = $routeParams.tripId; $scope.close = () => { $uibModalInstance.close(); }; //Not only do we want to delete the trip object connected to that user from Firebase but we also want to delete anything associated with the trip - notes, packing list, and trails that have been added. $scope.deleteTrip = ()=>{ TripFactory.deleteTrip(tripId) .then(()=>{ console.log("trip was deleted"); $scope.close(); $window.location.href='#/parks/explore'; return ActivityFactory.getActivities(tripId) }) .then((activityData)=>{ console.log("activities in trip", activityData); Object.keys(activityData).forEach((activityId)=>{ ActivityFactory.deleteActivityFromTrip(activityId); }); return TripFactory.getUserPackingList(tripId) }) .then((packingData)=>{ console.log("user packing list", packingData); Object.keys(packingData).forEach((listId)=>{ TripFactory.deleteItemFromList(listId); }); return MemberFactory.getMembersOfTrip(tripId) }) .then((members)=>{ console.log("members", members); Object.keys(members).forEach((memberId)=>{ MemberFactory.deleteMember(memberId); }); return TripFactory.getInvitationsInTrip(tripId) }) .then((invitations)=>{ console.log("invitations", invitations); Object.keys(invitations).forEach((invitationId)=>{ TripFactory.deleteInvitation(invitationId); }); }) }; });
delainewendling/NP_trip_planner
deploy/app/controllers/DeleteTripModalCtrl.js
JavaScript
mit
1,660
import isArray from '../../util/isArray' import forEach from '../../util/forEach' import TreeIndex from '../../util/TreeIndex' import NodeIndex from './NodeIndex' class PropertyIndex extends NodeIndex { constructor(property) { super() this._property = property || 'id' this.index = new TreeIndex() } /** Get all indexed nodes for a given path. @param {Array<String>} path @returns A node or an object with ids and nodes as values. */ get(path) { return this.index.get(path) || {} } /** Collects nodes recursively. @returns An object with ids as keys and nodes as values. */ getAll(path) { return this.index.getAll(path) } /** Check if a node should be indexed. Used internally only. Override this in subclasses to achieve a custom behavior. @private @param {Node} @returns {Boolean} true if the given node should be added to the index. */ select(node) { // eslint-disable-line return true } /** Called when a node has been created. Override this in subclasses for customization. @private @param {Node} node */ create(node) { var values = node[this._property] if (!isArray(values)) { values = [values] } forEach(values, function(value) { this.index.set([value, node.id], node) }.bind(this)) } /** * Called when a node has been deleted. * * Override this in subclasses for customization. * * @private * @param {model/data/Node} node */ delete(node) { var values = node[this._property] if (!isArray(values)) { values = [values] } forEach(values, function(value) { this.index.delete([value, node.id]) }.bind(this)) } /** Called when a property has been updated. Override this in subclasses for customization. @private @param {Node} node */ update(node, path, newValue, oldValue) { if (!this.select(node) || path[1] !== this._property) return var values = oldValue if (!isArray(values)) { values = [values] } forEach(values, function(value) { this.index.delete([value, node.id]) }.bind(this)) values = newValue if (!isArray(values)) { values = [values] } forEach(values, function(value) { this.index.set([value, node.id], node) }.bind(this)) } set(node, path, newValue, oldValue) { this.update(node, path, newValue, oldValue) } _clear() { this.index.clear() } _initialize(data) { forEach(data.getNodes(), function(node) { if (this.select(node)) { this.create(node) } }.bind(this)) } } export default PropertyIndex
andene/substance
model/data/PropertyIndex.js
JavaScript
mit
2,682
(function(){ function buildForm(attrs) { attrs = $.extend({ action: '/echo', 'data-remote': 'true' }, attrs); $('#qunit-fixture').append($('<form />', attrs)) .find('form').append($('<input type="text" name="user_name" value="john">')); }; module('call-remote'); function submit(fn) { $('form') .on('ajax:success', fn) .on('ajax:complete', function() { start() }) .trigger('submit'); } asyncTest('form method is read from "method" and not from "data-method"', 1, function() { buildForm({ method: 'post', 'data-method': 'get' }); submit(function(e, data, status, xhr) { App.assertPostRequest(data); }); }); asyncTest('form method is not read from "data-method" attribute in case of missing "method"', 1, function() { buildForm({ 'data-method': 'put' }); submit(function(e, data, status, xhr) { App.assertGetRequest(data); }); }); asyncTest('form method is read from submit button "formmethod" if submit is triggered by that button', 1, function() { var submitButton = $('<input type="submit" formmethod="get">') buildForm({ method: 'post' }); $('#qunit-fixture').find('form').append(submitButton) .on('ajax:success', function(e, data, status, xhr) { App.assertGetRequest(data); }) .on('ajax:complete', function() { start() }); submitButton.trigger('click'); }); asyncTest('form default method is GET', 1, function() { buildForm(); submit(function(e, data, status, xhr) { App.assertGetRequest(data); }); }); asyncTest('form url is picked up from "action"', 1, function() { buildForm({ method: 'post' }); submit(function(e, data, status, xhr) { App.assertRequestPath(data, '/echo'); }); }); asyncTest('form url is read from "action" not "href"', 1, function() { buildForm({ method: 'post', href: '/echo2' }); submit(function(e, data, status, xhr) { App.assertRequestPath(data, '/echo'); }); }); asyncTest('form url is read from submit button "formaction" if submit is triggered by that button', 1, function() { var submitButton = $('<input type="submit" formaction="/echo">') buildForm({ method: 'post', href: '/echo2' }); $('#qunit-fixture').find('form').append(submitButton) .on('ajax:success', function(e, data, status, xhr) { App.assertRequestPath(data, '/echo'); }) .on('ajax:complete', function() { start() }); submitButton.trigger('click'); }); asyncTest('prefer JS, but accept any format', 1, function() { buildForm({ method: 'post' }); submit(function(e, data, status, xhr) { var accept = data.HTTP_ACCEPT; ok(accept.indexOf('*/*;q=0.5, text/javascript, application/javascript') === 0, 'Accept: ' + accept); }); }); asyncTest('accept application/json if "data-type" is json', 1, function() { buildForm({ method: 'post', 'data-type': 'json' }); submit(function(e, data, status, xhr) { equal(data.HTTP_ACCEPT, 'application/json, text/javascript, */*; q=0.01'); }); }); asyncTest('allow empty "data-remote" attribute', 1, function() { var form = $('#qunit-fixture').append($('<form action="/echo" data-remote />')).find('form'); submit(function() { ok(true, 'form with empty "data-remote" attribute is also allowed'); }); }); asyncTest('allow empty form "action"', 1, function() { var currentLocation, ajaxLocation; buildForm({ action: '' }); $('#qunit-fixture').find('form') .on('ajax:beforeSend', function(e, xhr, settings) { // Get current location (the same way jQuery does) try { currentLocation = location.href; } catch(e) { currentLocation = document.createElement( "a" ); currentLocation.href = ""; currentLocation = currentLocation.href; } currentLocation = currentLocation.replace(/\?$/, ''); // Actual location (strip out settings.data that jQuery serializes and appends) // HACK: can no longer use settings.data below to see what was appended to URL, as of // jQuery 1.6.3 (see http://bugs.jquery.com/ticket/10202 and https://github.com/jquery/jquery/pull/544) ajaxLocation = settings.url.replace("user_name=john","").replace(/&$/, "").replace(/\?$/, ""); equal(ajaxLocation.match(/^(.*)/)[1], currentLocation, 'URL should be current page by default'); // Prevent the request from actually getting sent to the current page and // causing an error. return false; }) .trigger('submit'); setTimeout(function() { start(); }, 13); }); asyncTest('sends CSRF token in custom header', 1, function() { buildForm({ method: 'post' }); $('#qunit-fixture').append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae" />'); submit(function(e, data, status, xhr) { equal(data.HTTP_X_CSRF_TOKEN, 'cf50faa3fe97702ca1ae', 'X-CSRF-Token header should be sent'); }); }); asyncTest('intelligently guesses crossDomain behavior when target URL has a different protocol and/or hostname', 1, function(e, xhr) { // Don't set data-cross-domain here, just set action to be a different domain than localhost buildForm({ action: 'http://www.alfajango.com' }); $('#qunit-fixture').append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae" />'); $('#qunit-fixture').find('form') .on('ajax:beforeSend', function(e, xhr, settings) { equal(settings.crossDomain, true, 'crossDomain should be set to true'); // prevent request from actually getting sent off-domain return false; }) .trigger('submit'); setTimeout(function() { start(); }, 13); }); asyncTest('intelligently guesses crossDomain behavior when target URL consists of only a path', 1, function(e, xhr) { // Don't set data-cross-domain here, just set action to be a different domain than localhost buildForm({ action: '/just/a/path' }); $('#qunit-fixture').append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae" />'); $('#qunit-fixture').find('form') .on('ajax:beforeSend', function(e, xhr, settings) { equal(settings.crossDomain, false, 'crossDomain should be set to false'); // prevent request from actually getting sent off-domain return false; }) .trigger('submit'); setTimeout(function() { start(); }, 13); }); })();
rails/jquery-ujs
test/public/test/call-remote.js
JavaScript
mit
6,202
/* * Smush In - jQuery plugin * * Copyright (c) 2013 Shane Donnelly * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Project home: * http://shanejdonnelly.github.io/smush-in * Version: 1.0 * */ ;(function ($) { "use strict"; /* CLASS DEFINITION * ====================== */ var SmushIn = function ($element, options) { this.settings = options; this.$el = $element; this.setup(); } SmushIn.prototype = { constructor: SmushIn, setup: function(){ this.height = this.$el.height(); this.width = this.$el.width(); this.left = parseInt(this.$el.css('left')); this.top = parseInt(this.$el.css('top')); this.font_size = parseInt(this.$el.css('font-size')); this.window_width = $(window).width(); this.window_height = $(window).height(); this.max_anim_speed = (this.settings.speed === 'slow') ? 130 : 75; if(this.settings.overshot === 0){ this.settings.overshot = this.rand(10,70) } //decide direction if(this.settings.from_direction === 'random') { var random_direction = (this.rand(0,20) < 10) ? 'left' : 'right'; this.horzAnim(random_direction); } else{ this.horzAnim(this.settings.from_direction); } }, horzAnim: function(from_direction){ var base = this, start_position = (from_direction === 'right') ? ( base.rand((base.window_width * 1.1), (base.window_width * 2)) ) : ( start_position = -1 * base.rand((base.window_width * 1.1), (base.window_width * 2)) ), fly_to = (from_direction === 'right') ? (base.left - base.settings.overshot) : (base.left + base.settings.overshot); //set start position base.$el.css('left', start_position ); setTimeout(function(){ //fly in base.$el.show().animate({'left': fly_to}, base.rand(200,500 ), function(){ //hit the 'wall' base.$el.animate( { 'height': (base.height * base.rand(1,2)), 'width': base.width * base.rand(.3, .7), 'margin-top': -(base.height * base.rand(.2,.4)) }, base.max_anim_speed, function(){ //bounce back base.$el.animate( { 'height': base.height, 'width': base.width, 'margin-top':0, 'left':base.left }, ( base.max_anim_speed * 1.75)); }); }); }, base.rand(500,1500)); }, //returns float rand: function(min, max){ return Math.random() * (max - min) + min; } } /* PLUGIN DEFINITION * ======================= */ $.fn.smushIn = function (custom_options) { return this.each(function () { var $el = $(this), options = $.extend({}, $.fn.smushIn.defaults, custom_options); new SmushIn($el, options) }) } $.fn.smushIn.defaults = { 'overshot' : 0, 'speed' : 'slow', 'from_direction' : 'left' } $.fn.smushIn.Constructor = SmushIn })(window.jQuery);
shanejdonnelly/smush-in
smushIn.js
JavaScript
mit
3,613
#!/usr/bin/env node "use strict"; // XXX currently this project is written to support node 0.10.* // when Meteor 1.4 is ready, we can rewrite in es6 var Vorpal = require("vorpal")(), Path = require("path"), Fs = require("fs"), Exec = require("child_process").exec, Spawn = require("child_process").spawn, Rimraf = require("rimraf").sync, Promise = require("es6-promise").Promise, GitHub = require("github-download"), Mkdirp = require("mkdirp") ; var root = Path.resolve(__dirname, "../"); var built = [ ".remote", "node_modules", "packages", ".meteor/local" ]; function installDep(src, dep){ return new Promise(function(resolve, reject){ Mkdirp(src, function(err) { if (err) return reject(err); GitHub(dep, src) .on("error", function(err){}) // XXX handle error .on("end", resolve); }); }); } Vorpal .command("setup") .description("Bootstrap an application. This may take some time...") .option("-c, --clean", "Force rebuild of application(s)") .option("-l, --log [level]", "Sets verbosity level.") .action(function(args, cb) { var app = root; var options = args.options; if (options.clean) { console.log("Cleaning all dependencies..."); for (var i = 0; i < built.length; i++) { var localPath = built[i]; Rimraf(Path.join(app, localPath)); } } var packageFile = require(Path.join(app, "package.json")); var depPromises = []; if (packageFile.apollos && packageFile.apollos.resource) { for (var subDir in packageFile.apollos.resource) { if (!packageFile.apollos.resource.hasOwnProperty(subDir)) continue; var localPath = Path.join(app, subDir); var deps = packageFile.apollos.resource[subDir]; for (var dep in deps) { if (!deps.hasOwnProperty(dep)) continue; console.log("installing resource: " + dep) depPromises.push(installDep(Path.join(localPath, dep), deps[dep])); } } } // var npmPromises = []; // npmPromises.push( // new Promise(function(p, f){ // console.log("installing npm deps"); // var child = Spawn("npm", ["install"], { // cwd: app, stdio: "inherit" // }); // child.on("error", f); // }) // ); return Promise.all(depPromises) .then(function(){ console.log("Holtzmann should be ready to go!"); // console.log("you will need to clone it down manually"); // console.log("\n"); // console.log(" cd " + app + "/.remote/ && git clone https://github.com/NewSpring/ops-settings.git settings"); // console.log("\n"); cb(); }) .catch(function(err) { console.error(err); cb(); }) }); Vorpal .command("run") .description("Start a local server to serve the site and print its address in your console") .option("-p, --port", "Choose a port to run the application") .option("-v, --verbosity [level]", "Sets verbosity level.") .option("-q, --quick", "Only runs the app, not apollos watcher as well") .option("-n, --native", "Runs the native version of the application") .option("--ios", "Run the native app of a given site in the iOS simulator") .option("--android", "Run the native app of a given site in the Android simulator") .option("--device", "Run the native app of a given site on the device of the platform") .option("--production", "Run the application in production mode") .option("--debug", "Run the application in debug mode") .action(function(args, cb) { var app = root; var options = args.options; var packageFile = require(Path.join(app, "package.json")); var env = process.env; env.METEOR_DISABLE_FS_FIBERS = 1; // https://github.com/meteor/meteor/pull/7668#issuecomment-256230102 if (options.debug) env.METEOR_PROFILE = 200; if (options.production) env.NODE_ENV = "production"; if (!options.ios && !options.android && !options.native) env.WEB = true; if (options.native || options.ios || options.android) env.NATIVE = true; var configFile = Path.join(__dirname, "apollos-runtime.json"); if (!Fs.existsSync(configFile)) { Fs.writeFileSync(configFile, JSON.stringify({ WEB: !!env.WEB }, null, 2), "utf8"); } var apolloRuntime = require(configFile); // removes the built files for a rebuild if (!options.quick && !!apolloRuntime.WEB != !!env.WEB) { Rimraf(Path.join(app, ".meteor/local")); } var meteorArgs = [ "--settings" ]; if (options.ios && !options.device) meteorArgs.unshift("run", "ios"); if (options.android && !options.device) meteorArgs.unshift("run", "android"); if (options.ios && options.device) meteorArgs.unshift("run", "ios-device"); if (options.android && options.device) meteorArgs.unshift("run", "android-device"); if ( packageFile.apollos && packageFile.apollos.settings && Fs.existsSync(Path.join(app, packageFile.apollos.settings)) ) { meteorArgs.push(packageFile.apollos.settings) } else { meteorArgs.push(Path.join(app, ".meteor/sample.settings.json")); } function run() { var meteor = Spawn("meteor", meteorArgs, { stdio: "inherit", cwd: app, env: env }); } Fs.writeFileSync(configFile, JSON.stringify({ WEB: !!env.WEB }, null, 2), "utf8"); if (options.production) { console.log("Building apollos in production mode"); meteorArgs.push("--production"); } run(); }); Vorpal .parse(process.argv);
NewSpring/apollos-core
.bin/index.js
JavaScript
mit
5,565
function calculaIMC(altura, peso) { return peso / (altura * altura); } console.log("O seu imc é: " + calculaIMC(prompt("Sua altura? "), prompt("Seu peso? "))); //https://pt.stackoverflow.com/q/327751/101
maniero/SOpt
JavaScript/Algorithm/Bmi2.js
JavaScript
mit
207
/** * JS initialization and core functions for API test servlet * * @depends {3rdparty/jquery.js} * @depends {3rdparty/bootstrap.js} * @depends {3rdparty/highlight.pack.js} */ var ATS = (function(ATS, $, undefined) { ATS.apiCalls = []; ATS.selectedApiCalls = []; ATS.init = function() { hljs.initHighlightingOnLoad(); ATS.selectedApiCalls = ATS.setSelectedApiCalls(); ATS.selectedApiCallsChange(); $('#search').keyup(function(e) { if (e.keyCode == 13) { ATS.performSearch($(this).val()); } }); $(".collapse-link").click(function(event) { event.preventDefault(); }); $('#navi-show-open').click(function(e) { $('.api-call-All').each(function() { if($(this).find('.panel-collapse.in').length != 0) { $(this).show(); } else { $(this).hide(); } }); $('#navi-show-all').css('font-weight', 'normal'); $(this).css('font-weight', 'bold'); e.preventDefault(); }); $('#navi-show-all').click(function(e) { $('.api-call-All').show(); $('#navi-show-open').css('font-weight', 'normal'); $(this).css('font-weight', 'bold'); e.preventDefault(); }); $('.api-call-sel-ALL').change(function() { if($(this).is(":checked")) { ATS.addToSelected($(this)); } else { ATS.removeFromSelected($(this)); } }); $('#navi-select-all-d-add-btn').click(function(e) { $.each($('.api-call-sel-ALL:visible:not(:checked)'), function(key, value) { ATS.addToSelected($(value)); }); e.preventDefault(); }); $('#navi-select-all-d-replace-btn').click(function(e) { ATS.selectedApiCalls = []; $.each($('.api-call-sel-ALL:visible'), function(key, value) { ATS.addToSelected($(value)); }); e.preventDefault(); }); $('#navi-deselect-all-d-btn').click(function(e) { $.each($('.api-call-sel-ALL:visible'), function(key, value) { ATS.removeFromSelected($(value)); }); e.preventDefault(); }); $('#navi-deselect-all-btn').click(function(e) { ATS.selectedApiCalls = []; $('.api-call-sel-ALL').prop('checked', false); ATS.selectedApiCallsChange(); e.preventDefault(); }); } ATS.performSearch = function(searchStr) { if (searchStr == '') { $('.api-call-All').show(); } else { $('.api-call-All').hide(); $('.topic-link').css('font-weight', 'normal'); for(var i=0; i<ATS.apiCalls.length; i++) { var apiCall = ATS.apiCalls[i]; if (new RegExp(searchStr.toLowerCase()).test(apiCall.toLowerCase())) { $('#api-call-' + apiCall).show(); } } } } ATS.submitForm = function(form) { var url = '/life'; var params = {}; for (i = 0; i < form.elements.length; i++) { if (form.elements[i].type != 'button' && form.elements[i].value && form.elements[i].value != 'submit') { var key = form.elements[i].name; var value = form.elements[i].value; if(key in params) { var index = params[key].length; params[key][index] = value; } else { params[key] = [value]; } } } $.ajax({ url: url, type: 'POST', data: params, traditional: true // "true" needed for duplicate params }) .done(function(result) { var resultStr = JSON.stringify(JSON.parse(result), null, 4); var code_elem = form.getElementsByClassName("result")[0]; code_elem.textContent = resultStr; hljs.highlightBlock(code_elem); }) .error(function() { alert('API not available, check if Life Server is running!'); }); if ($(form).has('.uri-link').length > 0) { var uri = '/life?' + jQuery.param(params, true); var html = '<a href="' + uri + '" target="_blank" style="font-size:12px;font-weight:normal;">Open GET URL</a>'; form.getElementsByClassName("uri-link")[0].innerHTML = html; } return false; } ATS.selectedApiCallsChange = function() { var newUrl = '/test?requestTypes=' + encodeURIComponent(ATS.selectedApiCalls.join('_')); $('#navi-selected').attr('href', newUrl); $('#navi-selected').text('SELECTED (' + ATS.selectedApiCalls.length + ')'); ATS.setCookie('selected_api_calls', ATS.selectedApiCalls.join('_'), 30); } ATS.setSelectedApiCalls = function() { var calls = []; var getParam = ATS.getUrlParameter('requestTypes'); var cookieParam = ATS.getCookie('selected_api_calls'); if (getParam != undefined && getParam != '') { calls=getParam.split('_'); } else if (cookieParam != undefined && cookieParam != ''){ calls=cookieParam.split('_'); } for (var i=0; i<calls.length; i++) { $('#api-call-sel-' + calls[i]).prop('checked', true); } return calls; } ATS.addToSelected = function(elem) { var type=elem.attr('id').substr(13); elem.prop('checked', true); if($.inArray(type, ATS.selectedApiCalls) == -1) { ATS.selectedApiCalls.push(type); ATS.selectedApiCallsChange(); } } ATS.removeFromSelected = function(elem) { var type=elem.attr('id').substr(13); elem.prop('checked', false); var index = ATS.selectedApiCalls.indexOf(type); if (index > -1) { ATS.selectedApiCalls.splice(index, 1); ATS.selectedApiCallsChange(); } } return ATS; }(ATS || {}, jQuery)); $(document).ready(function() { ATS.init(); });
YawLife/LIFE
html/ui/js/ats.js
JavaScript
mit
6,337
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _assign = require('lodash/assign'); var _assign2 = _interopRequireDefault(_assign); exports.default = termsAggregation; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /** * Construct a Terms aggregation. * * @param {String} field Field name to aggregate over. * @param {String} name Aggregation name. Defaults to agg_terms_<field>. * @param {Object} opts Additional options to include in the aggregation. * @return {Object} Terms aggregation. */ function termsAggregation(field, name, opts) { name = name || 'agg_terms_' + field; return _defineProperty({}, name, { terms: function () { return (0, _assign2.default)({ field: field }, opts); }() }); }
evgenypoyarkov/bodybuilder
lib/aggregations/terms-aggregation.js
JavaScript
mit
1,036
YUI.add('selector', function (Y, NAME) { }, '3.10.3', {"requires": ["selector-native"]});
braz/mojito-helloworld
node_modules/mojito/node_modules/yui/selector/selector.js
JavaScript
mit
93
'use strict'; //Setting up route angular.module('mean.articles').config(['$stateProvider', 'markedProvider', function($stateProvider, markedProvider) { markedProvider.setOptions({ gfm: true, tables: true, breaks: true, highlight: function (code) { /* jshint ignore:start */ return hljs.highlightAuto(code).value; /* jshint ignore:end */ } }); // Check if the user is connected var checkLoggedin = function($q, $timeout, $http, $location) { // Initialize a new promise var deferred = $q.defer(); // Make an AJAX call to check if the user is logged in $http.get('/loggedin').success(function(user) { // Authenticated if (user !== '0') $timeout(deferred.resolve); // Not Authenticated else { $timeout(deferred.reject); $location.url('/login'); } }); return deferred.promise; }; // states for my app $stateProvider .state('all articles', { url: '/articles', templateUrl: 'articles/views/list.html', //resolve: { // loggedin: checkLoggedin //} }) .state('create article', { url: '/articles/create', templateUrl: 'articles/views/create.html', resolve: { loggedin: checkLoggedin } }) .state('edit article', { url: '/articles/:articleId/edit', templateUrl: 'articles/views/edit.html', resolve: { loggedin: checkLoggedin } }) .state('article by id', { url: '/articles/:articleId', templateUrl: 'articles/views/view.html', //resolve: { // loggedin: checkLoggedin //} }); } ]);
darul75/nsjoy.github.io2
packages/articles/public/routes/articles.js
JavaScript
mit
1,768
BASE.require(["Object"], function () { BASE.namespace("LG.core.dataModel.core"); LG.core.dataModel.core.PeopleGroupToPermission = (function (Super) { var PeopleGroupToPermission = function () { var self = this; if (!(self instanceof arguments.callee)) { return new PeopleGroupToPermission(); } Super.call(self); return self; }; BASE.extend(PeopleGroupToPermission, Super); return PeopleGroupToPermission; }(Object)); });
jaredjbarnes/WoodlandCreatures
packages/WebLib.2.0.0.724/content/lib/weblib/lib/BASE/LG/core/dataModel/core/PeopleGroupToPermission.js
JavaScript
mit
545
/* global chrome */ const VERSION = 1; const handlers = { 'vclub:screenShare:requestSourceId': () => { chrome.runtime.sendMessage({ type: 'vclub:requestSourceId' }, (response) => { window.postMessage({ type: 'vclub:screenShare:response', response, }, '*'); }); }, 'vclub:ping': () => { window.postMessage({ type: 'vclub:extension:loaded', version: VERSION, }, '*'); }, }; window.addEventListener('message', (event) => { if (event.source !== window) return; const handler = handlers[event.data.type]; if (handler) { handler(event.data, event); } }); handlers['vclub:ping']();
VirtualClub/vclub
browserExtensions/chromeExtension/content-script.js
JavaScript
mit
658
'use strict'; var Pagelet = require('pagelet') , async = require('async') , path = require('path'); Pagelet.extend({ view: 'view.ejs', css: 'css.styl', js: 'client.js', // // Allow FORM submits to be streaming. // streaming: true, // // Force a name. // name: 'service-select', // // What data needs to be synced with the front-end. // query: ['services'], pagelets: { target: Pagelet.extend({ view: 'target.ejs', streaming: true }).on(module) }, // // External dependencies that should be included on the page using a regular // script tag. This dependency is needed for the `package.js` client file. // dependencies: [ path.join(__dirname, '/selectize.default.css'), '//code.jquery.com/jquery-2.1.0.min.js', path.join(__dirname, '/selectize.js') ], /** * Respond to POST requests. * * @param {Object} fields The input fields. * @param {Object} files Optional uploaded files. * @param {Function} next Completion callback. * @api public */ post: function post(fields, files, next) { if ('delete' in fields) { this.remove(fields, next); } else if ('add' in fields) { this.add(fields, next); } else { next(new Error('Invalid form data')); } }, /** * Called when a new service has to be added. * * @param {Object} data The data to add. * @param {FUnction} next Continuation function. * @api public */ add: function add(data, next) { throw new Error([ 'You, as a developer need to implement the `.add` method of the service', 'select pagelet. If you dont know how to do this, see the documenation', 'about Pagelet.extend({});' ].join(' ')); }, /** * A service has been removed from the UI. * * @param {Object} data The data containing the info about the service */ remove: function remove(data, next) { throw new Error([ 'You, as a developer need to implement the `.remove` method of the service', 'select pagelet. If you dont know how to do this, see the documenation', 'about Pagelet.extend({});' ].join(' ')); }, /** * The available services that should be listed in the UI. * * @param {Function} next Continuation callback * @api public */ services: function services(next) { throw new Error([ 'You, as a developer need to implement the `.services` method of the service', 'select pagelet. If you dont know how to do this, see the documenation', 'about Pagelet.extend({});' ].join(' ')); }, /** * List of added services that should be displayed in the UI. * * @param {Fucntion} next Continuation callback. * @api public */ added: function added(next) { throw new Error([ 'You, as a developer need to implement the `.added` method of the service', 'select pagelet. If you dont know how to do this, see the documenation', 'about Pagelet.extend({});' ].join(' ')); }, /** * Render the HTML things. * * @param {Function} done Continuation callback. * @api public */ get: function get(done) { var pagelet = this; async.parallel({ services: this.services.bind(this), added: this.added.bind(this) }, function completed(err, data) { if (err) return done(err); data.services = data.services || []; data.added = data.added || []; ['services', 'added'].forEach(function transform(key) { if (Array.isArray(data[key])) return; data[key] = Object.keys(data[key]).map(function map(name) { var thing = data[key][name]; thing.name = thing.name || name; return thing; }); }); data.description = pagelet.description; data.name = pagelet.name.replace('-', ' '); data.name = data.name.slice(0, 1).toUpperCase() + data.name.slice(1); done(err, data); }); } }).on(module);
nodejitsu/service-select
index.js
JavaScript
mit
3,961
function listEvent(login, userCity, done, fail, always) { done = typeof done !== 'undefined' ? done : function() { }; fail = typeof fail !== 'undefined' ? fail : function() { }; always = typeof always !== 'undefined' ? always : function() { }; $.ajax({ url : 'rest/event/' + login + '/' + userCity, type : 'GET' }).done(done).fail(fail).always(always); } function joinEvent(login, eventId, done, fail, always) { done = typeof done !== 'undefined' ? done : function() { }; fail = typeof fail !== 'undefined' ? fail : function() { }; always = typeof always !== 'undefined' ? always : function() { }; $.ajax({ url : 'rest/event/' + eventId + '/' + login, type : 'POST' }).done(done).fail(fail).always(always); }
michada/HYS2
DAAExample-master/src/main/webapp/js/dao/event.js
JavaScript
mit
737
module.exports = Transport; var C = { // Transport status codes STATUS_READY: 0, STATUS_DISCONNECTED: 1, STATUS_ERROR: 2 }; /** * Expose C object. */ Transport.C = C; /** * Dependencies. */ var debug = require('debug')('JsSIP:Transport'); var debugerror = require('debug')('JsSIP:ERROR:Transport'); debugerror.log = console.warn.bind(console); var JsSIP_C = require('./Constants'); var Parser = require('./Parser'); var UA = require('./UA'); var SIPMessage = require('./SIPMessage'); var sanityCheck = require('./sanityCheck'); // 'websocket' module uses the native WebSocket interface when bundled to run in a browser. var W3CWebSocket = require('websocket').w3cwebsocket; function Transport(ua, server) { this.ua = ua; this.ws = null; this.server = server; this.reconnection_attempts = 0; this.closed = false; this.connected = false; this.reconnectTimer = null; this.lastTransportError = {}; /** * Options for the Node "websocket" library. */ this.node_websocket_options = this.ua.configuration.node_websocket_options || {}; // Add our User-Agent header. this.node_websocket_options.headers = this.node_websocket_options.headers || {}; this.node_websocket_options.headers['User-Agent'] = JsSIP_C.USER_AGENT; } Transport.prototype = { /** * Connect socket. */ connect: function() { var transport = this; if(this.ws && (this.ws.readyState === this.ws.OPEN || this.ws.readyState === this.ws.CONNECTING)) { debug('WebSocket ' + this.server.ws_uri + ' is already connected'); return false; } if(this.ws) { this.ws.close(); } debug('connecting to WebSocket ' + this.server.ws_uri); this.ua.onTransportConnecting(this, (this.reconnection_attempts === 0)?1:this.reconnection_attempts); try { // Hack in case W3CWebSocket is not the class exported by Node-WebSocket // (may just happen if the above `var W3CWebSocket` line is overriden by // `var W3CWebSocket = global.W3CWebSocket`). if (W3CWebSocket.length > 3) { this.ws = new W3CWebSocket(this.server.ws_uri, 'sip', this.node_websocket_options.origin, this.node_websocket_options.headers, this.node_websocket_options.requestOptions, this.node_websocket_options.clientConfig); } else { this.ws = new W3CWebSocket(this.server.ws_uri, 'sip'); } this.ws.binaryType = 'arraybuffer'; this.ws.onopen = function() { transport.onOpen(); }; this.ws.onclose = function(e) { transport.onClose(e); }; this.ws.onmessage = function(e) { transport.onMessage(e); }; this.ws.onerror = function(e) { transport.onError(e); }; } catch(e) { debugerror('error connecting to WebSocket ' + this.server.ws_uri + ': ' + e); this.lastTransportError.code = null; this.lastTransportError.reason = e.message; this.ua.onTransportError(this); } }, /** * Disconnect socket. */ disconnect: function() { if(this.ws) { // Clear reconnectTimer clearTimeout(this.reconnectTimer); // TODO: should make this.reconnectTimer = null here? this.closed = true; debug('closing WebSocket ' + this.server.ws_uri); this.ws.close(); } // TODO: Why this?? if (this.reconnectTimer !== null) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; this.ua.onTransportDisconnected({ transport: this, code: this.lastTransportError.code, reason: this.lastTransportError.reason }); } }, /** * Send a message. */ send: function(msg) { var message = msg.toString(); if(this.ws && this.ws.readyState === this.ws.OPEN) { debug('sending WebSocket message:\n%s\n', message); this.ws.send(message); return true; } else { debugerror('unable to send message, WebSocket is not open'); return false; } }, // Transport Event Handlers onOpen: function() { this.connected = true; debug('WebSocket ' + this.server.ws_uri + ' connected'); // Clear reconnectTimer since we are not disconnected if (this.reconnectTimer !== null) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } // Reset reconnection_attempts this.reconnection_attempts = 0; // Disable closed this.closed = false; // Trigger onTransportConnected callback this.ua.onTransportConnected(this); }, onClose: function(e) { var connected_before = this.connected; this.connected = false; this.lastTransportError.code = e.code; this.lastTransportError.reason = e.reason; debug('WebSocket disconnected (code: ' + e.code + (e.reason? '| reason: ' + e.reason : '') +')'); if(e.wasClean === false) { debugerror('WebSocket abrupt disconnection'); } // Transport was connected if (connected_before === true) { this.ua.onTransportClosed(this); // Check whether the user requested to close. if(!this.closed) { this.reConnect(); } } else { // This is the first connection attempt // May be a network error (or may be UA.stop() was called) this.ua.onTransportError(this); } }, onMessage: function(e) { var message, transaction, data = e.data; // CRLF Keep Alive response from server. Ignore it. if(data === '\r\n') { debug('received WebSocket message with CRLF Keep Alive response'); return; } // WebSocket binary message. else if (typeof data !== 'string') { try { data = String.fromCharCode.apply(null, new Uint8Array(data)); } catch(evt) { debugerror('received WebSocket binary message failed to be converted into string, message discarded'); return; } debug('received WebSocket binary message:\n%s\n', data); } // WebSocket text message. else { debug('received WebSocket text message:\n%s\n', data); } message = Parser.parseMessage(data, this.ua); if (! message) { return; } if(this.ua.status === UA.C.STATUS_USER_CLOSED && message instanceof SIPMessage.IncomingRequest) { return; } // Do some sanity check if(! sanityCheck(message, this.ua, this)) { return; } if(message instanceof SIPMessage.IncomingRequest) { message.transport = this; this.ua.receiveRequest(message); } else if(message instanceof SIPMessage.IncomingResponse) { /* Unike stated in 18.1.2, if a response does not match * any transaction, it is discarded here and no passed to the core * in order to be discarded there. */ switch(message.method) { case JsSIP_C.INVITE: transaction = this.ua.transactions.ict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; case JsSIP_C.ACK: // Just in case ;-) break; default: transaction = this.ua.transactions.nict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; } } }, onError: function(e) { debugerror('WebSocket connection error: %o', e); }, /** * Reconnection attempt logic. */ reConnect: function() { var transport = this; this.reconnection_attempts += 1; if(this.reconnection_attempts > this.ua.configuration.ws_server_max_reconnection) { debugerror('maximum reconnection attempts for WebSocket ' + this.server.ws_uri); this.ua.onTransportError(this); } else { debug('trying to reconnect to WebSocket ' + this.server.ws_uri + ' (reconnection attempt ' + this.reconnection_attempts + ')'); this.reconnectTimer = setTimeout(function() { transport.connect(); transport.reconnectTimer = null; }, this.ua.configuration.ws_server_reconnection_timeout * 1000); } } };
rusekr/JsSIP
lib/Transport.js
JavaScript
mit
8,034
'use strict'; require('../../../lib/common/init'); var assert = require('assert'), request = require('supertest'), danf = require('../../../lib/server/app')(require('../../fixture/http/danf'), null, {environment: 'test', verbosity: 0, cluster: null}) ; danf.buildServer(function(app) { describe('SessionHandler', function() { it('should allow to get and set values in session', function(done) { request(app) .get('/session/0') .expect(204) .end(function(err, res) { if (err) { if (res) { console.log(res.text); } else { console.log(err); } throw err; } done(); }) ; }) it('should allow to regenerate the session', function(done) { request(app) .get('/session/1') .expect(204) .end(function(err, res) { if (err) { if (res) { console.log(res.text); } else { console.log(err); } throw err; } done(); }) ; }) it('should allow to destroy a session', function(done) { request(app) .get('/session/2') .expect(500) .end(function(err, res) { if (err) { if (res) { /^The session does not exist or has been destroyed\./.test(res.text); } else { /^The session does not exist or has been destroyed\./.test(err); } throw err; } done(); }) ; }) it('should allow to save and reload a session', function(done) { request(app) .get('/session/3') .expect(204) .end(function(err, res) { if (err) { if (res) { console.log(res.text); } else { console.log(err); } throw err; } done(); }) ; }) }) });
Gnucki/danf
test/unit/http/session-handler.js
JavaScript
mit
2,669
/** * @author Richard Davey <[email protected]> * @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var CONST = require('../../const'); var Smoothing = require('./Smoothing'); // The pool into which the canvas elements are placed. var pool = []; // Automatically apply smoothing(false) to created Canvas elements var _disableContextSmoothing = false; /** * The CanvasPool is a global static object, that allows Phaser to recycle and pool 2D Context Canvas DOM elements. * It does not pool WebGL Contexts, because once the context options are set they cannot be modified again, * which is useless for some of the Phaser pipelines / renderer. * * This singleton is instantiated as soon as Phaser loads, before a Phaser.Game instance has even been created. * Which means all instances of Phaser Games on the same page can share the one single pool. * * @namespace Phaser.Display.Canvas.CanvasPool * @since 3.0.0 */ var CanvasPool = function () { /** * Creates a new Canvas DOM element, or pulls one from the pool if free. * * @function Phaser.Display.Canvas.CanvasPool.create * @since 3.0.0 * * @param {*} parent - The parent of the Canvas object. * @param {integer} [width=1] - The width of the Canvas. * @param {integer} [height=1] - The height of the Canvas. * @param {integer} [canvasType=Phaser.CANVAS] - The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. * @param {boolean} [selfParent=false] - Use the generated Canvas element as the parent? * * @return {HTMLCanvasElement} The canvas element that was created or pulled from the pool */ var create = function (parent, width, height, canvasType, selfParent) { if (width === undefined) { width = 1; } if (height === undefined) { height = 1; } if (canvasType === undefined) { canvasType = CONST.CANVAS; } if (selfParent === undefined) { selfParent = false; } var canvas; var container = first(canvasType); if (container === null) { container = { parent: parent, canvas: document.createElement('canvas'), type: canvasType }; if (canvasType === CONST.CANVAS) { pool.push(container); } canvas = container.canvas; } else { container.parent = parent; canvas = container.canvas; } if (selfParent) { container.parent = canvas; } canvas.width = width; canvas.height = height; if (_disableContextSmoothing && canvasType === CONST.CANVAS) { Smoothing.disable(canvas.getContext('2d')); } return canvas; }; /** * Creates a new Canvas DOM element, or pulls one from the pool if free. * * @function Phaser.Display.Canvas.CanvasPool.create2D * @since 3.0.0 * * @param {*} parent - The parent of the Canvas object. * @param {integer} [width=1] - The width of the Canvas. * @param {integer} [height=1] - The height of the Canvas. * * @return {HTMLCanvasElement} The created canvas. */ var create2D = function (parent, width, height) { return create(parent, width, height, CONST.CANVAS); }; /** * Creates a new Canvas DOM element, or pulls one from the pool if free. * * @function Phaser.Display.Canvas.CanvasPool.createWebGL * @since 3.0.0 * * @param {*} parent - The parent of the Canvas object. * @param {integer} [width=1] - The width of the Canvas. * @param {integer} [height=1] - The height of the Canvas. * * @return {HTMLCanvasElement} The created WebGL canvas. */ var createWebGL = function (parent, width, height) { return create(parent, width, height, CONST.WEBGL); }; /** * Gets the first free canvas index from the pool. * * @function Phaser.Display.Canvas.CanvasPool.first * @since 3.0.0 * * @param {integer} [canvasType=Phaser.CANVAS] - The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. * * @return {HTMLCanvasElement} The first free canvas, or `null` if a WebGL canvas was requested or if the pool doesn't have free canvases. */ var first = function (canvasType) { if (canvasType === undefined) { canvasType = CONST.CANVAS; } if (canvasType === CONST.WEBGL) { return null; } for (var i = 0; i < pool.length; i++) { var container = pool[i]; if (!container.parent && container.type === canvasType) { return container; } } return null; }; /** * Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use. * The canvas has its width and height set to 1, and its parent attribute nulled. * * @function Phaser.Display.Canvas.CanvasPool.remove * @since 3.0.0 * * @param {*} parent - The canvas or the parent of the canvas to free. */ var remove = function (parent) { // Check to see if the parent is a canvas object var isCanvas = parent instanceof HTMLCanvasElement; pool.forEach(function (container) { if ((isCanvas && container.canvas === parent) || (!isCanvas && container.parent === parent)) { container.parent = null; container.canvas.width = 1; container.canvas.height = 1; } }); }; /** * Gets the total number of used canvas elements in the pool. * * @function Phaser.Display.Canvas.CanvasPool.total * @since 3.0.0 * * @return {integer} The number of used canvases. */ var total = function () { var c = 0; pool.forEach(function (container) { if (container.parent) { c++; } }); return c; }; /** * Gets the total number of free canvas elements in the pool. * * @function Phaser.Display.Canvas.CanvasPool.free * @since 3.0.0 * * @return {integer} The number of free canvases. */ var free = function () { return pool.length - total(); }; /** * Disable context smoothing on any new Canvas element created. * * @function Phaser.Display.Canvas.CanvasPool.disableSmoothing * @since 3.0.0 */ var disableSmoothing = function () { _disableContextSmoothing = true; }; /** * Enable context smoothing on any new Canvas element created. * * @function Phaser.Display.Canvas.CanvasPool.enableSmoothing * @since 3.0.0 */ var enableSmoothing = function () { _disableContextSmoothing = false; }; return { create2D: create2D, create: create, createWebGL: createWebGL, disableSmoothing: disableSmoothing, enableSmoothing: enableSmoothing, first: first, free: free, pool: pool, remove: remove, total: total }; }; // If we export the called function here, it'll only be invoked once (not every time it's required). module.exports = CanvasPool();
mahill/phaser
src/display/canvas/CanvasPool.js
JavaScript
mit
7,526
import React from 'react'; import { Link as RouterLink } from 'react-router'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import counterActions from 'actions/counter'; import Radium from 'radium'; import { Scroll, Link, Element, Events } from 'react-scroll'; import { FlatButton, Paper } from 'material-ui/lib'; import { styles } from 'styles/HomeViewStyles'; const mapStateToProps = (state) => ({ counter: state.counter, routerState: state.router }); const mapDispatchToProps = (dispatch) => ({ actions: bindActionCreators(counterActions, dispatch) }); @Radium class HomeView extends React.Component { static propTypes = { actions: React.PropTypes.object, counter: React.PropTypes.number } render() { return ( <div className='landing main-body' style={styles.mainBody}> <div style={styles.heroDiv}> <img src={require('styles/assets/splash3.png')} style={styles.heroImg} draggable='false' /> <div style={styles.heroText}> a simple, intuitive, <br/>drag-and-drop resume builder </div> {Radium.getState(this.state, 'callToAction', 'hover')} <RouterLink to='/resume'> <div style={styles.callToAction} key='callToAction'> get started </div> </RouterLink> {Radium.getState(this.state, 'circle', 'hover')} <Link to='Features' spy={true} smooth={true} duration={800}> <div style={styles.circle} key='circle'> <img src={require('styles/assets/downArrow.png')} style={styles.downArrow} /> </div> </Link> <div style={styles.diagonalLine}></div> </div> <div style={styles.grayDivMiddle}> <div style={styles.copy}> <Element name='Features'> <div style={styles.wysiwyg}>what you see is what you get</div> <div style={styles.video}> <iframe src="https://player.vimeo.com/video/149104789?color=ff9f10&title=0&byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> </Element> <div style={styles.middleCopy}> <div>Import your information from LinkedIn</div> <div>Save your progress to the cloud</div> <div>Easily print or export to PDF when you're done</div> </div> <RouterLink to='/resume'> <div style={styles.getStartedButton}> get started </div> </RouterLink> </div> </div> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(HomeView); /* Here lies the counter. It was a good counter; it incremented when clicked. But it was more than just a simple counter. It was a window into another world; a stateful lighthouse to our souls. The counter is dead. Long live the counter! <div style={{ margin: '20px' }}> <div style={{ margin: '5px' }}> For no reason, a counter: {this.props.counter} </div> <RaisedButton label='Increment' onClick={this.props.actions.increment} /> </div> */
dont-fear-the-repo/fear-the-repo
src/views/HomeView.js
JavaScript
mit
3,354
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./app.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./app.ts": /*!****************!*\ !*** ./app.ts ***! \****************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; eval("\nexports.__esModule = true;\nconsole.log('do something');\n// The DEBUG constant will be inlined by webpack's DefinePlugin (see config)\n// The whole if-statement can then be removed by UglifyJS\nif (false) { var debug; }\nconsole.log('do something else');\n\n\n//# sourceURL=webpack:///./app.ts?"); /***/ }) /******/ });
jbrantly/ts-loader
test/comparison-tests/conditionalRequire/expectedOutput-2.8/bundle.js
JavaScript
mit
3,132
/* */ var cof = require("./_cof"), TAG = require("./_wks")('toStringTag'), ARG = cof(function() { return arguments; }()) == 'Arguments'; module.exports = function(it) { var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' : typeof(T = (O = Object(it))[TAG]) == 'string' ? T : ARG ? cof(O) : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; };
jdanyow/aurelia-plunker
jspm_packages/npm/[email protected]/modules/_classof.js
JavaScript
mit
427
var searchData= [ ['analogread',['analogRead',['../_arduino_8h.html#a13782c0f73097cea014616d749e7c52d',1,'analogRead(uint8_t):&#160;wiring_analog.c'],['../wiring__analog_8c.html#a2eda513a6bb35bf13675a24711d4e864',1,'analogRead(uint8_t pin):&#160;wiring_analog.c']]], ['analogreference',['analogReference',['../_arduino_8h.html#a529863849f86a63b517cd96cbcd47705',1,'analogReference(uint8_t mode):&#160;wiring_analog.c'],['../wiring__analog_8c.html#a529863849f86a63b517cd96cbcd47705',1,'analogReference(uint8_t mode):&#160;wiring_analog.c']]], ['analogwrite',['analogWrite',['../_arduino_8h.html#a428477da35f3b1cf51bc2653125d9d9d',1,'analogWrite(uint8_t, int):&#160;wiring_analog.c'],['../wiring__analog_8c.html#a62a628c40d93ea1823a1cdb8cae9e7be',1,'analogWrite(uint8_t pin, int val):&#160;wiring_analog.c']]], ['atexit',['atexit',['../_arduino_8h.html#a2f34e9ad40b966beef5bda170015d19b',1,'atexit(void(*func)()) __attribute__((weak)):&#160;main.cpp'],['../main_8cpp.html#a7962f8536e3c743c8380411e184c7e2f',1,'atexit(void(*func)()):&#160;main.cpp']]], ['attachinterrupt',['attachInterrupt',['../_arduino_8h.html#a3ed3d1d750935833a6f9b0363a5e6f13',1,'attachInterrupt(uint8_t, void(*)(void), int mode):&#160;WInterrupts.c'],['../_w_interrupts_8c.html#ad0d73becebba7c663f8e9ed73efee544',1,'attachInterrupt(uint8_t interruptNum, void(*userFunc)(void), int mode):&#160;WInterrupts.c']]], ['available',['available',['../class_client.html#aebd60457902debb30b07971a16f24ebd',1,'Client::available()'],['../class_hardware_serial.html#aeec8f4dbef97221a6041d6cdc6e9b716',1,'HardwareSerial::available()'],['../class_stream.html#aebd60457902debb30b07971a16f24ebd',1,'Stream::available()'],['../class_u_d_p.html#aebd60457902debb30b07971a16f24ebd',1,'UDP::available()']]], ['availableforwrite',['availableForWrite',['../class_hardware_serial.html#a4afe5933dbdb0ad962857d00e04c3bfc',1,'HardwareSerial']]] ];
trex2000/Arobs-Academy
Doxygen Generated/html/search/functions_1.js
JavaScript
mit
1,903
/* eslint node/no-unsupported-features: ["error", { version: 4 }] */ // this file is not transpiled by Jest when configured in "snapshotSerializers" "use strict"; const _ = require("lodash"); const normalizeNewline = require("normalize-newline"); const constants = require("./constants"); const VERSION_REGEX = new RegExp(`^(?:((?:.*?version )|\\^)|v?)${constants.LERNA_VERSION}`, "gm"); const VERSION_REPLACEMENT = `$1${constants.__TEST_VERSION__}`; // TODO: maybe even less naïve regex? function needsReplacement(str) { return ( str.indexOf(constants.__TEST_VERSION__) === -1 ); } function stableVersion(str) { return str.replace(VERSION_REGEX, VERSION_REPLACEMENT); } const stabilizeString = _.flow([ normalizeNewline, stableVersion, ]); /** A snapshot serializer that replaces all instances of unstable version number with __TEST_VERSION__ when found in snapshotted strings or object properties. @see http://facebook.github.io/jest/docs/expect.html#expectaddsnapshotserializerserializer **/ module.exports = { test(thing) { return _.isString(thing) && needsReplacement(thing) || ( _.isPlainObject(thing) && _.isString(thing.lerna) && needsReplacement(thing.lerna) ); }, print(thing, serialize) { if (_.isString(thing)) { thing = stabilizeString(thing); } else if (_.isPlainObject(thing)) { thing.lerna = stableVersion(thing.lerna); } return serialize(thing); }, };
FaHeymann/lerna
test/helpers/serializePlaceholders.js
JavaScript
mit
1,443
/*! * address.js - address object for decentraland * Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * Copyright (c) 2016-2017, Manuel Araoz (MIT License). * https://github.com/decentraland/decentraland-node */ 'use strict'; var networks = require('../protocol/networks'); var constants = require('../protocol/constants'); var util = require('../utils/util'); var crypto = require('../crypto/crypto'); var assert = require('assert'); var BufferReader = require('../utils/reader'); var StaticWriter = require('../utils/staticwriter'); var base58 = require('../utils/base58'); var scriptTypes = constants.scriptTypes; /** * Represents an address. * @exports Address * @constructor * @param {Object} options * @param {Buffer|Hash} options.hash - Address hash. * @param {AddressType} options.type - Address type * `{witness,}{pubkeyhash,scripthash}`. * @param {Number} [options.version=-1] - Witness program version. * @property {Buffer} hash * @property {AddressType} type * @property {Number} version */ function Address(options) { if (!(this instanceof Address)) return new Address(options); this.hash = constants.ZERO_HASH160; this.type = scriptTypes.PUBKEYHASH; this.version = -1; var Network = require('../protocol/network'); this.network = Network.primary; if (options) this.fromOptions(options); } /** * Address types. * @enum {Number} */ Address.types = scriptTypes; /** * Inject properties from options object. * @private * @param {Object} options */ Address.prototype.fromOptions = function fromOptions(options) { if (typeof options === 'string') return this.fromBase58(options); if (Buffer.isBuffer(options)) return this.fromRaw(options); return this.fromHash( options.hash, options.type, options.version, options.network ); }; /** * Insantiate address from options. * @param {Object} options * @returns {Address} */ Address.fromOptions = function fromOptions(options) { return new Address().fromOptions(options); }; /** * Get the address hash. * @param {String?} enc - Can be `"hex"` or `null`. * @returns {Hash|Buffer} */ Address.prototype.getHash = function getHash(enc) { if (enc === 'hex') return this.hash.toString(enc); return this.hash; }; /** * Get a network address prefix for the address. * @returns {Number} */ Address.prototype.getPrefix = function getPrefix(network) { if (!network) network = this.network; var Network = require('../protocol/network'); network = Network.get(network); return Address.getPrefix(this.type, network); }; /** * Verify an address network (compares prefixes). * @returns {Boolean} */ Address.prototype.verifyNetwork = function verifyNetwork(network) { assert(network); return this.getPrefix() === this.getPrefix(network); }; /** * Get the address type as a string. * @returns {AddressType} */ Address.prototype.getType = function getType() { return constants.scriptTypesByVal[this.type].toLowerCase(); }; /** * Calculate size of serialized address. * @returns {Number} */ Address.prototype.getSize = function getSize() { var size = 5 + this.hash.length; if (this.version !== -1) size += 2; return size; }; /** * Compile the address object to its raw serialization. * @returns {Buffer} * @throws Error on bad hash/prefix. */ Address.prototype.toRaw = function toRaw(network) { var size = this.getSize(); var bw = new StaticWriter(size); var prefix = this.getPrefix(network); assert(prefix !== -1, 'Not a valid address prefix.'); bw.writeU8(prefix); if (this.version !== -1) { bw.writeU8(this.version); bw.writeU8(0); } bw.writeBytes(this.hash); bw.writeChecksum(); return bw.render(); }; /** * Compile the address object to a base58 address. * @returns {Base58Address} * @throws Error on bad hash/prefix. */ Address.prototype.toBase58 = function toBase58(network) { return base58.encode(this.toRaw(network)); }; /** * Convert the Address to a string. * @returns {Base58Address} */ Address.prototype.toString = function toString() { return this.toBase58(); }; /** * Inspect the Address. * @returns {Object} */ Address.prototype.inspect = function inspect() { return '<Address:' + ' type=' + this.getType() + ' version=' + this.version + ' base58=' + this.toBase58() + '>'; }; /** * Inject properties from serialized data. * @private * @param {Buffer} data * @throws Parse error */ Address.prototype.fromRaw = function fromRaw(data) { var br = new BufferReader(data, true); var i, prefix, network, type, version, hash; prefix = br.readU8(); for (i = 0; i < networks.types.length; i++) { network = networks[networks.types[i]]; type = Address.getType(prefix, network); if (type !== -1) break; } assert(i < networks.types.length, 'Unknown address prefix.'); if (data.length > 25) { version = br.readU8(); assert(br.readU8() === 0, 'Address version padding is non-zero.'); } else { version = -1; } hash = br.readBytes(br.left() - 4); br.verifyChecksum(); return this.fromHash(hash, type, version, network.type); }; /** * Create an address object from a serialized address. * @param {Buffer} data * @returns {Address} * @throws Parse error. */ Address.fromRaw = function fromRaw(data) { return new Address().fromRaw(data); }; /** * Inject properties from base58 address. * @private * @param {Base58Address} data * @throws Parse error */ Address.prototype.fromBase58 = function fromBase58(data) { assert(typeof data === 'string'); return this.fromRaw(base58.decode(data)); }; /** * Create an address object from a base58 address. * @param {Base58Address} address * @returns {Address} * @throws Parse error. */ Address.fromBase58 = function fromBase58(address) { return new Address().fromBase58(address); }; /** * Inject properties from output script. * @private * @param {Script} script */ Address.prototype.fromScript = function fromScript(script) { if (script.isPubkey()) { this.hash = crypto.hash160(script.get(0)); this.type = scriptTypes.PUBKEYHASH; this.version = -1; return this; } if (script.isPubkeyhash()) { this.hash = script.get(2); this.type = scriptTypes.PUBKEYHASH; this.version = -1; return this; } if (script.isScripthash()) { this.hash = script.get(1); this.type = scriptTypes.SCRIPTHASH; this.version = -1; return this; } if (script.isWitnessPubkeyhash()) { this.hash = script.get(1); this.type = scriptTypes.WITNESSPUBKEYHASH; this.version = 0; return this; } if (script.isWitnessScripthash()) { this.hash = script.get(1); this.type = scriptTypes.WITNESSSCRIPTHASH; this.version = 0; return this; } if (script.isWitnessMasthash()) { this.hash = script.get(1); this.type = scriptTypes.WITNESSSCRIPTHASH; this.version = 1; return this; } // Put this last: it's the slowest to check. if (script.isMultisig()) { this.hash = script.hash160(); this.type = scriptTypes.SCRIPTHASH; this.version = -1; return this; } }; /** * Inject properties from witness. * @private * @param {Witness} witness */ Address.prototype.fromWitness = function fromWitness(witness) { // We're pretty much screwed here // since we can't get the version. if (witness.isPubkeyhashInput()) { this.hash = crypto.hash160(witness.get(1)); this.type = scriptTypes.WITNESSPUBKEYHASH; this.version = 0; return this; } if (witness.isScripthashInput()) { this.hash = crypto.sha256(witness.get(witness.length - 1)); this.type = scriptTypes.WITNESSSCRIPTHASH; this.version = 0; return this; } }; /** * Inject properties from input script. * @private * @param {Script} script */ Address.prototype.fromInputScript = function fromInputScript(script) { if (script.isPubkeyhashInput()) { this.hash = crypto.hash160(script.get(1)); this.type = scriptTypes.PUBKEYHASH; this.version = -1; return this; } if (script.isScripthashInput()) { this.hash = crypto.hash160(script.get(script.length - 1)); this.type = scriptTypes.SCRIPTHASH; this.version = -1; return this; } }; /** * Create an Address from a witness. * Attempt to extract address * properties from a witness. * @param {Witness} * @returns {Address|null} */ Address.fromWitness = function fromWitness(witness) { return new Address().fromWitness(witness); }; /** * Create an Address from an input script. * Attempt to extract address * properties from an input script. * @param {Script} * @returns {Address|null} */ Address.fromInputScript = function fromInputScript(script) { return new Address().fromInputScript(script); }; /** * Create an Address from an output script. * Parse an output script and extract address * properties. Converts pubkey and multisig * scripts to pubkeyhash and scripthash addresses. * @param {Script} * @returns {Address|null} */ Address.fromScript = function fromScript(script) { return new Address().fromScript(script); }; /** * Inject properties from a hash. * @private * @param {Buffer|Hash} hash * @param {AddressType} type * @param {Number} [version=-1] * @throws on bad hash size */ Address.prototype.fromHash = function fromHash(hash, type, version, network) { if (typeof hash === 'string') hash = new Buffer(hash, 'hex'); if (typeof type === 'string') type = scriptTypes[type.toUpperCase()]; if (type == null) type = scriptTypes.PUBKEYHASH; if (version == null) version = -1; var Network = require('../protocol/network'); network = Network.get(network); assert(Buffer.isBuffer(hash)); assert(util.isNumber(type)); assert(util.isNumber(version)); assert(Address.getPrefix(type, network) !== -1, 'Not a valid address type.'); if (version === -1) { assert(!Address.isWitness(type), 'Wrong version (witness)'); assert(hash.length === 20, 'Hash is the wrong size.'); } else { assert(Address.isWitness(type), 'Wrong version (non-witness).'); assert(version >= 0 && version <= 16, 'Bad program version.'); if (version === 0 && type === scriptTypes.WITNESSPUBKEYHASH) assert(hash.length === 20, 'Hash is the wrong size.'); else if (version === 0 && type === scriptTypes.WITNESSSCRIPTHASH) assert(hash.length === 32, 'Hash is the wrong size.'); else if (version === 1 && type === scriptTypes.WITNESSSCRIPTHASH) assert(hash.length === 32, 'Hash is the wrong size.'); } this.hash = hash; this.type = type; this.version = version; this.network = network; return this; }; /** * Create a naked address from hash/type/version. * @param {Buffer|Hash} hash * @param {AddressType} type * @param {Number} [version=-1] * @returns {Address} * @throws on bad hash size */ Address.fromHash = function fromHash(hash, type, version, network) { return new Address().fromHash(hash, type, version, network); }; /** * Inject properties from data. * @private * @param {Buffer|Buffer[]} data * @param {AddressType} type * @param {Number} [version=-1] */ Address.prototype.fromData = function fromData(data, type, version, network) { if (typeof type === 'string') type = scriptTypes[type.toUpperCase()]; if (type === scriptTypes.WITNESSSCRIPTHASH) { if (version === 0) { assert(Buffer.isBuffer(data)); data = crypto.sha256(data); } else if (version === 1) { assert(Array.isArray(data)); throw new Error('MASTv2 creation not implemented.'); } else { throw new Error('Cannot create from version=' + version); } } else if (type === scriptTypes.WITNESSPUBKEYHASH) { if (version !== 0) throw new Error('Cannot create from version=' + version); assert(Buffer.isBuffer(data)); data = crypto.hash160(data); } else { data = crypto.hash160(data); } return this.fromHash(data, type, version, network); }; /** * Create an Address from data/type/version. * @param {Buffer|Buffer[]} data - Data to be hashed. * Normally a buffer, but can also be an array of * buffers for MAST. * @param {AddressType} type * @param {Number} [version=-1] * @returns {Address} * @throws on bad hash size */ Address.fromData = function fromData(data, type, version, network) { return new Address().fromData(data, type, version, network); }; /** * Validate an address, optionally test against a type. * @param {Base58Address} address * @param {AddressType} * @returns {Boolean} */ Address.validate = function validate(address, type) { if (!address) return false; if (!Buffer.isBuffer(address) && typeof address !== 'string') return false; try { address = Address.fromBase58(address); } catch (e) { return false; } if (typeof type === 'string') type = scriptTypes[type.toUpperCase()]; if (type && address.type !== type) return false; return true; }; /** * Get the hex hash of a base58 * address or address object. * @param {Base58Address|Address} data * @returns {Hash|null} */ Address.getHash = function getHash(data, enc) { var hash; if (typeof data === 'string') { if (data.length === 40 || data.length === 64) return enc === 'hex' ? data : new Buffer(data, 'hex'); try { hash = Address.fromBase58(data).hash; } catch (e) { return; } } else if (Buffer.isBuffer(data)) { hash = data; } else if (data instanceof Address) { hash = data.hash; } else { return; } return enc === 'hex' ? hash.toString('hex') : hash; }; /** * Get a network address prefix for a specified address type. * @param {AddressType} type * @returns {Number} */ Address.getPrefix = function getPrefix(type, network) { var prefixes = network.addressPrefix; switch (type) { case scriptTypes.PUBKEYHASH: return prefixes.pubkeyhash; case scriptTypes.SCRIPTHASH: return prefixes.scripthash; case scriptTypes.WITNESSPUBKEYHASH: return prefixes.witnesspubkeyhash; case scriptTypes.WITNESSSCRIPTHASH: return prefixes.witnessscripthash; default: return -1; } }; /** * Get an address type for a specified network address prefix. * @param {Number} prefix * @returns {AddressType} */ Address.getType = function getType(prefix, network) { var prefixes = network.addressPrefix; switch (prefix) { case prefixes.pubkeyhash: return scriptTypes.PUBKEYHASH; case prefixes.scripthash: return scriptTypes.SCRIPTHASH; case prefixes.witnesspubkeyhash: return scriptTypes.WITNESSPUBKEYHASH; case prefixes.witnessscripthash: return scriptTypes.WITNESSSCRIPTHASH; default: return -1; } }; /** * Test whether an address type is a witness program. * @param {AddressType} type * @returns {Boolean} */ Address.isWitness = function isWitness(type) { switch (type) { case scriptTypes.WITNESSPUBKEYHASH: return true; case scriptTypes.WITNESSSCRIPTHASH: return true; default: return false; } }; /* * Expose */ module.exports = Address;
decentraland/bronzeage-node
lib/primitives/address.js
JavaScript
mit
15,225
// @flow declare module '@reach/portal' { declare export default React$ComponentType<{| children: React$Node, type?: string, |}>; }
flowtype/flow-typed
definitions/npm/@reach/portal_v0.2.x/flow_v0.84.x-/portal_v0.2.x.js
JavaScript
mit
145
version https://git-lfs.github.com/spec/v1 oid sha256:90773470146a0daefafb65539bea2a9c6537067655a435ffce48433658e3d73a size 943
yogeshsaroya/new-cdnjs
ajax/libs/highlight.js/7.5/languages/actionscript.min.js
JavaScript
mit
128
App.SubmissionsResponseController = Ember.ObjectController.extend({ actions: { saveNotes: function() { var onSuccess = function(post) { $(".alert-box").remove(); $("textarea").before("<div data-alert class='alert-box'>Your notes were saved!<a class='close'>&times;</a></div>"); }; var onFail = function(post) { $(".alert-box").remove(); $("textarea").before("<div data-alert class='alert-box alert'>Uh oh! Something went wrong...<a class='close'>&times;</a></div>"); }; var model = this.get('model'); model.save().then(onSuccess, onFail); return model; } } });
andrewjadams3/Klassewerk
app/assets/javascripts/controllers/submissions_response_controller.js
JavaScript
mit
648
'use strict'; const helpers = require('../../../src/helpers'); const assert = require('assert'); const arghun = require('../../../'); const opt = { blDir: ['even-more', 'crap', 'A-characters'] }; const expected = { './test/testData/testDirectory/B-characters': 6, './test/testData/testDirectory/B-characters/more-B': 3, './test/testData/testDirectory/B-characters/more-B/inside-B': 2, './test/testData/testDirectory/B-characters/more-B/inside-B/custom': 4, './test/testData/testDirectory/B-characters/my-man': 1, './test/testData/testDirectory/C-characters': 6, './test/testData/testDirectory/C-characters/my-man': 2, './test/testData/testDirectory/D-characters': 7, './test/testData/testDirectory/D-characters/more-and-more-D': 6, './test/testData/testDirectory/D-characters/my-man': 1, './test/testData/testDirectory/E-characters': 12, './test/testData/testDirectory/F-characters': 5, './test/testData/testDirectory/F-characters/moremoremore': 3, './test/testData/testDirectory/F-characters/my-man': 1, './test/testData/testDirectory/G-characters': 7 }; async function walkDirBlacklistDirs(path) { try { const result = await arghun.walkDir(path, opt); assert.deepEqual(result, expected, 'walkDir failed with dirs blacklist'); helpers.log('walkDir with dirs blacklist - successful'); } catch(err) { helpers.log(err); throw new Error(err); } } module.exports = walkDirBlacklistDirs;
derberg/zlicz
test/testCases/walkDir/walkDirBlacklistDirs.js
JavaScript
mit
1,491
import Ember from 'ember'; export default Ember.Route.extend({ setupController: function(controller) { controller.set('setupRoutes', [ { label: false, links: [ { href: 'heatmap.index', text: 'Setup' }, { href: 'heatmap.properties', text: 'Properties' }, { href: 'heatmap.marker', text: 'Heatmap Marker' } ] } ]); } });
Matt-Jensen/ember-cli-g-maps
tests/dummy/app/pods/heatmap/route.js
JavaScript
mit
499
(function(){ "use strict"; KC3StrategyTabs.aircraft = new KC3StrategyTab("aircraft"); KC3StrategyTabs.aircraft.definition = { tabSelf: KC3StrategyTabs.aircraft, squadNames: {}, _items: {}, _holders: {}, _slotNums: {}, /* INIT Prepares static data needed ---------------------------------*/ init :function(){ }, /* RELOAD Prepares latest player data ---------------------------------*/ reload :function(){ var self = this; this._items = {}; this._holders = {}; this._slotNums = {}; KC3ShipManager.load(); KC3GearManager.load(); PlayerManager.loadBases(); // Get squad names if(typeof localStorage.planes == "undefined"){ localStorage.planes = "{}"; } this.squadNames = JSON.parse(localStorage.planes); // Compile equipment holders var ctr, ThisItem, MasterItem, ThisShip, MasterShip; for(ctr in KC3ShipManager.list){ this.checkShipSlotForItemHolder(0, KC3ShipManager.list[ctr]); this.checkShipSlotForItemHolder(1, KC3ShipManager.list[ctr]); this.checkShipSlotForItemHolder(2, KC3ShipManager.list[ctr]); this.checkShipSlotForItemHolder(3, KC3ShipManager.list[ctr]); // No plane is able to be equipped in ex-slot for now } for(ctr in PlayerManager.bases){ this.checkLbasSlotForItemHolder(PlayerManager.bases[ctr]); } for(ctr in PlayerManager.baseConvertingSlots){ this._holders["s"+PlayerManager.baseConvertingSlots[ctr]] = "LbasMoving"; } // Compile ships on Index var thisType, thisSlotitem, thisGearInstance; function GetMyHolder(){ return self._holders["s"+this.itemId]; } function NoHolder(){ return false; } for(ctr in KC3GearManager.list){ ThisItem = KC3GearManager.list[ctr]; MasterItem = ThisItem.master(); if(!MasterItem) continue; //if(KC3GearManager.carrierBasedAircraftType3Ids.indexOf(MasterItem.api_type[3]) == -1) continue; // Add holder to the item object temporarily via function return if(typeof this._holders["s"+ThisItem.itemId] != "undefined"){ ThisItem.MyHolder = GetMyHolder; }else{ ThisItem.MyHolder = NoHolder; } // Check if slotitem_type is filled if(typeof this._items["t"+MasterItem.api_type[3]] == "undefined"){ this._items["t"+MasterItem.api_type[3]] = []; } thisType = this._items["t"+MasterItem.api_type[3]]; // Check if slotitem_id is filled if(typeof this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id] == "undefined"){ this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id] = { id: ThisItem.masterId, type_id: MasterItem.api_type[3], english: ThisItem.name(), japanese: MasterItem.api_name, stats: { fp: MasterItem.api_houg, tp: MasterItem.api_raig, aa: MasterItem.api_tyku, ar: MasterItem.api_souk, as: MasterItem.api_tais, ev: MasterItem.api_houk, ls: MasterItem.api_saku, dv: MasterItem.api_baku, ht: MasterItem.api_houm, rn: MasterItem.api_leng, or: MasterItem.api_distance }, instances: [] }; } thisSlotitem = this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id]; thisSlotitem.instances.push(ThisItem); } // sort this_items var sortMasterItem = function(a, b){ var attr; switch( i ){ case 't6': case 6: attr = 'aa'; break; case 't7': case 7: attr = 'dv'; break; case 't8': case 8: attr = 'tp'; break; case 't9': case 9: attr = 'ls'; break; case 't10': case 10: attr = 'dv'; break; default: attr = 'aa'; break; } if( b.stats[attr] == a.stats[attr] ) return b.stats.ht - a.stats.ht; return b.stats[attr] - a.stats[attr]; }; var sortSlotItem = function(a,b){ return b.ace - a.ace; }; for( var i in this._items ){ // make elements in this._items true Array for( var j in this._items[i] ){ // sort item by ace this._items[i][j].instances.sort(sortSlotItem); this._items[i].push( this._items[i][j] ); delete this._items[i][j]; } // sort MasterItem by stat this._items[i].sort(sortMasterItem); } }, /* Check a ship's equipment slot of an item is equipped --------------------------------------------*/ checkShipSlotForItemHolder :function(slot, ThisShip){ if(ThisShip.items[slot] > 0){ this._holders["s"+ThisShip.items[slot]] = ThisShip; this._slotNums["s"+ThisShip.items[slot]] = slot; } }, /* Check LBAS slot of an aircraft is equipped --------------------------------------------*/ checkLbasSlotForItemHolder :function(LandBase){ for(var squad in LandBase.planes){ if(LandBase.planes[squad].api_slotid > 0){ this._holders["s"+LandBase.planes[squad].api_slotid] = LandBase; } } }, /* EXECUTE Places data onto the interface ---------------------------------*/ execute :function(){ var self = this; $(".tab_aircraft .item_type").on("click", function(){ KC3StrategyTabs.gotoTab(null, $(this).data("type")); }); $(".tab_aircraft .item_list").on("change", ".instance_name input", function(){ self.squadNames["p"+$(this).attr("data-gearId")] = $(this).val(); localStorage.planes = JSON.stringify(self.squadNames); }); if(!!KC3StrategyTabs.pageParams[1]){ this.showType(KC3StrategyTabs.pageParams[1]); } else { this.showType($(".tab_aircraft .item_type").first().data("type")); } }, /* Show slotitem type --------------------------------------------*/ showType :function(type_id){ $(".tab_aircraft .item_type").removeClass("active"); $(".tab_aircraft .item_type[data-type={0}]".format(type_id)).addClass("active"); $(".tab_aircraft .item_list").html(""); var ctr, ThisType, ItemElem, ThisSlotitem; var gearClickFunc = function(e){ KC3StrategyTabs.gotoTab("mstgear", $(this).attr("alt")); }; var lbasPlanesFilter = function(s){ return s.api_slotid === ThisPlane.itemId; }; for(ctr in this._items["t"+type_id]){ ThisSlotitem = this._items["t"+type_id][ctr]; ItemElem = $(".tab_aircraft .factory .slotitem").clone().appendTo(".tab_aircraft .item_list"); $(".icon img", ItemElem).attr("src", "../../assets/img/items/"+type_id+".png"); $(".icon img", ItemElem).attr("alt", ThisSlotitem.id); $(".icon img", ItemElem).click(gearClickFunc); $(".english", ItemElem).text(ThisSlotitem.english); $(".japanese", ItemElem).text(ThisSlotitem.japanese); this.slotitem_stat(ItemElem, ThisSlotitem, "fp"); this.slotitem_stat(ItemElem, ThisSlotitem, "tp"); this.slotitem_stat(ItemElem, ThisSlotitem, "aa"); this.slotitem_stat(ItemElem, ThisSlotitem, "ar"); this.slotitem_stat(ItemElem, ThisSlotitem, "as"); this.slotitem_stat(ItemElem, ThisSlotitem, "ev"); this.slotitem_stat(ItemElem, ThisSlotitem, "ls"); this.slotitem_stat(ItemElem, ThisSlotitem, "dv"); this.slotitem_stat(ItemElem, ThisSlotitem, "ht"); this.slotitem_stat(ItemElem, ThisSlotitem, "rn"); this.slotitem_stat(ItemElem, ThisSlotitem, "or"); var PlaneCtr, ThisPlane, PlaneBox, rankLines, ThisCapacity; for(PlaneCtr in ThisSlotitem.instances){ ThisPlane = ThisSlotitem.instances[PlaneCtr]; PlaneBox = $(".tab_aircraft .factory .instance").clone(); $(".instances", ItemElem).append(PlaneBox); $(".instance_icon img", PlaneBox).attr("src", "../../assets/img/items/"+type_id+".png"); if(ThisPlane.stars > 0){ $(".instance_star span", PlaneBox).text( ThisPlane.stars > 9 ? "m" : ThisPlane.stars); } else { $(".instance_star img", PlaneBox).hide(); } if(ThisPlane.ace > 0){ $(".instance_chev img", PlaneBox).attr("src", "../../assets/img/client/achev/"+ThisPlane.ace+".png"); }else{ $(".instance_chev img", PlaneBox).hide(); } $(".instance_name input", PlaneBox).attr("data-gearId", ThisPlane.itemId); if(typeof this.squadNames["p"+ThisPlane.itemId] != "undefined"){ $(".instance_name input", PlaneBox).val( this.squadNames["p"+ThisPlane.itemId] ); } if(ThisPlane.MyHolder()){ if(ThisPlane.MyHolder() instanceof KC3LandBase){ $(".holder_pic img", PlaneBox).attr("src", "../../../../assets/img/items/33.png" ); $(".holder_name", PlaneBox).text( "LBAS World "+ThisPlane.MyHolder().map ); $(".holder_level", PlaneBox).text( "#"+ThisPlane.MyHolder().rid ); ThisCapacity = ThisPlane.MyHolder().planes .filter(lbasPlanesFilter)[0].api_max_count; } else if(ThisPlane.MyHolder() === "LbasMoving"){ $(".holder_pic img", PlaneBox).attr("src", "../../../../assets/img/items/33.png" ); $(".holder_name", PlaneBox).text( "LBAS Moving" ); $(".holder_level", PlaneBox).text( "" ); ThisCapacity = ""; } else { $(".holder_pic img", PlaneBox).attr("src", KC3Meta.shipIcon(ThisPlane.MyHolder().masterId) ); $(".holder_name", PlaneBox).text( ThisPlane.MyHolder().name() ); $(".holder_level", PlaneBox).text("Lv."+ThisPlane.MyHolder().level); ThisCapacity = ThisPlane.MyHolder().slots[ this._slotNums["s"+ThisPlane.itemId] ]; } if(ThisCapacity > 0){ // Compute for veteranized fighter power var MyFighterPowerText = ""; if(ConfigManager.air_formula == 1){ MyFighterPowerText = ThisPlane.fighterPower(ThisCapacity); }else{ MyFighterPowerText = "~"+ThisPlane.fighterVeteran(ThisCapacity); } $(".instance_aaval", PlaneBox).text( MyFighterPowerText ); } $(".instance_aaval", PlaneBox).addClass("activeSquad"); $(".instance_slot", PlaneBox).text(ThisCapacity); }else{ $(".holder_pic", PlaneBox).hide(); $(".holder_name", PlaneBox).hide(); $(".holder_level", PlaneBox).hide(); $(".instance_aaval", PlaneBox).addClass("reserveSquad"); $(".instance_aaval", PlaneBox).text( ThisSlotitem.stats.aa ); } } } }, /* Determine if an item has a specific stat --------------------------------------------*/ slotitem_stat :function(ItemElem, SlotItem, statName){ if(SlotItem.stats[statName] !== 0 && (statName !== "or" || (statName === "or" && KC3GearManager.landBasedAircraftType3Ids.indexOf(SlotItem.type_id)>-1) ) ){ $(".stats .item_"+statName+" span", ItemElem).text(SlotItem.stats[statName]); }else{ $(".stats .item_"+statName, ItemElem).hide(); } } }; })();
c933103/KC3Kai
src/pages/strategy/tabs/aircraft/aircraft.js
JavaScript
mit
10,605
'use strict'; /* This is the primary module of the Ava bot, if you are not using docker to run the bot you can use another method to run this file as long as you make sure you have the correct dependencies */ const bot = require('./bot.js'); const log = require('./logger.js')(module); log.info('======== ava.js running ========'); // This step serves the important purpose of allowing a specific function to be called to start the bot bot.startup();
JamesLongman/ava-bot
lib/ava.js
JavaScript
mit
455
/** * @class Jaml * @author Ed Spencer (http://edspencer.net) * Jaml is a simple JavaScript library which makes HTML generation easy and pleasurable. * Examples: http://edspencer.github.com/jaml * Introduction: http://edspencer.net/2009/11/jaml-beautiful-html-generation-for-javascript.html */ Jaml = function() { return { templates: {}, /** * Registers a template by name * @param {String} name The name of the template * @param {Function} template The template function */ register: function(name, template) { this.templates[name] = template; }, /** * Renders the given template name with an optional data object * @param {String} name The name of the template to render * @param {Object} thisObj Optional data object * @param {Object} data Optional data object */ render: function(name, thisObj, data) { var template = this.templates[name], renderer = new Jaml.Template(template); return renderer.render.apply(renderer, Array.prototype.slice.call(arguments, 1)); } }; }();
edspencer/jaml
src/Jaml.js
JavaScript
mit
1,100
define({"oj-message":{fatal:"ร้ายแรง",error:"ข้อผิดพลาด",warning:"คำเตือน",info:"ข้อมูล",confirmation:"การยืนยัน","compact-type-summary":"{0}: {1}"},"oj-converter":{summary:"ค่าไม่อยู่ในรูปแบบที่ต้องการ",detail:"ป้อนค่าในรูปแบบที่ต้องการ","plural-separator":", ",hint:{summary:"ตัวอย่าง: {exampleValue}",detail:"ป้อนค่าในรูปแบบเดียวกับตัวอย่างต่อไปนี้: '{exampleValue}'","detail-plural":"ป้อนค่าในรูปแบบเดียวกับตัวอย่างต่อไปนี้: '{exampleValue}'"},optionHint:{detail:"ค่าที่ยอมรับสำหรับตัวเลือก '{propertyName}' คือ '{propertyValueValid}'", "detail-plural":"ค่าที่ยอมรับสำหรับตัวเลือก '{propertyName}' คือ '{propertyValueValid}'"},optionTypesMismatch:{summary:"ต้องระบุค่าสำหรับตัวเลือก '{requiredPropertyName}' เมื่อตั้งค่าตัวเลือก '{propertyName}' เป็น '{propertyValue}'"},optionTypeInvalid:{summary:"ไม่ได้ระบุค่าของประเภทที่ต้องการสำหรับตัวเลือก '{propertyName}'"},optionOutOfRange:{summary:"ค่า {propertyValue} อยู่นอกช่วงสำหรับตัวเลือก '{propertyName}'"},optionValueInvalid:{summary:"ค่า '{propertyValue}' ที่ระบุสำหรับตัวเลือก '{propertyName}' ไม่ถูกต้อง"}, number:{decimalFormatMismatch:{summary:"'{value}' ไม่อยู่ในรูปแบบตัวเลขที่ต้องการ"},decimalFormatUnsupportedParse:{summary:"decimalFormat: ไม่รองรับ 'short' และ 'long' สำหรับการพาร์ซตัวแปลง",detail:"เปลี่ยนองค์ประกอบเป็น readOnly ฟิลด์ readOnly ไม่ได้เรียกฟังก์ชันพาร์ซของตัวแปลง"},currencyFormatMismatch:{summary:"'{value}' ไม่อยู่ในรูปแบบสกุลเงินที่ต้องการ"},percentFormatMismatch:{summary:"'{value}' ไม่อยู่ในรูปแบบเปอร์เซ็นต์ที่ต้องการ"}},datetime:{datetimeOutOfRange:{summary:"ค่า '{value}' อยู่นอกช่วงสำหรับ '{propertyName}'", detail:"ป้อนค่าตั้งแต่ '{minValue}' ถึง '{maxValue}'"},dateFormatMismatch:{summary:"'{value}' ไม่อยู่ในรูปแบบวันที่ที่ต้องการ"},timeFormatMismatch:{summary:"'{value}' ไม่อยู่ในรูปแบบเวลาที่ต้องการ"},datetimeFormatMismatch:{summary:"'{value}' ไม่อยู่ในรูปแบบวันที่และเวลาที่ต้องการ"},dateToWeekdayMismatch:{summary:"วันที่ '{date}' ไม่ตรงกับ '{weekday}'",detail:"ป้อนวันทำการที่ตรงกับวันที่"}}},"oj-validator":{length:{hint:{min:"ป้อนอักขระ {min} ตัวหรือมากกว่า",max:"ป้อนอักขระ {max} ตัวหรือน้อยกว่า", inRange:"ป้อนอักขระ {min} ตัวหรือมากกว่า และไม่เกิน {max} ตัว",exact:"ป้อนอักขระ {length} ตัว"},messageDetail:{tooShort:"ป้อนอักขระไม่ต่ำกว่า {min} ตัว",tooLong:"ป้อนอักขระไม่เกิน {max} ตัว"},messageSummary:{tooShort:"มีอักขระจำนวนน้อยเกินไป",tooLong:"มีอักขระจำนวนมากเกินไป"}},range:{number:{hint:{min:"ป้อนตัวเลขที่มากกว่าหรือเท่ากับ {min}",max:"ป้อนตัวเลขที่น้อยกว่าหรือเท่ากับ {max}",inRange:"ป้อนตัวเลขตั้งแต่ {min} ถึง {max}"},messageDetail:{rangeUnderflow:"ตัวเลขต้องมากกว่าหรือเท่ากับ {min}",rangeOverflow:"ตัวเลขต้องน้อยกว่าหรือเท่ากับ {max}"}, messageSummary:{rangeUnderflow:"ตัวเลขน้อยเกินไป",rangeOverflow:"ตัวเลขสูงเกินไป"}},datetime:{hint:{min:"ป้อนวันที่และเวลาตรงกับหรือหลัง {min}",max:"ป้อนวันที่และเวลาตรงกับหรือก่อน {max}",inRange:"ป้อนวันที่และเวลาตั้งแต่ {min} ถึง {max}"},messageDetail:{rangeUnderflow:"วันที่และเวลาต้องตรงกับหรือหลัง {min}",rangeOverflow:"วันที่และเวลาต้องตรงกับหรือก่อน {max}"},messageSummary:{rangeUnderflow:"วันที่และเวลาอยู่ก่อนวันที่เริ่มต้น",rangeOverflow:"วันที่และเวลาอยู่หลังวันที่สิ้นสุด"}}},restriction:{date:{messageSummary:"วันที่ {value} มาจากรายการที่เลิกใช้", messageDetail:"วันที่ {value} ไม่ควรมาจากรายการที่เลิกใช้"}},regExp:{summary:"รูปแบบไม่ถูกต้อง",detail:"ค่า '{value}' ต้องตรงกับรูปแบบต่อไปนี้: '{pattern}'"},required:{summary:"ต้องระบุค่า",detail:"คุณต้องป้อนค่า"}},"oj-editableValue":{required:{hint:"",messageSummary:"",messageDetail:""}},"oj-ojInputDate":{prevText:"ก่อนหน้า",nextText:"ถัดไป",currentText:"วันนี้",weekHeader:"สัปดาห์",tooltipCalendar:"เลือกวันที่",tooltipCalendarDisabled:"เลิกใช้การเลือกวันที่",weekText:"สัปดาห์",datePicker:"ตัวเลือกวันที่", inputHelp:"กดลูกศรชี้ลงหรือลูกศรชี้ขึ้นเพื่อเข้าใช้ปฏิทิน",inputHelpBoth:"กดลูกศรชี้ลงหรือลูกศรชี้ขึ้นเพื่อเข้าใช้ปฏิทิน และ Shift + ลูกศรชี้ลงหรือ Shift + ลูกศรชี้ขึ้นเพื่อเข้าใช้ดรอปดาวน์เวลา",dateTimeRange:{hint:{min:"",max:"",inRange:""},messageDetail:{rangeUnderflow:"",rangeOverflow:""},messageSummary:{rangeUnderflow:"",rangeOverflow:""}},dateRestriction:{hint:"",messageSummary:"",messageDetail:""}},"oj-ojInputTime":{tooltipTime:"เลือกเวลา",tooltipTimeDisabled:"เลิกใช้การเลือกเวลา",inputHelp:"กดลูกศรชี้ลงหรือลูกศรชี้ขึ้นเพื่อเข้าใช้ดรอปดาวน์เวลา", dateTimeRange:{hint:{min:"",max:"",inRange:""},messageDetail:{rangeUnderflow:"",rangeOverflow:""},messageSummary:{rangeUnderflow:"",rangeOverflow:""}}},"oj-inputBase":{regexp:{messageSummary:"",messageDetail:""}},"oj-ojInputPassword":{regexp:{messageDetail:"ค่าต้องตรงกับรูปแบบต่อไปนี้: '{pattern}'"}},"oj-ojFilmStrip":{labelAccArrowNextPage:"เพจถัดไป",labelAccArrowPreviousPage:"เพจก่อนหน้า",tipArrowNextPage:"ถัดไป",tipArrowPreviousPage:"ก่อนหน้า"},"oj-ojDataGrid":{accessibleSortAscending:"{id} เรียงจากน้อยไปมาก", accessibleSortDescending:"{id} เรียกจากมากไปน้อย",accessibleActionableMode:"เข้าสู่โหมดที่สามารถดำเนินการได้",accessibleNavigationMode:"เข้าสู่โหมดการนาวิเกต",accessibleSummaryExact:"นี่คือกริดข้อมูลที่มี {rownum} แถวและ {colnum} คอลัมน์",accessibleSummaryEstimate:"นี่คือกริดข้อมูลที่ไม่ทราบจำนวนแถวและคอลัมน์",accessibleSummaryExpanded:"ขณะนี้มีการขยายแถวแล้ว {num} แถว",accessibleRowExpanded:"ขยายแถวแล้ว",accessibleRowCollapsed:"ยุบแถวแล้ว",accessibleRowSelected:"เลือกแถว {row}",accessibleColumnSelected:"เลือกคอลัมน์ {column}", accessibleStateSelected:"รายการที่เลือก",accessibleMultiCellSelected:"เลือกไว้ {num} เซลล์",accessibleRowContext:"แถว {index}",accessibleColumnContext:"คอลัมน์ {index}",accessibleRowHeaderContext:"ส่วนหัวของแถว {index}",accessibleColumnHeaderContext:"ส่วนหัวของคอลัมน์ {index}",accessibleLevelContext:"ระดับ {level}",accessibleRangeSelectModeOn:"เปิดโหมดการเพิ่มช่วงของเซลล์ที่เลือก",accessibleRangeSelectModeOff:"ปิดโหมดการเพิ่มช่วงของเซลล์ที่เลือก",accessibleFirstRow:"คุณอยู่ที่แถวแรก",accessibleLastRow:"คุณอยู่ที่แถวสุดท้าย", accessibleFirstColumn:"คุณอยู่ที่คอลัมน์แรก",accessibleLastColumn:"คุณอยู่ที่คอลัมน์สุดท้าย",accessibleSelectionAffordanceTop:"แฮนเดิลการเลือกด้านบน",accessibleSelectionAffordanceBottom:"แฮนเดิลการเลือกด้านล่าง",msgFetchingData:"กำลังดึงข้อมูล...",msgNoData:"ไม่มีรายการที่จะแสดงผล",labelResize:"ปรับขนาด",labelResizeWidth:"ปรับความกว้าง",labelResizeHeight:"ปรับความสูง",labelSortRow:"จัดเรียงแถว",labelSortRowAsc:"จัดเรียงแถวจากน้อยไปมาก",labelSortRowDsc:"จัดเรียงแถวจากมากไปน้อย",labelSortCol:"จัดเรียงคอลัมน์", labelSortColAsc:"จัดเรียงคอลัมน์จากน้อยไปมาก",labelSortColDsc:"จัดเรียงคอลัมน์จากมากไปน้อย",labelCut:"ตัด",labelPaste:"วาง",labelEnableNonContiguous:"ใช้การเลือกแบบไม่ต่อเนื่อง",labelDisableNonContiguous:"เลิกใช้การเลือกแบบไม่ต่อเนื่อง",labelResizeDialogSubmit:"ตกลง"},"oj-ojRowExpander":{accessibleLevelDescription:"ระดับ {level}",accessibleRowDescription:"ระดับ {level}, แถว {num} จาก {total}",accessibleRowExpanded:"ขยายแถวแล้ว",accessibleRowCollapsed:"ยุบแถวแล้ว",accessibleStateExpanded:"ขยายแล้ว", accessibleStateCollapsed:"ยุบแล้ว"},"oj-ojListView":{msgFetchingData:"กำลังดึงข้อมูล...",msgNoData:"ไม่มีรายการที่จะแสดงผล",indexerCharacters:"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z"},"oj-_ojLabel":{tooltipHelp:"วิธีใช้",tooltipRequired:"ต้องระบุ"},"oj-ojInputNumber":{numberRange:{hint:{min:"",max:"",inRange:""},messageDetail:{rangeUnderflow:"",rangeOverflow:""},messageSummary:{rangeUnderflow:"",rangeOverflow:""}},tooltipDecrement:"ส่วนลด",tooltipIncrement:"ส่วนเพิ่ม"},"oj-ojTable":{labelAccSelectionAffordanceTop:"แฮนเดิลการเลือกด้านบน", labelAccSelectionAffordanceBottom:"แฮนเดิลการเลือกด้านล่าง",labelEnableNonContiguousSelection:"ใช้การเลือกแบบไม่ต่อเนื่อง",labelDisableNonContiguousSelection:"เลิกใช้การเลือกแบบไม่ต่อเนื่อง",labelSelectRow:"เลือกแถว",labelSelectColumn:"เลือกคอลัมน์",labelSort:"จัดเรียง",labelSortAsc:"เรียงจากน้อยไปมาก",labelSortDsc:"เรียงจากมากไปน้อย",msgFetchingData:"กำลังดึงข้อมูล...",msgNoData:"ไม่มีข้อมูลที่จะแสดงผล"},"oj-ojTabs":{labelCut:"ตัด",labelPasteBefore:"วางก่อน",labelPasteAfter:"วางหลัง",labelRemove:"ย้ายออก", labelReorder:"จัดลำดับใหม่",removeCueText:"ย้ายออกได้"},"oj-ojSelect":{seachField:"ฟิลด์ค้นหา",noMatchesFound:"ไม่พบรายการที่ค้นหา"},"oj-ojSwitch":{SwitchON:"เปิด",SwitchOFF:"ปิด"},"oj-ojCombobox":{noMatchesFound:"ไม่พบรายการที่ค้นหา"},"oj-ojInputSearch":{noMatchesFound:"ไม่พบรายการที่ค้นหา"},"oj-ojTree":{stateLoading:"กำลังโหลด...",labelNewNode:"โหนดใหม่",labelMultiSelection:"การเลือกหลายรายการ",labelEdit:"แก้ไข",labelCreate:"สร้าง",labelCut:"ตัด",labelCopy:"คัดลอก",labelPaste:"วาง",labelRemove:"ย้ายออก", labelRename:"เปลี่ยนชื่อ",labelNoData:"ไม่มีข้อมูล"},"oj-ojPagingControl":{labelAccPaging:"แบ่งหน้า",labelAccNavFirstPage:"เพจแรก",labelAccNavLastPage:"เพจสุดท้าย",labelAccNavNextPage:"เพจถัดไป",labelAccNavPreviousPage:"เพจก่อนหน้า",labelAccNavPage:"เพจ",labelLoadMore:"แสดงเพิ่มเติม...",labelLoadMoreMaxRows:"ถึงขีดจำกัดสูงสุด {maxRows} แถวแล้ว",labelNavInputPage:"เพจ",labelNavInputPageMax:"จาก {pageMax}",msgItemRangeCurrent:"{pageFrom}-{pageTo}",msgItemRangeCurrentSingle:"{pageFrom}",msgItemRangeOf:"จาก", msgItemRangeOfAtLeast:"จากอย่างน้อย",msgItemRangeOfApprox:"จากประมาณ",msgItemRangeItems:"รายการ",tipNavInputPage:"ไปที่เพจ",tipNavPageLink:"ไปที่เพจ {pageNum}",tipNavNextPage:"ถัดไป",tipNavPreviousPage:"ก่อนหน้า",tipNavFirstPage:"แรก",tipNavLastPage:"สุดท้าย",pageInvalid:{summary:"ค่าของเพจที่ป้อนไม่ถูกต้อง",detail:"โปรดป้อนค่ามากกว่า 0"},maxPageLinksInvalid:{summary:"ค่าสำหรับ maxPageLinks ไม่ถูกต้อง",detail:"โปรดป้อนค่ามากกว่า 4"}},"oj-ojMasonryLayout":{labelCut:"ตัด",labelPasteBefore:"วางก่อน", labelPasteAfter:"วางหลัง"},"oj-panel":{labelAccButtonExpand:"ขยาย",labelAccButtonCollapse:"ยุบ",labelAccButtonRemove:"ย้ายออก"},"oj-ojChart":{labelDefaultGroupName:"กลุ่ม {0}",labelSeries:"ชุด",labelGroup:"กลุ่ม",labelDate:"วันที่",labelValue:"ค่า",labelTargetValue:"เป้าหมาย",labelX:"X",labelY:"Y",labelZ:"Z",labelPercentage:"เปอร์เซ็นต์",labelLow:"ต่ำ",labelHigh:"สูง",labelOpen:"เปิด",labelClose:"ปิด",labelVolume:"ปริมาณ",labelMin:"ต่ำสุด",labelMax:"สูงสุด",labelOther:"อื่นๆ",tooltipPan:"แพน",tooltipSelect:"เลือกเฉพาะในกรอบ", tooltipZoom:"ซูมเฉพาะในกรอบ",componentName:"แผนภูมิ"},"oj-dvtBaseGauge":{componentName:"มาตรวัด"},"oj-ojDiagram":{componentName:"ไดอะแกรม"},"oj-ojLegend":{componentName:"คำอธิบาย"},"oj-ojNBox":{highlightedCount:"{0}/{1}",labelOther:"อื่นๆ",labelGroup:"กลุ่ม",labelSize:"ขนาด",labelAdditionalData:"ข้อมูลเพิ่มเติม",componentName:"NBox"},"oj-ojPictoChart":{componentName:"แผนภูมิรูปภาพ"},"oj-ojSparkChart":{componentName:"แผนภูมิ"},"oj-ojSunburst":{labelColor:"สี",labelSize:"ขนาด",componentName:"ซันเบิร์สท์"}, "oj-ojTagCloud":{componentName:"แท็กคลาวด์"},"oj-ojThematicMap":{componentName:"แผนที่เฉพาะทาง"},"oj-ojTimeline":{componentName:"ระยะเวลา",labelSeries:"ชุด",tooltipZoomIn:"ซูมเข้า",tooltipZoomOut:"ซูมออก"},"oj-ojTreemap":{labelColor:"สี",labelSize:"ขนาด",tooltipIsolate:"แยก",tooltipRestore:"เรียกคืน",componentName:"แผนที่โครงสร้าง"},"oj-dvtBaseComponent":{labelScalingSuffixThousand:"K",labelScalingSuffixMillion:"M",labelScalingSuffixBillion:"B",labelScalingSuffixTrillion:"T",labelScalingSuffixQuadrillion:"Q", labelInvalidData:"ข้อมูลไม่ถูกต้อง",labelNoData:"ไม่มีข้อมูลที่จะแสดงผล",labelClearSelection:"ล้างข้อมูลที่เลือกไว้",labelDataVisualization:"การแสดงข้อมูล",stateSelected:"เลือกไว้",stateUnselected:"ไม่ได้เลือกไว้",stateMaximized:"ขนาดใหญ่สุด",stateMinimized:"ขนาดเล็กสุด",stateExpanded:"ขยายแล้ว",stateCollapsed:"ยุบแล้ว",stateIsolated:"แยก",stateHidden:"ซ่อน",stateVisible:"มองเห็นได้",stateDrillable:"ดริลล์ได้",labelAndValue:"{0}: {1}",labelCountWithTotal:"{0} จาก {1}"},"oj-ojNavigationList":{defaultRootLabel:"ลิสต์การนาวิเกต", hierMenuBtnLabel:"ปุ่มเมนูย่อย",selectedLabel:"รายการที่เลือก",previousIcon:"ก่อนหน้า",msgFetchingData:"กำลังดึงข้อมูล...",msgNoData:"ไม่มีรายการที่จะแสดงผล"},"oj-ojSlider":{noValue:"ojSlider ไม่มีค่า",maxMin:"สูงสุดต้องไม่น้อยกว่าต่ำสุด",valueRange:"ค่าต้องอยู่ภายในช่วงต่ำสุดถึงสูงสุด",optionNum:"ตัวเลือก {option} ไม่ใช่ตัวเลข",invalidStep:"ขั้นตอนไม่ถูกต้อง ขั้นตอนต้อง > 0"},"oj-ojPopup":{ariaLiveRegionInitialFocusFirstFocusable:"กำลังเข้าสู่ป็อปอัป กด F6 เพื่อนาวิเกตระหว่างป็อปอัปและการควบคุมที่เกี่ยวข้อง", ariaLiveRegionInitialFocusNone:"ป็อปอัปเปิดอยู่ กด F6 เพื่อนาวิเกตระหว่างป็อปอัปและการควบคุมที่เกี่ยวข้อง",ariaLiveRegionInitialFocusFirstFocusableTouch:"กำลังเข้าสู่ป็อปอัป สามารถปิดป็อปอัปได้โดยนาวิเกตไปยังลิงค์ล่าสุดภายในป็อปอัป",ariaLiveRegionInitialFocusNoneTouch:"ป็อปอัปเปิดอยู่ โปรดนาวิเกตไปยังลิงค์ถัดไปเพื่อกำหนดโฟกัสภายในป็อปอัป",ariaFocusSkipLink:"แตะสองครั้งเพื่อนาวิเกตไปยังป็อปอัปที่เปิดอยู่",ariaCloseSkipLink:"แตะสองครั้งเพื่อปิดป็อปอัปที่เปิดอยู่"},"oj-pullToRefresh":{ariaRefreshLink:"เปิดใช้งานลิงค์เพื่อรีเฟรชเนื้อหา", ariaRefreshingLink:"กำลังรีเฟรชเนื้อหา",ariaRefreshCompleteLink:"รีเฟรชเสร็จสมบูรณ์"},"oj-ojIndexer":{indexerOthers:"#",ariaDisabledLabel:"ไม่พบส่วนหัวของกลุ่มที่ตรงกัน",ariaOthersLabel:"ตัวเลข",ariaInBetweenText:"ตั้งแต่ {first} ถึง {second}",ariaKeyboardInstructionText:"กด Enter เพื่อเลือกค่า",ariaTouchInstructionText:"แตะสองครั้งและกดค้างไว้เพื่อเข้าสู่โหมดการวาดนิ้ว จากนั้นลากขึ้นหรือลงเพื่อปรับค่า"}});
peppertech/OracleJET-Samples
MagicEightBall/hybrid/www/js/libs/oj/v2.0.0/resources/nls/th/ojtranslations.js
JavaScript
mit
22,262
module.exports = { vert: [ 'uniform mat4 u_view_matrix;', 'attribute vec2 a_position;', 'attribute vec4 a_color;', 'varying vec4 v_color;', 'void main () {', ' gl_Position = u_view_matrix * vec4(a_position, 1.0, 1.0);', ' v_color = a_color;', '}' ].join('\n'), frag:[ 'precision lowp float;', 'varying vec4 v_color;', 'void main() {', ' gl_FragColor = v_color;', '}' ].join('\n') };
clark-stevenson/phaser
v3/src/renderer/webgl/shaders/UntexturedAndTintedShader.js
JavaScript
mit
509
/* YUI 3.7.2 (build 5639) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('node-base', function (Y, NAME) { /** * @module node * @submodule node-base */ var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment * @for Node */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; Y.mix(Y_Node.prototype, { /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Inserts the content before the reference node. * @method insert * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {Int | Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ append: function(content) { return this.insert(content, null); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Appends the node to the given node. * @method appendTo * @param {Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); return this; }, /** * Replaces the node's current content with the content. * Note that this passes to innerHTML and is not escaped. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content or `set('text')` to add as text. * @method setContent * @deprecated Use setHTML * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @deprecated Use getHTML * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); } }); /** * Replaces the node's current html content with the content provided. * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @method setHTML * @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ Y.Node.prototype.setHTML = Y.Node.prototype.setContent; /** * Returns the node's current html content (e.g. innerHTML) * @method getHTML * @return {String} The html content */ Y.Node.prototype.getHTML = Y.Node.prototype.getContent; Y.NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** * Called on each Node instance * @for NodeList * @method insert * @see Node.insert */ 'insert', /** * Called on each Node instance * @for NodeList * @method appendChild * @see Node.appendChild */ 'appendChild', /** * Called on each Node instance * @for NodeList * @method insertBefore * @see Node.insertBefore */ 'insertBefore', /** * Called on each Node instance * @for NodeList * @method prepend * @see Node.prepend */ 'prepend', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setContent * @deprecated Use setHTML */ 'setContent', /** * Called on each Node instance * @for NodeList * @method getContent * @deprecated Use getHTML */ 'getContent', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setHTML * @see Node.setHTML */ 'setHTML', /** * Called on each Node instance * @for NodeList * @method getHTML * @see Node.getHTML */ 'getHTML' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config for * @type String */ 'for': { getter: function() { return Y_DOM.getAttribute(this._node, 'for'); }, setter: function(val) { Y_DOM.setAttribute(this._node, 'for', val); return val; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i].tagName) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; Y.Node.importMethod(Y.DOM, [ /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; var Y_NodeList = Y.NodeList; /** * List of events that route to DOM events * @static * @property DOM_EVENTS * @for Node */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); Y.augment(Y_Node, Y.EventTarget); Y.mix(Y_Node.prototype, { /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; } }); Y.mix(Y.NodeList.prototype, { _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** Subscribe a callback function for each `Node` in the collection to execute in response to a DOM event. NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in favor of using event delegation from a parent Node. See the Event user guide for details. Most DOM events are associated with a preventable default behavior, such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. By default, the `this` object will be the `NodeList` that the subscription came from, <em>not the `Node` that received the event</em>. Use `e.currentTarget` to refer to the `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.all(".sku").on("keydown", function (e) { if (e.keyCode === 13) { e.preventDefault(); // Use e.currentTarget to refer to the individual Node var item = Y.MyApp.searchInventory( e.currentTarget.get('value') ); // etc ... } }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for NodeList **/ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList * that will be called only after all on() handlers are called and the * event is not prevented. * * @method onceAfter * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ onceAfter: function(type, fn, context) { return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments)); } }); Y_NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @method detach * @see Node.detach * @for NodeList */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll * @for NodeList */ 'detachAll' ]); /** Subscribe a callback function to execute in response to a DOM event or custom event. Most DOM events are associated with a preventable default behavior such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. If the event name passed as the first parameter is not a whitelisted DOM event, it will be treated as a custom event subscriptions, allowing `node.fire('customEventName')` later in the code. Refer to the Event user guide for the full DOM event whitelist. By default, the `this` object in the callback will refer to the subscribed `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.one("#my-form").on("submit", function (e) { e.preventDefault(); // proceed with ajax form submission instead... }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for Node **/ Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to toggle the style.display property. * @method _show * @protected * @chainable */ _show: function() { this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getStyle(this._node, 'display') === 'none'; }, /** * Displays or hides the node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method toggleView * @for Node * @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ toggleView: function(on, callback) { this._toggleView.apply(this, arguments); return this; }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to toggle the style.display property. * @method _hide * @protected * @chainable */ _hide: function() { this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', /** * Displays or hides each node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the nodes using either the default * transition effect ('fadeIn'), or the given named effect. * @method toggleView * @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ 'toggleView' ]); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { Y.log('error focusing node: ' + e.toString(), 'error', 'node'); } return this; }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { Y.log('error setting type: ' + val, 'info', 'node'); } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } /** * Provides methods for managing custom Node data. * * @module node * @main node * @submodule node-data */ Y.mix(Y.Node.prototype, { _initData: function() { if (! ('_data' in this)) { this._data = {}; } }, /** * @method getData * @for Node * @description Retrieves arbitrary data stored on a Node instance. * If no data is associated with the Node, it will attempt to retrieve * a value from the corresponding HTML data attribute. (e.g. node.getData('foo') * will check node.getAttribute('data-foo')). * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { this._initData(); var data = this._data, ret = data; if (arguments.length) { // single field if (name in data) { ret = data[name]; } else { // initialize from HTML attribute ret = this._getDataAttribute(name); } } else if (typeof data == 'object' && data !== null) { // all fields ret = {}; Y.Object.each(data, function(v, n) { ret[n] = v; }); ret = this._getDataAttributes(ret); } return ret; }, _getDataAttributes: function(ret) { ret = ret || {}; var i = 0, attrs = this._node.attributes, len = attrs.length, prefix = this.DATA_PREFIX, prefixLength = prefix.length, name; while (i < len) { name = attrs[i].name; if (name.indexOf(prefix) === 0) { name = name.substr(prefixLength); if (!(name in ret)) { // only merge if not already stored ret[name] = this._getDataAttribute(name); } } i += 1; } return ret; }, _getDataAttribute: function(name) { var name = this.DATA_PREFIX + name, node = this._node, attrs = node.attributes, data = attrs && attrs[name] && attrs[name].value; return data; }, /** * @method setData * @for Node * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no val * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._initData(); if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @for Node * @description Clears internally stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (typeof name != 'undefined') { delete this._data[name]; } else { delete this._data; } } return this; } }); Y.mix(Y.NodeList.prototype, { /** * @method getData * @for NodeList * @description Retrieves arbitrary data stored on each Node instance * bound to the NodeList. * @see Node * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {Array} An array containing all of the data for each Node instance. * or an object hash of all fields. */ getData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('getData', args, true); }, /** * @method setData * @for NodeList * @description Stores arbitrary data on each Node instance bound to the * NodeList. This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { var args = (arguments.length > 1) ? [name, val] : [name]; return this._invoke('setData', args); }, /** * @method clearData * @for NodeList * @description Clears data on all Node instances bound to the NodeList. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('clearData', [name]); } }); }, '3.7.2', {"requires": ["event-base", "node-core", "dom-base"]});
spadin/coverphoto
node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/node-base/node-base-debug.js
JavaScript
mit
33,629
'use strict'; var assert = require('assert') var Promise = require('promise') var connect = require('../') var client = connect({ version: 3, cache: 'file', auth: '90993e4e47b0fdd1f51f4c67b17368c62a3d6097' // github-basic-js-test }); describe('async', function () { it('can make simple api requests', function (done) { this.timeout(5000) client.get('/users/:user/gists', {user: 'ForbesLindesay'}, function (err, res) { if (err) return done(err) assert(Array.isArray(res)) res.forEach(function (gist) { assert(typeof gist.url === 'string') assert(typeof gist.public === 'boolean') }) done() }) }) it('can have a `host` option passed in', function (done) { this.timeout(5000) client.headBuffer('https://github.com/ForbesLindesay/github-basic', done) }) it('can make streaming requests', function (done) { this.timeout(20000) client.getStream('/repos/:owner/:repo/subscribers', { owner: 'visionmedia', repo: 'jade', per_page: 100 }).buffer(function (err, res) { if (err) return done(err) assert(Array.isArray(res)) assert(res.length > 150) done() }) }) it('can make streaming requests for commits', function (done) { this.timeout(20000) client.getStream('/repos/:owner/:repo/commits', { owner: 'ForbesLindesay', repo: 'browserify-middleware', per_page: 100 }).buffer(function (err, res) { if (err) return done(err) assert(Array.isArray(res)) assert(res.length > 140) done() }) }) it('can make streaming requests with just one page', function (done) { this.timeout(20000) client.getStream('/repos/:owner/:repo/subscribers', { owner: 'ForbesLindesay', repo: 'github-basic', per_page: 100 }).buffer(function (err, res) { if (err) return done(err) assert(Array.isArray(res)) done() }) }) describe('helpers', function () { describe('exists(user, repo)', function () { it('returns `true` if a repo exists', function (done) { client.exists('ForbesLindesay', 'pull-request', function (err, res) { if (err) return done(err); assert(res === true); done(); }); }); it('returns `false` if a repo does not exist', function (done) { client.exists('ForbesLindesay', 'i-wont-ever-create-this', function (err, res) { if (err) return done(err); assert(res === false); done(); }); }); }); var branch = (new Date()).toISOString().replace(/[^0-9a-zA-Z]+/g, '') + 'async'; describe('fork(user, repo, options)', function () { it('forks `user/repo` to the current user', function (done) { this.timeout(60000); client.fork('ForbesLindesay', 'pull-request-test', function (err, res) { if (err) return done(err); client.exists('github-basic-js-test', 'pull-request-test', function (err, res) { if (err) return done(err); assert(res === true); done(); }); }); }); }); describe('branch(user, repo, form, to, options)', function () { it('creates a new branch `to` in `user/repo` based on `from`', function (done) { this.timeout(10000); client.branch('github-basic-js-test', 'pull-request-test', 'master', branch, function (err, res) { if (err) return done(err); client.head('/repos/github-basic-js-test/pull-request-test/git/refs/heads/:branch', {branch: branch}, done); }); }); }); describe('commit(commit, options)', function () { it('commits an update to a branch', function (done) { this.timeout(15000) var commit = { branch: branch, message: 'test commit', updates: [{path: 'test-file.txt', content: 'lets-add-a-file wahooo'}] }; client.commit('github-basic-js-test', 'pull-request-test', commit, function (err, res) { if (err) return done(err); client.head('https://github.com/github-basic-js-test/pull-request-test/blob/' + branch + '/test-file.txt', done); }); }); }); describe('pull(from, to, message, options)', function () { it('creates a pull request', function (done) { this.timeout(15000) var from = { user: 'github-basic-js-test', repo: 'pull-request-test', branch: branch }; var to = { user: 'github-basic-js-test', repo: 'pull-request-test', branch: 'master' }; var message = { title: branch, body: 'A test pull request' }; client.pull(from, to, message, function (err, res) { if (err) return done(err); ///repos/github-basic-js-test/pull-request-test/pulls/1 client.head('/repos/github-basic-js-test/pull-request-test/pulls/' + res.number, done); }); }); }); }); });
scriptit/github-basic
test/async.js
JavaScript
mit
5,038
// moment.js locale configuration // locale : Russian [ru] // author : Viktorminator : https://github.com/Viktorminator // Author : Menelion Elensúle : https://github.com/Oire // author : Коренберг Марк : https://github.com/socketpair function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(num, withoutSuffix, key) { var format = { mm: withoutSuffix ? 'минута_минуты_минут' : 'минуту_минуты_минут', hh: 'час_часа_часов', dd: 'день_дня_дней', MM: 'месяц_месяца_месяцев', yy: 'год_года_лет' }; if (key === 'm') { return withoutSuffix ? 'минута' : 'минуту'; } else { return num + " " + plural(format[key], +num); } } var monthsParse = [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[йя]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i]; // http://new.gramota.ru/spravka/rules/139-prop : § 103 // Сокращения месяцев: http://new.gramota.ru/spravka/buro/search-answer?s=242637 // CLDR data: http://www.unicode.org/cldr/charts/28/summary/ru.html#1753 export var ru = { abbr: 'ru', months: { format: 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_'), standalone: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_') }, monthsShort: { // по CLDR именно "июл." и "июн.", но какой смысл менять букву на точку ? format: 'янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.'.split('_'), standalone: 'янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.'.split('_') }, weekdays: { standalone: 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'), format: 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_'), isFormat: /\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/ }, weekdaysShort: 'вс_пн_вт_ср_чт_пт_сб'.split('_'), weekdaysMin: 'вс_пн_вт_ср_чт_пт_сб'.split('_'), monthsParse: monthsParse, longMonthsParse: monthsParse, shortMonthsParse: monthsParse, // полные названия с падежами, по три буквы, для некоторых, по 4 буквы, сокращения с точкой и без точки monthsRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, // копия предыдущего monthsShortRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, // полные названия с падежами monthsStrictRegex: /^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i, // Выражение, которое соотвествует только сокращённым формам monthsShortStrictRegex: /^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD.MM.YYYY', LL: 'D MMMM YYYY г.', LLL: 'D MMMM YYYY г., HH:mm', LLLL: 'dddd, D MMMM YYYY г., HH:mm' }, relativeTime: { future: 'через %s', past: '%s назад', s: 'несколько секунд', m: relativeTimeWithPlural, mm: relativeTimeWithPlural, h: 'час', hh: relativeTimeWithPlural, d: 'день', dd: relativeTimeWithPlural, M: 'месяц', MM: relativeTimeWithPlural, y: 'год', yy: relativeTimeWithPlural }, meridiemParse: /ночи|утра|дня|вечера/i, isPM: function (input) { return /^(дня|вечера)$/.test(input); }, meridiem: function (hour) { if (hour < 4) { return 'ночи'; } else if (hour < 12) { return 'утра'; } else if (hour < 17) { return 'дня'; } else { return 'вечера'; } }, dayOfMonthOrdinalParse: /\d{1,2}-(й|го|я)/, ordinal: function (num, period) { switch (period) { case 'M': case 'd': case 'DDD': return num + "-\u0439"; case 'D': return num + "-\u0433\u043E"; case 'w': case 'W': return num + "-\u044F"; default: return num.toString(10); } }, week: { dow: 1, doy: 4 // The week that contains Jan 4th is the first week of the year. } }; //# sourceMappingURL=ru.js.map
CatsPoo/ShiftOnline
angular.src/node_modules/ngx-bootstrap/bs-moment/i18n/ru.js
JavaScript
mit
6,071
var express = require('express'); var router = express.Router(); var request = require('request'); // Setup Redis Client var redis = require("redis"); var client = redis.createClient(process.env.REDISCACHE_SSLPORT, process.env.REDISCACHE_HOSTNAME, { auth_pass: process.env.REDISCACHE_PRIMARY_KEY, tls: { servername: process.env.REDISCACHE_HOSTNAME } }); /* GET dashboard. */ router.get('/', function (req, res) { // Query the API for incident data getIncidents().then(function (incidents) { // Render view res.render('dashboard', { title: 'Outage Dashboard', incidents: incidents }); }); }); module.exports = router; function getIncidents() { return new Promise(function (resolve, reject) { // Check cache for incidentData key client.get('incidentData', function (error, reply) { if (reply) { // Cached key exists console.log('Cached key found'); // Parse results var incidents; if (reply === 'undefined') { // No results, return null incidents = null; } else { incidents = JSON.parse(reply); } // Resolve Promise with incident data resolve(incidents); } else { // Cached key does not exist console.log('Cached key not found'); // Define URL to use for the API var apiUrl = `${process.env.INCIDENT_API_URL}/incidents`; // Make a GET request with the Request libary request(apiUrl, { json: true }, function (error, results, body) { // Store results in cache client.set("incidentData", JSON.stringify(body), 'EX', 60, function (error, reply) { console.log('Stored results in cache'); }); // Resolve Promise with incident data resolve(body); }); } }); }); }
AzureCAT-GSI/DevCamp
HOL/node/03-azuread-office365/start/routes/dashboard.js
JavaScript
mit
2,173
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), meta: { version: '<%= pkg.version %>', banner: '// Backbone.Intercept v<%= meta.version %>\n' }, preprocess: { intercept: { src: 'src/wrapper.js', dest: 'dist/backbone.intercept.js' } }, template: { options: { data: { version: '<%= meta.version %>' } }, intercept: { src: '<%= preprocess.intercept.dest %>', dest: '<%= preprocess.intercept.dest %>' } }, concat: { options: { banner: '<%= meta.banner %>' }, intercept: { src: '<%= preprocess.intercept.dest %>', dest: '<%= preprocess.intercept.dest %>' } }, uglify: { options: { banner: '<%= meta.banner %>' }, intercept: { src: '<%= preprocess.intercept.dest %>', dest: 'dist/backbone.intercept.min.js', options: { sourceMap: true } } }, jshint: { intercept: { options: { jshintrc: '.jshintrc' }, src: ['src/backbone.intercept.js'] }, tests: { options: { jshintrc: 'test/.jshintrc' }, src: ['test/unit/*.js'] } }, mochaTest: { spec: { options: { require: 'test/setup/node.js', reporter: 'dot', clearRequireCache: true, mocha: require('mocha') }, src: [ 'test/setup/helpers.js', 'test/unit/*.js' ] } }, connect: { options: { port: 8000, keepalive: true }, browser: {} } }); grunt.registerTask('test:browser', 'Test the library in the browser', [ 'jshint', 'connect' ]); grunt.registerTask('test', 'Test the library', [ 'jshint', 'mochaTest' ]); grunt.registerTask('build', 'Build the library', [ 'test', 'preprocess:intercept', 'template', 'concat', 'uglify' ]); grunt.registerTask('default', 'An alias of test', [ 'test' ]); };
elgubenis/backbone.intercept
gruntfile.js
JavaScript
mit
2,239
System.register([], function (_export, _context) { "use strict"; var p; return { setters: [], execute: function () { _export("p", p = 4); _export("p", p); } }; });
ModuleLoader/es-module-loader
test/fixtures/register-modules/rebinding.js
JavaScript
mit
197
module.exports = { //get global stats 'GET /stat': { controller: "StatController", action: "getGlobalStat" } }
badfuture/huoshui-backend-api
api/routes/statRoute.js
JavaScript
mit
126
'use strict'; var digits = require('./../../../utils/number').digits; // TODO this could be improved by simplifying seperated constants under associative and commutative operators function factory(type, config, load, typed, math) { var util = load(require('./util')); var isCommutative = util.isCommutative; var isAssociative = util.isAssociative; var allChildren = util.allChildren; var createMakeNodeFunction = util.createMakeNodeFunction; var ConstantNode = math.expression.node.ConstantNode; var OperatorNode = math.expression.node.OperatorNode; var FunctionNode = math.expression.node.FunctionNode; function simplifyConstant(expr) { var res = foldFraction(expr); return type.isNode(res) ? res : _toNode(res); } function _eval(fnname, args) { try { return _toNumber(math[fnname].apply(null, args)); } catch (ignore) { // sometimes the implicit type conversion causes the evaluation to fail, so we'll try again after removing Fractions args = args.map(function(x){ if (type.isFraction(x)) { return x.valueOf(); } return x; }); return _toNumber(math[fnname].apply(null, args)); } } var _toNode = typed({ 'Fraction': _fractionToNode, 'number': function(n) { if (n < 0) { return unaryMinusNode(new ConstantNode(-n)); } return new ConstantNode(n); }, 'BigNumber': function(n) { if (n < 0) { return unaryMinusNode(new ConstantNode(n.negated().toString(), 'number')); } return new ConstantNode(n.toString(), 'number'); }, 'Complex': function(s) { throw 'Cannot convert Complex number to Node'; } }); // convert a number to a fraction only if it can be expressed exactly function _exactFraction(n) { if (isFinite(n)) { var f = math.fraction(n); if (f.valueOf() === n) { return f; } } return n; } // Convert numbers to a preferred number type in preference order: Fraction, number, Complex // BigNumbers are left alone var _toNumber = typed({ 'string': function(s) { if (config.number === 'BigNumber') { return math.bignumber(s); } else if (config.number === 'Fraction') { return math.fraction(s); } else { return _exactFraction(parseFloat(s)); } }, 'Fraction': function(s) { return s; }, 'BigNumber': function(s) { return s; }, 'number': function(s) { return _exactFraction(s); }, 'Complex': function(s) { if (s.im !== 0) { return s; } return _exactFraction(s.re); }, }); function unaryMinusNode(n) { return new OperatorNode('-', 'unaryMinus', [n]); } function _fractionToNode(f) { var n; var vn = f.s*f.n; if (vn < 0) { n = new OperatorNode('-', 'unaryMinus', [new ConstantNode(-vn)]) } else { n = new ConstantNode(vn); } if (f.d === 1) { return n; } return new OperatorNode('/', 'divide', [n, new ConstantNode(f.d)]); } /* * Create a binary tree from a list of Fractions and Nodes. * Tries to fold Fractions by evaluating them until the first Node in the list is hit, so * `args` should be sorted to have the Fractions at the start (if the operator is commutative). * @param args - list of Fractions and Nodes * @param fn - evaluator for the binary operation evaluator that accepts two Fractions * @param makeNode - creates a binary OperatorNode/FunctionNode from a list of child Nodes * if args.length is 1, returns args[0] * @return - Either a Node representing a binary expression or Fraction */ function foldOp(fn, args, makeNode) { return args.reduce(function(a, b) { if (!type.isNode(a) && !type.isNode(b)) { try { return _eval(fn, [a,b]); } catch (ignoreandcontinue) {} a = _toNode(a); b = _toNode(b); } else if (!type.isNode(a)) { a = _toNode(a); } else if (!type.isNode(b)) { b = _toNode(b); } return makeNode([a, b]); }); } // destroys the original node and returns a folded one function foldFraction(node) { switch(node.type) { case 'SymbolNode': return node; case 'ConstantNode': if (node.valueType === 'number') { return _toNumber(node.value); } return node; case 'FunctionNode': if (math[node.name] && math[node.name].rawArgs) { return node; } // Process operators as OperatorNode var operatorFunctions = [ 'add', 'multiply' ]; if (operatorFunctions.indexOf(node.name) === -1) { var args = node.args.map(foldFraction); // If all args are numbers if (!args.some(type.isNode)) { try { return _eval(node.name, args); } catch (ignoreandcontine) {} } // Convert all args to nodes and construct a symbolic function call args = args.map(function(arg) { return type.isNode(arg) ? arg : _toNode(arg); }); return new FunctionNode(node.name, args); } else { // treat as operator } /* falls through */ case 'OperatorNode': var fn = node.fn.toString(); var args; var res; var makeNode = createMakeNodeFunction(node); if (node.args.length === 1) { args = [foldFraction(node.args[0])]; if (!type.isNode(args[0])) { res = _eval(fn, args); } else { res = makeNode(args); } } else if (isAssociative(node)) { args = allChildren(node); args = args.map(foldFraction); if (isCommutative(fn)) { // commutative binary operator var consts = [], vars = []; for (var i=0; i < args.length; i++) { if (!type.isNode(args[i])) { consts.push(args[i]); } else { vars.push(args[i]); } } if (consts.length > 1) { res = foldOp(fn, consts, makeNode); vars.unshift(res); res = foldOp(fn, vars, makeNode); } else { // we won't change the children order since it's not neccessary res = foldOp(fn, args, makeNode); } } else { // non-commutative binary operator res = foldOp(fn, args, makeNode); } } else { // non-associative binary operator args = node.args.map(foldFraction); res = foldOp(fn, args, makeNode); } return res; case 'ParenthesisNode': // remove the uneccessary parenthesis return foldFraction(node.content); case 'AccessorNode': /* falls through */ case 'ArrayNode': /* falls through */ case 'AssignmentNode': /* falls through */ case 'BlockNode': /* falls through */ case 'FunctionAssignmentNode': /* falls through */ case 'IndexNode': /* falls through */ case 'ObjectNode': /* falls through */ case 'RangeNode': /* falls through */ case 'UpdateNode': /* falls through */ case 'ConditionalNode': /* falls through */ default: throw 'Unimplemented node type in simplifyConstant: '+node.type; } } return simplifyConstant; } exports.math = true; exports.name = 'simplifyConstant'; exports.path = 'algebra.simplify'; exports.factory = factory;
ocadni/citychrone
node_modules/mathjs/lib/function/algebra/simplify/simplifyConstant.js
JavaScript
mit
7,764
/** * @author Richard Davey <[email protected]> * @copyright 2022 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * Rotates the vertices of a Face to the given angle. * * The actual vertex positions are adjusted, not their transformed positions. * * Therefore, this updates the vertex data directly. * * @function Phaser.Geom.Mesh.RotateFace * @since 3.50.0 * * @param {Phaser.Geom.Mesh.Face} face - The Face to rotate. * @param {number} angle - The angle to rotate to, in radians. * @param {number} [cx] - An optional center of rotation. If not given, the Face in-center is used. * @param {number} [cy] - An optional center of rotation. If not given, the Face in-center is used. */ var RotateFace = function (face, angle, cx, cy) { var x; var y; // No point of rotation? Use the inCenter instead, then. if (cx === undefined && cy === undefined) { var inCenter = face.getInCenter(); x = inCenter.x; y = inCenter.y; } var c = Math.cos(angle); var s = Math.sin(angle); var v1 = face.vertex1; var v2 = face.vertex2; var v3 = face.vertex3; var tx = v1.x - x; var ty = v1.y - y; v1.set(tx * c - ty * s + x, tx * s + ty * c + y); tx = v2.x - x; ty = v2.y - y; v2.set(tx * c - ty * s + x, tx * s + ty * c + y); tx = v3.x - x; ty = v3.y - y; v3.set(tx * c - ty * s + x, tx * s + ty * c + y); }; module.exports = RotateFace;
photonstorm/phaser
src/geom/mesh/RotateFace.js
JavaScript
mit
1,512
/*! * iCheck v1.0.3, http://git.io/arlzeA * =================================== * Powerful jQuery and Zepto plugin for checkboxes and radio buttons customization * * (c) 2013 Damir Sultanov, http://fronteed.com * MIT Licensed */ (function($) { // Cached vars var _iCheck = 'iCheck', _iCheckHelper = _iCheck + '-helper', _checkbox = 'checkbox', _radio = 'radio', _checked = 'checked', _unchecked = 'un' + _checked, _disabled = 'disabled', _determinate = 'determinate', _indeterminate = 'in' + _determinate, _update = 'update', _type = 'type', _click = 'click', _touch = 'touchbegin.i touchend.i', _add = 'addClass', _remove = 'removeClass', _callback = 'trigger', _label = 'label', _cursor = 'cursor', _mobile = /ip(hone|od|ad)|android|blackberry|windows phone|opera mini|silk/i.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1); // Plugin init $.fn[_iCheck] = function(options, fire) { // Walker var handle = 'input[type="' + _checkbox + '"], input[type="' + _radio + '"]', stack = $(), walker = function(object) { object.each(function() { var self = $(this); if (self.is(handle)) { stack = stack.add(self); } else { stack = stack.add(self.find(handle)); } }); }; // Check if we should operate with some method if (/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(options)) { // Normalize method's name options = options.toLowerCase(); // Find checkboxes and radio buttons walker(this); return stack.each(function() { var self = $(this); if (options == 'destroy') { tidy(self, 'ifDestroyed'); } else { operate(self, true, options); } // Fire method's callback if ($.isFunction(fire)) { fire(); } }); // Customization } else if (typeof options == 'object' || !options) { // Check if any options were passed var settings = $.extend({ checkedClass: _checked, disabledClass: _disabled, indeterminateClass: _indeterminate, labelHover: true }, options), selector = settings.handle, hoverClass = settings.hoverClass || 'hover', focusClass = settings.focusClass || 'focus', activeClass = settings.activeClass || 'active', labelHover = !!settings.labelHover, labelHoverClass = settings.labelHoverClass || 'hover', // Setup clickable area area = ('' + settings.increaseArea).replace('%', '') | 0; // Selector limit if (selector == _checkbox || selector == _radio) { handle = 'input[type="' + selector + '"]'; } // Clickable area limit if (area < -50) { area = -50; } // Walk around the selector walker(this); return stack.each(function() { var self = $(this); // If already customized tidy(self); var node = this, id = node.id, // Layer styles offset = -area + '%', size = 100 + (area * 2) + '%', layer = { position: 'absolute', top: offset, left: offset, display: 'block', width: size, height: size, margin: 0, padding: 0, background: '#fff', border: 0, opacity: 0 }, // Choose how to hide input hide = _mobile ? { position: 'absolute', visibility: 'hidden' } : area ? layer : { position: 'absolute', opacity: 0 }, // Get proper class className = node[_type] == _checkbox ? settings.checkboxClass || 'i' + _checkbox : settings.radioClass || 'i' + _radio, // Find assigned labels label = $(_label + '[for="' + id + '"]').add(self.closest(_label)), // Check ARIA option aria = !!settings.aria, // Set ARIA placeholder ariaID = _iCheck + '-' + Math.random().toString(36).substr(2,6), // Parent & helper parent = '<div class="' + className + '" ' + (aria ? 'role="' + node[_type] + '" ' : ''), helper; // Set ARIA "labelledby" if (aria) { label.each(function() { parent += 'aria-labelledby="'; if (this.id) { parent += this.id; } else { this.id = ariaID; parent += ariaID; } parent += '"'; }); } // Wrap input parent = self.wrap(parent + '/>')[_callback]('ifCreated').parent().append(settings.insert); // Layer addition helper = $('<ins class="' + _iCheckHelper + '"/>').css(layer).appendTo(parent); // Finalize customization self.data(_iCheck, {o: settings, s: self.attr('style')}).css(hide); !!settings.inheritClass && parent[_add](node.className || ''); !!settings.inheritID && id && parent.attr('id', _iCheck + '-' + id); parent.css('position') == 'static' && parent.css('position', 'relative'); operate(self, true, _update); // Label events if (label.length) { label.on(_click + '.i mouseover.i mouseout.i ' + _touch, function(event) { var type = event[_type], item = $(this); // Do nothing if input is disabled if (!node[_disabled]) { // Click if (type == _click) { if ($(event.target).is('a')) { return; } operate(self, false, true); // Hover state } else if (labelHover) { // mouseout|touchend if (/ut|nd/.test(type)) { parent[_remove](hoverClass); item[_remove](labelHoverClass); } else { parent[_add](hoverClass); item[_add](labelHoverClass); } } if (_mobile) { event.stopPropagation(); } else { return false; } } }); } // Input events self.on(_click + '.i focus.i blur.i keyup.i keydown.i keypress.i', function(event) { var type = event[_type], key = event.keyCode; // Click if (type == _click) { return false; // Keydown } else if (type == 'keydown' && key == 32) { if (!(node[_type] == _radio && node[_checked])) { if (node[_checked]) { off(self, _checked); } else { on(self, _checked); } } return false; // Keyup } else if (type == 'keyup' && node[_type] == _radio) { !node[_checked] && on(self, _checked); // Focus/blur } else if (/us|ur/.test(type)) { parent[type == 'blur' ? _remove : _add](focusClass); } }); // Helper events helper.on(_click + ' mousedown mouseup mouseover mouseout ' + _touch, function(event) { var type = event[_type], // mousedown|mouseup toggle = /wn|up/.test(type) ? activeClass : hoverClass; // Do nothing if input is disabled if (!node[_disabled]) { // Click if (type == _click) { operate(self, false, true); // Active and hover states } else { // State is on if (/wn|er|in/.test(type)) { // mousedown|mouseover|touchbegin parent[_add](toggle); // State is off } else { parent[_remove](toggle + ' ' + activeClass); } // Label hover if (label.length && labelHover && toggle == hoverClass) { // mouseout|touchend label[/ut|nd/.test(type) ? _remove : _add](labelHoverClass); } } if (_mobile) { event.stopPropagation(); } else { return false; } } }); }); } else { return this; } }; // Do something with inputs function operate(input, direct, method) { var node = input[0], state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked, active = method == _update ? { checked: node[_checked], disabled: node[_disabled], indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'false' } : node[state]; // Check, disable or indeterminate if (/^(ch|di|in)/.test(method) && !active) { on(input, state); // Uncheck, enable or determinate } else if (/^(un|en|de)/.test(method) && active) { off(input, state); // Update } else if (method == _update) { // Handle states for (var each in active) { if (active[each]) { on(input, each, true); } else { off(input, each, true); } } } else if (!direct || method == 'toggle') { // Helper or label was clicked if (!direct) { input[_callback]('ifClicked'); } // Toggle checked state if (active) { if (node[_type] !== _radio) { off(input, state); } } else { on(input, state); } } } // Add checked, disabled or indeterminate state function on(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, disabled = state == _disabled, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(input, callback + capitalize(node[_type])), specific = option(input, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== true) { // Toggle assigned radio buttons if (!keep && state == _checked && node[_type] == _radio && node.name) { var form = input.closest('form'), inputs = 'input[name="' + node.name + '"]'; inputs = form.length ? form.find(inputs) : $(inputs); inputs.each(function() { if (this !== node && $(this).data(_iCheck)) { off($(this), state); } }); } // Indeterminate state if (indeterminate) { // Add indeterminate state node[state] = true; // Remove checked state if (node[_checked]) { off(input, _checked, 'force'); } // Checked or disabled state } else { // Add checked or disabled state if (!keep) { node[state] = true; } // Remove indeterminate state if (checked && node[_indeterminate]) { off(input, _indeterminate, false); } } // Trigger callbacks callbacks(input, checked, state, keep); } // Add proper cursor if (node[_disabled] && !!option(input, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'default'); } // Add state class parent[_add](specific || option(input, state) || ''); // Set ARIA attribute if (!!parent.attr('role') && !indeterminate) { parent.attr('aria-' + (disabled ? _disabled : _checked), 'true'); } // Remove regular state class parent[_remove](regular || option(input, callback) || ''); } // Remove checked, disabled or indeterminate state function off(input, state, keep) { var node = input[0], parent = input.parent(), checked = state == _checked, indeterminate = state == _indeterminate, disabled = state == _disabled, callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled', regular = option(input, callback + capitalize(node[_type])), specific = option(input, state + capitalize(node[_type])); // Prevent unnecessary actions if (node[state] !== false) { // Toggle state if (indeterminate || !keep || keep == 'force') { node[state] = false; } // Trigger callbacks callbacks(input, checked, callback, keep); } // Add proper cursor if (!node[_disabled] && !!option(input, _cursor, true)) { parent.find('.' + _iCheckHelper).css(_cursor, 'pointer'); } // Remove state class parent[_remove](specific || option(input, state) || ''); // Set ARIA attribute if (!!parent.attr('role') && !indeterminate) { parent.attr('aria-' + (disabled ? _disabled : _checked), 'false'); } // Add regular state class parent[_add](regular || option(input, callback) || ''); } // Remove all traces function tidy(input, callback) { if (input.data(_iCheck)) { // Remove everything except input input.parent().html(input.attr('style', input.data(_iCheck).s || '')); // Callback if (callback) { input[_callback](callback); } // Unbind events input.off('.i').unwrap(); $(_label + '[for="' + input[0].id + '"]').add(input.closest(_label)).off('.i'); } } // Get some option function option(input, state, regular) { if (input.data(_iCheck)) { return input.data(_iCheck).o[state + (regular ? '' : 'Class')]; } } // Capitalize some string function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); } // Executable handlers function callbacks(input, checked, callback, keep) { if (!keep) { if (checked) { input[_callback]('ifToggled'); } input[_callback]('change')[_callback]('ifChanged')[_callback]('if' + capitalize(callback)); } } })(window.jQuery || window.Zepto);
cdnjs/cdnjs
ajax/libs/iCheck/1.0.3/icheck.js
JavaScript
mit
14,225
const Route = require('../../structures/Route'); class usersGET extends Route { constructor() { super('/admin/users', 'get', { adminOnly: true }); } async run(req, res, db) { try { const users = await db.table('users') .select('id', 'username', 'enabled', 'isAdmin', 'createdAt'); return res.json({ message: 'Successfully retrieved users', users }); } catch (error) { return super.error(res, error); } } } module.exports = usersGET;
WeebDev/lolisafe
src/api/routes/admin/usersGET.js
JavaScript
mit
473
function DetailCellRenderer() {} DetailCellRenderer.prototype.init = function(params) { this.eGui = document.createElement('div'); this.eGui.innerHTML = '<h1 style="padding: 20px;">My Custom Detail</h1>'; }; DetailCellRenderer.prototype.getGui = function() { return this.eGui; };
ceolter/angular-grid
grid-packages/ag-grid-docs/documentation/src/pages/master-detail-custom-detail/examples/simple-custom-detail/detailCellRenderer_vanilla.js
JavaScript
mit
294
/* * * * (c) 2009-2017 Highsoft, Black Label * * License: www.highcharts.com/license * * */ 'use strict'; import H from '../parts/Globals.js'; import U from '../parts/Utilities.js'; var defined = U.defined, destroyObjectProperties = U.destroyObjectProperties, erase = U.erase, extend = U.extend, pick = U.pick, splat = U.splat, wrap = U.wrap; import '../parts/Chart.js'; import controllableMixin from './controllable/controllableMixin.js'; import ControllableRect from './controllable/ControllableRect.js'; import ControllableCircle from './controllable/ControllableCircle.js'; import ControllablePath from './controllable/ControllablePath.js'; import ControllableImage from './controllable/ControllableImage.js'; import ControllableLabel from './controllable/ControllableLabel.js'; import eventEmitterMixin from './eventEmitterMixin.js'; import MockPoint from './MockPoint.js'; import ControlPoint from './ControlPoint.js'; var merge = H.merge, addEvent = H.addEvent, fireEvent = H.fireEvent, find = H.find, reduce = H.reduce, chartProto = H.Chart.prototype; /* ********************************************************************* * * ANNOTATION * ******************************************************************** */ /** * @typedef { * Annotation.ControllableCircle| * Annotation.ControllableImage| * Annotation.ControllablePath| * Annotation.ControllableRect * } * Annotation.Shape */ /** * @typedef {Annotation.ControllableLabel} Annotation.Label */ /** * An annotation class which serves as a container for items like labels or * shapes. Created items are positioned on the chart either by linking them to * existing points or created mock points * * @class * @name Highcharts.Annotation * * @param {Highcharts.Chart} chart a chart instance * @param {Highcharts.AnnotationsOptions} userOptions the options object */ var Annotation = H.Annotation = function (chart, userOptions) { var labelsAndShapes; /** * The chart that the annotation belongs to. * * @type {Highcharts.Chart} */ this.chart = chart; /** * The array of points which defines the annotation. * * @type {Array<Highcharts.Point>} */ this.points = []; /** * The array of control points. * * @type {Array<Annotation.ControlPoint>} */ this.controlPoints = []; this.coll = 'annotations'; /** * The array of labels which belong to the annotation. * * @type {Array<Annotation.Label>} */ this.labels = []; /** * The array of shapes which belong to the annotation. * * @type {Array<Annotation.Shape>} */ this.shapes = []; /** * The options for the annotations. * * @type {Highcharts.AnnotationsOptions} */ this.options = merge(this.defaultOptions, userOptions); /** * The user options for the annotations. * * @type {Highcharts.AnnotationsOptions} */ this.userOptions = userOptions; // Handle labels and shapes - those are arrays // Merging does not work with arrays (stores reference) labelsAndShapes = this.getLabelsAndShapesOptions( this.options, userOptions ); this.options.labels = labelsAndShapes.labels; this.options.shapes = labelsAndShapes.shapes; /** * The callback that reports to the overlapping-labels module which * labels it should account for. * * @name labelCollector * @memberOf Annotation# * @type {Function} */ /** * The group svg element. * * @name group * @memberOf Annotation# * @type {Highcharts.SVGElement} */ /** * The group svg element of the annotation's shapes. * * @name shapesGroup * @memberOf Annotation# * @type {Highcharts.SVGElement} */ /** * The group svg element of the annotation's labels. * * @name labelsGroup * @memberOf Annotation# * @type {Highcharts.SVGElement} */ this.init(chart, this.options); }; merge( true, Annotation.prototype, controllableMixin, eventEmitterMixin, /** @lends Annotation# */ { /** * List of events for `annotation.options.events` that should not be * added to `annotation.graphic` but to the `annotation`. * * @type {Array<string>} */ nonDOMEvents: ['add', 'afterUpdate', 'drag', 'remove'], /** * A basic type of an annotation. It allows to add custom labels * or shapes. The items can be tied to points, axis coordinates * or chart pixel coordinates. * * @sample highcharts/annotations/basic/ * Basic annotations * @sample highcharts/demo/annotations/ * Advanced annotations * @sample highcharts/css/annotations * Styled mode * @sample highcharts/annotations-advanced/controllable * Controllable items * @sample {highstock} stock/annotations/fibonacci-retracements * Custom annotation, Fibonacci retracement * * @type {Array<*>} * @since 6.0.0 * @requires modules/annotations * @optionparent annotations */ defaultOptions: { /** * Sets an ID for an annotation. Can be user later when removing an * annotation in [Chart#removeAnnotation(id)]( * /class-reference/Highcharts.Chart#removeAnnotation) method. * * @type {string|number} * @apioption annotations.id */ /** * Whether the annotation is visible. * * @sample highcharts/annotations/visible/ * Set annotation visibility */ visible: true, /** * Allow an annotation to be draggable by a user. Possible * values are `"x"`, `"xy"`, `"y"` and `""` (disabled). * * @sample highcharts/annotations/draggable/ * Annotations draggable: 'xy' * * @type {string} * @validvalue ["x", "xy", "y", ""] */ draggable: 'xy', /** * Options for annotation's labels. Each label inherits options * from the labelOptions object. An option from the labelOptions * can be overwritten by config for a specific label. * * @requires modules/annotations */ labelOptions: { /** * The alignment of the annotation's label. If right, * the right side of the label should be touching the point. * * @sample highcharts/annotations/label-position/ * Set labels position * * @type {Highcharts.AlignValue} */ align: 'center', /** * Whether to allow the annotation's labels to overlap. * To make the labels less sensitive for overlapping, * the can be set to 0. * * @sample highcharts/annotations/tooltip-like/ * Hide overlapping labels */ allowOverlap: false, /** * The background color or gradient for the annotation's label. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} */ backgroundColor: 'rgba(0, 0, 0, 0.75)', /** * The border color for the annotation's label. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options * * @type {Highcharts.ColorString} */ borderColor: 'black', /** * The border radius in pixels for the annotaiton's label. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options */ borderRadius: 3, /** * The border width in pixels for the annotation's label * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options */ borderWidth: 1, /** * A class name for styling by CSS. * * @sample highcharts/css/annotations * Styled mode annotations * * @since 6.0.5 */ className: '', /** * Whether to hide the annotation's label * that is outside the plot area. * * @sample highcharts/annotations/label-crop-overflow/ * Crop or justify labels */ crop: false, /** * The label's pixel distance from the point. * * @sample highcharts/annotations/label-position/ * Set labels position * * @type {number} * @apioption annotations.labelOptions.distance */ /** * A * [format](https://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting) * string for the data label. * * @see [plotOptions.series.dataLabels.format](plotOptions.series.dataLabels.format.html) * * @sample highcharts/annotations/label-text/ * Set labels text * * @type {string} * @apioption annotations.labelOptions.format */ /** * Alias for the format option. * * @see [format](annotations.labelOptions.format.html) * * @sample highcharts/annotations/label-text/ * Set labels text * * @type {string} * @apioption annotations.labelOptions.text */ /** * Callback JavaScript function to format the annotation's * label. Note that if a `format` or `text` are defined, the * format or text take precedence and the formatter is ignored. * `This` refers to a point object. * * @sample highcharts/annotations/label-text/ * Set labels text * * @type {Highcharts.FormatterCallbackFunction<Highcharts.Point>} * @default function () { return defined(this.y) ? this.y : 'Annotation label'; } */ formatter: function () { return defined(this.y) ? this.y : 'Annotation label'; }, /** * How to handle the annotation's label that flow outside the * plot area. The justify option aligns the label inside the * plot area. * * @sample highcharts/annotations/label-crop-overflow/ * Crop or justify labels * * @validvalue ["allow", "justify"] */ overflow: 'justify', /** * When either the borderWidth or the backgroundColor is set, * this is the padding within the box. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options */ padding: 5, /** * The shadow of the box. The shadow can be an object * configuration containing `color`, `offsetX`, `offsetY`, * `opacity` and `width`. * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options * * @type {boolean|Highcharts.ShadowOptionsObject} */ shadow: false, /** * The name of a symbol to use for the border around the label. * Symbols are predefined functions on the Renderer object. * * @sample highcharts/annotations/shapes/ * Available shapes for labels */ shape: 'callout', /** * Styles for the annotation's label. * * @see [plotOptions.series.dataLabels.style](plotOptions.series.dataLabels.style.html) * * @sample highcharts/annotations/label-presentation/ * Set labels graphic options * * @type {Highcharts.CSSObject} */ style: { /** @ignore */ fontSize: '11px', /** @ignore */ fontWeight: 'normal', /** @ignore */ color: 'contrast' }, /** * Whether to [use HTML](https://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html) * to render the annotation's label. */ useHTML: false, /** * The vertical alignment of the annotation's label. * * @sample highcharts/annotations/label-position/ * Set labels position * * @type {Highcharts.VerticalAlignValue} */ verticalAlign: 'bottom', /** * The x position offset of the label relative to the point. * Note that if a `distance` is defined, the distance takes * precedence over `x` and `y` options. * * @sample highcharts/annotations/label-position/ * Set labels position */ x: 0, /** * The y position offset of the label relative to the point. * Note that if a `distance` is defined, the distance takes * precedence over `x` and `y` options. * * @sample highcharts/annotations/label-position/ * Set labels position */ y: -16 }, /** * An array of labels for the annotation. For options that apply to * multiple labels, they can be added to the * [labelOptions](annotations.labelOptions.html). * * @type {Array<*>} * @extends annotations.labelOptions * @apioption annotations.labels */ /** * This option defines the point to which the label will be * connected. It can be either the point which exists in the * series - it is referenced by the point's id - or a new point with * defined x, y properties and optionally axes. * * @sample highcharts/annotations/mock-point/ * Attach annotation to a mock point * * @type {string|Highcharts.MockPointOptionsObject} * @requires modules/annotations * @apioption annotations.labels.point */ /** * The x position of the point. Units can be either in axis * or chart pixel coordinates. * * @type {number} * @apioption annotations.labels.point.x */ /** * The y position of the point. Units can be either in axis * or chart pixel coordinates. * * @type {number} * @apioption annotations.labels.point.y */ /** * This number defines which xAxis the point is connected to. It * refers to either the axis id or the index of the axis in the * xAxis array. If the option is not configured or the axis is not * found the point's x coordinate refers to the chart pixels. * * @type {number|string} * @apioption annotations.labels.point.xAxis */ /** * This number defines which yAxis the point is connected to. It * refers to either the axis id or the index of the axis in the * yAxis array. If the option is not configured or the axis is not * found the point's y coordinate refers to the chart pixels. * * @type {number|string} * @apioption annotations.labels.point.yAxis */ /** * An array of shapes for the annotation. For options that apply to * multiple shapes, then can be added to the * [shapeOptions](annotations.shapeOptions.html). * * @type {Array<*>} * @extends annotations.shapeOptions * @apioption annotations.shapes */ /** * This option defines the point to which the shape will be * connected. It can be either the point which exists in the * series - it is referenced by the point's id - or a new point with * defined x, y properties and optionally axes. * * @type {string|Highcharts.MockPointOptionsObject} * @extends annotations.labels.point * @apioption annotations.shapes.point */ /** * An array of points for the shape. This option is available for * shapes which can use multiple points such as path. A point can be * either a point object or a point's id. * * @see [annotations.shapes.point](annotations.shapes.point.html) * * @type {Array<string|Highcharts.MockPointOptionsObject>} * @extends annotations.labels.point * @apioption annotations.shapes.points */ /** * Id of the marker which will be drawn at the final vertex of the * path. Custom markers can be defined in defs property. * * @see [defs.markers](defs.markers.html) * * @sample highcharts/annotations/custom-markers/ * Define a custom marker for annotations * * @type {string} * @apioption annotations.shapes.markerEnd */ /** * Id of the marker which will be drawn at the first vertex of the * path. Custom markers can be defined in defs property. * * @see [defs.markers](defs.markers.html) * * @sample {highcharts} highcharts/annotations/custom-markers/ * Define a custom marker for annotations * * @type {string} * @apioption annotations.shapes.markerStart */ /** * Options for annotation's shapes. Each shape inherits options from * the shapeOptions object. An option from the shapeOptions can be * overwritten by config for a specific shape. * * @requires modules/annotations */ shapeOptions: { /** * The width of the shape. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {number} * @apioption annotations.shapeOptions.width **/ /** * The height of the shape. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {number} * @apioption annotations.shapeOptions.height */ /** * The type of the shape, e.g. circle or rectangle. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {string} * @default 'rect' * @apioption annotations.shapeOptions.type */ /** * The color of the shape's stroke. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {Highcharts.ColorString} */ stroke: 'rgba(0, 0, 0, 0.75)', /** * The pixel stroke width of the shape. * * @sample highcharts/annotations/shape/ * Basic shape annotation */ strokeWidth: 1, /** * The color of the shape's fill. * * @sample highcharts/annotations/shape/ * Basic shape annotation * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} */ fill: 'rgba(0, 0, 0, 0.75)', /** * The radius of the shape. * * @sample highcharts/annotations/shape/ * Basic shape annotation */ r: 0, /** * Defines additional snapping area around an annotation * making this annotation to focus. Defined in pixels. */ snap: 2 }, /** * Options for annotation's control points. Each control point * inherits options from controlPointOptions object. * Options from the controlPointOptions can be overwritten * by options in a specific control point. * * @type {Annotation.ControlPoint.Options} * @requires modules/annotations * @apioption annotations.controlPointOptions */ controlPointOptions: { /** * @function {Annotation.ControlPoint.Positioner} * @apioption annotations.controlPointOptions.positioner */ symbol: 'circle', width: 10, height: 10, style: { stroke: 'black', 'stroke-width': 2, fill: 'white' }, visible: false, events: {} }, /** * Event callback when annotation is added to the chart. * * @type {Highcharts.EventCallbackFunction<Highcharts.Annotation>} * @since 7.1.0 * @apioption annotations.events.add */ /** * Event callback when annotation is updated (e.g. drag and * droppped or resized by control points). * * @type {Highcharts.EventCallbackFunction<Highcharts.Annotation>} * @since 7.1.0 * @apioption annotations.events.afterUpdate */ /** * Event callback when annotation is removed from the chart. * * @type {Highcharts.EventCallbackFunction<Highcharts.Annotation>} * @since 7.1.0 * @apioption annotations.events.remove */ /** * Events available in annotations. * * @requires modules/annotations */ events: {}, /** * The Z index of the annotation. */ zIndex: 6 }, /** * Initialize the annotation. * * @param {Highcharts.Chart} * The chart * @param {Highcharts.AnnotationsOptions} * The user options for the annotation */ init: function () { this.linkPoints(); this.addControlPoints(); this.addShapes(); this.addLabels(); this.addClipPaths(); this.setLabelCollector(); }, getLabelsAndShapesOptions: function (baseOptions, newOptions) { var mergedOptions = {}; ['labels', 'shapes'].forEach(function (name) { if (baseOptions[name]) { mergedOptions[name] = splat(newOptions[name]).map( function (basicOptions, i) { return merge(baseOptions[name][i], basicOptions); } ); } }); return mergedOptions; }, addShapes: function () { (this.options.shapes || []).forEach(function (shapeOptions, i) { var shape = this.initShape(shapeOptions, i); merge(true, this.options.shapes[i], shape.options); }, this); }, addLabels: function () { (this.options.labels || []).forEach(function (labelsOptions, i) { var labels = this.initLabel(labelsOptions, i); merge(true, this.options.labels[i], labels.options); }, this); }, addClipPaths: function () { this.setClipAxes(); if (this.clipXAxis && this.clipYAxis) { this.clipRect = this.chart.renderer.clipRect( this.getClipBox() ); } }, setClipAxes: function () { var xAxes = this.chart.xAxis, yAxes = this.chart.yAxis, linkedAxes = reduce( (this.options.labels || []) .concat(this.options.shapes || []), function (axes, labelOrShape) { return [ xAxes[ labelOrShape && labelOrShape.point && labelOrShape.point.xAxis ] || axes[0], yAxes[ labelOrShape && labelOrShape.point && labelOrShape.point.yAxis ] || axes[1] ]; }, [] ); this.clipXAxis = linkedAxes[0]; this.clipYAxis = linkedAxes[1]; }, getClipBox: function () { return { x: this.clipXAxis.left, y: this.clipYAxis.top, width: this.clipXAxis.width, height: this.clipYAxis.height }; }, setLabelCollector: function () { var annotation = this; annotation.labelCollector = function () { return annotation.labels.reduce( function (labels, label) { if (!label.options.allowOverlap) { labels.push(label.graphic); } return labels; }, [] ); }; annotation.chart.labelCollectors.push( annotation.labelCollector ); }, /** * Set an annotation options. * * @param {Highcharts.AnnotationsOptions} - user options for an annotation */ setOptions: function (userOptions) { this.options = merge(this.defaultOptions, userOptions); }, redraw: function (animation) { this.linkPoints(); if (!this.graphic) { this.render(); } if (this.clipRect) { this.clipRect.animate(this.getClipBox()); } this.redrawItems(this.shapes, animation); this.redrawItems(this.labels, animation); controllableMixin.redraw.call(this, animation); }, /** * @param {Array<(Annotation.Label|Annotation.Shape)>} items * @param {boolean} [animation] */ redrawItems: function (items, animation) { var i = items.length; // needs a backward loop // labels/shapes array might be modified // due to destruction of the item while (i--) { this.redrawItem(items[i], animation); } }, render: function () { var renderer = this.chart.renderer; this.graphic = renderer .g('annotation') .attr({ zIndex: this.options.zIndex, visibility: this.options.visible ? 'visible' : 'hidden' }) .add(); this.shapesGroup = renderer .g('annotation-shapes') .add(this.graphic) .clip(this.chart.plotBoxClip); this.labelsGroup = renderer .g('annotation-labels') .attr({ // hideOverlappingLabels requires translation translateX: 0, translateY: 0 }) .add(this.graphic); if (this.clipRect) { this.graphic.clip(this.clipRect); } this.addEvents(); controllableMixin.render.call(this); }, /** * Set the annotation's visibility. * * @param {Boolean} [visible] - Whether to show or hide an annotation. * If the param is omitted, the annotation's visibility is toggled. */ setVisibility: function (visibility) { var options = this.options, visible = pick(visibility, !options.visible); this.graphic.attr( 'visibility', visible ? 'visible' : 'hidden' ); if (!visible) { this.setControlPointsVisibility(false); } options.visible = visible; }, setControlPointsVisibility: function (visible) { var setItemControlPointsVisibility = function (item) { item.setControlPointsVisibility(visible); }; controllableMixin.setControlPointsVisibility.call( this, visible ); this.shapes.forEach(setItemControlPointsVisibility); this.labels.forEach(setItemControlPointsVisibility); }, /** * Destroy the annotation. This function does not touch the chart * that the annotation belongs to (all annotations are kept in * the chart.annotations array) - it is recommended to use * {@link Highcharts.Chart#removeAnnotation} instead. */ destroy: function () { var chart = this.chart, destroyItem = function (item) { item.destroy(); }; this.labels.forEach(destroyItem); this.shapes.forEach(destroyItem); this.clipXAxis = null; this.clipYAxis = null; erase(chart.labelCollectors, this.labelCollector); eventEmitterMixin.destroy.call(this); controllableMixin.destroy.call(this); destroyObjectProperties(this, chart); }, /** * See {@link Highcharts.Chart#removeAnnotation}. */ remove: function () { // Let chart.update() remove annoations on demand return this.chart.removeAnnotation(this); }, update: function (userOptions) { var chart = this.chart, labelsAndShapes = this.getLabelsAndShapesOptions( this.userOptions, userOptions ), userOptionsIndex = chart.annotations.indexOf(this), options = H.merge(true, this.userOptions, userOptions); options.labels = labelsAndShapes.labels; options.shapes = labelsAndShapes.shapes; this.destroy(); this.constructor(chart, options); // Update options in chart options, used in exporting (#9767): chart.options.annotations[userOptionsIndex] = options; this.isUpdating = true; this.redraw(); this.isUpdating = false; fireEvent(this, 'afterUpdate'); }, /* ************************************************************* * ITEM SECTION * Contains methods for handling a single item in an annotation **************************************************************** */ /** * Initialisation of a single shape * * @param {Object} shapeOptions - a confg object for a single shape */ initShape: function (shapeOptions, index) { var options = merge( this.options.shapeOptions, { controlPointOptions: this.options.controlPointOptions }, shapeOptions ), shape = new Annotation.shapesMap[options.type]( this, options, index ); shape.itemType = 'shape'; this.shapes.push(shape); return shape; }, /** * Initialisation of a single label * * @param {Object} labelOptions **/ initLabel: function (labelOptions, index) { var options = merge( this.options.labelOptions, { controlPointOptions: this.options.controlPointOptions }, labelOptions ), label = new ControllableLabel( this, options, index ); label.itemType = 'label'; this.labels.push(label); return label; }, /** * Redraw a single item. * * @param {Annotation.Label|Annotation.Shape} item * @param {boolean} [animation] */ redrawItem: function (item, animation) { item.linkPoints(); if (!item.shouldBeDrawn()) { this.destroyItem(item); } else { if (!item.graphic) { this.renderItem(item); } item.redraw( pick(animation, true) && item.graphic.placed ); if (item.points.length) { this.adjustVisibility(item); } } }, /** * Hide or show annotaiton attached to points. * * @param {Annotation.Label|Annotation.Shape} item */ adjustVisibility: function (item) { // #9481 var hasVisiblePoints = false, label = item.graphic; item.points.forEach(function (point) { if ( point.series.visible !== false && point.visible !== false ) { hasVisiblePoints = true; } }); if (!hasVisiblePoints) { label.hide(); } else if (label.visibility === 'hidden') { label.show(); } }, /** * Destroy a single item. * * @param {Annotation.Label|Annotation.Shape} item */ destroyItem: function (item) { // erase from shapes or labels array erase(this[item.itemType + 's'], item); item.destroy(); }, /** * @private */ renderItem: function (item) { item.render( item.itemType === 'label' ? this.labelsGroup : this.shapesGroup ); } } ); /** * An object uses for mapping between a shape type and a constructor. * To add a new shape type extend this object with type name as a key * and a constructor as its value. */ Annotation.shapesMap = { 'rect': ControllableRect, 'circle': ControllableCircle, 'path': ControllablePath, 'image': ControllableImage }; Annotation.types = {}; Annotation.MockPoint = MockPoint; Annotation.ControlPoint = ControlPoint; H.extendAnnotation = function ( Constructor, BaseConstructor, prototype, defaultOptions ) { BaseConstructor = BaseConstructor || Annotation; merge( true, Constructor.prototype, BaseConstructor.prototype, prototype ); Constructor.prototype.defaultOptions = merge( Constructor.prototype.defaultOptions, defaultOptions || {} ); }; /* ********************************************************************* * * EXTENDING CHART PROTOTYPE * ******************************************************************** */ extend(chartProto, /** @lends Highcharts.Chart# */ { initAnnotation: function (userOptions) { var Constructor = Annotation.types[userOptions.type] || Annotation, annotation = new Constructor(this, userOptions); this.annotations.push(annotation); return annotation; }, /** * Add an annotation to the chart after render time. * * @param {Highcharts.AnnotationsOptions} options * The annotation options for the new, detailed annotation. * @param {boolean} [redraw] * * @return {Highcharts.Annotation} - The newly generated annotation. */ addAnnotation: function (userOptions, redraw) { var annotation = this.initAnnotation(userOptions); this.options.annotations.push(annotation.options); if (pick(redraw, true)) { annotation.redraw(); } return annotation; }, /** * Remove an annotation from the chart. * * @param {String|Number|Annotation} idOrAnnotation - The annotation's id or * direct annotation object. */ removeAnnotation: function (idOrAnnotation) { var annotations = this.annotations, annotation = idOrAnnotation.coll === 'annotations' ? idOrAnnotation : find( annotations, function (annotation) { return annotation.options.id === idOrAnnotation; } ); if (annotation) { fireEvent(annotation, 'remove'); erase(this.options.annotations, annotation.options); erase(annotations, annotation); annotation.destroy(); } }, drawAnnotations: function () { this.plotBoxClip.attr(this.plotBox); this.annotations.forEach(function (annotation) { annotation.redraw(); }); } }); // Let chart.update() update annotations chartProto.collectionsWithUpdate.push('annotations'); // Let chart.update() create annoations on demand chartProto.collectionsWithInit.annotations = [chartProto.addAnnotation]; chartProto.callbacks.push(function (chart) { chart.annotations = []; if (!chart.options.annotations) { chart.options.annotations = []; } chart.plotBoxClip = this.renderer.clipRect(this.plotBox); chart.controlPointsGroup = chart.renderer .g('control-points') .attr({ zIndex: 99 }) .clip(chart.plotBoxClip) .add(); chart.options.annotations.forEach(function (annotationOptions, i) { var annotation = chart.initAnnotation(annotationOptions); chart.options.annotations[i] = annotation.options; }); chart.drawAnnotations(); addEvent(chart, 'redraw', chart.drawAnnotations); addEvent(chart, 'destroy', function () { chart.plotBoxClip.destroy(); chart.controlPointsGroup.destroy(); }); }); wrap( H.Pointer.prototype, 'onContainerMouseDown', function (proceed) { if (!this.chart.hasDraggedAnnotation) { proceed.apply(this, Array.prototype.slice.call(arguments, 1)); } } );
cdnjs/cdnjs
ajax/libs/highcharts/8.0.0/es-modules/annotations/annotations.src.js
JavaScript
mit
42,338
this.primereact = this.primereact || {}; this.primereact.multiselect = (function (exports, React, core, inputtext, virtualscroller, PrimeReact) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var React__default = /*#__PURE__*/_interopDefaultLegacy(React); var PrimeReact__default = /*#__PURE__*/_interopDefaultLegacy(PrimeReact); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$1(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Checkbox = /*#__PURE__*/function (_Component) { _inherits(Checkbox, _Component); var _super = _createSuper$4(Checkbox); function Checkbox(props) { var _this; _classCallCheck(this, Checkbox); _this = _super.call(this, props); _this.state = { focused: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.inputRef = /*#__PURE__*/React.createRef(_this.props.inputRef); return _this; } _createClass(Checkbox, [{ key: "onClick", value: function onClick(e) { if (!this.props.disabled && !this.props.readOnly && this.props.onChange) { this.props.onChange({ originalEvent: e, value: this.props.value, checked: !this.props.checked, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { type: 'checkbox', name: this.props.name, id: this.props.id, value: this.props.value, checked: !this.props.checked } }); this.inputRef.current.checked = !this.props.checked; this.inputRef.current.focus(); e.preventDefault(); } } }, { key: "updateInputRef", value: function updateInputRef() { var ref = this.props.inputRef; if (ref) { if (typeof ref === 'function') { ref(this.inputRef.current); } else { ref.current = this.inputRef.current; } } } }, { key: "componentDidMount", value: function componentDidMount() { this.updateInputRef(); if (this.props.tooltip) { this.renderTooltip(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.tooltip) { this.tooltip.destroy(); this.tooltip = null; } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { this.inputRef.current.checked = this.props.checked; if (prevProps.tooltip !== this.props.tooltip || prevProps.tooltipOptions !== this.props.tooltipOptions) { if (this.tooltip) this.tooltip.update(_objectSpread$2({ content: this.props.tooltip }, this.props.tooltipOptions || {}));else this.renderTooltip(); } } }, { key: "onFocus", value: function onFocus() { this.setState({ focused: true }); } }, { key: "onBlur", value: function onBlur() { this.setState({ focused: false }); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.key === 'Enter') { this.onClick(event); event.preventDefault(); } } }, { key: "renderTooltip", value: function renderTooltip() { this.tooltip = core.tip({ target: this.element, content: this.props.tooltip, options: this.props.tooltipOptions }); } }, { key: "render", value: function render() { var _this2 = this; var containerClass = core.classNames('p-checkbox p-component', { 'p-checkbox-checked': this.props.checked, 'p-checkbox-disabled': this.props.disabled, 'p-checkbox-focused': this.state.focused }, this.props.className); var boxClass = core.classNames('p-checkbox-box', { 'p-highlight': this.props.checked, 'p-disabled': this.props.disabled, 'p-focus': this.state.focused }); var iconClass = core.classNames('p-checkbox-icon p-c', _defineProperty({}, this.props.icon, this.props.checked)); return /*#__PURE__*/React__default['default'].createElement("div", { ref: function ref(el) { return _this2.element = el; }, id: this.props.id, className: containerClass, style: this.props.style, onClick: this.onClick, onContextMenu: this.props.onContextMenu, onMouseDown: this.props.onMouseDown }, /*#__PURE__*/React__default['default'].createElement("div", { className: "p-hidden-accessible" }, /*#__PURE__*/React__default['default'].createElement("input", { ref: this.inputRef, type: "checkbox", "aria-labelledby": this.props.ariaLabelledBy, id: this.props.inputId, name: this.props.name, tabIndex: this.props.tabIndex, defaultChecked: this.props.checked, onKeyDown: this.onKeyDown, onFocus: this.onFocus, onBlur: this.onBlur, disabled: this.props.disabled, readOnly: this.props.readOnly, required: this.props.required })), /*#__PURE__*/React__default['default'].createElement("div", { className: boxClass, ref: function ref(el) { return _this2.box = el; }, role: "checkbox", "aria-checked": this.props.checked }, /*#__PURE__*/React__default['default'].createElement("span", { className: iconClass }))); } }]); return Checkbox; }(React.Component); _defineProperty(Checkbox, "defaultProps", { id: null, inputRef: null, inputId: null, value: null, name: null, checked: false, style: null, className: null, disabled: false, required: false, readOnly: false, tabIndex: null, icon: 'pi pi-check', tooltip: null, tooltipOptions: null, ariaLabelledBy: null, onChange: null, onMouseDown: null, onContextMenu: null }); function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var MultiSelectHeader = /*#__PURE__*/function (_Component) { _inherits(MultiSelectHeader, _Component); var _super = _createSuper$3(MultiSelectHeader); function MultiSelectHeader(props) { var _this; _classCallCheck(this, MultiSelectHeader); _this = _super.call(this, props); _this.onFilter = _this.onFilter.bind(_assertThisInitialized(_this)); _this.onSelectAll = _this.onSelectAll.bind(_assertThisInitialized(_this)); return _this; } _createClass(MultiSelectHeader, [{ key: "onFilter", value: function onFilter(event) { if (this.props.onFilter) { this.props.onFilter({ originalEvent: event, query: event.target.value }); } } }, { key: "onSelectAll", value: function onSelectAll(event) { if (this.props.onSelectAll) { this.props.onSelectAll({ originalEvent: event, checked: this.props.selectAll }); } } }, { key: "renderFilterElement", value: function renderFilterElement() { if (this.props.filter) { return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-filter-container" }, /*#__PURE__*/React__default['default'].createElement(inputtext.InputText, { type: "text", role: "textbox", value: this.props.filterValue, onChange: this.onFilter, className: "p-multiselect-filter", placeholder: this.props.filterPlaceholder }), /*#__PURE__*/React__default['default'].createElement("span", { className: "p-multiselect-filter-icon pi pi-search" })); } return null; } }, { key: "render", value: function render() { var filterElement = this.renderFilterElement(); var checkboxElement = this.props.showSelectAll && /*#__PURE__*/React__default['default'].createElement(Checkbox, { checked: this.props.selectAll, onChange: this.onSelectAll, role: "checkbox", "aria-checked": this.props.selectAll }); var closeElement = /*#__PURE__*/React__default['default'].createElement("button", { type: "button", className: "p-multiselect-close p-link", onClick: this.props.onClose }, /*#__PURE__*/React__default['default'].createElement("span", { className: "p-multiselect-close-icon pi pi-times" }), /*#__PURE__*/React__default['default'].createElement(core.Ripple, null)); var element = /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-header" }, checkboxElement, filterElement, closeElement); if (this.props.template) { var defaultOptions = { className: 'p-multiselect-header', checkboxElement: checkboxElement, checked: this.props.selectAll, onChange: this.onSelectAll, filterElement: filterElement, closeElement: closeElement, closeElementClassName: 'p-multiselect-close p-link', closeIconClassName: 'p-multiselect-close-icon pi pi-times', onCloseClick: this.props.onClose, element: element, props: this.props }; return core.ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return MultiSelectHeader; }(React.Component); function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var MultiSelectItem = /*#__PURE__*/function (_Component) { _inherits(MultiSelectItem, _Component); var _super = _createSuper$2(MultiSelectItem); function MultiSelectItem(props) { var _this; _classCallCheck(this, MultiSelectItem); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(MultiSelectItem, [{ key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, option: this.props.option }); } event.preventDefault(); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (this.props.onKeyDown) { this.props.onKeyDown({ originalEvent: event, option: this.props.option }); } } }, { key: "render", value: function render() { var className = core.classNames('p-multiselect-item', { 'p-highlight': this.props.selected, 'p-disabled': this.props.disabled }, this.props.option.className); var checkboxClassName = core.classNames('p-checkbox-box', { 'p-highlight': this.props.selected }); var checkboxIcon = core.classNames('p-checkbox-icon p-c', { 'pi pi-check': this.props.selected }); var content = this.props.template ? core.ObjectUtils.getJSXElement(this.props.template, this.props.option) : this.props.label; var tabIndex = this.props.disabled ? null : this.props.tabIndex || 0; return /*#__PURE__*/React__default['default'].createElement("li", { className: className, onClick: this.onClick, tabIndex: tabIndex, onKeyDown: this.onKeyDown, role: "option", "aria-selected": this.props.selected }, /*#__PURE__*/React__default['default'].createElement("div", { className: "p-checkbox p-component" }, /*#__PURE__*/React__default['default'].createElement("div", { className: checkboxClassName }, /*#__PURE__*/React__default['default'].createElement("span", { className: checkboxIcon }))), /*#__PURE__*/React__default['default'].createElement("span", null, content), /*#__PURE__*/React__default['default'].createElement(core.Ripple, null)); } }]); return MultiSelectItem; }(React.Component); _defineProperty(MultiSelectItem, "defaultProps", { option: null, label: null, selected: false, disabled: false, tabIndex: null, template: null, onClick: null, onKeyDown: null }); function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var MultiSelectPanelComponent = /*#__PURE__*/function (_Component) { _inherits(MultiSelectPanelComponent, _Component); var _super = _createSuper$1(MultiSelectPanelComponent); function MultiSelectPanelComponent(props) { var _this; _classCallCheck(this, MultiSelectPanelComponent); _this = _super.call(this, props); _this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this)); _this.onFilterInputChange = _this.onFilterInputChange.bind(_assertThisInitialized(_this)); return _this; } _createClass(MultiSelectPanelComponent, [{ key: "onEnter", value: function onEnter() { var _this2 = this; this.props.onEnter(function () { if (_this2.virtualScrollerRef) { var selectedIndex = _this2.props.getSelectedOptionIndex(); if (selectedIndex !== -1) { _this2.virtualScrollerRef.scrollToIndex(selectedIndex); } } }); } }, { key: "onFilterInputChange", value: function onFilterInputChange(event) { if (this.virtualScrollerRef) { this.virtualScrollerRef.scrollToIndex(0); } this.props.onFilterInputChange && this.props.onFilterInputChange(event); } }, { key: "isEmptyFilter", value: function isEmptyFilter() { return !(this.props.visibleOptions && this.props.visibleOptions.length) && this.props.hasFilter(); } }, { key: "renderHeader", value: function renderHeader() { return /*#__PURE__*/React__default['default'].createElement(MultiSelectHeader, { filter: this.props.filter, filterValue: this.props.filterValue, onFilter: this.onFilterInputChange, filterPlaceholder: this.props.filterPlaceholder, onClose: this.props.onCloseClick, showSelectAll: this.props.showSelectAll, selectAll: this.props.isAllSelected(), onSelectAll: this.props.onSelectAll, template: this.props.panelHeaderTemplate }); } }, { key: "renderFooter", value: function renderFooter() { if (this.props.panelFooterTemplate) { var content = core.ObjectUtils.getJSXElement(this.props.panelFooterTemplate, this.props, this.props.onOverlayHide); return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-footer" }, content); } return null; } }, { key: "renderGroupChildren", value: function renderGroupChildren(optionGroup) { var _this3 = this; var groupChildren = this.props.getOptionGroupChildren(optionGroup); return groupChildren.map(function (option, j) { var optionLabel = _this3.props.getOptionLabel(option); var optionKey = j + '_' + _this3.props.getOptionRenderKey(option); var disabled = _this3.props.isOptionDisabled(option); var tabIndex = disabled ? null : _this3.props.tabIndex || 0; return /*#__PURE__*/React__default['default'].createElement(MultiSelectItem, { key: optionKey, label: optionLabel, option: option, template: _this3.props.itemTemplate, selected: _this3.props.isSelected(option), onClick: _this3.props.onOptionSelect, onKeyDown: _this3.props.onOptionKeyDown, tabIndex: tabIndex, disabled: disabled }); }); } }, { key: "renderEmptyFilter", value: function renderEmptyFilter() { var emptyFilterMessage = core.ObjectUtils.getJSXElement(this.props.emptyFilterMessage, this.props); return /*#__PURE__*/React__default['default'].createElement("li", { className: "p-multiselect-empty-message" }, emptyFilterMessage); } }, { key: "renderItem", value: function renderItem(option, index) { if (this.props.optionGroupLabel) { var groupContent = this.props.optionGroupTemplate ? core.ObjectUtils.getJSXElement(this.props.optionGroupTemplate, option, index) : this.props.getOptionGroupLabel(option); var groupChildrenContent = this.renderGroupChildren(option); var key = index + '_' + this.props.getOptionGroupRenderKey(option); return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, { key: key }, /*#__PURE__*/React__default['default'].createElement("li", { className: "p-multiselect-item-group" }, groupContent), groupChildrenContent); } else { var optionLabel = this.props.getOptionLabel(option); var optionKey = index + '_' + this.props.getOptionRenderKey(option); var disabled = this.props.isOptionDisabled(option); var tabIndex = disabled ? null : this.props.tabIndex || 0; return /*#__PURE__*/React__default['default'].createElement(MultiSelectItem, { key: optionKey, label: optionLabel, option: option, template: this.props.itemTemplate, selected: this.props.isSelected(option), onClick: this.props.onOptionSelect, onKeyDown: this.props.onOptionKeyDown, tabIndex: tabIndex, disabled: disabled }); } } }, { key: "renderItems", value: function renderItems() { var _this4 = this; if (this.props.visibleOptions && this.props.visibleOptions.length) { return this.props.visibleOptions.map(function (option, index) { return _this4.renderItem(option, index); }); } else if (this.props.hasFilter()) { return this.renderEmptyFilter(); } return null; } }, { key: "renderContent", value: function renderContent() { var _this5 = this; if (this.props.virtualScrollerOptions) { var virtualScrollerProps = _objectSpread$1(_objectSpread$1({}, this.props.virtualScrollerOptions), { style: _objectSpread$1(_objectSpread$1({}, this.props.virtualScrollerOptions.style), { height: this.props.scrollHeight }), className: core.classNames('p-multiselect-items-wrapper', this.props.virtualScrollerOptions.className), items: this.props.visibleOptions, onLazyLoad: function onLazyLoad(event) { return _this5.props.virtualScrollerOptions.onLazyLoad(_objectSpread$1(_objectSpread$1({}, event), { filter: _this5.props.filterValue })); }, itemTemplate: function itemTemplate(item, options) { return item && _this5.renderItem(item, options.index); }, contentTemplate: function contentTemplate(options) { var className = core.classNames('p-multiselect-items p-component', options.className); var content = _this5.isEmptyFilter() ? _this5.renderEmptyFilter() : options.children; return /*#__PURE__*/React__default['default'].createElement("ul", { ref: options.ref, className: className, role: "listbox", "aria-multiselectable": true }, content); } }); return /*#__PURE__*/React__default['default'].createElement(virtualscroller.VirtualScroller, _extends({ ref: function ref(el) { return _this5.virtualScrollerRef = el; } }, virtualScrollerProps)); } else { var items = this.renderItems(); return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-items-wrapper", style: { maxHeight: this.props.scrollHeight } }, /*#__PURE__*/React__default['default'].createElement("ul", { className: "p-multiselect-items p-component", role: "listbox", "aria-multiselectable": true }, items)); } } }, { key: "renderElement", value: function renderElement() { var panelClassName = core.classNames('p-multiselect-panel p-component', { 'p-multiselect-limited': !this.props.allowOptionSelect() }, this.props.panelClassName); var header = this.renderHeader(); var content = this.renderContent(); var footer = this.renderFooter(); return /*#__PURE__*/React__default['default'].createElement(core.CSSTransition, { nodeRef: this.props.forwardRef, classNames: "p-connected-overlay", in: this.props.in, timeout: { enter: 120, exit: 100 }, options: this.props.transitionOptions, unmountOnExit: true, onEnter: this.onEnter, onEntered: this.props.onEntered, onExit: this.props.onExit, onExited: this.props.onExited }, /*#__PURE__*/React__default['default'].createElement("div", { ref: this.props.forwardRef, className: panelClassName, style: this.props.panelStyle, onClick: this.props.onClick }, header, content, footer)); } }, { key: "render", value: function render() { var element = this.renderElement(); return /*#__PURE__*/React__default['default'].createElement(core.Portal, { element: element, appendTo: this.props.appendTo }); } }]); return MultiSelectPanelComponent; }(React.Component); var MultiSelectPanel = /*#__PURE__*/React__default['default'].forwardRef(function (props, ref) { return /*#__PURE__*/React__default['default'].createElement(MultiSelectPanelComponent, _extends({ forwardRef: ref }, props)); }); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var MultiSelect = /*#__PURE__*/function (_Component) { _inherits(MultiSelect, _Component); var _super = _createSuper(MultiSelect); function MultiSelect(props) { var _this; _classCallCheck(this, MultiSelect); _this = _super.call(this, props); _this.state = { filter: '', focused: false, overlayVisible: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.onOptionSelect = _this.onOptionSelect.bind(_assertThisInitialized(_this)); _this.onOptionKeyDown = _this.onOptionKeyDown.bind(_assertThisInitialized(_this)); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onFilterInputChange = _this.onFilterInputChange.bind(_assertThisInitialized(_this)); _this.onCloseClick = _this.onCloseClick.bind(_assertThisInitialized(_this)); _this.onSelectAll = _this.onSelectAll.bind(_assertThisInitialized(_this)); _this.onOverlayEnter = _this.onOverlayEnter.bind(_assertThisInitialized(_this)); _this.onOverlayEntered = _this.onOverlayEntered.bind(_assertThisInitialized(_this)); _this.onOverlayExit = _this.onOverlayExit.bind(_assertThisInitialized(_this)); _this.onOverlayExited = _this.onOverlayExited.bind(_assertThisInitialized(_this)); _this.onPanelClick = _this.onPanelClick.bind(_assertThisInitialized(_this)); _this.getOptionLabel = _this.getOptionLabel.bind(_assertThisInitialized(_this)); _this.getOptionRenderKey = _this.getOptionRenderKey.bind(_assertThisInitialized(_this)); _this.isOptionDisabled = _this.isOptionDisabled.bind(_assertThisInitialized(_this)); _this.getOptionGroupChildren = _this.getOptionGroupChildren.bind(_assertThisInitialized(_this)); _this.getOptionGroupLabel = _this.getOptionGroupLabel.bind(_assertThisInitialized(_this)); _this.getOptionGroupRenderKey = _this.getOptionGroupRenderKey.bind(_assertThisInitialized(_this)); _this.allowOptionSelect = _this.allowOptionSelect.bind(_assertThisInitialized(_this)); _this.isSelected = _this.isSelected.bind(_assertThisInitialized(_this)); _this.isAllSelected = _this.isAllSelected.bind(_assertThisInitialized(_this)); _this.hasFilter = _this.hasFilter.bind(_assertThisInitialized(_this)); _this.getSelectedOptionIndex = _this.getSelectedOptionIndex.bind(_assertThisInitialized(_this)); _this.hide = _this.hide.bind(_assertThisInitialized(_this)); _this.onOptionKeyDown = _this.onOptionKeyDown.bind(_assertThisInitialized(_this)); _this.overlayRef = /*#__PURE__*/React.createRef(); _this.inputRef = /*#__PURE__*/React.createRef(_this.props.inputRef); return _this; } _createClass(MultiSelect, [{ key: "onPanelClick", value: function onPanelClick(event) { core.OverlayService.emit('overlay-click', { originalEvent: event, target: this.container }); } }, { key: "allowOptionSelect", value: function allowOptionSelect() { return !this.props.selectionLimit || !this.props.value || this.props.value && this.props.value.length < this.props.selectionLimit; } }, { key: "onOptionSelect", value: function onOptionSelect(event) { var _this2 = this; var originalEvent = event.originalEvent, option = event.option; if (this.props.disabled || this.isOptionDisabled(option)) { return; } var optionValue = this.getOptionValue(option); var isOptionValueUsed = this.isOptionValueUsed(option); var selected = this.isSelected(option); var allowOptionSelect = this.allowOptionSelect(); if (selected) this.updateModel(originalEvent, this.props.value.filter(function (val) { return !core.ObjectUtils.equals(isOptionValueUsed ? val : _this2.getOptionValue(val), optionValue, _this2.equalityKey()); }));else if (allowOptionSelect) this.updateModel(originalEvent, [].concat(_toConsumableArray(this.props.value || []), [optionValue])); } }, { key: "onOptionKeyDown", value: function onOptionKeyDown(event) { var originalEvent = event.originalEvent; var listItem = originalEvent.currentTarget; switch (originalEvent.which) { //down case 40: var nextItem = this.findNextItem(listItem); if (nextItem) { nextItem.focus(); } originalEvent.preventDefault(); break; //up case 38: var prevItem = this.findPrevItem(listItem); if (prevItem) { prevItem.focus(); } originalEvent.preventDefault(); break; //enter and space case 13: case 32: this.onOptionSelect(event); originalEvent.preventDefault(); break; //escape case 27: this.hide(); this.inputRef.current.focus(); break; } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return core.DomHandler.hasClass(nextItem, 'p-disabled') || core.DomHandler.hasClass(nextItem, 'p-multiselect-item-group') ? this.findNextItem(nextItem) : nextItem;else return null; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return core.DomHandler.hasClass(prevItem, 'p-disabled') || core.DomHandler.hasClass(prevItem, 'p-multiselect-item-group') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "onClick", value: function onClick(event) { if (!this.props.disabled && !this.isPanelClicked(event) && !core.DomHandler.hasClass(event.target, 'p-multiselect-token-icon') && !this.isClearClicked(event)) { if (this.state.overlayVisible) { this.hide(); } else { this.show(); } this.inputRef.current.focus(); } } }, { key: "onKeyDown", value: function onKeyDown(event) { switch (event.which) { //down case 40: if (!this.state.overlayVisible && event.altKey) { this.show(); event.preventDefault(); } break; //space case 32: if (this.state.overlayVisible) this.hide();else this.show(); event.preventDefault(); break; //escape case 27: this.hide(); break; //tab case 9: if (this.state.overlayVisible) { var firstFocusableElement = core.DomHandler.getFirstFocusableElement(this.overlayRef.current); if (firstFocusableElement) { firstFocusableElement.focus(); event.preventDefault(); } } break; } } }, { key: "onSelectAll", value: function onSelectAll(event) { var _this3 = this; if (this.props.onSelectAll) { this.props.onSelectAll(event); } else { var value = null; var visibleOptions = this.getVisibleOptions(); if (event.checked) { value = []; if (visibleOptions) { var selectedOptions = visibleOptions.filter(function (option) { return _this3.isOptionDisabled(option) && _this3.isSelected(option); }); value = selectedOptions.map(function (option) { return _this3.getOptionValue(option); }); } } else if (visibleOptions) { visibleOptions = visibleOptions.filter(function (option) { return !_this3.isOptionDisabled(option); }); if (this.props.optionGroupLabel) { value = []; visibleOptions.forEach(function (optionGroup) { return value = [].concat(_toConsumableArray(value), _toConsumableArray(_this3.getOptionGroupChildren(optionGroup).filter(function (option) { return !_this3.isOptionDisabled(option); }).map(function (option) { return _this3.getOptionValue(option); }))); }); } else { value = visibleOptions.map(function (option) { return _this3.getOptionValue(option); }); } value = _toConsumableArray(new Set([].concat(_toConsumableArray(value), _toConsumableArray(this.props.value || [])))); } this.updateModel(event.originalEvent, value); } } }, { key: "updateModel", value: function updateModel(event, value) { if (this.props.onChange) { this.props.onChange({ originalEvent: event, value: value, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: this.props.name, id: this.props.id, value: value } }); } } }, { key: "onFilterInputChange", value: function onFilterInputChange(event) { var _this4 = this; var filter = event.query; this.setState({ filter: filter }, function () { if (_this4.props.onFilter) { _this4.props.onFilter({ originalEvent: event, filter: filter }); } }); } }, { key: "resetFilter", value: function resetFilter() { var _this5 = this; var filter = ''; this.setState({ filter: filter }, function () { _this5.props.onFilter && _this5.props.onFilter({ filter: filter }); }); } }, { key: "show", value: function show() { this.setState({ overlayVisible: true }); } }, { key: "hide", value: function hide() { this.setState({ overlayVisible: false }); } }, { key: "onOverlayEnter", value: function onOverlayEnter(callback) { core.ZIndexUtils.set('overlay', this.overlayRef.current); this.alignOverlay(); this.scrollInView(); callback && callback(); } }, { key: "onOverlayEntered", value: function onOverlayEntered(callback) { this.bindDocumentClickListener(); this.bindScrollListener(); this.bindResizeListener(); callback && callback(); this.props.onShow && this.props.onShow(); } }, { key: "onOverlayExit", value: function onOverlayExit() { this.unbindDocumentClickListener(); this.unbindScrollListener(); this.unbindResizeListener(); } }, { key: "onOverlayExited", value: function onOverlayExited() { if (this.props.filter && this.props.resetFilterOnHide) { this.resetFilter(); } core.ZIndexUtils.clear(this.overlayRef.current); this.props.onHide && this.props.onHide(); } }, { key: "alignOverlay", value: function alignOverlay() { core.DomHandler.alignOverlay(this.overlayRef.current, this.label.parentElement, this.props.appendTo || PrimeReact__default['default'].appendTo); } }, { key: "scrollInView", value: function scrollInView() { var highlightItem = core.DomHandler.findSingle(this.overlayRef.current, 'li.p-highlight'); if (highlightItem) { highlightItem.scrollIntoView({ block: 'nearest', inline: 'start' }); } } }, { key: "onCloseClick", value: function onCloseClick(event) { this.hide(); this.inputRef.current.focus(); event.preventDefault(); event.stopPropagation(); } }, { key: "getSelectedOptionIndex", value: function getSelectedOptionIndex() { if (this.props.value != null && this.props.options) { if (this.props.optionGroupLabel) { for (var i = 0; i < this.props.options.length; i++) { var selectedOptionIndex = this.findOptionIndexInList(this.props.value, this.getOptionGroupChildren(this.props.options[i])); if (selectedOptionIndex !== -1) { return { group: i, option: selectedOptionIndex }; } } } else { return this.findOptionIndexInList(this.props.value, this.props.options); } } return -1; } }, { key: "findOptionIndexInList", value: function findOptionIndexInList(value, list) { var _this6 = this; var key = this.equalityKey(); return list.findIndex(function (item) { return value.some(function (val) { return core.ObjectUtils.equals(val, _this6.getOptionValue(item), key); }); }); } }, { key: "isSelected", value: function isSelected(option) { var _this7 = this; var selected = false; if (this.props.value) { var optionValue = this.getOptionValue(option); var isOptionValueUsed = this.isOptionValueUsed(option); var key = this.equalityKey(); selected = this.props.value.some(function (val) { return core.ObjectUtils.equals(isOptionValueUsed ? val : _this7.getOptionValue(val), optionValue, key); }); } return selected; } }, { key: "getLabelByValue", value: function getLabelByValue(val) { var option; if (this.props.options) { if (this.props.optionGroupLabel) { var _iterator = _createForOfIteratorHelper(this.props.options), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var optionGroup = _step.value; option = this.findOptionByValue(val, this.getOptionGroupChildren(optionGroup)); if (option) { break; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } else { option = this.findOptionByValue(val, this.props.options); } } return option ? this.getOptionLabel(option) : null; } }, { key: "findOptionByValue", value: function findOptionByValue(val, list) { var key = this.equalityKey(); var _iterator2 = _createForOfIteratorHelper(list), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var option = _step2.value; var optionValue = this.getOptionValue(option); if (core.ObjectUtils.equals(optionValue, val, key)) { return option; } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return null; } }, { key: "onFocus", value: function onFocus(event) { var _this8 = this; event.persist(); this.setState({ focused: true }, function () { if (_this8.props.onFocus) { _this8.props.onFocus(event); } }); } }, { key: "onBlur", value: function onBlur(event) { var _this9 = this; event.persist(); this.setState({ focused: false }, function () { if (_this9.props.onBlur) { _this9.props.onBlur(event); } }); } }, { key: "bindDocumentClickListener", value: function bindDocumentClickListener() { var _this10 = this; if (!this.documentClickListener) { this.documentClickListener = function (event) { if (_this10.state.overlayVisible && _this10.isOutsideClicked(event)) { _this10.hide(); } }; document.addEventListener('click', this.documentClickListener); } } }, { key: "bindScrollListener", value: function bindScrollListener() { var _this11 = this; if (!this.scrollHandler) { this.scrollHandler = new core.ConnectedOverlayScrollHandler(this.container, function () { if (_this11.state.overlayVisible) { _this11.hide(); } }); } this.scrollHandler.bindScrollListener(); } }, { key: "unbindScrollListener", value: function unbindScrollListener() { if (this.scrollHandler) { this.scrollHandler.unbindScrollListener(); } } }, { key: "bindResizeListener", value: function bindResizeListener() { var _this12 = this; if (!this.resizeListener) { this.resizeListener = function () { if (_this12.state.overlayVisible && !core.DomHandler.isAndroid()) { _this12.hide(); } }; window.addEventListener('resize', this.resizeListener); } } }, { key: "unbindResizeListener", value: function unbindResizeListener() { if (this.resizeListener) { window.removeEventListener('resize', this.resizeListener); this.resizeListener = null; } } }, { key: "isOutsideClicked", value: function isOutsideClicked(event) { return this.container && !(this.container.isSameNode(event.target) || this.isClearClicked(event) || this.container.contains(event.target) || this.isPanelClicked(event)); } }, { key: "isClearClicked", value: function isClearClicked(event) { return core.DomHandler.hasClass(event.target, 'p-multiselect-clear-icon'); } }, { key: "isPanelClicked", value: function isPanelClicked(event) { return this.overlayRef && this.overlayRef.current && this.overlayRef.current.contains(event.target); } }, { key: "unbindDocumentClickListener", value: function unbindDocumentClickListener() { if (this.documentClickListener) { document.removeEventListener('click', this.documentClickListener); this.documentClickListener = null; } } }, { key: "updateInputRef", value: function updateInputRef() { var ref = this.props.inputRef; if (ref) { if (typeof ref === 'function') { ref(this.inputRef.current); } else { ref.current = this.inputRef.current; } } } }, { key: "componentDidMount", value: function componentDidMount() { this.updateInputRef(); if (this.props.tooltip) { this.renderTooltip(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.tooltip !== this.props.tooltip || prevProps.tooltipOptions !== this.props.tooltipOptions) { if (this.tooltip) this.tooltip.update(_objectSpread({ content: this.props.tooltip }, this.props.tooltipOptions || {}));else this.renderTooltip(); } if (this.state.overlayVisible && this.hasFilter()) { this.alignOverlay(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unbindDocumentClickListener(); this.unbindResizeListener(); if (this.scrollHandler) { this.scrollHandler.destroy(); this.scrollHandler = null; } if (this.tooltip) { this.tooltip.destroy(); this.tooltip = null; } core.ZIndexUtils.clear(this.overlayRef.current); } }, { key: "hasFilter", value: function hasFilter() { return this.state.filter && this.state.filter.trim().length > 0; } }, { key: "isAllSelected", value: function isAllSelected() { var _this13 = this; if (this.props.onSelectAll) { return this.props.selectAll; } else { var visibleOptions = this.getVisibleOptions(); if (visibleOptions.length === 0) { return false; } visibleOptions = visibleOptions.filter(function (option) { return !_this13.isOptionDisabled(option); }); if (this.props.optionGroupLabel) { var _iterator3 = _createForOfIteratorHelper(visibleOptions), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var optionGroup = _step3.value; var visibleOptionsGroupChildren = this.getOptionGroupChildren(optionGroup).filter(function (option) { return !_this13.isOptionDisabled(option); }); var _iterator4 = _createForOfIteratorHelper(visibleOptionsGroupChildren), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var option = _step4.value; if (!this.isSelected(option)) { return false; } } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } } else { var _iterator5 = _createForOfIteratorHelper(visibleOptions), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var _option = _step5.value; if (!this.isSelected(_option)) { return false; } } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } } } return true; } }, { key: "getOptionLabel", value: function getOptionLabel(option) { return this.props.optionLabel ? core.ObjectUtils.resolveFieldData(option, this.props.optionLabel) : option && option['label'] !== undefined ? option['label'] : option; } }, { key: "getOptionValue", value: function getOptionValue(option) { if (this.props.optionValue) { var data = core.ObjectUtils.resolveFieldData(option, this.props.optionValue); return data !== null ? data : option; } return option && option['value'] !== undefined ? option['value'] : option; } }, { key: "getOptionRenderKey", value: function getOptionRenderKey(option) { return this.props.dataKey ? core.ObjectUtils.resolveFieldData(option, this.props.dataKey) : this.getOptionLabel(option); } }, { key: "getOptionGroupRenderKey", value: function getOptionGroupRenderKey(optionGroup) { return core.ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupLabel); } }, { key: "getOptionGroupLabel", value: function getOptionGroupLabel(optionGroup) { return core.ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupLabel); } }, { key: "getOptionGroupChildren", value: function getOptionGroupChildren(optionGroup) { return core.ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupChildren); } }, { key: "isOptionDisabled", value: function isOptionDisabled(option) { if (this.props.optionDisabled) { return core.ObjectUtils.isFunction(this.props.optionDisabled) ? this.props.optionDisabled(option) : core.ObjectUtils.resolveFieldData(option, this.props.optionDisabled); } return option && option['disabled'] !== undefined ? option['disabled'] : false; } }, { key: "isOptionValueUsed", value: function isOptionValueUsed(option) { return this.props.optionValue || option && option['value'] !== undefined; } }, { key: "getVisibleOptions", value: function getVisibleOptions() { if (this.hasFilter()) { var filterValue = this.state.filter.trim().toLocaleLowerCase(this.props.filterLocale); var searchFields = this.props.filterBy ? this.props.filterBy.split(',') : [this.props.optionLabel || 'label']; if (this.props.optionGroupLabel) { var filteredGroups = []; var _iterator6 = _createForOfIteratorHelper(this.props.options), _step6; try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { var optgroup = _step6.value; var filteredSubOptions = core.FilterUtils.filter(this.getOptionGroupChildren(optgroup), searchFields, filterValue, this.props.filterMatchMode, this.props.filterLocale); if (filteredSubOptions && filteredSubOptions.length) { filteredGroups.push(_objectSpread(_objectSpread({}, optgroup), { items: filteredSubOptions })); } } } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } return filteredGroups; } else { return core.FilterUtils.filter(this.props.options, searchFields, filterValue, this.props.filterMatchMode, this.props.filterLocale); } } else { return this.props.options; } } }, { key: "isEmpty", value: function isEmpty() { return !this.props.value || this.props.value.length === 0; } }, { key: "equalityKey", value: function equalityKey() { return this.props.optionValue ? null : this.props.dataKey; } }, { key: "checkValidity", value: function checkValidity() { return this.inputRef.current.checkValidity(); } }, { key: "removeChip", value: function removeChip(event, item) { var key = this.equalityKey(); var value = this.props.value.filter(function (val) { return !core.ObjectUtils.equals(val, item, key); }); this.updateModel(event, value); } }, { key: "getSelectedItemsLabel", value: function getSelectedItemsLabel() { var pattern = /{(.*?)}/; if (pattern.test(this.props.selectedItemsLabel)) { return this.props.selectedItemsLabel.replace(this.props.selectedItemsLabel.match(pattern)[0], this.props.value.length + ''); } return this.props.selectedItemsLabel; } }, { key: "getLabel", value: function getLabel() { var label; if (!this.isEmpty() && !this.props.fixedPlaceholder) { if (this.props.value.length <= this.props.maxSelectedLabels) { label = ''; for (var i = 0; i < this.props.value.length; i++) { if (i !== 0) { label += ','; } label += this.getLabelByValue(this.props.value[i]); } return label; } else { return this.getSelectedItemsLabel(); } } return label; } }, { key: "getLabelContent", value: function getLabelContent() { var _this14 = this; if (this.props.selectedItemTemplate) { if (!this.isEmpty()) { if (this.props.value.length <= this.props.maxSelectedLabels) { return this.props.value.map(function (val, index) { var item = core.ObjectUtils.getJSXElement(_this14.props.selectedItemTemplate, val); return /*#__PURE__*/React__default['default'].createElement(React__default['default'].Fragment, { key: index }, item); }); } else { return this.getSelectedItemsLabel(); } } else { return core.ObjectUtils.getJSXElement(this.props.selectedItemTemplate); } } else { if (this.props.display === 'chip' && !this.isEmpty()) { return this.props.value.map(function (val) { var label = _this14.getLabelByValue(val); return /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-token", key: label }, /*#__PURE__*/React__default['default'].createElement("span", { className: "p-multiselect-token-label" }, label), !_this14.props.disabled && /*#__PURE__*/React__default['default'].createElement("span", { className: "p-multiselect-token-icon pi pi-times-circle", onClick: function onClick(e) { return _this14.removeChip(e, val); } })); }); } return this.getLabel(); } } }, { key: "renderTooltip", value: function renderTooltip() { this.tooltip = core.tip({ target: this.container, content: this.props.tooltip, options: this.props.tooltipOptions }); } }, { key: "renderClearIcon", value: function renderClearIcon() { var _this15 = this; var empty = this.isEmpty(); if (!empty && this.props.showClear && !this.props.disabled) { return /*#__PURE__*/React__default['default'].createElement("i", { className: "p-multiselect-clear-icon pi pi-times", onClick: function onClick(e) { return _this15.updateModel(e, null); } }); } return null; } }, { key: "renderLabel", value: function renderLabel() { var _this16 = this; var empty = this.isEmpty(); var content = this.getLabelContent(); var labelClassName = core.classNames('p-multiselect-label', { 'p-placeholder': empty && this.props.placeholder, 'p-multiselect-label-empty': empty && !this.props.placeholder && !this.props.selectedItemTemplate, 'p-multiselect-items-label': !empty && this.props.value.length > this.props.maxSelectedLabels }); return /*#__PURE__*/React__default['default'].createElement("div", { ref: function ref(el) { return _this16.label = el; }, className: "p-multiselect-label-container" }, /*#__PURE__*/React__default['default'].createElement("div", { className: labelClassName }, content || this.props.placeholder || 'empty')); } }, { key: "render", value: function render() { var _this17 = this; var className = core.classNames('p-multiselect p-component p-inputwrapper', { 'p-multiselect-chip': this.props.display === 'chip', 'p-disabled': this.props.disabled, 'p-multiselect-clearable': this.props.showClear && !this.props.disabled, 'p-focus': this.state.focused, 'p-inputwrapper-filled': this.props.value && this.props.value.length > 0, 'p-inputwrapper-focus': this.state.focused || this.state.overlayVisible }, this.props.className); var iconClassName = core.classNames('p-multiselect-trigger-icon p-c', this.props.dropdownIcon); var visibleOptions = this.getVisibleOptions(); var label = this.renderLabel(); var clearIcon = this.renderClearIcon(); return /*#__PURE__*/React__default['default'].createElement("div", { id: this.props.id, className: className, onClick: this.onClick, ref: function ref(el) { return _this17.container = el; }, style: this.props.style }, /*#__PURE__*/React__default['default'].createElement("div", { className: "p-hidden-accessible" }, /*#__PURE__*/React__default['default'].createElement("input", { ref: this.inputRef, id: this.props.inputId, name: this.props.name, readOnly: true, type: "text", onFocus: this.onFocus, onBlur: this.onBlur, onKeyDown: this.onKeyDown, role: "listbox", "aria-haspopup": "listbox", "aria-labelledby": this.props.ariaLabelledBy, "aria-expanded": this.state.overlayVisible, disabled: this.props.disabled, tabIndex: this.props.tabIndex })), label, clearIcon, /*#__PURE__*/React__default['default'].createElement("div", { className: "p-multiselect-trigger" }, /*#__PURE__*/React__default['default'].createElement("span", { className: iconClassName })), /*#__PURE__*/React__default['default'].createElement(MultiSelectPanel, _extends({ ref: this.overlayRef, visibleOptions: visibleOptions }, this.props, { onClick: this.onPanelClick, onOverlayHide: this.hide, filterValue: this.state.filter, hasFilter: this.hasFilter, onFilterInputChange: this.onFilterInputChange, onCloseClick: this.onCloseClick, onSelectAll: this.onSelectAll, getOptionLabel: this.getOptionLabel, getOptionRenderKey: this.getOptionRenderKey, isOptionDisabled: this.isOptionDisabled, getOptionGroupChildren: this.getOptionGroupChildren, getOptionGroupLabel: this.getOptionGroupLabel, getOptionGroupRenderKey: this.getOptionGroupRenderKey, isSelected: this.isSelected, getSelectedOptionIndex: this.getSelectedOptionIndex, isAllSelected: this.isAllSelected, onOptionSelect: this.onOptionSelect, allowOptionSelect: this.allowOptionSelect, onOptionKeyDown: this.onOptionKeyDown, in: this.state.overlayVisible, onEnter: this.onOverlayEnter, onEntered: this.onOverlayEntered, onExit: this.onOverlayExit, onExited: this.onOverlayExited }))); } }]); return MultiSelect; }(React.Component); _defineProperty(MultiSelect, "defaultProps", { id: null, inputRef: null, name: null, value: null, options: null, optionLabel: null, optionValue: null, optionDisabled: null, optionGroupLabel: null, optionGroupChildren: null, optionGroupTemplate: null, display: 'comma', style: null, className: null, panelClassName: null, panelStyle: null, virtualScrollerOptions: null, scrollHeight: '200px', placeholder: null, fixedPlaceholder: false, disabled: false, showClear: false, filter: false, filterBy: null, filterMatchMode: 'contains', filterPlaceholder: null, filterLocale: undefined, emptyFilterMessage: 'No results found', resetFilterOnHide: false, tabIndex: 0, dataKey: null, inputId: null, appendTo: null, tooltip: null, tooltipOptions: null, maxSelectedLabels: 3, selectionLimit: null, selectedItemsLabel: '{0} items selected', ariaLabelledBy: null, itemTemplate: null, selectedItemTemplate: null, panelHeaderTemplate: null, panelFooterTemplate: null, transitionOptions: null, dropdownIcon: 'pi pi-chevron-down', showSelectAll: true, selectAll: false, onChange: null, onFocus: null, onBlur: null, onShow: null, onHide: null, onFilter: null, onSelectAll: null }); exports.MultiSelect = MultiSelect; Object.defineProperty(exports, '__esModule', { value: true }); return exports; }({}, React, primereact.core, primereact.inputtext, primereact.virtualscroller, primereact.api));
cdnjs/cdnjs
ajax/libs/primereact/6.5.1/multiselect/multiselect.js
JavaScript
mit
72,104
/* Highstock JS v9.3.2 (2021-11-29) Indicator series type for Highcharts Stock (c) 2010-2021 Daniel Studencki License: www.highcharts.com/license */ 'use strict';(function(b){"object"===typeof module&&module.exports?(b["default"]=b,module.exports=b):"function"===typeof define&&define.amd?define("highcharts/indicators/keltner-channels",["highcharts","highcharts/modules/stock"],function(k){b(k);b.Highcharts=k;return b}):b("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(b){function k(b,f,e,k){b.hasOwnProperty(f)||(b[f]=k.apply(null,e))}b=b?b._modules:{};k(b,"Stock/Indicators/MultipleLinesComposition.js",[b["Core/Series/SeriesRegistry.js"], b["Core/Utilities.js"]],function(b,f){var e=b.seriesTypes.sma,k=f.defined,n=f.error,r=f.merge,h;(function(f){function m(a){var c,g=[];a=a||this.points;if(this.fillGraph&&this.nextPoints){if((c=e.prototype.getGraphPath.call(this,this.nextPoints))&&c.length){c[0][0]="L";g=e.prototype.getGraphPath.call(this,a);c=c.slice(0,g.length);for(var b=c.length-1;0<=b;b--)g.push(c[b])}}else g=e.prototype.getGraphPath.apply(this,arguments);return g}function q(){var a=this,c=a.linesApiNames,g=a.areaLinesNames,d= a.points,f=a.options,q=a.graph,w={options:{gapSize:f.gapSize}},m=[],h=a.getTranslatedLinesNames(a.pointValKey),u=d.length,l;h.forEach(function(a,c){for(m[c]=[];u--;)l=d[u],m[c].push({x:l.x,plotX:l.plotX,plotY:l[a],isNull:!k(l[a])});u=d.length});if(this.userOptions.fillColor&&g.length){var v=h.indexOf(x(g[0]));v=m[v];g=1===g.length?d:m[h.indexOf(x(g[1]))];h=a.color;a.points=g;a.nextPoints=v;a.color=this.userOptions.fillColor;a.options=r(d,w);a.graph=a.area;a.fillGraph=!0;b.seriesTypes.sma.prototype.drawGraph.call(a); a.area=a.graph;delete a.nextPoints;delete a.fillGraph;a.color=h}c.forEach(function(c,b){m[b]?(a.points=m[b],f[c]?a.options=r(f[c].styles,w):n('Error: "There is no '+c+' in DOCS options declared. Check if linesApiNames are consistent with your DOCS line names." at mixin/multiple-line.js:34'),a.graph=a["graph"+c],e.prototype.drawGraph.call(a),a["graph"+c]=a.graph):n('Error: "'+c+" doesn't have equivalent in pointArrayMap. To many elements in linesApiNames relative to pointArrayMap.\"")});a.points=d; a.options=f;a.graph=q;e.prototype.drawGraph.call(a)}function d(a){var c=[];(this.pointArrayMap||[]).forEach(function(b){b!==a&&c.push(x(b))});return c}function x(a){return"plot"+a.charAt(0).toUpperCase()+a.slice(1)}function w(a){var c=[];(this.pointArrayMap||[]).forEach(function(b){c.push(a[b])});return c}function u(){var a=this,c=a.pointArrayMap,b=[],d;b=a.getTranslatedLinesNames();e.prototype.translate.apply(a,arguments);a.points.forEach(function(f){c.forEach(function(c,g){d=f[c];a.dataModify&& (d=a.dataModify.modifyValue(d));null!==d&&(f[b[g]]=a.yAxis.toPixels(d,!0))})})}var h=[],l=["bottomLine"],v=["top","bottom"],z=["top"];f.compose=function(a){if(-1===h.indexOf(a)){h.push(a);var c=a.prototype;c.linesApiNames=c.linesApiNames||l.slice();c.pointArrayMap=c.pointArrayMap||v.slice();c.pointValKey=c.pointValKey||"top";c.areaLinesNames=c.areaLinesNames||z.slice();c.drawGraph=q;c.getGraphPath=m;c.toYData=w;c.translate=u;c.getTranslatedLinesNames=d}return a}})(h||(h={}));return h});k(b,"Stock/Indicators/KeltnerChannels/KeltnerChannelsIndicator.js", [b["Stock/Indicators/MultipleLinesComposition.js"],b["Core/Series/SeriesRegistry.js"],b["Core/Utilities.js"]],function(b,f,e){var k=this&&this.__extends||function(){var b=function(f,d){b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,d){b.__proto__=d}||function(b,d){for(var f in d)d.hasOwnProperty(f)&&(b[f]=d[f])};return b(f,d)};return function(f,d){function e(){this.constructor=f}b(f,d);f.prototype=null===d?Object.create(d):(e.prototype=d.prototype,new e)}}(),n=f.seriesTypes.sma, r=e.correctFloat,h=e.extend,y=e.merge;e=function(b){function e(){var d=null!==b&&b.apply(this,arguments)||this;d.data=void 0;d.options=void 0;d.points=void 0;return d}k(e,b);e.prototype.init=function(){f.seriesTypes.sma.prototype.init.apply(this,arguments);this.options=y({topLine:{styles:{lineColor:this.color}},bottomLine:{styles:{lineColor:this.color}}},this.options)};e.prototype.getValues=function(b,e){var d=e.period,h=e.periodATR,k=e.multiplierATR,l=b.yData;l=l?l.length:0;var m=[];e=f.seriesTypes.ema.prototype.getValues(b, {period:d,index:e.index});var n=f.seriesTypes.atr.prototype.getValues(b,{period:h}),a=[],c=[],g;if(!(l<d)){for(g=d;g<=l;g++){var p=e.values[g-d];var t=n.values[g-h];var q=p[0];b=r(p[1]+k*t[1]);t=r(p[1]-k*t[1]);p=p[1];m.push([q,b,p,t]);a.push(q);c.push([b,p,t])}return{values:m,xData:a,yData:c}}};e.defaultOptions=y(n.defaultOptions,{params:{index:0,period:20,periodATR:10,multiplierATR:2},bottomLine:{styles:{lineWidth:1,lineColor:void 0}},topLine:{styles:{lineWidth:1,lineColor:void 0}},tooltip:{pointFormat:'<span style="color:{point.color}">\u25cf</span><b> {series.name}</b><br/>Upper Channel: {point.top}<br/>EMA({series.options.params.period}): {point.middle}<br/>Lower Channel: {point.bottom}<br/>'}, marker:{enabled:!1},dataGrouping:{approximation:"averages"},lineWidth:1});return e}(n);h(e.prototype,{nameBase:"Keltner Channels",areaLinesNames:["top","bottom"],nameComponents:["period","periodATR","multiplierATR"],linesApiNames:["topLine","bottomLine"],pointArrayMap:["top","middle","bottom"],pointValKey:"middle"});b.compose(e);f.registerSeriesType("keltnerchannels",e);"";return e});k(b,"masters/indicators/keltner-channels.src.js",[],function(){})}); //# sourceMappingURL=keltner-channels.js.map
cdnjs/cdnjs
ajax/libs/highcharts/9.3.2/indicators/keltner-channels.js
JavaScript
mit
5,499
/* * * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import H from '../parts/Globals.js'; import U from '../parts/Utilities.js'; var isArray = U.isArray; import reduceArrayMixin from '../mixins/reduce-array.js'; import multipleLinesMixin from '../mixins/multipe-lines.js'; var merge = H.merge, SMA = H.seriesTypes.sma, getArrayExtremes = reduceArrayMixin.getArrayExtremes; /** * The Stochastic series type. * * @private * @class * @name Highcharts.seriesTypes.stochastic * * @augments Highcharts.Series */ H.seriesType('stochastic', 'sma', /** * Stochastic oscillator. This series requires the `linkedTo` option to be * set and should be loaded after the `stock/indicators/indicators.js` file. * * @sample stock/indicators/stochastic * Stochastic oscillator * * @extends plotOptions.sma * @since 6.0.0 * @product highstock * @excluding allAreas, colorAxis, joinBy, keys, navigatorOptions, * pointInterval, pointIntervalUnit, pointPlacement, * pointRange, pointStart, showInNavigator, stacking * @requires stock/indicators/indicators * @requires stock/indicators/stochastic * @optionparent plotOptions.stochastic */ { /** * @excluding index, period */ params: { /** * Periods for Stochastic oscillator: [%K, %D]. * * @type {Array<number,number>} * @default [14, 3] */ periods: [14, 3] }, marker: { enabled: false }, tooltip: { pointFormat: '<span style="color:{point.color}">\u25CF</span><b> {series.name}</b><br/>%K: {point.y}<br/>%D: {point.smoothed}<br/>' }, /** * Smoothed line options. */ smoothedLine: { /** * Styles for a smoothed line. */ styles: { /** * Pixel width of the line. */ lineWidth: 1, /** * Color of the line. If not set, it's inherited from * [plotOptions.stochastic.color * ](#plotOptions.stochastic.color). * * @type {Highcharts.ColorString} */ lineColor: undefined } }, dataGrouping: { approximation: 'averages' } }, /** * @lends Highcharts.Series# */ H.merge(multipleLinesMixin, { nameComponents: ['periods'], nameBase: 'Stochastic', pointArrayMap: ['y', 'smoothed'], parallelArrays: ['x', 'y', 'smoothed'], pointValKey: 'y', linesApiNames: ['smoothedLine'], init: function () { SMA.prototype.init.apply(this, arguments); // Set default color for lines: this.options = merge({ smoothedLine: { styles: { lineColor: this.color } } }, this.options); }, getValues: function (series, params) { var periodK = params.periods[0], periodD = params.periods[1], xVal = series.xData, yVal = series.yData, yValLen = yVal ? yVal.length : 0, // 0- date, 1-%K, 2-%D SO = [], xData = [], yData = [], slicedY, close = 3, low = 2, high = 1, CL, HL, LL, K, D = null, points, extremes, i; // Stochastic requires close value if (yValLen < periodK || !isArray(yVal[0]) || yVal[0].length !== 4) { return false; } // For a N-period, we start from N-1 point, to calculate Nth point // That is why we later need to comprehend slice() elements list // with (+1) for (i = periodK - 1; i < yValLen; i++) { slicedY = yVal.slice(i - periodK + 1, i + 1); // Calculate %K extremes = getArrayExtremes(slicedY, low, high); LL = extremes[0]; // Lowest low in %K periods CL = yVal[i][close] - LL; HL = extremes[1] - LL; K = CL / HL * 100; xData.push(xVal[i]); yData.push([K, null]); // Calculate smoothed %D, which is SMA of %K if (i >= (periodK - 1) + (periodD - 1)) { points = SMA.prototype.getValues.call(this, { xData: xData.slice(-periodD), yData: yData.slice(-periodD) }, { period: periodD }); D = points.yData[0]; } SO.push([xVal[i], K, D]); yData[yData.length - 1][1] = D; } return { values: SO, xData: xData, yData: yData }; } })); /** * A Stochastic indicator. If the [type](#series.stochastic.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.stochastic * @since 6.0.0 * @product highstock * @excluding allAreas, colorAxis, dataParser, dataURL, joinBy, keys, * navigatorOptions, pointInterval, pointIntervalUnit, * pointPlacement, pointRange, pointStart, showInNavigator, stacking * @requires stock/indicators/indicators * @requires stock/indicators/stochastic * @apioption series.stochastic */ ''; // to include the above in the js output
cdnjs/cdnjs
ajax/libs/highcharts/7.2.2/es-modules/indicators/stochastic.src.js
JavaScript
mit
5,303
/******************************************************************************* * Copyright (c) 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ define(["intern!tdd","intern/chai!assert","dojo/Deferred","js/toolbox/toolbox"], function(tdd,assert,Deferred,toolbox) { var server, testBookmark, testFeatureTool; with(assert) { /** * Defines the 'toolbox' module test suite. */ tdd.suite("Toolbox Tests", function() { tdd.before(function() { testBookmark = { id: "myTool", type:"bookmark", name:"myTool", url:"ibm.com", icon:"default.png" }; testToolEntry = { id: "myFeature-1.0", type:"featureTool", }; }); tdd.beforeEach(function() { // Mock the admin center server since it is not available in a unittest server = sinon.fakeServer.create(); }); tdd.afterEach(function() { server.restore(); }); tdd.test("ToolEntry - create from ToolEntry", function() { var tool = new Toolbox.ToolEntry(testToolEntry); console.log("DEBUG", tool); assert.equal(tool.id, testToolEntry.id, "ToolEntry was not constructed with correct value for 'id'"); assert.equal(tool.type, testToolEntry.type, "ToolEntry was not constructed with correct value for 'type'"); assert.isUndefined(tool.name, "ToolEntry should not have a name"); }); tdd.test("ToolEntry - create from Bookmark", function() { var tool = new Toolbox.ToolEntry(testBookmark); console.log("DEBUG", tool); assert.equal(tool.id, testBookmark.id, "ToolEntry was not constructed with correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "ToolEntry was not constructed with correct value for 'type'"); assert.isUndefined(tool.name, "ToolEntry should not have a name even though it was created from an Object that had a name"); }); tdd.test("Bookmark - create", function() { var tool = new Toolbox.Bookmark(testBookmark); assert.isUndefined(tool.id, "Tool was constructed with an 'id'"); assert.isUndefined(tool.type, "Tool was constructed with an 'type'"); assert.equal(tool.name, testBookmark.name, "Tool was not constructed with correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Tool was not constructed with correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Tool was not constructed with correct value for 'icon'"); }); tdd.test("Toolbox - construct", function() { var tb = new Toolbox(); assert.isTrue(tb instanceof Toolbox, "Unable to construct Toolbox"); }); tdd.test("Toolbox - get instance", function() { var tb = toolbox.getToolbox(); assert.isTrue(tb instanceof Toolbox, "Unable to get instance of Toolbox"); }); tdd.test("Toolbox - get instance is same instance", function() { var tbNew = new Toolbox(); var tbInst = toolbox.getToolbox(); assert.isFalse(tbInst === tbNew, "The 'singleton' instance of Toolbox should not match a 'new' instance of Toolbox"); assert.isTrue(tbInst === toolbox.getToolbox(), "The 'singleton' instance of Toolbox should match the previous return for the singleton"); }); tdd.test("toolbox.getToolEntries - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().getToolEntries() instanceof Deferred, "Toolbox.getToolEntries should return a Deferred"); }); tdd.test("toolbox.getToolEntries - resolves with Array (no Tools)", function() { var dfd = this.async(1000); toolbox.getToolbox().getToolEntries().then(dfd.callback(function(tools) { assert.isTrue(tools instanceof Array, "Toolbox.getToolEntries should resolve with an Array"); }), function(err) { dfd.reject(err); }); server.respondWith("GET", "/ibm/api/adminCenter/v1/toolbox/toolEntries", [200, { "Content-Type": "application/json" },'{"toolEntries":[]}']); server.respond(); return dfd; }); tdd.test("toolbox.getToolEntries - resolves with Array of Tool objects", function() { var dfd = this.async(1000); toolbox.getToolbox().getToolEntries().then(dfd.callback(function(tools) { assert.isTrue(tools instanceof Array, "Toolbox.getToolEntries should resolve with an Array"); assert.equal(tools.length, 1, "Expected exactly 1 tool back from the mock response"); var tool = tools[0]; assert.equal(tool.id, testToolEntry.id, "Tool was not constructed with correct value for 'id'"); assert.equal(tool.type, testToolEntry.type, "Tool was not constructed with correct value for 'type'"); }), function(err) { dfd.reject(err); }); server.respondWith("GET", "/ibm/api/adminCenter/v1/toolbox/toolEntries", [200, { "Content-Type": "application/json" },'['+JSON.stringify(testToolEntry)+']']); server.respond(); return dfd; }); tdd.test("toolbox.getTool - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().getTool('myTool') instanceof Deferred, "Toolbox.getTool should return a Deferred"); }); tdd.test("toolbox.getTool - returns a Tool", function() { var dfd = this.async(1000); toolbox.getToolbox().getTool('myTool').then(dfd.callback(function(tool) { assert.equal(tool.id, testBookmark.id, "Returned tool did not have correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "Returned tool did not have correct value for 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Returned tool did not have correct value for 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("GET", "/ibm/api/adminCenter/v1/toolbox/toolEntries/myTool", [200, { "Content-Type": "application/json" }, JSON.stringify(testBookmark)]); server.respond(); return dfd; }); tdd.test("Toolbox.getTool - filtered Tool", function() { var dfd = this.async(1000); toolbox.getToolbox().getTool('myTool', 'name,url').then(dfd.callback(function(tool) { assert.equal(tool.id, null, "Returned tool was filtered and should not have an 'id'"); assert.equal(tool.type, null, "Returned tool was filtered and should not have a 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, null, "Returned tool was filtered and should not have an 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("GET", "/ibm/api/adminCenter/v1/toolbox/toolEntries/myTool?fields=name,url", [200, { "Content-Type": "application/json" }, '{"name":"'+testBookmark.name+'","url":"'+testBookmark.url+'"}']); server.respond(); return dfd; }); tdd.test("Toolbox.getTool - no provided Tool ID", function() { try { toolbox.getToolbox().getTool(); assert.isTrue(false, "Toolbox.getTool should throw an error when no tool ID is provided"); } catch(err) { // Pass } }); tdd.test("Toolbox.addToolEntry - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().addToolEntry(testBookmark) instanceof Deferred, "Toolbox.addToolEntry should return a Deferred"); }); tdd.test("Toolbox.addToolEntry - returns the created ToolEntry", function() { var dfd = this.async(1000); toolbox.getToolbox().addToolEntry(testBookmark).then(dfd.callback(function(tool) { assert.equal(tool.id, testBookmark.id, "Returned tool did not have correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "Returned tool did not have correct value for 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Returned tool did not have correct value for 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("POST", "/ibm/api/adminCenter/v1/toolbox/toolEntries", [201, { "Content-Type": "application/json" }, JSON.stringify(testBookmark)]); server.respond(); return dfd; }); tdd.test("Toolbox.addToolEntry - no provided ToolEntry props", function() { try { toolbox.getToolbox().addToolEntry(); assert.isTrue(false, "Toolbox.addToolEntry should throw an error when no tool ID is provided"); } catch(err) { // Pass } }); tdd.test("Toolbox.addBookmark - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().addBookmark(testBookmark) instanceof Deferred, "Toolbox.addBookmark should return a Deferred"); }); tdd.test("Toolbox.addBookmark - returns the created Bookmark", function() { var dfd = this.async(1000); toolbox.getToolbox().addBookmark(testBookmark).then(dfd.callback(function(tool) { assert.equal(tool.id, testBookmark.id, "Returned tool did not have correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "Returned tool did not have correct value for 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Returned tool did not have correct value for 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("POST", "/ibm/api/adminCenter/v1/toolbox/bookmarks", [201, { "Content-Type": "application/json" }, JSON.stringify(testBookmark)]); server.respond(); return dfd; }); tdd.test("Toolbox.addBookmark - no provided Bookmark props", function() { try { toolbox.getToolbox().addBookmark(); assert.isTrue(false, "Toolbox.addBookmark should throw an error when no tool ID is provided"); } catch(err) { // Pass } }); tdd.test("Toolbox.deleteTool - returns Deferred", function() { assert.isTrue(toolbox.getToolbox().deleteTool('myTool') instanceof Deferred, "Toolbox.deleteTool should return a Deferred"); }); tdd.test("Toolbox.deleteTool - returns the deleted entry's JSON", function() { var dfd = this.async(1000); toolbox.getToolbox().deleteTool(testBookmark.id).then(dfd.callback(function(tool) { assert.equal(tool.id, testBookmark.id, "Returned tool did not have correct value for 'id'"); assert.equal(tool.type, testBookmark.type, "Returned tool did not have correct value for 'type'"); assert.equal(tool.name, testBookmark.name, "Returned tool did not have correct value for 'name'"); assert.equal(tool.url, testBookmark.url, "Returned tool did not have correct value for 'url'"); assert.equal(tool.icon, testBookmark.icon, "Returned tool did not have correct value for 'icon'"); }), function(err) { dfd.reject(err); }); server.respondWith("DELETE", "/ibm/api/adminCenter/v1/toolbox/toolEntries/myTool", [200, { "Content-Type": "application/json" }, JSON.stringify(testBookmark)]); server.respond(); return dfd; }); tdd.test("Toolbox.deleteTool - no provided Tool ID", function() { try { toolbox.getToolbox().deleteTool(); assert.isTrue(false, "Toolbox.deleteTool should throw an error when no tool ID is provided"); } catch(err) { // Pass } }); }); } });
OpenLiberty/open-liberty
dev/com.ibm.ws.ui/resources/WEB-CONTENT/unittest/toolbox/toolboxTests.js
JavaScript
epl-1.0
14,570
// We do this in this rather complicated manner since Joomla groups // external javascript includes and script declarations seperately // and this call has to be made right after loading jQuery. jQuery.noConflict();
lau-ibarra/ETISIGChacoJoomla
tmp/install_515c4270221dc/plg_system_jquery/site/jquery/no_conflict.js
JavaScript
gpl-2.0
218
akeeba.jQuery(document).ready(function($){ akeeba.jQuery('#addTickets').click(function(){ if(document.adminForm.boxchecked.value == 0) { alert(akeeba.jQuery('#chooseone').val()); return false; } if(document.adminForm.boxchecked.value > 1) { alert(akeeba.jQuery('#chooseonlyone').val()); return false; } Joomla.submitbutton('addtickets'); }); });
SirPiter/folk
www/media/com_ats/js/adm_buckets_choose.js
JavaScript
gpl-2.0
382
'use strict'; angular.module('syliusApp', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ui.router', 'ui.bootstrap' ]) .config(function ($stateProvider, $urlRouterProvider, $locationProvider) { $urlRouterProvider .otherwise('/'); $locationProvider.html5Mode(true); });
nike-17/sylius.ru
client/app/app.js
JavaScript
gpl-2.0
295
var lvl1 = (function () { var xPartition = 320; var preload = function () { // tilemap this.xPartition = xPartition; game.load.tilemap('map', 'assets/map.json', null, Phaser.Tilemap.TILED_JSON); game.load.image('floor', 'assets/floor.png'); game.load.image('tileset', 'assets/tileset.png'); game.load.image('wall', 'assets/wall.png'); // furniture game.load.spritesheet('door', 'assets/door.png', 48, 80); game.load.spritesheet('phone', 'assets/phone.png', 32, 48); game.load.spritesheet('atm', 'assets/atm.png', 48, 80); // ppj game.load.spritesheet('cracker', 'assets/cracker.png', 48, 96); game.load.spritesheet('sysadmin', 'assets/sysadmin.png', 48, 96); game.load.spritesheet('secre0', 'assets/ingenuous.png', 48, 96); game.load.spritesheet('secre1', 'assets/ingenuous2.png', 48, 96); game.load.image('pear', 'assets/pear.png'); // removing blury images game.stage.smoothed = false; }; var create = function () { // Background color. game.stage.backgroundColor = '#eee'; // Physics. game.physics.startSystem(Phaser.Physics.ARCADE); // Sprites creation this.tilemap = map(this, xPartition); this.cracker = cracker(this); this.cursor = cursor(); // this is a horrible patch: do not remove it, unless // you wanna fix cracker's overlapDoor conflict this.cracker.cursor = this.cursor; // creating doors this.doors = this.tilemap.parseDoors(); // creating phones this.phones = parsePhones(this, this.tilemap, this.tilemap.phone); // creating sysadmins this.sysadmins = parseSysadmins(this, this.tilemap, this.tilemap.sysadmin, this.phones); // creating atms this.atms = parseAtms(this, this.tilemap, this.tilemap.atm); // scoreboard this.scoreboard = scoreboard(this.phones); // creating secres this.secres = parseSecres(this, this.tilemap, this.tilemap.secre, this.phones, this.scoreboard); this.spawner = new spawner(this); // bringing to top things (below this line) this.cracker.bringToTop(); this.sysadmins.forEach( function (sysadmin) { sysadmin.bringToTop(); }); this.secres.forEach( function (secre) { secre.bringToTop(); }); }; var update = function () { this.spawner.update(); // sysadmin fixes the atm's game.physics.arcade.overlap(this.atms, this.sysadmins, function (atm, sysadmin) { atm.animations.play('ok'); }); this.secres.lookPhone(); }; // check the cracker.js file! the overlapDoor function ;) return { create : create, preload : preload, update : update }; })(); var game = new Phaser.Game(800, 640, Phaser.AUTO, 'game'); game.state.add('lvl1', lvl1); game.state.start('lvl1'); // Global variables window.firstAtmCracked = false; window.firstPhishing = false;
mehhhh/TheLammerGame
game.js
JavaScript
gpl-2.0
3,254
/** * @fileoverview * Tool '서식' Source, * */ TrexConfig.addTool( "tabletemplate", { sync: _FALSE, status: _TRUE, rows: 5, cols: 9, options: [ { label: 'image', data: 1 , klass: 'tx-tabletemplate-1' }, { label: 'image', data: 2 , klass: 'tx-tabletemplate-2' }, { label: 'image', data: 3 , klass: 'tx-tabletemplate-3' }, { label: 'image', data: 4 , klass: 'tx-tabletemplate-4' }, { label: 'image', data: 5 , klass: 'tx-tabletemplate-5' }, { label: 'image', data: 6 , klass: 'tx-tabletemplate-6' }, { label: 'image', data: 7 , klass: 'tx-tabletemplate-7' }, { label: 'image', data: 8 , klass: 'tx-tabletemplate-8' }, { label: 'image', data: 9 , klass: 'tx-tabletemplate-9' }, { label: 'image', data: 10 , klass: 'tx-tabletemplate-10' }, { label: 'image', data: 11 , klass: 'tx-tabletemplate-11' }, { label: 'image', data: 12 , klass: 'tx-tabletemplate-12' }, { label: 'image', data: 13 , klass: 'tx-tabletemplate-13' }, { label: 'image', data: 14 , klass: 'tx-tabletemplate-14' }, { label: 'image', data: 15 , klass: 'tx-tabletemplate-15' }, { label: 'image', data: 16 , klass: 'tx-tabletemplate-16' }, { label: 'image', data: 17 , klass: 'tx-tabletemplate-17' }, { label: 'image', data: 18 , klass: 'tx-tabletemplate-18' }, { label: 'image', data: 19 , klass: 'tx-tabletemplate-19' }, { label: 'image', data: 20 , klass: 'tx-tabletemplate-20' }, { label: 'image', data: 21 , klass: 'tx-tabletemplate-21' }, { label: 'image', data: 22 , klass: 'tx-tabletemplate-22' }, { label: 'image', data: 23 , klass: 'tx-tabletemplate-23' }, { label: 'image', data: 24 , klass: 'tx-tabletemplate-24' }, { label: 'image', data: 25 , klass: 'tx-tabletemplate-25' }, { label: 'image', data: 26 , klass: 'tx-tabletemplate-26' }, { label: 'image', data: 27 , klass: 'tx-tabletemplate-27' }, { label: 'image', data: 28 , klass: 'tx-tabletemplate-28' }, { label: 'image', data: 29 , klass: 'tx-tabletemplate-29' }, { label: 'image', data: 30 , klass: 'tx-tabletemplate-30' }, { label: 'image', data: 31 , klass: 'tx-tabletemplate-31' }, { label: 'image', data: 32 , klass: 'tx-tabletemplate-32' }, { label: 'image', data: 33 , klass: 'tx-tabletemplate-33' }, { label: 'image', data: 34 , klass: 'tx-tabletemplate-34' }, { label: 'image', data: 35 , klass: 'tx-tabletemplate-35' }, { label: 'image', data: 36 , klass: 'tx-tabletemplate-36' }, { label: 'image', data: 37 , klass: 'tx-tabletemplate-37' }, { label: 'image', data: 38 , klass: 'tx-tabletemplate-38' }, { label: 'image', data: 39 , klass: 'tx-tabletemplate-39' }, { label: 'image', data: 40 , klass: 'tx-tabletemplate-40' }, { label: 'image', data: 41 , klass: 'tx-tabletemplate-41' }, { label: 'image', data: 42 , klass: 'tx-tabletemplate-42' }, { label: 'image', data: 43 , klass: 'tx-tabletemplate-43' }, { label: 'image', data: 44 , klass: 'tx-tabletemplate-44' }, { label: 'image', data: 45 , klass: 'tx-tabletemplate-45' } ] } ); Trex.Tool.Tabletemplate = Trex.Class.create({ $const: { __Identity: 'tabletemplate' }, $extend: Trex.Tool, oninitialized: function(config) { var _tool = this; var _canvas = this.canvas; var _map = {}; config.options.each(function(option) { _map[option.data] = { type: option.type }; }); var _toolHandler = function(data) { if(!_map[data]) { return; } var _table = _NULL; _canvas.execute(function(processor) { if (processor.table) { _table = processor.findNode('table'); processor.table.setTemplateStyle(_table, data); } }); }; /* button & menu weave */ this.weave.bind(this)( /* button */ new Trex.Button(this.buttonCfg), /* menu */ new Trex.Menu.List(this.menuCfg), /* handler */ _toolHandler ); } });
zaljayo/TestProject
lib_editor/js/trex/tool/tabletemplate.js
JavaScript
gpl-2.0
3,877
/* * Media Plugin for FCKeditor 2.5 SVN * Copyright (C) 2007 Riceball LEE ([email protected]) * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Scripts related to the Media dialog window (see fck_media.html). */ var cWindowMediaPlayer = 0 , cRealMediaPlayer = 1 , cQuickTimePlayer = 2 , cFlashPlayer = 3 , cShockwavePlayer = 4 , cDefaultMediaPlayer = cWindowMediaPlayer ; var cFckMediaElementName = 'fckmedia'; //embed | object | fckmedia var cMediaTypeAttrName = 'mediatype'; //lowerCase only!! var cWMp6Compatible = false; //const cDefaultMediaPlayer = 0; //!!!DO NOT Use the constant! the IE do not support const! var cMediaPlayerTypes = ['application/x-mplayer2', 'audio/x-pn-realaudio-plugin', 'video/quicktime', 'application/x-shockwave-flash', 'application/x-director'] , cMediaPlayerClassId = [cWMp6Compatible? 'clsid:05589FA1-C356-11CE-BF01-00AA0055595A' : 'clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6', 'clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA' , 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' , 'clsid:166B1BCA-3F9C-11CF-8075-444553540000' ] , cMediaPlayerCodebase = ['http://microsoft.com/windows/mediaplayer/en/download/', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab' , 'http://www.apple.com/quicktime/download/', 'http://www.macromedia.com/go/getflashplayer', 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab' ] ; var cFCKMediaObjectAttrs = {width:1, height:1, align:1, id:1, name:1, 'class':1, className:1, style:1, title:1}; //the 'class' is keyword in IE!! //there are not object params in it. cFCKMediaSkipParams = {pluginspage:1, type:1}; cFCKMediaParamPrefix = 'MediaParam_'; var oWindowMediaPlayer = {id: cWindowMediaPlayer, type: cMediaPlayerTypes[cWindowMediaPlayer], ClsId: cMediaPlayerClassId[cWindowMediaPlayer], Codebase: cMediaPlayerCodebase[cWindowMediaPlayer] , Params: {autostart:true, enabled:true, enablecontextmenu:true, fullscreen:false, invokeurls:true, mute:false , stretchtofit:false, windowlessvideo:false, balance:'', baseurl:'', captioningid:'', currentmarker:'' , currentposition:'', defaultframe:'', playcount:'', rate:'', uimode:'', volume:'' } }; oRealMediaPlayer = {id: cRealMediaPlayer, type: cMediaPlayerTypes[cRealMediaPlayer], ClsId: cMediaPlayerClassId[cRealMediaPlayer], Codebase: cMediaPlayerCodebase[cRealMediaPlayer] , Params: {autostart:true, loop:false, autogotourl:true, center:false, imagestatus:true, maintainaspect:false , nojava:false, prefetch:true, shuffle:false, console:'', controls:'', numloop:'', scriptcallbacks:'' } }; oQuickTimePlayer = {id: cQuickTimePlayer, type: cMediaPlayerTypes[cQuickTimePlayer], ClsId: cMediaPlayerClassId[cQuickTimePlayer], Codebase: cMediaPlayerCodebase[cQuickTimePlayer] , Params: {autoplay:true, loop:false, cache:false, controller:true, correction:['none', 'full'], enablejavascript:false , kioskmode:false, autohref:false, playeveryframe:false, targetcache:false, scale:'', starttime:'', endtime:'', target:'', qtsrcchokespeed:'' , volume:'', qtsrc:'' } }; oFlashPlayer = {id: cFlashPlayer, type: cMediaPlayerTypes[cFlashPlayer], ClsId: cMediaPlayerClassId[cFlashPlayer], Codebase: cMediaPlayerCodebase[cFlashPlayer] , Params: {play:true, loop:false, menu:true, swliveconnect:true, quality:'', scale:['showall','noborder','exactfit'], salign:'', wmode:'', base:'' , flashvars:'' } }; oShockwavePlayer = {id: cShockwavePlayer, type: cMediaPlayerTypes[cShockwavePlayer], ClsId: cMediaPlayerClassId[cShockwavePlayer], Codebase: cMediaPlayerCodebase[cShockwavePlayer] , Params: {autostart:true, sound:true, progress:false, swliveconnect:false, swvolume:'', swstretchstyle:'', swstretchhalign:'', swstretchvalign:'' } }; var oFCKMediaPlayers = [oWindowMediaPlayer, oRealMediaPlayer, oQuickTimePlayer, oFlashPlayer, oShockwavePlayer]; String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); } String.prototype.ltrim = function() { return this.replace(/^\s+/,""); } String.prototype.rtrim = function() { return this.replace(/\s+$/,""); } function debugListMember(o) { var s = '\n'; if (typeof(o) == 'object') s +=o.toSource(); else s+= o; return s; } function GetMediaPlayerObject(aMediaType) { for (i = 0; i < cMediaPlayerTypes.length; i++ ) if (aMediaType.toLowerCase() == cMediaPlayerTypes[i]) return oFCKMediaPlayers[i]; return oFCKMediaPlayers[cDefaultMediaPlayer]; } function GetMediaPlayerTypeId(aMediaType) { for (i = 0; i < cMediaPlayerTypes.length; i++ ) if (aMediaType.toLowerCase() == cMediaPlayerTypes[i]) return i; return cDefaultMediaPlayer; } function isInt(aStr) { var i = parseInt(aStr); if (isNaN(i)) return false; i = i.toString(); return (i == aStr); } function DequotedStr(aStr) { aStr = aStr.trim(); //aStr.replace(/^(['"])(.*?)(\1)$/g, '$2'); if (aStr.length > 2) { if (aStr.charAt(0) == '"' && aStr.charAt(aStr.length-1) == '"' ) aStr = aStr.substring(1,aStr.length-1); else if (aStrcharAt(0) == '\'' && aStr.charAt(aStr.length-1) == '\'' ) aStr = aStr.substring(1,aStr.length-1); } //alert(aStr+ ': dd:'+aStr.charAt(0)+ aStr.charAt(aStr.length-1)); return aStr; } function WrapObjectToMedia(html, aMediaElementName) { //check media first function _ConvertMedia( m, params ) { //split params to array m = params; var params = params.match(/[\s]*(.+?)=['"](.*?)['"][\s]*/gi); var vObjectAttrs = ''; var Result = ''; var vParamName, vParamValue; var vIsMedia = false; for (var i = 0; i < params.length; i++) { vPos = params[i].indexOf('='); vParamName = params[i].substring(0, vPos).trim(); vParamName = vParamName.toLowerCase(); vParamValue = params[i].substring(vPos+1); vParamValue = DequotedStr(vParamValue); if (vParamName == cMediaTypeAttrName) { //alert(vParamName+':'+vParamValue); if (isInt(vParamValue)) { vIsMedia = true; vObjectAttrs += ' '+ cMediaTypeAttrName + '="' + vParamValue + '"'; vObjectAttrs += ' classid="' + oFCKMediaPlayers[vParamValue].ClsId + '"'; vObjectAttrs += ' codebase="' + oFCKMediaPlayers[vParamValue].Codebase + '"'; }else { break; } } else if (cFCKMediaObjectAttrs[vParamName]) { vObjectAttrs += ' ' + vParamName + '="' + vParamValue + '"'; } else if (!cFCKMediaSkipParams[vParamName]) { Result += '<param name="' + vParamName + '" value="' + vParamValue + '"/>'; } } //for //wrap the <object> tag to <embed> if (vIsMedia) { Result = '<object' + vObjectAttrs + '>' + Result + '<embed' + m + '></embed></object>'; //alert(Result); return Result; } } if (aMediaElementName == '') aMediaElementName = cFckMediaElementName; var regexMedia = new RegExp( '<'+aMediaElementName+'(.+?)><\/'+aMediaElementName+'>', 'gi' ); //var regexMedia = /<fckMedia\s+(.+?)><\/fckMedia>/gi; //alert('b:'+html); return html.replace( regexMedia, _ConvertMedia ) ; }
zy73122/table2form
tools/fckeditor/editor/plugins/Media/js/fck_media_inc.js
JavaScript
gpl-2.0
7,657
jQuery(document).ready(function($){ jQuery('.ifeature-tabbed-wrap').tabs(); }); jQuery(document).ready(function($){ $("ul").parent("li").addClass("parent"); }); jQuery(document).ready(function($){ $("#gallery ul a:hover img").css("opacity", 1); $("#portfolio_wrap .portfolio_caption").css("opacity", 0); $("#portfolio_wrap a").hover(function(){ $(this).children("img").fadeTo("fast", 0.6); $(this).children(".portfolio_caption").fadeTo("fast", 1.0); },function(){ $(this).children("img").fadeTo("fast", 1.0); $(this).children(".portfolio_caption").fadeTo("fast", 0); }); $(".featured-image img").hover(function(){ $(this).fadeTo("fast", 0.75); },function(){ $(this).fadeTo("fast", 1.0); }); });
cyberchimps/ifeaturepro4
core/library/js/menu.js
JavaScript
gpl-2.0
744
var Models = window.Models || {}; jQuery.noConflict(); Models.Grid = function(w, h, el) { this.width = w; this.height = h; this.blocks = []; this.field = new Models.Block(w, h, 0, 0); this.element = el; this.place = function(block, x, y, html, creationIndex) { block.setPosition(x, y); return this._induct(block); }; this.add = function(block) { var grid = this; var opening = _(this.field.units()).detect(function(unit) { return grid.canFit(block, unit.x, unit.y); }); return this._induct(block); }; this._induct = function(block) { if(this.canFit(block)) { this.blocks.push(block); this.renderChild(block); if(this.isComplete()) { this.element.trigger('complete'); } return this; } return false; }; this.removeBlockWithIndex = function(blockIndex) { if (this.blocks.length == 1) { _(this.blocks).each(function(block) { block.destroy(); }); this.blocks = []; return this; } var indexToRemove = false; var cIndex = 0; _(this.blocks).each(function(block) { if (block.creationIndex == blockIndex) { indexToRemove = cIndex; block.destroy(); } cIndex++; }); if (indexToRemove !== false) { this.blocks.splice(indexToRemove, 1); } return this; }; this.clear = function() { _(this.blocks).each(function(block) { block.destroy(); }); this.blocks = []; return this; }; this.canFit = function(block, blockX, blockY) { block.setPosition(blockX, blockY); for (var i = 0; i < this.blocks.length; i++) { if(this.blocks[i].overlapsAny(block)) { return false; } } return block.overlappedFullyBy(this.field); }; this.blockAtPosition = function(unit) { var testBlock = new Models.Block(1, 1, unit.x, unit.y); return _(this.blocks).detect(function(block){ return block.overlapsAny(testBlock); }); }; this.blocksOverlappedByBlock = function(overlapper) { var grid = this; return _(this.blocks).select(function(block) { return block.overlapsAny(overlapper); }); }; this.isComplete = function() { var gridUnitCount = this.field.units().length; var blockUnitCount = _.reduce(this.blocks, function(memo, block) { return memo + block.units().length; }, 0); return gridUnitCount == blockUnitCount; }; this.render = function() { if (_(this.element).isUndefined()) { this.element = jQuery(document.createElement('div')).addClass('grid'); _.each(this.blocks, function(block) { this.renderChild(block); }, this); } return this.element; }; this.renderChild = function(block) { this.render(); this.element.append(block.render()); }; };
m-godefroid76/devrestofactory
wp-content/themes/berg-wp/admin/includes/js/grid.js
JavaScript
gpl-2.0
2,636
#!/usr/bin/env node console.log("Hello World!");
sumeettalwar/develop
node-js/src/week1/hello.js
JavaScript
gpl-2.0
49