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
//>>built define({"days-standAlone-short":"dom seg ter qua qui sex s\u00e1b".split(" "),"field-weekday":"Dia da semana","field-wed-relative+0":"esta quarta-feira","field-wed-relative+1":"pr\u00f3xima quarta-feira","dateFormatItem-GyMMMEd":"E, d 'de' MMM 'de' y G","dateFormatItem-MMMEd":"E, d 'de' MMM","field-tue-relative+-1":"ter\u00e7a-feira passada","days-format-short":"dom seg ter qua qui sex s\u00e1b".split(" "),"dateFormat-long":"d 'de' MMMM 'de' y G","field-fri-relative+-1":"sexta-feira passada","field-wed-relative+-1":"quarta-feira passada", "dateFormatItem-yyyyQQQ":"QQQQ 'de' y G","dateTimeFormat-medium":"{1}, {0}","dayPeriods-format-wide-pm":"da tarde","dateFormat-full":"EEEE, d 'de' MMMM 'de' y G","dateFormatItem-yyyyMEd":"E, dd/MM/y GGGGG","field-thu-relative+-1":"quinta-feira passada","dateFormatItem-Md":"d/M","dayPeriods-format-abbr-am":"a.m.","dayPeriods-format-wide-noon":"meio-dia","field-era":"Era","quarters-format-wide":["1.\u00ba trimestre","2.\u00ba trimestre","3.\u00ba trimestre","4.\u00ba trimestre"],"field-year":"Ano", "field-hour":"Hora","field-sat-relative+0":"este s\u00e1bado","field-sat-relative+1":"pr\u00f3ximo s\u00e1bado","field-day-relative+0":"hoje","field-thu-relative+0":"esta quinta-feira","field-day-relative+1":"amanh\u00e3","field-thu-relative+1":"pr\u00f3xima quinta-feira","dateFormatItem-GyMMMd":"d 'de' MMM 'de' y G","field-day-relative+2":"depois de amanh\u00e3","quarters-format-abbr":["T1","T2","T3","T4"],"quarters-standAlone-wide":["1.\u00ba trimestre","2.\u00ba trimestre","3.\u00ba trimestre", "4.\u00ba trimestre"],"dateFormatItem-Gy":"y G","dateFormatItem-yyyyMMMEd":"E, d/MM/y G","days-standAlone-wide":"domingo segunda-feira ter\u00e7a-feira quarta-feira quinta-feira sexta-feira s\u00e1bado".split(" "),"dateFormatItem-yyyyMMM":"MM/y G","dateFormatItem-yyyyMMMd":"d/MM/y G","field-sun-relative+0":"este domingo","field-sun-relative+1":"pr\u00f3ximo domingo","quarters-standAlone-abbr":["T1","T2","T3","T4"],"field-minute":"Minuto","field-dayperiod":"Da manh\u00e3/da tarde","days-standAlone-abbr":"dom seg ter qua qui sex s\u00e1b".split(" "), "field-day-relative+-1":"ontem","dateTimeFormat-long":"{1} '\u00e0s' {0}","dayPeriods-format-narrow-am":"a.m.","field-day-relative+-2":"anteontem","dateFormatItem-MMMd":"d 'de' MMM","dateFormatItem-MEd":"E, dd/MM","dateTimeFormat-full":"{1} '\u00e0s' {0}","field-fri-relative+0":"esta sexta-feira","field-fri-relative+1":"pr\u00f3xima sexta-feira","field-day":"Dia","days-format-wide":"domingo segunda-feira ter\u00e7a-feira quarta-feira quinta-feira sexta-feira s\u00e1bado".split(" "),"field-zone":"Fuso hor\u00e1rio", "dateFormatItem-y":"y G","field-year-relative+-1":"ano passado","field-month-relative+-1":"m\u00eas passado","dayPeriods-format-abbr-pm":"p.m.","days-format-abbr":"dom seg ter qua qui sex s\u00e1b".split(" "),"days-format-narrow":"DSTQQSS".split(""),"dateFormatItem-yyyyMd":"dd/MM/y GGGGG","field-month":"M\u00eas","days-standAlone-narrow":"DSTQQSS".split(""),"field-tue-relative+0":"esta ter\u00e7a-feira","field-tue-relative+1":"pr\u00f3xima ter\u00e7a-feira","dayPeriods-format-wide-am":"da manh\u00e3", "field-mon-relative+0":"esta segunda-feira","field-mon-relative+1":"pr\u00f3xima segunda-feira","dateFormat-short":"d/M/y G","field-second":"Segundo","field-sat-relative+-1":"s\u00e1bado passado","field-sun-relative+-1":"domingo passado","field-month-relative+0":"este m\u00eas","field-month-relative+1":"pr\u00f3ximo m\u00eas","dateFormatItem-Ed":"E, d","field-week":"Semana","dateFormat-medium":"d 'de' MMM, y G","field-year-relative+0":"este ano","field-week-relative+-1":"semana passada","dateFormatItem-yyyyM":"MM/y GGGGG", "field-year-relative+1":"pr\u00f3ximo ano","dayPeriods-format-narrow-pm":"p.m.","dateFormatItem-yyyyQQQQ":"QQQQ 'de' y G","dateTimeFormat-short":"{1}, {0}","dateFormatItem-GyMMM":"MMM 'de' y G","field-mon-relative+-1":"segunda-feira passada","dateFormatItem-yyyy":"y G","field-week-relative+0":"esta semana","field-week-relative+1":"pr\u00f3xima semana"});
ycabon/presentations
2020-devsummit/arcgis-js-api-road-ahead/js-api/dojo/cldr/nls/pt-pt/islamic.js
JavaScript
mit
4,028
class A { static get #x() {} get #x() {} }
kaicataldo/babel
packages/babel-parser/test/fixtures/experimental/class-private-names-duplicated/static-get-instance-get/input.js
JavaScript
mit
46
const fs = require('fs'); const fse = require('fs-extra'); const path = require('path'); module.exports = function (params) { const unpackFile = path.join( params.appOutDir, '*NAMECASENOSPACE*.app/Contents/Resources/app.asar.unpacked' ); fse.removeSync(unpackFile); };
cmgustavo/copay
app-template/afterPack-template.js
JavaScript
mit
283
var WINDOW = { ms_Width: 0, ms_Height: 0, ms_Callbacks: { 70: "WINDOW.toggleFullScreen()" // Toggle fullscreen }, initialize: function initialize() { this.updateSize(); // Create callbacks from keyboard $(document).keydown(function(inEvent) { WINDOW.callAction(inEvent.keyCode); }) ; $(window).resize(function(inEvent) { WINDOW.updateSize(); WINDOW.resizeCallback(WINDOW.ms_Width, WINDOW.ms_Height); }); }, updateSize: function updateSize() { this.ms_Width = $(window).width(); this.ms_Height = $(window).height() - 4; }, callAction: function callAction(inId) { if(inId in this.ms_Callbacks) { eval(this.ms_Callbacks[inId]); return false ; } }, toggleFullScreen: function toggleFullScreen() { if(!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) { if(document.documentElement.requestFullscreen) document.documentElement.requestFullscreen(); else if(document.documentElement.mozRequestFullScreen) document.documentElement.mozRequestFullScreen(); else if(document.documentElement.webkitRequestFullscreen) document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); } else { if(document.cancelFullScreen) document.cancelFullScreen(); else if(document.mozCancelFullScreen) document.mozCancelFullScreen(); else if (document.webkitCancelFullScreen) document.webkitCancelFullScreen(); } }, resizeCallback: function resizeCallback(inWidth, inHeight) {} };
Kike-Ramirez/canoaGame
public/js/window.js
JavaScript
mit
1,521
// Converted from: ../../examples/obj/torus/Torus.obj // vertices: 576 // faces: 576 // materials: 1 // // Generated with OBJ -> Three.js converter // http://github.com/alteredq/three.js/blob/master/utils/exporters/convert_obj_three.py var model = { "version" : 1, "materials": [ { "DbgColor" : 15658734, "DbgIndex" : 0, "DbgName" : "(null)" }], "buffers": "Torus_bin.bin" }; postMessage( model ); close();
pushmatrix/three.js
examples/obj/torus/Torus_bin.js
JavaScript
mit
464
/*! * Module dependencies. */ 'use strict'; const MongooseError = require('./'); /** * Schema validator error * * @param {Object} properties * @inherits MongooseError * @api private */ function ValidatorError(properties) { let msg = properties.message; if (!msg) { msg = MongooseError.messages.general.default; } const message = this.formatMessage(msg, properties); MongooseError.call(this, message); properties = Object.assign({}, properties, { message: message }); this.name = 'ValidatorError'; if (Error.captureStackTrace) { Error.captureStackTrace(this); } else { this.stack = new Error().stack; } this.properties = properties; this.kind = properties.type; this.path = properties.path; this.value = properties.value; this.reason = properties.reason; } /*! * Inherits from MongooseError */ ValidatorError.prototype = Object.create(MongooseError.prototype); ValidatorError.prototype.constructor = MongooseError; /*! * The object used to define this validator. Not enumerable to hide * it from `require('util').inspect()` output re: gh-3925 */ Object.defineProperty(ValidatorError.prototype, 'properties', { enumerable: false, writable: true, value: null }); /*! * Formats error messages */ ValidatorError.prototype.formatMessage = function(msg, properties) { if (typeof msg === 'function') { return msg(properties); } const propertyNames = Object.keys(properties); for (let i = 0; i < propertyNames.length; ++i) { const propertyName = propertyNames[i]; if (propertyName === 'message') { continue; } msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]); } return msg; }; /*! * toString helper */ ValidatorError.prototype.toString = function() { return this.message; }; /*! * exports */ module.exports = ValidatorError;
aguerny/LacquerTracker
node_modules/mongoose/lib/error/validator.js
JavaScript
mit
1,874
/* @Name: Horizontal multilevel menu @Author: Muffin Group @WWW: www.muffingroup.com @Version: 1.5.2 */ (function($){ $.fn.extend({ muffingroup_menu: function(options) { var menu = $(this); var defaults = { delay : 100, hoverClass : 'hover', arrows : true, animation : 'fade', addLast : true }; options = $.extend(defaults, options); // add class if menu item has sumbenu menu.find("li:has(ul)") .addClass("submenu") .append("<span class='menu-toggle'>") // responsive menu toggle .append("<span class='menu-arr-bottom'></span><span class='menu-arr-top'></span>") // border arrows ; // add class if submanu item has another sumbenu if( options.arrows ) { menu.find( "li ul li:has(ul) > a" ).append( "<span class='menu-arrow'><i class='icon-chevron-right'></i></span>" ); } // add bullets in each top-level menu item menu.children( "li:not(:last)" ).append( "<em>&#8226;</em>" ); // hover menu.find("li").hover(function() { $(this).addClass(options.hoverClass); if (options.animation === "fade") { $(this).children("ul").fadeIn(options.delay); } else if (options.animation === "toggle") { $(this).children("ul").stop(true,true).slideDown(options.delay); } }, function(){ $(this).removeClass(options.hoverClass); if (options.animation === "fade") { $(this).children("ul").fadeOut(options.delay); } else if (options.animation === "toggle") { $(this).children("ul").stop(true,true).slideUp(options.delay); } }); // add class .last-item to last sumbenu item $(".submenu ul li:last-child", menu).addClass("last-item"); // addLast if(options.addLast) { $("> li:last-child", menu) .addClass("last") .prev() .addClass("last"); } } }); })(jQuery);
dwivivagoal/KuizMilioner
themes/standar/assets/js/mfn.menu.js
JavaScript
mit
1,868
import Moment from 'moment'; import { functions, has, includes } from 'lodash'; export default function(dateString, context) { const date = Moment(dateString); if (has(context.hash, 'type') && includes(functions(date), context.hash.type)) { return date[context.hash.type](); } return date.calendar(); }
pierredup/CSBill
src/CoreBundle/Resources/public/js/extend/handlebars/helpers/date.js
JavaScript
mit
330
Clazz.declarePackage ("J.smiles"); Clazz.load (["java.util.Hashtable", "JU.BS", "J.smiles.VTemp"], "J.smiles.SmilesGenerator", ["JU.List", "$.SB", "J.smiles.InvalidSmilesException", "$.SmilesAromatic", "$.SmilesAtom", "$.SmilesBond", "$.SmilesParser", "$.SmilesSearch", "J.util.BSUtil", "$.Elements", "$.JmolMolecule", "$.Logger"], function () { c$ = Clazz.decorateAsClass (function () { this.atoms = null; this.atomCount = 0; this.bsSelected = null; this.bsAromatic = null; this.ringSets = null; this.vTemp = null; this.nPairs = 0; this.bsBondsUp = null; this.bsBondsDn = null; this.bsToDo = null; this.prevAtom = null; this.prevSp2Atoms = null; this.htRingsSequence = null; this.htRings = null; this.bsIncludingH = null; Clazz.instantialize (this, arguments); }, J.smiles, "SmilesGenerator"); Clazz.prepareFields (c$, function () { this.vTemp = new J.smiles.VTemp (); this.bsBondsUp = new JU.BS (); this.bsBondsDn = new JU.BS (); this.htRingsSequence = new java.util.Hashtable (); this.htRings = new java.util.Hashtable (); }); $_M(c$, "getSmiles", function (atoms, atomCount, bsSelected) { var i = bsSelected.nextSetBit (0); if (i < 0) return ""; this.atoms = atoms; this.atomCount = atomCount; this.bsSelected = bsSelected = J.util.BSUtil.copy (bsSelected); return this.getSmilesComponent (atoms[i], bsSelected, false); }, "~A,~N,JU.BS"); $_M(c$, "getBioSmiles", function (atoms, atomCount, bsSelected, allowUnmatchedRings, addCrossLinks, comment) { this.atoms = atoms; this.atomCount = atomCount; var sb = new JU.SB (); var bs = J.util.BSUtil.copy (bsSelected); if (comment != null) sb.append ("//* Jmol bioSMILES ").append (comment.$replace ('*', '_')).append (" *//"); var end = "\n"; var bsIgnore = new JU.BS (); var lastComponent = null; var s; var vLinks = new JU.List (); try { var len = 0; for (var i = bs.nextSetBit (0); i >= 0; i = bs.nextSetBit (i + 1)) { var a = atoms[i]; var ch = a.getGroup1 ('?'); var bioStructureName = a.getBioStructureTypeName (); var unknown = (ch.equals ("?")); if (end != null) { if (sb.length () > 0) sb.append (end); end = null; len = 0; if (bioStructureName.length > 0) { var id = a.getChainID (); if (id != 0) { s = "//* chain " + a.getChainIDStr () + " " + bioStructureName + " " + a.getResno () + " *// "; len = s.length; sb.append (s); }sb.append ("~").appendC (bioStructureName.charAt (0)).append ("~"); len++; } else { s = this.getSmilesComponent (a, bs, true); if (s.equals (lastComponent)) { end = ""; } else { lastComponent = s; var groupName = a.getGroup3 (true); if (groupName != null) sb.append ("//* ").append (groupName).append (" *//"); sb.append (s); end = ".\n"; }continue; }}if (len >= 75) { sb.append ("\n "); len = 2; }if (unknown) { this.addBracketedBioName (sb, a, bioStructureName.length > 0 ? ".0" : null); } else { sb.append (ch); }len++; var i0 = a.getOffsetResidueAtom ("0", 0); if (addCrossLinks) { a.getCrossLinkLeadAtomIndexes (vLinks); for (var j = 0; j < vLinks.size (); j++) { sb.append (":"); s = this.getRingCache (i0, vLinks.get (j).intValue (), this.htRingsSequence); sb.append (s); len += 1 + s.length; } vLinks.clear (); }a.getGroupBits (bsIgnore); bs.andNot (bsIgnore); var i2 = a.getOffsetResidueAtom ("0", 1); if (i2 < 0 || !bs.get (i2)) { sb.append (" //* ").appendI (a.getResno ()).append (" *//"); if (i2 < 0 && (i2 = bs.nextSetBit (i + 1)) < 0) break; if (len > 0) end = ".\n"; }i = i2 - 1; } } catch (e) { if (Clazz.exceptionOf (e, Exception)) { System.out.println (e.toString ()); return ""; } else { throw e; } } if (!allowUnmatchedRings && !this.htRingsSequence.isEmpty ()) { this.dumpRingKeys (sb, this.htRingsSequence); throw new J.smiles.InvalidSmilesException ("//* ?ring error? *//"); }s = sb.toString (); if (s.endsWith (".\n")) s = s.substring (0, s.length - 2); return s; }, "~A,~N,JU.BS,~B,~B,~S"); $_M(c$, "addBracketedBioName", ($fz = function (sb, a, atomName) { sb.append ("["); if (atomName != null) { var chain = a.getChainIDStr (); sb.append (a.getGroup3 (false)); if (!atomName.equals (".0")) sb.append (atomName).append ("#").appendI (a.getElementNumber ()); sb.append ("//* ").appendI (a.getResno ()); if (chain.length > 0) sb.append (":").append (chain); sb.append (" *//"); } else { sb.append (J.util.Elements.elementNameFromNumber (a.getElementNumber ())); }sb.append ("]"); }, $fz.isPrivate = true, $fz), "JU.SB,J.util.JmolNode,~S"); $_M(c$, "getSmilesComponent", ($fz = function (atom, bs, allowConnectionsToOutsideWorld) { if (atom.getElementNumber () == 1 && atom.getEdges ().length > 0) atom = this.atoms[atom.getBondedAtomIndex (0)]; this.bsSelected = J.util.JmolMolecule.getBranchBitSet (this.atoms, atom.getIndex (), J.util.BSUtil.copy (bs), null, -1, true, false); bs.andNot (this.bsSelected); this.bsIncludingH = J.util.BSUtil.copy (this.bsSelected); for (var j = this.bsSelected.nextSetBit (0); j >= 0; j = this.bsSelected.nextSetBit (j + 1)) { var a = this.atoms[j]; if (a.getElementNumber () == 1 && a.getIsotopeNumber () == 0) this.bsSelected.clear (j); } if (this.bsSelected.cardinality () > 2) { var search = null; search = J.smiles.SmilesParser.getMolecule ("A[=&@]A", true); search.jmolAtoms = this.atoms; search.setSelected (this.bsSelected); search.jmolAtomCount = this.atomCount; search.ringDataMax = 7; search.setRingData (null); this.bsAromatic = search.bsAromatic; this.ringSets = search.ringSets; this.setBondDirections (); } else { this.bsAromatic = new JU.BS (); }this.bsToDo = J.util.BSUtil.copy (this.bsSelected); var sb = new JU.SB (); for (var i = this.bsToDo.nextSetBit (0); i >= 0; i = this.bsToDo.nextSetBit (i + 1)) if (this.atoms[i].getCovalentBondCount () > 4) { this.getSmiles (sb, this.atoms[i], allowConnectionsToOutsideWorld, false); atom = null; } if (atom != null) while ((atom = this.getSmiles (sb, atom, allowConnectionsToOutsideWorld, true)) != null) { } while (this.bsToDo.cardinality () > 0 || !this.htRings.isEmpty ()) { var e = this.htRings.values ().iterator (); if (e.hasNext ()) { atom = this.atoms[(e.next ()[1]).intValue ()]; if (!this.bsToDo.get (atom.getIndex ())) break; } else { atom = this.atoms[this.bsToDo.nextSetBit (0)]; }sb.append ("."); this.prevSp2Atoms = null; this.prevAtom = null; while ((atom = this.getSmiles (sb, atom, allowConnectionsToOutsideWorld, true)) != null) { } } if (!this.htRings.isEmpty ()) { this.dumpRingKeys (sb, this.htRings); throw new J.smiles.InvalidSmilesException ("//* ?ring error? *//\n" + sb); }return sb.toString (); }, $fz.isPrivate = true, $fz), "J.util.JmolNode,JU.BS,~B"); $_M(c$, "getBondStereochemistry", ($fz = function (bond, atomFrom) { if (bond == null) return '\0'; var i = bond.index; var isFirst = (atomFrom == null || bond.getAtomIndex1 () == atomFrom.getIndex ()); return (this.bsBondsUp.get (i) ? (isFirst ? '/' : '\\') : this.bsBondsDn.get (i) ? (isFirst ? '\\' : '/') : '\0'); }, $fz.isPrivate = true, $fz), "J.util.JmolEdge,J.util.JmolNode"); $_M(c$, "setBondDirections", ($fz = function () { var bsDone = new JU.BS (); var edges = Clazz.newArray (2, 3, null); for (var i = this.bsSelected.nextSetBit (0); i >= 0; i = this.bsSelected.nextSetBit (i + 1)) { var atom1 = this.atoms[i]; var bonds = atom1.getEdges (); for (var k = 0; k < bonds.length; k++) { var bond = bonds[k]; var index = bond.index; if (bsDone.get (index)) continue; var atom2 = bond.getOtherAtomNode (atom1); if (bond.getCovalentOrder () != 2 || J.smiles.SmilesSearch.isRingBond (this.ringSets, i, atom2.getIndex ())) continue; bsDone.set (index); var b0 = null; var a0 = null; var i0 = 0; var atom12 = [atom1, atom2]; if (J.util.Logger.debugging) J.util.Logger.debug (atom1 + " == " + atom2); var edgeCount = 1; for (var j = 0; j < 2 && edgeCount > 0 && edgeCount < 3; j++) { edgeCount = 0; var atomA = atom12[j]; var bb = atomA.getEdges (); for (var b = 0; b < bb.length; b++) { if (bb[b].getCovalentOrder () != 1) continue; edges[j][edgeCount++] = bb[b]; if (this.getBondStereochemistry (bb[b], atomA) != '\0') { b0 = bb[b]; i0 = j; }} } if (edgeCount == 3 || edgeCount == 0) continue; if (b0 == null) { i0 = 0; b0 = edges[i0][0]; this.bsBondsUp.set (b0.index); }var c0 = this.getBondStereochemistry (b0, atom12[i0]); a0 = b0.getOtherAtomNode (atom12[i0]); if (a0 == null) continue; for (var j = 0; j < 2; j++) for (var jj = 0; jj < 2; jj++) { var b1 = edges[j][jj]; if (b1 == null || b1 === b0) continue; var bi = b1.index; var a1 = b1.getOtherAtomNode (atom12[j]); if (a1 == null) continue; var c1 = this.getBondStereochemistry (b1, atom12[j]); var isOpposite = J.smiles.SmilesSearch.isDiaxial (atom12[i0], atom12[j], a0, a1, this.vTemp, 0); if (c1 == '\0' || (c1 != c0) == isOpposite) { var isUp = (c0 == '\\' && isOpposite || c0 == '/' && !isOpposite); if (isUp == (b1.getAtomIndex1 () != a1.getIndex ())) this.bsBondsUp.set (bi); else this.bsBondsDn.set (bi); } else { J.util.Logger.error ("BOND STEREOCHEMISTRY ERROR"); }if (J.util.Logger.debugging) J.util.Logger.debug (this.getBondStereochemistry (b0, atom12[0]) + " " + a0.getIndex () + " " + a1.getIndex () + " " + this.getBondStereochemistry (b1, atom12[j])); } } } }, $fz.isPrivate = true, $fz)); $_M(c$, "getSmiles", ($fz = function (sb, atom, allowConnectionsToOutsideWorld, allowBranches) { var atomIndex = atom.getIndex (); if (!this.bsToDo.get (atomIndex)) return null; this.bsToDo.clear (atomIndex); var isExtension = (!this.bsSelected.get (atomIndex)); var prevIndex = (this.prevAtom == null ? -1 : this.prevAtom.getIndex ()); var isAromatic = this.bsAromatic.get (atomIndex); var havePreviousSp2Atoms = (this.prevSp2Atoms != null); var sp2Atoms = this.prevSp2Atoms; var nSp2Atoms = 0; var atomicNumber = atom.getElementNumber (); var nH = 0; var v = new JU.List (); var bond0 = null; var bondPrev = null; var bonds = atom.getEdges (); var aH = null; var stereoFlag = (isAromatic ? 10 : 0); var stereo = new Array (7); if (J.util.Logger.debugging) J.util.Logger.debug (sb.toString ()); if (bonds != null) for (var i = bonds.length; --i >= 0; ) { var bond = bonds[i]; if (!bond.isCovalent ()) continue; var atom1 = bonds[i].getOtherAtomNode (atom); var index1 = atom1.getIndex (); if (index1 == prevIndex) { bondPrev = bonds[i]; continue; }var isH = (atom1.getElementNumber () == 1 && atom1.getIsotopeNumber () == 0); if (!this.bsIncludingH.get (index1)) { if (!isH && allowConnectionsToOutsideWorld && this.bsSelected.get (atomIndex)) this.bsToDo.set (index1); else continue; }if (isH) { aH = atom1; nH++; if (nH > 1) stereoFlag = 10; } else { v.addLast (bonds[i]); }} var strBond = null; if (sp2Atoms == null) sp2Atoms = new Array (5); if (bondPrev != null) { strBond = J.smiles.SmilesBond.getBondOrderString (bondPrev.getCovalentOrder ()); if (this.prevSp2Atoms == null) sp2Atoms[nSp2Atoms++] = this.prevAtom; else nSp2Atoms = 2; }nSp2Atoms += nH; var nMax = 0; var bsBranches = new JU.BS (); if (allowBranches) for (var i = 0; i < v.size (); i++) { var bond = v.get (i); var a = bond.getOtherAtomNode (atom); var n = a.getCovalentBondCount () - a.getCovalentHydrogenCount (); var order = bond.getCovalentOrder (); if (order == 1 && n == 1 && i < v.size () - (bond0 == null ? 1 : 0)) { bsBranches.set (bond.index); } else if ((order > 1 || n > nMax) && !this.htRings.containsKey (J.smiles.SmilesGenerator.getRingKey (a.getIndex (), atomIndex))) { nMax = (order > 1 ? 1000 + order : n); bond0 = bond; }} var atomNext = (bond0 == null ? null : bond0.getOtherAtomNode (atom)); var orderNext = (bond0 == null ? 0 : bond0.getCovalentOrder ()); if (stereoFlag < 7 && bondPrev != null) { if (bondPrev.getCovalentOrder () == 2 && orderNext == 2 && this.prevSp2Atoms != null && this.prevSp2Atoms[1] != null) { stereo[stereoFlag++] = this.prevSp2Atoms[0]; stereo[stereoFlag++] = this.prevSp2Atoms[1]; } else { stereo[stereoFlag++] = this.prevAtom; }}if (stereoFlag < 7 && nH == 1) stereo[stereoFlag++] = aH; var deferStereo = (orderNext == 1 && this.prevSp2Atoms == null); var chBond = this.getBondStereochemistry (bondPrev, this.prevAtom); var sMore = new JU.SB (); for (var i = 0; i < v.size (); i++) { var bond = v.get (i); if (!bsBranches.get (bond.index)) continue; var a = bond.getOtherAtomNode (atom); var s2 = new JU.SB (); s2.append ("("); this.prevAtom = atom; this.prevSp2Atoms = null; var bond0t = bond0; this.getSmiles (s2, a, allowConnectionsToOutsideWorld, allowBranches); bond0 = bond0t; s2.append (")"); if (sMore.indexOf (s2.toString ()) >= 0) stereoFlag = 10; sMore.appendSB (s2); v.remove (i--); if (stereoFlag < 7) stereo[stereoFlag++] = a; if (nSp2Atoms < 5) sp2Atoms[nSp2Atoms++] = a; } var index2 = (orderNext == 2 ? atomNext.getIndex () : -1); if (nH > 1 || isAromatic || index2 < 0 || J.smiles.SmilesSearch.isRingBond (this.ringSets, atomIndex, index2)) { nSp2Atoms = -1; }if (nSp2Atoms < 0) sp2Atoms = null; if (strBond != null || chBond != '\0') { if (chBond != '\0') strBond = "" + chBond; sb.append (strBond); }var atat = null; if (!allowBranches && (v.size () == 5 || v.size () == 6)) atat = this.sortInorganic (atom, v); for (var i = 0; i < v.size (); i++) { var bond = v.get (i); if (bond === bond0) continue; var a = bond.getOtherAtomNode (atom); var s = this.getRingCache (atomIndex, a.getIndex (), this.htRings); strBond = J.smiles.SmilesBond.getBondOrderString (bond.order); if (!deferStereo) { chBond = this.getBondStereochemistry (bond, atom); if (chBond != '\0') strBond = "" + chBond; }sMore.append (strBond); sMore.append (s); if (stereoFlag < 7) stereo[stereoFlag++] = a; if (sp2Atoms != null && nSp2Atoms < 5) sp2Atoms[nSp2Atoms++] = a; } if (havePreviousSp2Atoms && stereoFlag == 2 && orderNext == 2 && atomNext.getCovalentBondCount () == 3) { bonds = atomNext.getEdges (); for (var k = 0; k < bonds.length; k++) { if (bonds[k].isCovalent () && atomNext.getBondedAtomIndex (k) != atomIndex) stereo[stereoFlag++] = this.atoms[atomNext.getBondedAtomIndex (k)]; } nSp2Atoms = 0; } else if (atomNext != null && stereoFlag < 7) { stereo[stereoFlag++] = atomNext; }var valence = atom.getValence (); var charge = atom.getFormalCharge (); var isotope = atom.getIsotopeNumber (); var atomName = atom.getAtomName (); var groupType = atom.getBioStructureTypeName (); if (J.util.Logger.debugging) sb.append ("\n//* " + atom + " *//\t"); if (isExtension && groupType.length != 0 && atomName.length != 0) this.addBracketedBioName (sb, atom, "." + atomName); else sb.append (J.smiles.SmilesAtom.getAtomLabel (atomicNumber, isotope, valence, charge, nH, isAromatic, atat != null ? atat : this.checkStereoPairs (atom, atomIndex, stereo, stereoFlag))); sb.appendSB (sMore); if (bond0 == null) return null; if (orderNext == 2 && (nSp2Atoms == 1 || nSp2Atoms == 2)) { if (sp2Atoms[0] == null) sp2Atoms[0] = atom; if (sp2Atoms[1] == null) sp2Atoms[1] = atom; } else { sp2Atoms = null; nSp2Atoms = 0; }this.prevSp2Atoms = sp2Atoms; this.prevAtom = atom; return atomNext; }, $fz.isPrivate = true, $fz), "JU.SB,J.util.JmolNode,~B,~B"); $_M(c$, "sortInorganic", ($fz = function (atom, v) { var atomIndex = atom.getIndex (); var n = v.size (); var axialPairs = new JU.List (); var bonds = new JU.List (); var a1; var a2; var bond1; var bond2; var bsDone = new JU.BS (); var pair0 = null; var stereo = new Array (6); var isOK = true; var s = ""; for (var i = 0; i < n; i++) { bond1 = v.get (i); stereo[0] = a1 = bond1.getOtherAtomNode (atom); if (i == 0) s = this.addStereoCheck (atomIndex, stereo, 0, ""); else if (isOK && this.addStereoCheck (atomIndex, stereo, 0, s) != null) isOK = false; if (bsDone.get (i)) continue; bsDone.set (i); var isAxial = false; for (var j = i + 1; j < n; j++) { if (bsDone.get (j)) continue; bond2 = v.get (j); a2 = bond2.getOtherAtomNode (atom); if (J.smiles.SmilesSearch.isDiaxial (atom, atom, a1, a2, this.vTemp, -0.95)) { axialPairs.addLast ([bond1, bond2]); isAxial = true; bsDone.set (j); break; }} if (!isAxial) bonds.addLast (bond1); } var nPairs = axialPairs.size (); if (isOK || n == 6 && nPairs != 3 || n == 5 && nPairs == 0) return ""; pair0 = axialPairs.get (0); bond1 = pair0[0]; stereo[0] = bond1.getOtherAtomNode (atom); v.clear (); v.addLast (bond1); if (nPairs > 1) bonds.addLast (axialPairs.get (1)[0]); if (nPairs == 3) bonds.addLast (axialPairs.get (2)[0]); if (nPairs > 1) bonds.addLast (axialPairs.get (1)[1]); if (nPairs == 3) bonds.addLast (axialPairs.get (2)[1]); for (var i = 0; i < bonds.size (); i++) { bond1 = bonds.get (i); v.addLast (bond1); stereo[i + 1] = bond1.getOtherAtomNode (atom); } v.addLast (pair0[1]); return J.smiles.SmilesGenerator.getStereoFlag (atom, stereo, n, this.vTemp); }, $fz.isPrivate = true, $fz), "J.util.JmolNode,JU.List"); $_M(c$, "checkStereoPairs", ($fz = function (atom, atomIndex, stereo, stereoFlag) { if (stereoFlag < 4) return ""; if (stereoFlag == 4 && (atom.getElementNumber ()) == 6) { var s = ""; for (var i = 0; i < 4; i++) if ((s = this.addStereoCheck (atomIndex, stereo, i, s)) == null) { stereoFlag = 10; break; } }return (stereoFlag > 6 ? "" : J.smiles.SmilesGenerator.getStereoFlag (atom, stereo, stereoFlag, this.vTemp)); }, $fz.isPrivate = true, $fz), "J.util.JmolNode,~N,~A,~N"); c$.getStereoFlag = $_M(c$, "getStereoFlag", ($fz = function (atom0, atoms, nAtoms, v) { var atom1 = atoms[0]; var atom2 = atoms[1]; var atom3 = atoms[2]; var atom4 = atoms[3]; var atom5 = atoms[4]; var atom6 = atoms[5]; var chiralClass = 4; switch (nAtoms) { default: case 5: case 6: return (J.smiles.SmilesSearch.checkStereochemistryAll (false, atom0, chiralClass, 1, atom1, atom2, atom3, atom4, atom5, atom6, v) ? "@" : "@@"); case 2: case 4: if (atom3 == null || atom4 == null) return ""; var d = J.smiles.SmilesAromatic.getNormalThroughPoints (atom1, atom2, atom3, v.vTemp, v.vA, v.vB); if (Math.abs (J.smiles.SmilesSearch.distanceToPlane (v.vTemp, d, atom4)) < 0.2) { chiralClass = 8; if (J.smiles.SmilesSearch.checkStereochemistryAll (false, atom0, chiralClass, 1, atom1, atom2, atom3, atom4, atom5, atom6, v)) return "@SP1"; if (J.smiles.SmilesSearch.checkStereochemistryAll (false, atom0, chiralClass, 2, atom1, atom2, atom3, atom4, atom5, atom6, v)) return "@SP2"; if (J.smiles.SmilesSearch.checkStereochemistryAll (false, atom0, chiralClass, 3, atom1, atom2, atom3, atom4, atom5, atom6, v)) return "@SP3"; } else { return (J.smiles.SmilesSearch.checkStereochemistryAll (false, atom0, chiralClass, 1, atom1, atom2, atom3, atom4, atom5, atom6, v) ? "@" : "@@"); }} return ""; }, $fz.isPrivate = true, $fz), "J.util.JmolNode,~A,~N,J.smiles.VTemp"); $_M(c$, "addStereoCheck", ($fz = function (atomIndex, stereo, i, s) { var n = stereo[i].getAtomicAndIsotopeNumber (); var nx = stereo[i].getCovalentBondCount (); var nh = (n == 6 ? stereo[i].getCovalentHydrogenCount () : 0); if (n == 6 ? nx != 4 || nh != 3 : nx > 1) return s; var sa = ";" + n + "/" + nh + "/" + nx + ","; if (s.indexOf (sa) >= 0) { if (nh == 3) { var ndt = 0; for (var j = 0; j < nx && ndt < 3; j++) { var ia = stereo[i].getBondedAtomIndex (j); if (ia == atomIndex) continue; ndt += this.atoms[ia].getAtomicAndIsotopeNumber (); } if (ndt > 3) return s; }return null; }return s + sa; }, $fz.isPrivate = true, $fz), "~N,~A,~N,~S"); $_M(c$, "getRingCache", ($fz = function (i0, i1, ht) { var key = J.smiles.SmilesGenerator.getRingKey (i0, i1); var o = ht.get (key); var s = (o == null ? null : o[0]); if (s == null) { ht.put (key, [s = J.smiles.SmilesParser.getRingPointer (++this.nPairs), Integer.$valueOf (i1)]); if (J.util.Logger.debugging) J.util.Logger.debug ("adding for " + i0 + " ring key " + this.nPairs + ": " + key); } else { ht.remove (key); if (J.util.Logger.debugging) J.util.Logger.debug ("using ring key " + key); }return s; }, $fz.isPrivate = true, $fz), "~N,~N,java.util.Map"); $_M(c$, "dumpRingKeys", ($fz = function (sb, ht) { J.util.Logger.info (sb.toString () + "\n\n"); for (var key, $key = ht.keySet ().iterator (); $key.hasNext () && ((key = $key.next ()) || true);) J.util.Logger.info ("unmatched ring key: " + key); }, $fz.isPrivate = true, $fz), "JU.SB,java.util.Map"); c$.getRingKey = $_M(c$, "getRingKey", function (i0, i1) { return Math.min (i0, i1) + "_" + Math.max (i0, i1); }, "~N,~N"); });
cheminfo/Visualizer-grunt
src/lib/jsmol/j2s/J/smiles/SmilesGenerator.js
JavaScript
mit
20,543
define([ // '../../../../src/utils/event', // '../../../../src/utils/objectCreate' ], function( // Event, // objectCreate ){ var objectCreate = hello.utils.objectCreate; var utils = hello.utils; // // Events // describe('utils / event', function(){ var hello, arbitary_data, event_name; beforeEach(function(){ // Pass an arbitary piece of data around arbitary_data = {boom:true}; event_name = 'custom'; hello = { utils : utils }; utils.Event.call(hello); }); it('should bind events by name and be able to trigger them by name', function(){ // Make request var spy = sinon.spy(function( data, type ){ expect( event_name ).to.be( type ); expect( arbitary_data ).to.be( data ); }); hello.on( event_name, spy ); hello.emit( event_name, arbitary_data ); expect( spy.called ).to.be.ok(); }); it('should listen to any event by using a "*"', function(){ // Make request var spy = sinon.spy(function( data, type ){ expect( event_name ).to.be( type ); expect( arbitary_data ).to.be( data ); }); hello.on( '*', spy ); hello.emit( event_name, arbitary_data ); expect( spy.called ).to.be.ok(); }); it('should unbind an event by name and callback', function(){ // Listeners var spy = sinon.spy(function(){ // should not be called. }); var spy2 = sinon.spy(function(){ // should not be called. }); // Bind hello.on( event_name, spy ); hello.on( event_name, spy2 ); // Remove hello.off( event_name, spy ); // Trigger hello.emit( event_name ); // Test spies expect( !spy.called ).to.be.ok(); expect( spy2.called ).to.be.ok(); }); it('should unbind all events by name', function(){ // Listeners var spy = sinon.spy(function(){ // should not be called. }); var spy2 = sinon.spy(function(){ // should not be called. }); // Bind hello.on( event_name, spy ); hello.on( event_name, spy2 ); // Remove hello.off( event_name ); // Trigger hello.emit( event_name ); // Test spies expect( !spy.called ).to.be.ok(); expect( !spy2.called ).to.be.ok(); }); it('should trigger events on its proto (predecessor in chain)', function(){ // PROTO // Listeners var spy = sinon.spy(function(){ // should not be called. }); // Bind hello.on( event_name, spy ); // PROTO var child = objectCreate(hello); var spy2 = sinon.spy(function(){ // should not be called. }); hello.on( event_name, spy2 ); // Trigger hello.emit( event_name ); // Test spies expect( spy.called ).to.be.ok(); expect( spy2.called ).to.be.ok(); }); }); });
HynesIP/hello.js
tests/specs/unit/utils/events.js
JavaScript
mit
2,636
import collapsibleFactory from '../common/collapsible'; import collapsibleGroupFactory from '../common/collapsible-group'; const PLUGIN_KEY = 'menu'; /* * Manage the behaviour of a menu * @param {jQuery} $menu */ class Menu { constructor($menu) { this.$menu = $menu; this.$body = $('body'); this.hasMaxMenuDisplayDepth = this.$body.find('.navPages-list').hasClass('navPages-list-depth-max'); // Init collapsible this.collapsibles = collapsibleFactory('[data-collapsible]', { $context: this.$menu }); this.collapsibleGroups = collapsibleGroupFactory($menu); // Auto-bind this.onMenuClick = this.onMenuClick.bind(this); this.onDocumentClick = this.onDocumentClick.bind(this); // Listen this.bindEvents(); } collapseAll() { this.collapsibles.forEach(collapsible => collapsible.close()); this.collapsibleGroups.forEach(group => group.close()); } collapseNeighbors($neighbors) { const $collapsibles = collapsibleFactory('[data-collapsible]', { $context: $neighbors }); $collapsibles.forEach($collapsible => $collapsible.close()); } bindEvents() { this.$menu.on('click', this.onMenuClick); this.$body.on('click', this.onDocumentClick); } unbindEvents() { this.$menu.off('click', this.onMenuClick); this.$body.off('click', this.onDocumentClick); } onMenuClick(event) { event.stopPropagation(); if (this.hasMaxMenuDisplayDepth) { const $neighbors = $(event.target).parent().siblings(); this.collapseNeighbors($neighbors); } } onDocumentClick() { this.collapseAll(); } } /* * Create a new Menu instance * @param {string} [selector] * @return {Menu} */ export default function menuFactory(selector = `[data-${PLUGIN_KEY}]`) { const $menu = $(selector).eq(0); const instanceKey = `${PLUGIN_KEY}Instance`; const cachedMenu = $menu.data(instanceKey); if (cachedMenu instanceof Menu) { return cachedMenu; } const menu = new Menu($menu); $menu.data(instanceKey, menu); return menu; }
sacr3dc0w/cornerstone
assets/js/theme/global/menu.js
JavaScript
mit
2,199
'use strict'; var users = require('../../app/controllers/users'), speakers = require('../../app/controllers/speakers'); module.exports = function(app) { // Speakers Routes app.route('/speakers') .get(speakers.list) .post(users.requiresLogin, speakers.create); app.route('/speakers/:speakerId') .get(speakers.read) .put(users.requiresLogin, speakers.hasAuthorization, speakers.update) .delete(users.requiresLogin, speakers.hasAuthorization, speakers.delete); // Finish by binding the Speaker middleware app.param('speakerId', speakers.speakerByID); };
IsabellaAlves/conference-api
app/routes/speakers.server.routes.js
JavaScript
mit
573
import * as React from 'react'; import ApiPage from 'docs/src/modules/components/ApiPage'; import mapApiPageTranslations from 'docs/src/modules/utils/mapApiPageTranslations'; import jsonPageContent from './avatar.json'; export default function Page(props) { const { descriptions, pageContent } = props; return <ApiPage descriptions={descriptions} pageContent={pageContent} />; } Page.getInitialProps = () => { const req = require.context('docs/translations/api-docs/avatar', false, /avatar.*.json$/); const descriptions = mapApiPageTranslations(req); return { descriptions, pageContent: jsonPageContent, }; };
oliviertassinari/material-ui
docs/pages/material/api/avatar.js
JavaScript
mit
633
var webpack = require('webpack'); var path = require('path'); module.exports = { entry: './src/main.ts', output: { filename: './bundle.js' }, resolve: { root: [ path.join(__dirname, 'src') ], extensions: ['', '.ts', '.js'] }, module: { loaders: [ { test: /\.ts$/, loader: 'ts-loader' } ] } };
lesliezjm/Angular2
hello-world/webpack.config.js
JavaScript
mit
335
(function($) { $.Redactor.prototype.source = function() { return { init: function() { var button = this.button.addFirst('html', 'HTML'); this.button.setIcon(button, '<i class="re-icon-html"></i>'); this.button.addCallback(button, this.source.toggle); var style = { 'width': '100%', 'margin': '0', 'background': '#1d1d1d', 'box-sizing': 'border-box', 'color': '#ccc', 'font-size': '15px', 'outline': 'none', 'padding': '20px', 'line-height': '24px', 'font-family': 'Consolas, Menlo, Monaco, "Courier New", monospace' }; this.source.$textarea = $('<textarea />'); this.source.$textarea.css(style).hide(); if (this.opts.type === 'textarea') { this.core.box().append(this.source.$textarea); } else { this.core.box().after(this.source.$textarea); } this.core.element().on('destroy.callback.redactor', $.proxy(function() { this.source.$textarea.remove(); }, this)); }, toggle: function() { return (this.source.$textarea.hasClass('open')) ? this.source.hide() : this.source.show(); }, setCaretOnShow: function() { this.source.offset = this.offset.get(); var scroll = $(window).scrollTop(); var width = this.core.editor().innerWidth(); var height = this.core.editor().innerHeight(); // caret position sync this.source.start = 0; this.source.end = 0; var $editorDiv = $("<div/>").append($.parseHTML(this.core.editor().html(), document, true)); var $selectionMarkers = $editorDiv.find("span.redactor-selection-marker"); if ($selectionMarkers.length > 0) { var editorHtml = $editorDiv.html().replace(/&amp;/g, '&'); if ($selectionMarkers.length === 1) { this.source.start = this.utils.strpos(editorHtml, $editorDiv.find("#selection-marker-1").prop("outerHTML")); this.source.end = this.source.start; } else if ($selectionMarkers.length === 2) { this.source.start = this.utils.strpos(editorHtml, $editorDiv.find("#selection-marker-1").prop("outerHTML")); this.source.end = this.utils.strpos(editorHtml, $editorDiv.find("#selection-marker-2").prop("outerHTML")) - $editorDiv.find("#selection-marker-1").prop("outerHTML").toString().length; } } }, setCaretOnHide: function(html) { this.source.start = this.source.$textarea.get(0).selectionStart; this.source.end = this.source.$textarea.get(0).selectionEnd; // if selection starts from end if (this.source.start > this.source.end && this.source.end > 0) { var tempStart = this.source.end; var tempEnd = this.source.start; this.source.start = tempStart; this.source.end = tempEnd; } this.source.start = this.source.enlargeOffset(html, this.source.start); this.source.end = this.source.enlargeOffset(html, this.source.end); html = html.substr(0, this.source.start) + this.marker.html(1) + html.substr(this.source.start); if (this.source.end > this.source.start) { var markerLength = this.marker.html(1).toString().length; html = html.substr(0, this.source.end + markerLength) + this.marker.html(2) + html.substr(this.source.end + markerLength); } return html; }, hide: function() { this.source.$textarea.removeClass('open').hide(); this.source.$textarea.off('.redactor-source'); var code = this.source.$textarea.val(); code = this.paragraphize.load(code); code = this.source.setCaretOnHide(code); this.code.start(code); this.button.enableAll(); this.core.editor().show().focus(); this.selection.restore(); this.placeholder.enable(); this.core.callback('visual'); }, show: function() { this.selection.save(); this.source.setCaretOnShow(); var height = this.core.editor().height(); var code = this.code.get(); // callback code = this.core.callback('source', code); this.core.editor().hide(); this.button.disableAll('html'); this.source.$textarea.val(code).height(height).addClass('open').show(); this.source.$textarea.on('keyup.redactor-source', $.proxy(function() { if (this.opts.type === 'textarea') { this.core.textarea().val(this.source.$textarea.val()); } }, this)); this.marker.remove(); $(window).scrollTop(scroll); if (this.source.$textarea[0].setSelectionRange) { this.source.$textarea[0].setSelectionRange(this.source.start, this.source.end); } this.source.$textarea[0].scrollTop = 0; setTimeout($.proxy(function() { this.source.$textarea.focus(); }, this), 0); }, enlargeOffset: function(html, offset) { var htmlLength = html.length; var c = 0; if (html[offset] === '>') { c++; } else { for(var i = offset; i <= htmlLength; i++) { c++; if (html[i] === '>') { break; } else if (html[i] === '<' || i === htmlLength) { c = 0; break; } } } return offset + c; } }; }; })(jQuery);
nathanhnew/NLNF
static/redactor/plugins/source.js
JavaScript
mit
5,162
(function () { 'use strict'; angular .module('crowdsource.config', ['angular-loading-bar']) .config(config); config.$inject = ['$httpProvider', '$locationProvider', '$mdThemingProvider', 'cfpLoadingBarProvider']; /** * @name config * @desc Enable HTML5 routing */ function config($httpProvider, $locationProvider, $mdThemingProvider, cfpLoadingBarProvider) { $httpProvider.interceptors.push('AuthHttpResponseInterceptor'); $locationProvider.html5Mode(true); $locationProvider.hashPrefix('!'); cfpLoadingBarProvider.includeSpinner = false; // Extend palettes var customBlue = $mdThemingProvider.extendPalette('indigo', { "50":"#e8e9f2","100":"#babdd8","200":"#8d91bf", "300":"#666ca9","400":"#404893","500":"#1a237e", "600":"#171f6e","700":"#141a5f","800":"#10164f", "900":"#0d123f","A100":"#babdd8","A200":"#8d91bf", "A400":"#404893","A700":"#141a5f" }); var customYellow = $mdThemingProvider.extendPalette('yellow', { "50": "#fffef3", "100": "#fffbdb", "200": "#fff9c4", "300": "#fff6b0", "400": "#fff49c", "500": "#fff288", "600": "#dfd477", "700": "#bfb666", "800": "#9f9755", "900": "#807944", "A100": "#fffbdb", "A200": "#fff9c4", "A400": "#fff49c", "A700": "#bfb666" }); var customGrey = $mdThemingProvider.extendPalette('grey', { "50":"#ffffff","100":"#ffffff","200":"#ffffff", "300":"#ffffff","400":"#ffffff","500":"#ffffff", "600":"#dfdfdf","700":"#bfbfbf","800":"#9f9f9f", "900":"#808080","A100":"#ffffff","A200":"#ffffff", "A400":"#ffffff","A700":"#bfbfbf" }); // Register the new color palette map with the name <code>neonRed</code> $mdThemingProvider.definePalette('customBlue', customBlue); $mdThemingProvider.definePalette('customYellow', customYellow); $mdThemingProvider.definePalette('customGrey', customGrey); $mdThemingProvider.theme('default') .primaryPalette('customBlue') .accentPalette('customYellow') .warnPalette('red') .backgroundPalette('customGrey'); $mdThemingProvider.theme('alternate') .primaryPalette('indigo') .accentPalette('orange') .warnPalette('red') .backgroundPalette('grey'); $mdThemingProvider.setDefaultTheme('default'); // $mdThemingProvider.alwaysWatchTheme(true); //testing /*OAuthProvider.configure({ baseUrl: 'http://localhost:8000', clientId: 'client_id', clientSecret: 'client_secret', grantPath : '/api/oauth2-ng/token' }); OAuthTokenProvider.configure({ name: 'token', options: { secure: false //TODO this has to be changed to True } });*/ } })();
xasos/crowdsource-platform
static/js/crowdsource.config.js
JavaScript
mit
2,999
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > If the eval function is called with some argument, then use a first argument es5id: 15.1.2.1_A1.2_T1 description: eval("x = 1", "x = 2"), x equal 1, not 2 ---*/ //CHECK#1 var x; eval("x = 1", "x = 2"); if (x !== 1) { $ERROR('#1: eval("x = 1", "x = 2"); x === 1. Actual: ' + (x)); }
PiotrDabkowski/Js2Py
tests/test_cases/built-ins/eval/S15.1.2.1_A1.2_T1.js
JavaScript
mit
440
module.exports = [ require('./ngdoc'), require('./name'), require('./area'), require('./module'), require('./id'), require('./restrict'), require('./eventType'), require('./example'), require('./element'), require('./fullName'), require('./priority'), require('./title'), require('./parent'), require('./packageName'), require('./scope') ];
uistyleguide/uistyleguide.github.io
node_modules/dgeni-packages/ngdoc/tag-defs/index.js
JavaScript
mit
370
Astro.createValidator({ name: 'array', validate: _.isArray, events: { validationerror: function(e) { var fieldName = e.data.field; e.data.message = 'The "' + fieldName + '" field\'s value has to be an array'; } } });
ribbedcrown/meteor-astronomy-validators
lib/validators/type/array.js
JavaScript
mit
254
/* * * * (c) 2010-2020 Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import H from './Globals.js'; /** * @interface Highcharts.PointEventsOptionsObject */ /** * Fires when the point is selected either programmatically or following a click * on the point. One parameter, `event`, is passed to the function. Returning * `false` cancels the operation. * @name Highcharts.PointEventsOptionsObject#select * @type {Highcharts.PointSelectCallbackFunction|undefined} */ /** * Fires when the point is unselected either programmatically or following a * click on the point. One parameter, `event`, is passed to the function. * Returning `false` cancels the operation. * @name Highcharts.PointEventsOptionsObject#unselect * @type {Highcharts.PointUnselectCallbackFunction|undefined} */ /** * Information about the select/unselect event. * * @interface Highcharts.PointInteractionEventObject * @extends global.Event */ /** * @name Highcharts.PointInteractionEventObject#accumulate * @type {boolean} */ /** * Gets fired when the point is selected either programmatically or following a * click on the point. * * @callback Highcharts.PointSelectCallbackFunction * * @param {Highcharts.Point} this * Point where the event occured. * * @param {Highcharts.PointInteractionEventObject} event * Event that occured. */ /** * Fires when the point is unselected either programmatically or following a * click on the point. * * @callback Highcharts.PointUnselectCallbackFunction * * @param {Highcharts.Point} this * Point where the event occured. * * @param {Highcharts.PointInteractionEventObject} event * Event that occured. */ import Legend from './Legend.js'; import Point from './Point.js'; import U from './Utilities.js'; var addEvent = U.addEvent, createElement = U.createElement, css = U.css, defined = U.defined, extend = U.extend, fireEvent = U.fireEvent, isArray = U.isArray, isFunction = U.isFunction, isObject = U.isObject, merge = U.merge, objectEach = U.objectEach, pick = U.pick; import './Chart.js'; import './Options.js'; import './Series.js'; var Chart = H.Chart, defaultOptions = H.defaultOptions, defaultPlotOptions = H.defaultPlotOptions, hasTouch = H.hasTouch, Series = H.Series, seriesTypes = H.seriesTypes, svg = H.svg, TrackerMixin; /* eslint-disable valid-jsdoc */ /** * TrackerMixin for points and graphs. * * @private * @mixin Highcharts.TrackerMixin */ TrackerMixin = H.TrackerMixin = { /** * Draw the tracker for a point. * * @private * @function Highcharts.TrackerMixin.drawTrackerPoint * @param {Highcharts.Series} this * @fires Highcharts.Series#event:afterDrawTracker */ drawTrackerPoint: function () { var series = this, chart = series.chart, pointer = chart.pointer, onMouseOver = function (e) { var point = pointer.getPointFromEvent(e); // undefined on graph in scatterchart if (typeof point !== 'undefined') { pointer.isDirectTouch = true; point.onMouseOver(e); } }, dataLabels; // Add reference to the point series.points.forEach(function (point) { dataLabels = (isArray(point.dataLabels) ? point.dataLabels : (point.dataLabel ? [point.dataLabel] : [])); if (point.graphic) { point.graphic.element.point = point; } dataLabels.forEach(function (dataLabel) { if (dataLabel.div) { dataLabel.div.point = point; } else { dataLabel.element.point = point; } }); }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { series.trackerGroups.forEach(function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass('highcharts-tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }); if (hasTouch) { series[key].on('touchstart', onMouseOver); } if (!chart.styledMode && series.options.cursor) { series[key] .css(css) .css({ cursor: series.options.cursor }); } } }); series._hasTracking = true; } fireEvent(this, 'afterDrawTracker'); }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. * * @private * @function Highcharts.TrackerMixin.drawTrackerGraph * @param {Highcharts.Series} this * @fires Highcharts.Series#event:afterDrawTracker */ drawTrackerGraph: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, i, onMouseOver = function (e) { pointer.normalize(e); if (chart.hoverSeries !== series && !pointer.isStickyTooltip(e)) { series.onMouseOver(); } }, /* * Empirical lowest possible opacities for TRACKER_FILL for an * element to stay invisible but clickable * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (svg ? 0.0001 : 0.002) + ')'; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === 'M') { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], 'L'); } if ((i && trackerPath[i] === 'M') || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, 'L', trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else if (series.graph) { // create series.tracker = renderer.path(trackerPath) .attr({ visibility: series.visible ? 'visible' : 'hidden', zIndex: 2 }) .addClass(trackByArea ? 'highcharts-tracker-area' : 'highcharts-tracker-line') .add(series.group); if (!chart.styledMode) { series.tracker.attr({ 'stroke-linejoin': 'round', stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : 'none', 'stroke-width': series.graph.strokeWidth() + (trackByArea ? 0 : 2 * snap) }); } // The tracker is added to the series group, which is clipped, but // is covered by the marker group. So the marker group also needs to // capture events. [series.tracker, series.markerGroup].forEach(function (tracker) { tracker.addClass('highcharts-tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }); if (options.cursor && !chart.styledMode) { tracker.css({ cursor: options.cursor }); } if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } fireEvent(this, 'afterDrawTracker'); } }; /* End TrackerMixin */ // Add tracking event listener to the series group, so the point graphics // themselves act as trackers if (seriesTypes.column) { /** * @private * @borrows Highcharts.TrackerMixin.drawTrackerPoint as Highcharts.seriesTypes.column#drawTracker */ seriesTypes.column.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.pie) { /** * @private * @borrows Highcharts.TrackerMixin.drawTrackerPoint as Highcharts.seriesTypes.pie#drawTracker */ seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.scatter) { /** * @private * @borrows Highcharts.TrackerMixin.drawTrackerPoint as Highcharts.seriesTypes.scatter#drawTracker */ seriesTypes.scatter.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } // Extend Legend for item events. extend(Legend.prototype, { /** * @private * @function Highcharts.Legend#setItemEvents * @param {Highcharts.BubbleLegend|Highcharts.Point|Highcharts.Series} item * @param {Highcharts.SVGElement} legendItem * @param {boolean} [useHTML=false] * @fires Highcharts.Point#event:legendItemClick * @fires Highcharts.Series#event:legendItemClick */ setItemEvents: function (item, legendItem, useHTML) { var legend = this, boxWrapper = legend.chart.renderer.boxWrapper, isPoint = item instanceof Point, activeClass = 'highcharts-legend-' + (isPoint ? 'point' : 'series') + '-active', styledMode = legend.chart.styledMode, // When `useHTML`, the symbol is rendered in other group, so // we need to apply events listeners to both places legendItems = useHTML ? [legendItem, item.legendSymbol] : [item.legendGroup]; // Set the events on the item group, or in case of useHTML, the item // itself (#1249) legendItems.forEach(function (element) { if (element) { element .on('mouseover', function () { if (item.visible) { legend.allItems.forEach(function (inactiveItem) { if (item !== inactiveItem) { inactiveItem.setState('inactive', !isPoint); } }); } item.setState('hover'); // A CSS class to dim or hide other than the hovered // series. // Works only if hovered series is visible (#10071). if (item.visible) { boxWrapper.addClass(activeClass); } if (!styledMode) { legendItem.css(legend.options.itemHoverStyle); } }) .on('mouseout', function () { if (!legend.chart.styledMode) { legendItem.css(merge(item.visible ? legend.itemStyle : legend.itemHiddenStyle)); } legend.allItems.forEach(function (inactiveItem) { if (item !== inactiveItem) { inactiveItem.setState('', !isPoint); } }); // A CSS class to dim or hide other than the hovered // series. boxWrapper.removeClass(activeClass); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { if (item.setVisible) { item.setVisible(); } // Reset inactive state legend.allItems.forEach(function (inactiveItem) { if (item !== inactiveItem) { inactiveItem.setState(item.visible ? 'inactive' : '', !isPoint); } }); }; // A CSS class to dim or hide other than the hovered // series. Event handling in iOS causes the activeClass // to be added prior to click in some cases (#7418). boxWrapper.removeClass(activeClass); // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); } }); }, /** * @private * @function Highcharts.Legend#createCheckboxForItem * @param {Highcharts.BubbleLegend|Highcharts.Point|Highcharts.Series} item * @fires Highcharts.Series#event:checkboxClick */ createCheckboxForItem: function (item) { var legend = this; item.checkbox = createElement('input', { type: 'checkbox', className: 'highcharts-legend-checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, legend.options.itemCheckboxStyle, legend.chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item.series || item, 'checkboxClick', { checked: target.checked, item: item }, function () { item.select(); }); }); } }); // Extend the Chart object with interaction extend(Chart.prototype, /** @lends Chart.prototype */ { /** * Display the zoom button, so users can reset zoom to the default view * settings. * * @function Highcharts.Chart#showResetZoom * * @fires Highcharts.Chart#event:afterShowResetZoom * @fires Highcharts.Chart#event:beforeShowResetZoom */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = (btnOptions.relativeTo === 'chart' || btnOptions.relativeTo === 'spaceBox' ? null : 'plotBox'); /** * @private */ function zoomOut() { chart.zoomOut(); } fireEvent(this, 'beforeShowResetZoom', null, function () { chart.resetZoomButton = chart.renderer .button(lang.resetZoom, null, null, zoomOut, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .addClass('highcharts-reset-zoom') .add() .align(btnOptions.position, false, alignTo); }); fireEvent(this, 'afterShowResetZoom'); }, /** * Zoom the chart out after a user has zoomed in. See also * [Axis.setExtremes](/class-reference/Highcharts.Axis#setExtremes). * * @function Highcharts.Chart#zoomOut * * @fires Highcharts.Chart#event:selection */ zoomOut: function () { fireEvent(this, 'selection', { resetSelection: true }, this.zoom); }, /** * Zoom into a given portion of the chart given by axis coordinates. * * @private * @function Highcharts.Chart#zoom * @param {Highcharts.SelectEventObject} event */ zoom: function (event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, mouseDownPos = chart.inverted ? pointer.mouseDownX : pointer.mouseDownY, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { chart.axes.forEach(function (axis) { hasZoomed = axis.zoom(); }); pointer.initiated = false; // #6804 } else { // else, zoom in on all axes event.xAxis.concat(event.yAxis).forEach(function (axisData) { var axis = axisData.axis, axisStartPos = chart.inverted ? axis.left : axis.top, axisEndPos = chart.inverted ? axisStartPos + axis.width : axisStartPos + axis.height, isXAxis = axis.isXAxis, isWithinPane = false; // Check if zoomed area is within the pane (#1289). // In case of multiple panes only one pane should be zoomed. if ((!isXAxis && mouseDownPos >= axisStartPos && mouseDownPos <= axisEndPos) || isXAxis || !defined(mouseDownPos)) { isWithinPane = true; } // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] && isWithinPane) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw(pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100)); } }, /** * Pan the chart by dragging the mouse across the pane. This function is * called on mouse move, and the distance to pan is computed from chartX * compared to the first chartX position in the dragging operation. * * @private * @function Highcharts.Chart#pan * @param {Highcharts.PointerEventObject} e * @param {string} panning */ pan: function (e, panning) { var chart = this, hoverPoints = chart.hoverPoints, panningOptions, chartOptions = chart.options.chart, doRedraw, type; if (typeof panning === 'object') { panningOptions = panning; } else { panningOptions = { enabled: panning, type: 'x' }; } if (chartOptions && chartOptions.panning) { chartOptions.panning = panningOptions; } type = panningOptions.type; fireEvent(this, 'pan', { originalEvent: e }, function () { // remove active points for shared tooltip if (hoverPoints) { hoverPoints.forEach(function (point) { point.setState(); }); } // panning axis mapping var xy = [1]; // x if (type === 'xy') { xy = [1, 0]; } else if (type === 'y') { xy = [0]; } xy.forEach(function (isX) { var axis = chart[isX ? 'xAxis' : 'yAxis'][0], axisOpt = axis.options, horiz = axis.horiz, mousePos = e[horiz ? 'chartX' : 'chartY'], mouseDown = horiz ? 'mouseDownX' : 'mouseDownY', startPos = chart[mouseDown], halfPointRange = (axis.pointRange || 0) / 2, pointRangeDirection = (axis.reversed && !chart.inverted) || (!axis.reversed && chart.inverted) ? -1 : 1, extremes = axis.getExtremes(), panMin = axis.toValue(startPos - mousePos, true) + halfPointRange * pointRangeDirection, panMax = axis.toValue(startPos + axis.len - mousePos, true) - halfPointRange * pointRangeDirection, flipped = panMax < panMin, newMin = flipped ? panMax : panMin, newMax = flipped ? panMin : panMax, paddedMin = Math.min(extremes.dataMin, halfPointRange ? extremes.min : axis.toValue(axis.toPixels(extremes.min) - axis.minPixelPadding)), paddedMax = Math.max(extremes.dataMax, halfPointRange ? extremes.max : axis.toValue(axis.toPixels(extremes.max) + axis.minPixelPadding)), spill; // It is not necessary to calculate extremes on ordinal axis, // because the are already calculated, so we don't want to // override them. if (!axisOpt.ordinal) { // If the new range spills over, either to the min or max, // adjust the new range. if (isX) { spill = paddedMin - newMin; if (spill > 0) { newMax += spill; newMin = paddedMin; } spill = newMax - paddedMax; if (spill > 0) { newMax = paddedMax; newMin -= spill; } } // Set new extremes if they are actually new if (axis.series.length && newMin !== extremes.min && newMax !== extremes.max && isX ? true : (axis.panningState && newMin >= axis.panningState .startMin && newMax <= axis.panningState .startMax // )) { axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' }); doRedraw = true; } // set new reference for next run: chart[mouseDown] = mousePos; } }); if (doRedraw) { chart.redraw(false); } css(chart.container, { cursor: 'move' }); }); } }); // Extend the Point object with interaction extend(Point.prototype, /** @lends Highcharts.Point.prototype */ { /** * Toggle the selection status of a point. * * @see Highcharts.Chart#getSelectedPoints * * @sample highcharts/members/point-select/ * Select a point from a button * @sample highcharts/chart/events-selection-points/ * Select a range of points through a drag selection * @sample maps/series/data-id/ * Select a point in Highmaps * * @function Highcharts.Point#select * * @param {boolean} [selected] * When `true`, the point is selected. When `false`, the point is * unselected. When `null` or `undefined`, the selection state is toggled. * * @param {boolean} [accumulate=false] * When `true`, the selection is added to other selected points. * When `false`, other selected points are deselected. Internally in * Highcharts, when * [allowPointSelect](https://api.highcharts.com/highcharts/plotOptions.series.allowPointSelect) * is `true`, selected points are accumulated on Control, Shift or Cmd * clicking the point. * * @fires Highcharts.Point#event:select * @fires Highcharts.Point#event:unselect */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); this.selectedStaging = selected; // fire the event with the default handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { /** * Whether the point is selected or not. * * @see Point#select * @see Chart#getSelectedPoints * * @name Highcharts.Point#selected * @type {boolean} */ point.selected = point.options.selected = selected; series.options.data[series.data.indexOf(point)] = point.options; point.setState(selected && 'select'); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { chart.getSelectedPoints().forEach(function (loopPoint) { var loopSeries = loopPoint.series; if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; loopSeries.options.data[loopSeries.data.indexOf(loopPoint)] = loopPoint.options; // Programatically selecting a point should restore // normal state, but when click happened on other // point, set inactive state to match other points loopPoint.setState(chart.hoverPoints && loopSeries.options.inactiveOtherPoints ? 'inactive' : ''); loopPoint.firePointEvent('unselect'); } }); } }); delete this.selectedStaging; }, /** * Runs on mouse over the point. Called internally from mouse and touch * events. * * @function Highcharts.Point#onMouseOver * * @param {Highcharts.PointerEventObject} [e] * The event arguments. */ onMouseOver: function (e) { var point = this, series = point.series, chart = series.chart, pointer = chart.pointer; e = e ? pointer.normalize(e) : // In cases where onMouseOver is called directly without an event pointer.getChartCoordinatesFromPoint(point, chart.inverted); pointer.runPointActions(e, point); }, /** * Runs on mouse out from the point. Called internally from mouse and touch * events. * * @function Highcharts.Point#onMouseOut * @fires Highcharts.Point#event:mouseOut */ onMouseOut: function () { var point = this, chart = point.series.chart; point.firePointEvent('mouseOut'); if (!point.series.options.inactiveOtherPoints) { (chart.hoverPoints || []).forEach(function (p) { p.setState(); }); } chart.hoverPoints = chart.hoverPoint = null; }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. * * @private * @function Highcharts.Point#importEvents */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events; point.events = events; objectEach(events, function (event, eventType) { if (isFunction(event)) { addEvent(point, eventType, event); } }); this.hasImportedEvents = true; } }, /** * Set the point's state. * * @function Highcharts.Point#setState * * @param {Highcharts.PointStateValue|""} [state] * The new state, can be one of `'hover'`, `'select'`, `'inactive'`, * or `''` (an empty string), `'normal'` or `undefined` to set to * normal state. * @param {boolean} [move] * State for animation. * * @fires Highcharts.Point#event:afterSetState */ setState: function (state, move) { var point = this, series = point.series, previousState = point.state, stateOptions = (series.options.states[state || 'normal'] || {}), markerOptions = (defaultPlotOptions[series.type].marker && series.options.marker), normalDisabled = (markerOptions && markerOptions.enabled === false), markerStateOptions = ((markerOptions && markerOptions.states && markerOptions.states[state || 'normal']) || {}), stateDisabled = markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, halo = series.halo, haloOptions, markerAttribs, pointAttribs, pointAttribsAnimation, hasMarkers = (markerOptions && series.markerAttribs), newSymbol; state = state || ''; // empty string if ( // already has this state (state === point.state && !move) || // selected points don't respond to hover (point.selected && state !== 'select') || // series' state options is disabled (stateOptions.enabled === false) || // general point marker's state options is disabled (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) || // individual point marker's state options is disabled (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610 ) { return; } point.state = state; if (hasMarkers) { markerAttribs = series.markerAttribs(point, state); } // Apply hover styles to the existing point if (point.graphic) { if (previousState) { point.graphic.removeClass('highcharts-point-' + previousState); } if (state) { point.graphic.addClass('highcharts-point-' + state); } if (!chart.styledMode) { pointAttribs = series.pointAttribs(point, state); pointAttribsAnimation = pick(chart.options.chart.animation, stateOptions.animation); // Some inactive points (e.g. slices in pie) should apply // oppacity also for it's labels if (series.options.inactiveOtherPoints) { (point.dataLabels || []).forEach(function (label) { if (label) { label.animate({ opacity: pointAttribs.opacity }, pointAttribsAnimation); } }); if (point.connector) { point.connector.animate({ opacity: pointAttribs.opacity }, pointAttribsAnimation); } } point.graphic.animate(pointAttribs, pointAttribsAnimation); } if (markerAttribs) { point.graphic.animate(markerAttribs, pick( // Turn off globally: chart.options.chart.animation, markerStateOptions.animation, markerOptions.animation)); } // Zooming in from a range with no markers to a range with markers if (stateMarkerGraphic) { stateMarkerGraphic.hide(); } } else { // if a graphic is not applied to each point in the normal state, // create a shared graphic for the hover state if (state && markerStateOptions) { newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw // away the state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (markerAttribs) { if (!stateMarkerGraphic) { if (newSymbol) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer .symbol(newSymbol, markerAttribs.x, markerAttribs.y, markerAttribs.width, markerAttribs.height) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; } // Move the existing graphic } else { stateMarkerGraphic[move ? 'animate' : 'attr']({ x: markerAttribs.x, y: markerAttribs.y }); } } if (!chart.styledMode && stateMarkerGraphic) { stateMarkerGraphic.attr(series.pointAttribs(point, state)); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && point.isInside ? 'show' : 'hide'](); // #2450 stateMarkerGraphic.element.point = point; // #4310 } } // Show me your halo haloOptions = stateOptions.halo; var markerGraphic = (point.graphic || stateMarkerGraphic); var markerVisibility = (markerGraphic && markerGraphic.visibility || 'inherit'); if (haloOptions && haloOptions.size && markerGraphic && markerVisibility !== 'hidden' && !point.isCluster) { if (!halo) { series.halo = halo = chart.renderer.path() // #5818, #5903, #6705 .add(markerGraphic.parentGroup); } halo.show()[move ? 'animate' : 'attr']({ d: point.haloPath(haloOptions.size) }); halo.attr({ 'class': 'highcharts-halo highcharts-color-' + pick(point.colorIndex, series.colorIndex) + (point.className ? ' ' + point.className : ''), 'visibility': markerVisibility, 'zIndex': -1 // #4929, #8276 }); halo.point = point; // #6055 if (!chart.styledMode) { halo.attr(extend({ 'fill': point.color || series.color, 'fill-opacity': haloOptions.opacity }, haloOptions.attributes)); } } else if (halo && halo.point && halo.point.haloPath) { // Animate back to 0 on the current halo point (#6055) halo.animate({ d: halo.point.haloPath(0) }, null, // Hide after unhovering. The `complete` callback runs in the // halo's context (#7681). halo.hide); } fireEvent(point, 'afterSetState'); }, /** * Get the path definition for the halo, which is usually a shadow-like * circle around the currently hovered point. * * @function Highcharts.Point#haloPath * * @param {number} size * The radius of the circular halo. * * @return {Highcharts.SVGElement} * The path definition. */ haloPath: function (size) { var series = this.series, chart = series.chart; return chart.renderer.symbols.circle(Math.floor(this.plotX) - size, this.plotY - size, size * 2, size * 2); } }); // Extend the Series object with interaction extend(Series.prototype, /** @lends Highcharts.Series.prototype */ { /** * Runs on mouse over the series graphical items. * * @function Highcharts.Series#onMouseOver * @fires Highcharts.Series#event:mouseOver */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState('hover'); /** * Contains the original hovered series. * * @name Highcharts.Chart#hoverSeries * @type {Highcharts.Series|null} */ chart.hoverSeries = series; }, /** * Runs on mouse out of the series graphical items. * * @function Highcharts.Series#onMouseOut * * @fires Highcharts.Series#event:mouseOut */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // #182, set to null before the mouseOut event fires chart.hoverSeries = null; // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !series.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // Reset all inactive states chart.series.forEach(function (s) { s.setState('', true); }); }, /** * Set the state of the series. Called internally on mouse interaction * operations, but it can also be called directly to visually * highlight a series. * * @function Highcharts.Series#setState * * @param {Highcharts.SeriesStateValue|""} [state] * The new state, can be either `'hover'`, `'inactive'`, `'select'`, * or `''` (an empty string), `'normal'` or `undefined` to set to * normal state. * @param {boolean} [inherit] * Determines if state should be inherited by points too. */ setState: function (state, inherit) { var series = this, options = series.options, graph = series.graph, inactiveOtherPoints = options.inactiveOtherPoints, stateOptions = options.states, lineWidth = options.lineWidth, opacity = options.opacity, // By default a quick animation to hover/inactive, // slower to un-hover stateAnimation = pick((stateOptions[state || 'normal'] && stateOptions[state || 'normal'].animation), series.chart.options.chart.animation), attribs, i = 0; state = state || ''; if (series.state !== state) { // Toggle class names [ series.group, series.markerGroup, series.dataLabelsGroup ].forEach(function (group) { if (group) { // Old state if (series.state) { group.removeClass('highcharts-series-' + series.state); } // New state if (state) { group.addClass('highcharts-series-' + state); } } }); series.state = state; if (!series.chart.styledMode) { if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = (stateOptions[state].lineWidth || lineWidth + (stateOptions[state].lineWidthPlus || 0)); // #4035 opacity = pick(stateOptions[state].opacity, opacity); } if (graph && !graph.dashstyle) { attribs = { 'stroke-width': lineWidth }; // Animate the graph stroke-width. graph.animate(attribs, stateAnimation); while (series['zone-graph-' + i]) { series['zone-graph-' + i].attr(attribs); i = i + 1; } } // For some types (pie, networkgraph, sankey) opacity is // resolved on a point level if (!inactiveOtherPoints) { [ series.group, series.markerGroup, series.dataLabelsGroup, series.labelBySeries ].forEach(function (group) { if (group) { group.animate({ opacity: opacity }, stateAnimation); } }); } } } // Don't loop over points on a series that doesn't apply inactive state // to siblings markers (e.g. line, column) if (inherit && inactiveOtherPoints && series.points) { series.setAllPointsToState(state); } }, /** * Set the state for all points in the series. * * @function Highcharts.Series#setAllPointsToState * * @private * * @param {string} [state] * Can be either `hover` or undefined to set to normal state. */ setAllPointsToState: function (state) { this.points.forEach(function (point) { if (point.setState) { point.setState(state); } }); }, /** * Show or hide the series. * * @function Highcharts.Series#setVisible * * @param {boolean} [visible] * True to show the series, false to hide. If undefined, the visibility is * toggled. * * @param {boolean} [redraw=true] * Whether to redraw the chart after the series is altered. If doing more * operations on the chart, it is a good idea to set redraw to false and * call {@link Chart#redraw|chart.redraw()} after. * * @fires Highcharts.Series#event:hide * @fires Highcharts.Series#event:show */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.options.visible = series.userOptions.visible = typeof vis === 'undefined' ? !oldVisibility : vis; // #5618 showOrHide = vis ? 'show' : 'hide'; // show or hide elements [ 'group', 'dataLabelsGroup', 'markerGroup', 'tracker', 'tt' ].forEach(function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { chart.series.forEach(function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series series.linkedSeries.forEach(function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } fireEvent(series, showOrHide); if (redraw !== false) { chart.redraw(); } }, /** * Show the series if hidden. * * @sample highcharts/members/series-hide/ * Toggle visibility from a button * * @function Highcharts.Series#show * @fires Highcharts.Series#event:show */ show: function () { this.setVisible(true); }, /** * Hide the series if visible. If the * [chart.ignoreHiddenSeries](https://api.highcharts.com/highcharts/chart.ignoreHiddenSeries) * option is true, the chart is redrawn without this series. * * @sample highcharts/members/series-hide/ * Toggle visibility from a button * * @function Highcharts.Series#hide * @fires Highcharts.Series#event:hide */ hide: function () { this.setVisible(false); }, /** * Select or unselect the series. This means its * {@link Highcharts.Series.selected|selected} * property is set, the checkbox in the legend is toggled and when selected, * the series is returned by the {@link Highcharts.Chart#getSelectedSeries} * function. * * @sample highcharts/members/series-select/ * Select a series from a button * * @function Highcharts.Series#select * * @param {boolean} [selected] * True to select the series, false to unselect. If undefined, the selection * state is toggled. * * @fires Highcharts.Series#event:select * @fires Highcharts.Series#event:unselect */ select: function (selected) { var series = this; series.selected = selected = this.options.selected = (typeof selected === 'undefined' ? !series.selected : selected); if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, /** * @private * @borrows Highcharts.TrackerMixin.drawTrackerGraph as Highcharts.Series#drawTracker */ drawTracker: TrackerMixin.drawTrackerGraph });
generalludd/expenses
js/highcharts/es-modules/parts/Interaction.js
JavaScript
mit
47,404
/* * ##### Sasson - advanced drupal theming. ##### * * SITENAME scripts. * */ (function($) { // DUPLICATE AND UNCOMMENT // Drupal.behaviors.behaviorName = { // attach: function(context) { // // Do some magic... // } // }; })(jQuery);
farald/pingvin
sites/all/themes/sasson/SUBTHEME/scripts/script.js
JavaScript
gpl-2.0
252
/* * jQuery The Final Countdown plugin v1.0.0 beta * http://github.com/hilios/jquery.countdown * * Copyright (c) 2011 Edson Hilios * * 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. */ (function($) { $.fn.countdown = function(toDate, callback) { var handlers = ['seconds', 'minutes', 'hours', 'days', 'weeks', 'daysLeft']; function delegate(scope, method) { return function() { return method.call(scope) } } return this.each(function() { // Convert var $this = $(this), values = {}, lasting = {}, interval = $this.data('countdownInterval'), secondsLeft = Math.floor((toDate - upcoming_data.c_time) ); function triggerEvents() { secondsLeft--; if(secondsLeft < 0) { secondsLeft = 0; } lasting = { seconds : secondsLeft % 60, minutes : Math.floor(secondsLeft / 60) % 60, hours : Math.floor(secondsLeft / 60 / 60) % 24, days : Math.floor(secondsLeft / 60 / 60 / 24), weeks : Math.floor(secondsLeft / 60 / 60 / 24 / 7), daysLeft: Math.floor(secondsLeft / 60 / 60 / 24) % 7 } for(var i=0; i<handlers.length; i++) { var eventName = handlers[i]; if(values[eventName] != lasting[eventName]) { values[eventName] = lasting[eventName]; dispatchEvent(eventName); } } if(secondsLeft == 0) { stop(); dispatchEvent('finished'); } } triggerEvents(); function dispatchEvent(eventName) { var event = $.Event(eventName); event.date = new Date(new Date().valueOf() + secondsLeft); event.value = values[eventName] || "0"; event.toDate = toDate; event.lasting = lasting; switch(eventName) { case "seconds": case "minutes": case "hours": event.value = event.value < 10 ? '0'+event.value.toString() : event.value.toString(); break; default: if(event.value) { event.value = event.value.toString(); } break; } callback.call($this, event); } $this.bind('remove', function() { stop(); // If the selector is removed clear the interval for memory sake! dispatchEvent('removed'); }); function stop() { clearInterval(interval); } function start() { $this.data('countdownInterval', setInterval(delegate($this, triggerEvents), 1000)); interval = $this.data('countdownInterval'); } if(interval) stop(); start(); }); } // Wrap the remove method to trigger an event when called var removeEvent = new $.Event('remove'), removeFunction = $.fn.remove; $.fn.remove = function() { $(this).trigger(removeEvent); return removeFunction.apply(this, arguments); } })(jQuery);
medisend/wp-production
wp-content/themes/NativeChurch/plugins/countdown/js/jquery.countdown.min.js
JavaScript
gpl-2.0
4,054
var findPosts; (function($){ findPosts = { open : function(af_name, af_val) { var st = document.documentElement.scrollTop || $(document).scrollTop(); if ( af_name && af_val ) { $('#affected').attr('name', af_name).val(af_val); } $('#find-posts').show().draggable({ handle: '#find-posts-head' }).css({'top':st + 50 + 'px','left':'50%','marginLeft':'-250px'}); $('#find-posts-input').focus().keyup(function(e){ if (e.which == 27) { findPosts.close(); } // close on Escape }); return false; }, close : function() { $('#find-posts-response').html(''); $('#find-posts').draggable('destroy').hide(); }, send : function() { var post = { ps: $('#find-posts-input').val(), action: 'find_posts', _ajax_nonce: $('#_ajax_nonce').val(), post_type: $('input[name="find-posts-what"]:checked').val() }; $.ajax({ type : 'POST', url : ajaxurl, data : post, success : function(x) { findPosts.show(x); }, error : function(r) { findPosts.error(r); } }); }, show : function(x) { if ( typeof(x) == 'string' ) { this.error({'responseText': x}); return; } var r = wpAjax.parseAjaxResponse(x); if ( r.errors ) { this.error({'responseText': wpAjax.broken}); } r = r.responses[0]; $('#find-posts-response').html(r.data); }, error : function(r) { var er = r.statusText; if ( r.responseText ) { er = r.responseText.replace( /<.[^<>]*?>/g, '' ); } if ( er ) { $('#find-posts-response').html(er); } } }; $(document).ready(function() { $('#find-posts-submit').click(function(e) { if ( '' == $('#find-posts-response').html() ) e.preventDefault(); }); $( '#find-posts .find-box-search :input' ).keypress( function( event ) { if ( 13 == event.which ) { findPosts.send(); return false; } } ); $( '#find-posts-search' ).click( findPosts.send ); $( '#find-posts-close' ).click( findPosts.close ); $('#doaction, #doaction2').click(function(e){ $('select[name^="action"]').each(function(){ if ( $(this).val() == 'attach' ) { e.preventDefault(); findPosts.open(); } }); }); }); })(jQuery);
shaonsikdar/Wishmagnet
wp-admin/js/media.dev.js
JavaScript
gpl-2.0
2,287
/***** Ajax login script ******/ var $ = jQuery; $(document).ready(function(){ $('#king-form>.btn-login').click(function(){ $('#king-form p.status').show().text(ajax_user_object.loadingmessage); $.ajax({ url: ajax_user_object.ajaxurl, data: $('#king-form').serialize(), type: 'POST', dataType: 'json', success: function(response){ $('#king-form p.status').show().text(response.message); if (response.loggedin == true){ document.location.href = ajax_user_object.redirecturl; } } }); }); $('#king-form>.btn-resetpwd').click(function(){ $('#king-form p.status').show().text(ajax_user_object.loadingmessage); $.ajax({ url: ajax_user_object.ajaxurl, data: $('#king-form').serialize(), type: 'POST', dataType: 'json', success: function(response){ $('#king-form p.status').show().text(response.message); if(response.status){ $('input[name="email"]').val(''); } } }); }); $('#king_form>.btn-register').click(function(){ $('#king_form p.status').show().text(ajax_user_object.loadingmessage); $.ajax({ url: ajax_user_object.ajaxurl, data: $('#king_form').serialize(), type: 'POST', dataType: 'json', success: function(response){ $('#king_form p.status').show().text(response.message); if (response.loggedin == true){ document.location.href = ajax_user_object.redirecturl; } } }); }); });
pivotlearning/wpsite
wp-content/themes/linstar/assets/js/king.user.js
JavaScript
gpl-2.0
1,502
๏ปฟ/** @constructor */ function RecordSet(f) { /** @function */ this.write = f; } /* [ { symbols: [ { doc: { tags: [] }, returns: [], type: "", properties: [], isa: "CONSTRUCTOR", desc: "", alias: "RecordSet", memberof: "", params: [ { title: "param", desc: "", type: "", name: "f", isOptional: false } ], methods: [ { name: "write", alias: "RecordSet.write" } ], name: "RecordSet" }, { doc: { tags: [] }, returns: [], type: "", properties: [], isa: "FUNCTION", desc: "", alias: "RecordSet.write", memberof: "RecordSet", params: [], methods: [], name: "write" } ], overview: { doc: { tags: [] }, returns: [], type: "", properties: [], isa: "FILE", desc: "No overview provided.", alias: "examples/data/properties_methods1.js", memberof: "", params: [], methods: [], name: "examples/data/properties_methods1.js" } } ] */
sdondley/timeline
similie_timeline/tools/jsdoc/examples/data/properties_methods1.js
JavaScript
gpl-2.0
1,435
var namespace_a_e_mmailer = [ [ "AEMMailer", "d5/d12/class_a_e_mmailer_1_1_a_e_m_mailer.html", "d5/d12/class_a_e_mmailer_1_1_a_e_m_mailer" ], [ "Error", "dc/d02/class_a_e_mmailer_1_1_error.html", null ], [ "MissingEmailAccountsException", "d9/d2a/class_a_e_mmailer_1_1_missing_email_accounts_exception.html", null ], [ "NoPasswordException", "d1/d47/class_a_e_mmailer_1_1_no_password_exception.html", null ] ];
gratefulfrog/SPI
RPI/Python/serialApp/DOC/Dox/html/d0/d90/namespace_a_e_mmailer.js
JavaScript
gpl-3.0
426
var EA_keys = {8:"Retour arriere",9:"Tabulation",12:"Milieu (pave numerique)",13:"Entrer",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"Verr Maj",27:"Esc",32:"Espace",33:"Page up",34:"Page down",35:"End",36:"Begin",37:"Fleche gauche",38:"Fleche haut",39:"Fleche droite",40:"Fleche bas",44:"Impr ecran",45:"Inser",46:"Suppr",91:"Menu Demarrer Windows / touche pomme Mac",92:"Menu Demarrer Windows",93:"Menu contextuel Windows",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"Verr Num",145:"Arret defil"}; function keyDown(e){ if(!e){ // if IE e=event; } // send the event to the plugins for(var i in editArea.plugins){ if(typeof(editArea.plugins[i].onkeydown)=="function"){ if(editArea.plugins[i].onkeydown(e)===false){ // stop propaging if(editArea.nav['isIE']) e.keyCode=0; return false; } } } var target_id=(e.target || e.srcElement).id; var use=false; if (EA_keys[e.keyCode]) letter=EA_keys[e.keyCode]; else letter=String.fromCharCode(e.keyCode); var low_letter= letter.toLowerCase(); if(letter=="Page up" && !editArea.nav['isOpera']){ editArea.execCommand("scroll_page", {"dir": "up", "shift": ShiftPressed(e)}); use=true; }else if(letter=="Page down" && !editArea.nav['isOpera']){ editArea.execCommand("scroll_page", {"dir": "down", "shift": ShiftPressed(e)}); use=true; }else if(editArea.is_editable==false){ // do nothing but also do nothing else (allow to navigate with page up and page down) return true; }else if(letter=="Tabulation" && target_id=="textarea" && !CtrlPressed(e) && !AltPressed(e)){ if(ShiftPressed(e)) editArea.execCommand("invert_tab_selection"); else editArea.execCommand("tab_selection"); use=true; if(editArea.nav['isOpera'] || (editArea.nav['isFirefox'] && editArea.nav['isMacOS']) ) // opera && firefox mac can't cancel tabulation events... setTimeout("editArea.execCommand('focus');", 1); }else if(letter=="Entrer" && target_id=="textarea"){ if(editArea.press_enter()) use=true; }else if(letter=="Entrer" && target_id=="area_search"){ editArea.execCommand("area_search"); use=true; }else if(letter=="Esc"){ editArea.execCommand("close_all_inline_popup", e); use=true; }else if(CtrlPressed(e) && !AltPressed(e) && !ShiftPressed(e)){ switch(low_letter){ case "f": editArea.execCommand("area_search"); use=true; break; case "r": editArea.execCommand("area_replace"); use=true; break; case "q": editArea.execCommand("close_all_inline_popup", e); use=true; break; case "h": editArea.execCommand("change_highlight"); use=true; break; case "g": setTimeout("editArea.execCommand('go_to_line');", 5); // the prompt stop the return false otherwise use=true; break; case "e": editArea.execCommand("show_help"); use=true; break; case "z": use=true; editArea.execCommand("undo"); break; case "y": use=true; editArea.execCommand("redo"); break; default: break; } } // check to disable the redo possibility if the textarea content change if(editArea.next.length > 0){ setTimeout("editArea.check_redo();", 10); } setTimeout("editArea.check_file_changes();", 10); if(use){ // in case of a control that sould'nt be used by IE but that is used => THROW a javascript error that will stop key action if(editArea.nav['isIE']) e.keyCode=0; return false; } //alert("Test: "+ letter + " ("+e.keyCode+") ALT: "+ AltPressed(e) + " CTRL "+ CtrlPressed(e) + " SHIFT "+ ShiftPressed(e)); return true; }; // return true if Alt key is pressed function AltPressed(e) { if (window.event) { return (window.event.altKey); } else { if(e.modifiers) return (e.altKey || (e.modifiers % 2)); else return e.altKey; } }; // return true if Ctrl key is pressed function CtrlPressed(e) { if (window.event) { return (window.event.ctrlKey); } else { return (e.ctrlKey || (e.modifiers==2) || (e.modifiers==3) || (e.modifiers>5)); } }; // return true if Shift key is pressed function ShiftPressed(e) { if (window.event) { return (window.event.shiftKey); } else { return (e.shiftKey || (e.modifiers>3)); } };
4n6g4/gtsdm
malra/fo/main/lib/editarea/edit_area/keyboard.js
JavaScript
gpl-3.0
4,425
/* YUI 3.9.0pr1 (build 202) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */ YUI.add('pjax-content', function (Y, NAME) { /** `Y.Router` extension that provides the content fetching and handling needed to implement the standard pjax (HTMP5 pushState + Ajax) functionality. @module pjax @submodule pjax-content @since 3.7.0 **/ /** `Y.Router` extension that provides the content fetching and handling needed to implement the standard pjax (HTMP5 pushState + Ajax) functionality. This makes it easy to fetch server rendered content for URLs using Ajax. By helping the router to fulfill the "request" for the content you can avoid full page loads. The `PjaxContent` class isn't useful on its own, but can be mixed into a `Router`-based class along with the `PjaxBase` class to add Pjax functionality to that Router. For a pre-made standalone Pjax router, see the `Pjax` class. var MyRouter = Y.Base.create('myRouter', Y.Router, [ Y.PjaxBase, Y.PjaxContent ], { // ... }); @class PjaxContent @extensionfor Router @since 3.7.0 **/ function PjaxContent() {} PjaxContent.prototype = { // -- Public Methods ------------------------------------------------------- /** Extracts and returns the relevant HTML content from an Ajax response. The content is extracted using the `contentSelector` attribute as a CSS selector. If `contentSelector` is `null`, the entire response will be returned. The return value is an object containing two properties: * `node`: A `Y.Node` instance for a document fragment containing the extracted HTML content. * `title`: The title of the HTML page, if any, extracted using the `titleSelector` attribute (which defaults to looking for a `<title>` element). If `titleSelector` is not set or if a title could not be found, this property will be `undefined`. @method getContent @param {String} responseText Raw Ajax response text. @return {Object} Content object with the properties described above. @since 3.5.0 **/ getContent: function (responseText) { var content = {}, contentSelector = this.get('contentSelector'), frag = Y.Node.create(responseText || ''), titleSelector = this.get('titleSelector'), titleNode; if (contentSelector && frag) { content.node = frag.all(contentSelector).toFrag(); } else { content.node = frag; } if (titleSelector && frag) { titleNode = frag.one(titleSelector); if (titleNode) { content.title = titleNode.get('text'); } } return content; }, /** Pjax route middleware to load content from a server. This makes an Ajax request for the requested URL, parses the returned content and puts it on the route's response object. This is route middleware and not intended to be the final callback for a route. This will add the following information to the route's request and response objects: - `req.ioURL`: The full URL that was used to make the `Y.io()` XHR. This may contain `"pjax=1"` if the `addPjaxParam` option is set. - `res.content`: An object containing `node` and `title` properties for the content extracted from the server's response. See `getContent()` for more details. - `res.ioResponse`: The full `Y.io()` response object. This is useful if you need access to the XHR's response `status` or HTTP headers. @example router.route('/foo/', 'loadContent', function (req, res, next) { Y.one('container').setHTML(res.content.node); Y.config.doc.title = res.content.title; }); @method loadContent @param {Object} req Request object. @param {Object} res Response Object. @param {Function} next Function to pass control to the next route callback. @since 3.7.0 @see Router.route() **/ loadContent: function (req, res, next) { var url = req.url; // If there's an outstanding request, abort it. if (this._request) { this._request.abort(); } // Add a 'pjax=1' query parameter if enabled. if (this.get('addPjaxParam')) { // Captures the path with query, and hash parts of the URL. Then // properly injects the "pjax=1" query param in the right place, // before any hash fragment, and returns the updated URL. url = url.replace(/([^#]*)(#.*)?$/, function (match, path, hash) { path += (path.indexOf('?') > -1 ? '&' : '?') + 'pjax=1'; return path + (hash || ''); }); } // Send a request. this._request = Y.io(url, { 'arguments': { route: { req : req, res : res, next: next }, url: url }, context: this, headers: {'X-PJAX': 'true'}, timeout: this.get('timeout'), on: { complete: this._onPjaxIOComplete, end : this._onPjaxIOEnd } }); }, // -- Event Handlers ------------------------------------------------------- /** Handles IO complete events. This parses the content from the `Y.io()` response and puts it on the route's response object. @method _onPjaxIOComplete @param {String} id The `Y.io` transaction id. @param {Object} ioResponse The `Y.io` response object. @param {Object} details Extra details carried through from `loadContent()`. @protected @since 3.7.0 **/ _onPjaxIOComplete: function (id, ioResponse, details) { var content = this.getContent(ioResponse.responseText), route = details.route, req = route.req, res = route.res; // Put the URL requested through `Y.io` on the route's `req` object. req.ioURL = details.url; // Put the parsed content and `Y.io` response object on the route's // `res` object. res.content = content; res.ioResponse = ioResponse; route.next(); }, /** Handles IO end events. @method _onPjaxIOEnd @param {String} id The `Y.io` transaction id. @param {Object} details Extra details carried through from `loadContent()`. @protected @since 3.5.0 **/ _onPjaxIOEnd: function () { this._request = null; } }; PjaxContent.ATTRS = { /** If `true`, a "pjax=1" query parameter will be appended to all URLs requested via Pjax. Browsers ignore HTTP request headers when caching content, so if the same URL is used to request a partial Pjax page and a full page, the browser will cache them under the same key and may later load the cached partial page when the user actually requests a full page (or vice versa). To prevent this, we can add a bogus query parameter to the URL so that Pjax URLs will always be cached separately from non-Pjax URLs. @attribute addPjaxParam @type Boolean @default true @since 3.5.0 **/ addPjaxParam: { value: true }, /** CSS selector used to extract a specific portion of the content of a page loaded via Pjax. For example, if you wanted to load the page `example.html` but only use the content within an element with the id "pjax-content", you'd set `contentSelector` to "#pjax-content". If not set, the entire page will be used. @attribute contentSelector @type String @default null @since 3.5.0 **/ contentSelector: { value: null }, /** CSS selector used to extract a page title from the content of a page loaded via Pjax. By default this is set to extract the title from the `<title>` element, but you could customize it to extract the title from an `<h1>`, or from any other element, if that's more appropriate for the content you're loading. @attribute titleSelector @type String @default "title" @since 3.5.0 **/ titleSelector: { value: 'title' }, /** Time in milliseconds after which an Ajax request should time out. @attribute timeout @type Number @default 30000 @since 3.5.0 **/ timeout: { value: 30000 } }; Y.PjaxContent = PjaxContent; }, '3.9.0pr1', {"requires": ["io-base", "node-base", "router"]});
rochestb/Adventurly
node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/pjax-content/pjax-content.js
JavaScript
gpl-3.0
8,651
'use strict'; var async = require('async'); var validator = require('validator'); var _ = require('underscore'); var db = require('../database'); var topics = require('../topics'); var user = require('../user'); var privileges = require('../privileges'); var plugins = require('../plugins'); var cache = require('./cache'); var pubsub = require('../pubsub'); var utils = require('../../public/src/utils'); module.exports = function (Posts) { pubsub.on('post:edit', function (pid) { cache.del(pid); }); Posts.edit = function (data, callback) { var postData; var results; async.waterfall([ function (next) { privileges.posts.canEdit(data.pid, data.uid, next); }, function (canEdit, next) { if (!canEdit.flag) { return next(new Error(canEdit.message)); } Posts.getPostData(data.pid, next); }, function (_postData, next) { if (!_postData) { return next(new Error('[[error:no-post]]')); } postData = _postData; postData.content = data.content; postData.edited = Date.now(); postData.editor = data.uid; if (data.handle) { postData.handle = data.handle; } plugins.fireHook('filter:post.edit', {req: data.req, post: postData, data: data, uid: data.uid}, next); }, function (result, next) { postData = result.post; Posts.setPostFields(data.pid, postData, next); }, function (next) { async.parallel({ editor: function (next) { user.getUserFields(data.uid, ['username', 'userslug'], next); }, topic: function (next) { editMainPost(data, postData, next); } }, next); }, function (_results, next) { results = _results; postData.cid = results.topic.cid; postData.topic = results.topic; plugins.fireHook('action:post.edit', _.clone(postData)); cache.del(String(postData.pid)); pubsub.publish('post:edit', String(postData.pid)); Posts.parsePost(postData, next); }, function (postData, next) { results.post = postData; next(null, results); } ], callback); }; function editMainPost(data, postData, callback) { var tid = postData.tid; var title = data.title ? data.title.trim() : ''; async.parallel({ topic: function (next) { topics.getTopicFields(tid, ['cid', 'title'], next); }, isMain: function (next) { Posts.isMain(data.pid, next); } }, function (err, results) { if (err) { return callback(err); } if (!results.isMain) { return callback(null, { tid: tid, cid: results.topic.cid, isMainPost: false, renamed: false }); } var topicData = { tid: tid, cid: results.topic.cid, uid: postData.uid, mainPid: data.pid }; if (title) { topicData.title = title; topicData.slug = tid + '/' + (utils.slugify(title) || 'topic'); } topicData.thumb = data.thumb || ''; data.tags = data.tags || []; async.waterfall([ function (next) { plugins.fireHook('filter:topic.edit', {req: data.req, topic: topicData, data: data}, next); }, function (results, next) { db.setObject('topic:' + tid, results.topic, next); }, function (next) { topics.updateTags(tid, data.tags, next); }, function (next) { topics.getTopicTagsObjects(tid, next); }, function (tags, next) { topicData.tags = data.tags; topicData.oldTitle = results.topic.title; plugins.fireHook('action:topic.edit', topicData); next(null, { tid: tid, cid: results.topic.cid, uid: postData.uid, title: validator.escape(String(title)), oldTitle: results.topic.title, slug: topicData.slug, isMainPost: true, renamed: title !== results.topic.title, tags: tags }); } ], callback); }); } };
sweetpi/NodeBB
src/posts/edit.js
JavaScript
gpl-3.0
3,791
/* * Copyright (c) 2011-2013 Lp digital system * * This file is part of BackBee. * * BackBee is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BackBee is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BackBee. If not, see <http://www.gnu.org/licenses/>. */ require.config({ paths: { 'app.content': 'src/tb/apps/content', //Controllers 'content.main.controller': 'src/tb/apps/content/controllers/main.controller', //Routing 'content.routes': 'src/tb/apps/content/routes', //Repositories 'content.repository': 'src/tb/apps/content/repository/content.repository', 'revision.repository': 'src/tb/apps/content/repository/revision.repository', 'resource.repository': 'src/tb/apps/content/repository/resource.repository', 'keyword.repository': 'src/tb/apps/content/repository/keyword.repository', 'crop.repository': 'src/tb/apps/content/repository/crop.repository', //DataStore 'media.datastore': 'src/tb/component/medialibrary/datastore/media.datastore', //Components 'content.manager': 'src/tb/apps/content/components/ContentManager', 'content.dnd.manager': 'src/tb/apps/content/components/DndManager', 'content.mouseevent.manager': 'src/tb/apps/content/components/MouseEventManager', 'content.save.manager': 'src/tb/apps/content/components/SaveManager', 'content.container': 'src/tb/apps/content/components/ContentContainer', 'definition.manager': 'src/tb/apps/content/components/DefinitionManager', 'content.breadcrumb': 'src/tb/apps/content/components/Breadcrumb', 'content.pluginmanager': 'src/tb/apps/content/components/PluginManager', //Widgets 'content.widget.DialogContentsList': 'src/tb/apps/content/widgets/DialogContentsList', 'content.widget.Breadcrumb': 'src/tb/apps/content/widgets/Breadcrumb', 'content.widget.Edition': 'src/tb/apps/content/widgets/Edition', 'content.widget.DialogAddToMediaLibrary': 'src/tb/apps/content/widgets/DialogAddToMediaLibrary', //Models 'content.models.AbstractContent': 'src/tb/apps/content/models/AbstractContent', 'content.models.Content': 'src/tb/apps/content/models/Content', 'content.models.ContentSet': 'src/tb/apps/content/models/ContentSet', 'content.models.ContentRevision': 'src/tb/apps/content/models/ContentRevision', //Templates 'content/tpl/button': 'src/tb/apps/content/templates/button.twig', 'content/tpl/content_breadcrumb': 'src/tb/apps/content/templates/content-breadcrumb.twig', 'content/tpl/contribution/index': 'src/tb/apps/content/templates/contribution.index.twig', 'content/tpl/edit/contribution/index': 'src/tb/apps/content/templates/edit-contribution.index.twig', 'content/tpl/carousel_blocks': 'src/tb/apps/content/templates/carousel-blocks.twig', 'content/tpl/block_display': 'src/tb/apps/content/templates/block-display.twig', 'content/tpl/dropzone': 'src/tb/apps/content/templates/dropzone.twig', 'content/tpl/content-action': 'src/tb/apps/content/templates/content-action.twig', 'content/tpl/breadcrumb': 'src/tb/apps/content/templates/breadcrumb.twig', 'content/tpl/scrollzone': 'src/tb/apps/content/templates/scrollzone.twig', 'content/tpl/block_description': 'src/tb/apps/content/templates/block-description.twig', 'content/tpl/block_informations': 'src/tb/apps/content/templates/block-informations.twig', 'content/tpl/rollback_items': 'src/tb/apps/content/plugins/rollback/templates/items.twig', //Views 'content.view.contribution.index': 'src/tb/apps/content/views/content.view.contribution.index', 'content.view.edit.contribution.index': 'src/tb/apps/content/views/content.view.edit_contribution.index' } }); define("app.content", ['Core', 'content.pluginmanager'], function (Core) { 'use strict'; Core.ApplicationManager.registerApplication('content', { onInit: function () { Core.ApplicationManager.launchApplication('contribution'); } }); });
backbee/BbCoreJs
src/tb/apps/content/main.js
JavaScript
gpl-3.0
4,642
// Copyright (C) 2015 Leslie Zhai <xiang.zhai@i-soft.com.cn> .pragma library var v2 = false; var isAway = false; var isRobot = false; var uin = ""; var sid = ""; var skey = ""; var ticket = ""; var deviceId = ""; var loginUserName = ""; var loginNickName = ""; var initSyncKey; var syncKey; var initContactList; var wxView; var chatView; function monitorNewMsg() { if (typeof(wxView) != 'undefined') wxView.doNewMsg(); if (typeof(chatView) != 'undefined' && typeof(chatView.doNewMsg) == 'function') chatView.doNewMsg(); }
oxmcvusd/qwx
qml/global.js
JavaScript
gpl-3.0
550
import register from '../../utils/register' import routeHelperConfig from './route-helper.provider' import routeHelper from './route-helper.factory' let registerApp = new register('blocks.router', [ 'ngRoute' ]) registerApp .provider('routeHelperConfig', routeHelperConfig) .factory('routeHelper', routeHelper)
remytms/Distribution
plugin/website/Resources/modules/blocks/router/router.module.js
JavaScript
gpl-3.0
318
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ (function(Mozilla){ 'use strict'; function onLoad() { var browserHelpContent = document.getElementById('browser-help'); var browserHelpIcon = document.getElementById('icon-browser-help'); var installerHelpContent = document.getElementById('installer-help'); var installerHelpIcon = document.querySelectorAll('.icon-installer-help'); function showHelpModal(modalContent, modalTitle, eventLabel) { Mzp.Modal.createModal(this, modalContent, { title: modalTitle, className: 'help-modal' }); window.dataLayer.push({ 'event': 'in-page-interaction', 'eAction': 'link click', 'eLabel': eventLabel }); } Mozilla.FirefoxDownloader.init(); // Browser help modal. browserHelpIcon.addEventListener('click', function(e) { e.preventDefault(); showHelpModal.call(this, browserHelpContent, browserHelpIcon.textContent, 'Get Browser Help'); }, false); // Installer help modal. for (var i = 0; i < installerHelpIcon.length; i++) { installerHelpIcon[i].addEventListener('click', function(e) { e.preventDefault(); showHelpModal.call(this, installerHelpContent, e.target.textContent, 'Get Installer Help'); }, false); } } Mozilla.run(onLoad); })(window.Mozilla);
sgarrity/bedrock
media/js/firefox/all/all-downloads-unified-init.js
JavaScript
mpl-2.0
1,683
import Route from '@ember/routing/route'; export default Route.extend({ beforeModel: function(transition) { if (transition.targetName === this.routeName) { transition.abort(); return this.replaceWith('vault.cluster.settings.mount-secret-backend'); } }, });
quixoten/vault
ui/app/routes/vault/cluster/settings/index.js
JavaScript
mpl-2.0
282
define(['jquery', 'uri', 'base/ui', 'masonry', 'base/login', 'analytics', 'localized', 'jquery-ui.autocomplete'], function ($, URI, UI, Masonry, webmakerAuth, analytics, localized) { var query = $('.search-poster').attr('data-query'), queryKeys = URI.parse(window.location.href).queryKey, $searchPoster = $('.search-poster'), $searchButton = $('.search-btn'), $searchField = $('#search-field'), $searchFilter = $('#search-type'), $forkBtns = $('.make-fork-btn'), $userNameLinks = $('.user-link'), mainGallery = $('.main-gallery')[0], tagSuggestionEnabled = false, searchType = 'all', totalHits, LIMIT, masonry, page; function onKeyDown() { $('html, body').animate({ scrollTop: 0 }, 200); $searchPoster.addClass('focus'); $searchField.off('keydown', onKeyDown); } $searchField.click(function () { $searchField.select(); }); $searchButton.click(function () { var searchInputVal = encodeURIComponent($searchField.val()); analytics.event('Search ' + searchType + ' Clicked', { label: searchInputVal }); }); // Show the big green UI if ($searchPoster.hasClass('focus') && query) { $searchField.val(query.replace(/,/g, ', ')); onKeyDown(); } else { $searchField.on('keydown', onKeyDown); } $searchField.autocomplete({ source: function (request, response) { var term = request.term; if (term === '#') { return response(); } term = term.replace(/(^#)/, ''); var searchUrl = '/api/20130724/make/tags?t=' + term; $.getJSON($('meta[name=\'make-endpoint\']').attr('content') + searchUrl, function (data) { response(data.tags.map(function (item) { return item.term; })); }); }, minLength: 1, delay: 200, select: function (e, ui) { $searchField.val(ui.item.value); $('.search-wrapper').submit(); } }); function likeClickCallback(e) { e.preventDefault(); e.stopPropagation(); var $this = $(this), makeID = $this.data('make-id'), method; if ($this.hasClass('fa-heart')) { method = '/unlike'; } else { method = '/like'; } $.post(method, { makeID: makeID, _csrf: $('meta[name=\'csrf-token\']').attr('content') }, function (res) { var newLen = res.likes.length, $count = $this.parent().parent().find('.like-count'), $text = $this.parent().parent().find('.like-text'); $this.toggleClass('fa-heart fa-heart-o'); $count.html(newLen); if (newLen === 0) { $text.html(localized.get('Like-0')); } else if (newLen === 1) { $text.html(localized.get('Like-1')); } else { $text.html(localized.get('Like-n')); } }).fail(function (res) { if (res.status === 401) { webmakerAuth.login(); } else { // already like/unliked, update UI to reflect. $this.toggleClass('fa-heart fa-heart-o'); } }); } $('.make-like-toggle') .off('click') .on('click', likeClickCallback); function enableTagSuggestion() { $searchField.autocomplete('enable'); tagSuggestionEnabled = true; } function disableTagSuggestion() { $searchField.autocomplete('disable'); tagSuggestionEnabled = false; } if ($searchFilter.find('[name=type]').val() === 'tags') { enableTagSuggestion(); } else { disableTagSuggestion(); } // Setup masonry masonry = new Masonry(mainGallery, { itemSelector: 'div.make', gutter: '.gutter-sizer', transitionDuration: '0.2' }); // Change what kind of search $searchFilter.find('li').click(function () { var $this = $(this); searchType = $this.attr('data-value'); $searchFilter.find('[name=type]').val(searchType); $searchFilter.attr('class', 'search-filter icon-' + searchType); $searchFilter.find('.ui-on').removeClass('ui-on'); $this.addClass('ui-on'); if (!tagSuggestionEnabled && searchType === 'tags') { enableTagSuggestion(); } else if (tagSuggestionEnabled) { disableTagSuggestion(); } }); $forkBtns.click(function (e) { e.stopPropagation(); }); $userNameLinks.click(function (e) { e.stopPropagation(); queryKeys.page = 1; queryKeys.type = 'user'; queryKeys.q = this.getAttribute('data-username'); window.location.search = $.param(queryKeys); }); page = queryKeys.page ? parseInt(queryKeys.page, 10) : 1; if (mainGallery) { totalHits = mainGallery.getAttribute('data-total-hits'); LIMIT = mainGallery.getAttribute('data-limit'); UI.pagination(page, totalHits, LIMIT, function (page) { queryKeys.page = page; if (queryKeys.q) { queryKeys.q = decodeURIComponent(queryKeys.q); } window.location.search = $.param(queryKeys); }); } });
mozilla/webmaker.org
public/js/pages/search.js
JavaScript
mpl-2.0
5,188
SchedulePolicyViewController = BaseViewController.extend( { el: '#schedule_policy_view_container', over_time_policy_api: null, initialize: function() { this._super( 'initialize' ); this.edit_view_tpl = 'SchedulePolicyEditView.html'; this.permission_id = 'schedule_policy'; this.viewId = 'SchedulePolicy'; this.script_name = 'SchedulePolicyView'; this.table_name_key = 'schedule_policy'; this.context_menu_name = $.i18n._( 'Schedule Policy' ); this.navigation_label = $.i18n._( 'Schedule Policy' ) + ':'; this.api = new (APIFactory.getAPIClass( 'APISchedulePolicy' ))(); this.over_time_policy_api = new (APIFactory.getAPIClass( 'APIOvertimePolicy' ))(); this.render(); this.buildContextMenu(); this.initData(); this.setSelectRibbonMenuIfNecessary( 'SchedulePolicy' ); }, buildEditViewUI: function() { this._super( 'buildEditViewUI' ); var $this = this; this.setTabLabels( { 'tab_schedule_policy': $.i18n._( 'Schedule Policy' ), 'tab_audit': $.i18n._( 'Audit' ) } ); this.navigation.AComboBox( { api_class: (APIFactory.getAPIClass( 'APISchedulePolicy' )), id: this.script_name + '_navigation', allow_multiple_selection: false, layout_name: ALayoutIDs.SCHEDULE_POLICY, navigation_mode: true, show_search_inputs: true } ); this.setNavigation(); //Tab 0 start var tab_schedule_policy = this.edit_view_tab.find( '#tab_schedule_policy' ); var tab_schedule_policy_column1 = tab_schedule_policy.find( '.first-column' ); this.edit_view_tabs[0] = []; this.edit_view_tabs[0].push( tab_schedule_policy_column1 ); //Name var form_item_input = Global.loadWidgetByName( FormItemType.TEXT_INPUT ); form_item_input.TTextInput( {field: 'name', width: '100%'} ); this.addEditFieldToColumn( $.i18n._( 'Name' ), form_item_input, tab_schedule_policy_column1, '' ); form_item_input.parent().width( '45%' ); // Description form_item_input = Global.loadWidgetByName( FormItemType.TEXT_AREA ); form_item_input.TTextArea( { field: 'description', width: '100%' } ); this.addEditFieldToColumn( $.i18n._( 'Description' ), form_item_input, tab_schedule_policy_column1, '', null, null, true ); form_item_input.parent().width( '45%' ); //Meal Policy form_item_input = Global.loadWidgetByName( FormItemType.AWESOME_BOX ); form_item_input.AComboBox( { api_class: (APIFactory.getAPIClass( 'APIMealPolicy' )), allow_multiple_selection: true, layout_name: ALayoutIDs.MEAL_POLICY, show_search_inputs: true, set_any: true, field: 'meal_policy', custom_first_label: $.i18n._( '-- No Meal --' ), addition_source_function: this.onMealOrBreakSourceCreate, added_items: [ {value: 0, label: $.i18n._( '-- Defined By Policy Group --' )} ] } ); this.addEditFieldToColumn( $.i18n._( 'Meal Policy' ), form_item_input, tab_schedule_policy_column1 ); //Break Policy form_item_input = Global.loadWidgetByName( FormItemType.AWESOME_BOX ); form_item_input.AComboBox( { api_class: (APIFactory.getAPIClass( 'APIBreakPolicy' )), allow_multiple_selection: true, layout_name: ALayoutIDs.BREAK_POLICY, show_search_inputs: true, set_any: true, field: 'break_policy', custom_first_label: '-- ' + $.i18n._( 'No Break' ) + ' --', addition_source_function: this.onMealOrBreakSourceCreate, added_items: [ {value: 0, label: '-- ' + $.i18n._( 'Defined By Policy Group' ) + ' --'} ] } ); this.addEditFieldToColumn( $.i18n._( 'Break Policy' ), form_item_input, tab_schedule_policy_column1 ); // Regular Time Policy var v_box = $( "<div class='v-box'></div>" ); //Include form_item_input = Global.loadWidgetByName( FormItemType.AWESOME_BOX ); form_item_input.AComboBox( { api_class: (APIFactory.getAPIClass( 'APIRegularTimePolicy' )), allow_multiple_selection: true, layout_name: ALayoutIDs.REGULAR_TIME_POLICY, show_search_inputs: true, set_empty: true, field: 'include_regular_time_policy' } ); var form_item = this.putInputToInsideFormItem( form_item_input, $.i18n._( 'Include' ) ); v_box.append( form_item ); v_box.append( "<div class='clear-both-div'></div>" ); //Exclude var form_item_input_1 = Global.loadWidgetByName( FormItemType.AWESOME_BOX ); form_item_input_1.AComboBox( { api_class: (APIFactory.getAPIClass( 'APIRegularTimePolicy' )), allow_multiple_selection: true, layout_name: ALayoutIDs.REGULAR_TIME_POLICY, show_search_inputs: true, set_empty: true, field: 'exclude_regular_time_policy' } ); form_item = this.putInputToInsideFormItem( form_item_input_1, $.i18n._( 'Exclude' ) ); v_box.append( form_item ); this.addEditFieldToColumn( $.i18n._( 'Regular Time Policy' ), [form_item_input, form_item_input_1], tab_schedule_policy_column1, '', v_box, false, true ); //Overtime Policy v_box = $( "<div class='v-box'></div>" ); var default_args = {}; default_args.filter_data = {}; default_args.filter_data.type_id = [200, 10]; //Include form_item_input = Global.loadWidgetByName( FormItemType.AWESOME_BOX ); form_item_input.AComboBox( { api_class: (APIFactory.getAPIClass( 'APIOvertimePolicy' )), allow_multiple_selection: true, layout_name: ALayoutIDs.OVER_TIME_POLICY, show_search_inputs: true, set_empty: true, field: 'include_over_time_policy' } ); form_item_input.setDefaultArgs( default_args ); form_item = this.putInputToInsideFormItem( form_item_input, $.i18n._( 'Include' ) ); v_box.append( form_item ); v_box.append( "<div class='clear-both-div'></div>" ); //Exclude form_item_input_1 = Global.loadWidgetByName( FormItemType.AWESOME_BOX ); form_item_input_1.AComboBox( { api_class: (APIFactory.getAPIClass( 'APIOvertimePolicy' )), allow_multiple_selection: true, layout_name: ALayoutIDs.OVER_TIME_POLICY, show_search_inputs: true, set_empty: true, field: 'exclude_over_time_policy' } ); form_item_input_1.setDefaultArgs( default_args ); form_item = this.putInputToInsideFormItem( form_item_input_1, $.i18n._( 'Exclude' ) ); v_box.append( form_item ); this.addEditFieldToColumn( $.i18n._( 'Overtime Policy' ), [form_item_input, form_item_input_1], tab_schedule_policy_column1, '', v_box, false, true ); //Premium Policy v_box = $( "<div class='v-box'></div>" ); //Include form_item_input = Global.loadWidgetByName( FormItemType.AWESOME_BOX ); form_item_input.AComboBox( { api_class: (APIFactory.getAPIClass( 'APIPremiumPolicy' )), allow_multiple_selection: true, layout_name: ALayoutIDs.PREMIUM_POLICY, show_search_inputs: true, set_empty: true, field: 'include_premium_policy' } ); form_item = this.putInputToInsideFormItem( form_item_input, $.i18n._( 'Include' ) ); v_box.append( form_item ); v_box.append( "<div class='clear-both-div'></div>" ); //Exclude form_item_input_1 = Global.loadWidgetByName( FormItemType.AWESOME_BOX ); form_item_input_1.AComboBox( { api_class: (APIFactory.getAPIClass( 'APIPremiumPolicy' )), allow_multiple_selection: true, layout_name: ALayoutIDs.PREMIUM_POLICY, show_search_inputs: true, set_empty: true, field: 'exclude_premium_policy' } ); form_item = this.putInputToInsideFormItem( form_item_input_1, $.i18n._( 'Exclude' ) ); v_box.append( form_item ); this.addEditFieldToColumn( $.i18n._( 'Premium Policy' ), [form_item_input, form_item_input_1], tab_schedule_policy_column1, '', v_box, false, true ); //Undertime Absence Policy form_item_input = Global.loadWidgetByName( FormItemType.AWESOME_BOX ); form_item_input.AComboBox( { api_class: (APIFactory.getAPIClass( 'APIAbsencePolicy' )), allow_multiple_selection: false, layout_name: ALayoutIDs.ABSENCES_POLICY, show_search_inputs: true, set_empty: true, field: 'absence_policy_id' } ); this.addEditFieldToColumn( $.i18n._( 'Undertime Absence Policy' ), form_item_input, tab_schedule_policy_column1 ); //Start / Stop Window form_item_input = Global.loadWidgetByName( FormItemType.TEXT_INPUT ); form_item_input.TTextInput( {field: 'start_stop_window', width: 50, need_parser_sec: true} ); var widgetContainer = $( "<div class='widget-h-box'></div>" ); var label = $( "<span class='widget-right-label'> (" + $.i18n._( 'ie' ) + ' : ' + LocalCacheData.getLoginUserPreference().time_unit_format_display + ")</span>" ); widgetContainer.append( form_item_input ); widgetContainer.append( label ); this.addEditFieldToColumn( $.i18n._( 'Start / Stop Window' ), form_item_input, tab_schedule_policy_column1, '', widgetContainer ); }, onMealOrBreakSourceCreate: function( target, source_data ) { var display_columns = target.getDisplayColumns(); var first_item = {}; $.each( display_columns, function( index, content ) { first_item.id = 0; first_item[content.name] = $.i18n._( '-- Defined By Policy Group --' ); return false; } ); source_data.unshift( first_item ); return source_data; }, setCurrentEditRecordData: function() { //Set current edit record data to all widgets for ( var key in this.current_edit_record ) { if ( !this.current_edit_record.hasOwnProperty( key ) ) { continue; } var widget = this.edit_view_ui_dic[key]; if ( Global.isSet( widget ) ) { switch ( key ) { case 'country': //popular case this.eSetProvince( this.current_edit_record[key] ); widget.setValue( this.current_edit_record[key] ); break; default: widget.setValue( this.current_edit_record[key] ); break; } } } this.collectUIDataToCurrentEditRecord(); this.setEditViewDataDone(); }, onFormItemChange: function( target, doNotValidate ) { this.setIsChanged( target ); this.setMassEditingFieldsWhenFormChange( target ); var key = target.getField(); var c_value = target.getValue(); // switch ( key ) { // case 'start_stop_window': // c_value = this.date_api.parseTimeUnit( target.getValue(), {async: false} ).getResult(); // break; // } this.current_edit_record[key] = c_value; if ( !doNotValidate ) { this.validate(); } }, buildSearchFields: function() { this._super( 'buildSearchFields' ); this.search_fields = [ new SearchField( {label: $.i18n._( 'Name' ), in_column: 1, field: 'name', multiple: true, basic_search: true, adv_search: false, form_item_type: FormItemType.TEXT_INPUT} ), new SearchField( {label: $.i18n._( 'Undertime Absence Policy' ), in_column: 1, field: 'absence_policy_id', layout_name: ALayoutIDs.ABSENCES_POLICY, api_class: (APIFactory.getAPIClass( 'APIAbsencePolicy' )), multiple: true, basic_search: true, adv_search: false, form_item_type: FormItemType.AWESOME_BOX} ), new SearchField( {label: $.i18n._( 'Created By' ), in_column: 2, field: 'created_by', layout_name: ALayoutIDs.USER, api_class: (APIFactory.getAPIClass( 'APIUser' )), multiple: true, basic_search: true, adv_search: false, form_item_type: FormItemType.AWESOME_BOX} ), new SearchField( {label: $.i18n._( 'Updated By' ), in_column: 2, field: 'updated_by', layout_name: ALayoutIDs.USER, api_class: (APIFactory.getAPIClass( 'APIUser' )), multiple: true, basic_search: true, adv_search: false, form_item_type: FormItemType.AWESOME_BOX} ) ]; } } ); SchedulePolicyViewController.loadView = function() { Global.loadViewSource( 'SchedulePolicy', 'SchedulePolicyView.html', function( result ) { var args = {}; var template = _.template( result, args ); Global.contentContainer().html( template ); } ); };
maestrano/timetrex
interface/html5/views/policy/schedule_policy/SchedulePolicyViewController.js
JavaScript
agpl-3.0
11,599
Clazz.declarePackage ("org.jmol.render"); Clazz.load (["org.jmol.render.ShapeRenderer", "org.jmol.util.Point3f", "$.Point3i", "$.Vector3f"], "org.jmol.render.FontLineShapeRenderer", ["java.lang.Float", "org.jmol.constant.EnumAxesMode", "org.jmol.util.TextFormat"], function () { c$ = Clazz.decorateAsClass (function () { this.imageFontScaling = 0; this.atomA = null; this.atomB = null; this.atomC = null; this.atomD = null; this.font3d = null; this.pt0 = null; this.pt1 = null; this.pt2 = null; this.pointT = null; this.pointT2 = null; this.pointT3 = null; this.vectorT = null; this.vectorT2 = null; this.vectorT3 = null; this.tickInfo = null; this.draw000 = true; this.endcap = 3; Clazz.instantialize (this, arguments); }, org.jmol.render, "FontLineShapeRenderer", org.jmol.render.ShapeRenderer); Clazz.prepareFields (c$, function () { this.pt0 = new org.jmol.util.Point3i (); this.pt1 = new org.jmol.util.Point3i (); this.pt2 = new org.jmol.util.Point3i (); this.pointT = new org.jmol.util.Point3f (); this.pointT2 = new org.jmol.util.Point3f (); this.pointT3 = new org.jmol.util.Point3f (); this.vectorT = new org.jmol.util.Vector3f (); this.vectorT2 = new org.jmol.util.Vector3f (); this.vectorT3 = new org.jmol.util.Vector3f (); }); Clazz.defineMethod (c$, "getDiameter", function (z, madOrPixels) { var diameter; var isMad = (madOrPixels > 20); switch (this.exportType) { case 1: diameter = (isMad ? madOrPixels : Clazz.doubleToInt (Math.floor (this.viewer.unscaleToScreen (z, madOrPixels * 2) * 1000))); break; default: if (isMad) { diameter = this.viewer.scaleToScreen (z, madOrPixels); } else { if (this.g3d.isAntialiased ()) madOrPixels += madOrPixels; diameter = madOrPixels; }} return diameter; }, "~N,~N"); Clazz.defineMethod (c$, "renderLine", function (p0, p1, diameter, pt0, pt1, drawTicks) { pt0.set (Clazz.doubleToInt (Math.floor (p0.x)), Clazz.doubleToInt (Math.floor (p0.y)), Clazz.doubleToInt (Math.floor (p0.z))); pt1.set (Clazz.doubleToInt (Math.floor (p1.x)), Clazz.doubleToInt (Math.floor (p1.y)), Clazz.doubleToInt (Math.floor (p1.z))); if (diameter < 0) this.g3d.drawDottedLine (pt0, pt1); else this.g3d.fillCylinder (this.endcap, diameter, pt0, pt1); if (!drawTicks || this.tickInfo == null) return; this.atomA.screenX = pt0.x; this.atomA.screenY = pt0.y; this.atomA.screenZ = pt0.z; this.atomB.screenX = pt1.x; this.atomB.screenY = pt1.y; this.atomB.screenZ = pt1.z; this.drawTicks (this.atomA, this.atomB, diameter, true); }, "org.jmol.util.Point3f,org.jmol.util.Point3f,~N,org.jmol.util.Point3i,org.jmol.util.Point3i,~B"); Clazz.defineMethod (c$, "drawTicks", function (pt1, pt2, diameter, withLabels) { if (Float.isNaN (this.tickInfo.first)) this.tickInfo.first = 0; this.drawTicks (pt1, pt2, this.tickInfo.ticks.x, 8, diameter, (!withLabels ? null : this.tickInfo.tickLabelFormats == null ? ["%0.2f"] : this.tickInfo.tickLabelFormats)); this.drawTicks (pt1, pt2, this.tickInfo.ticks.y, 4, diameter, null); this.drawTicks (pt1, pt2, this.tickInfo.ticks.z, 2, diameter, null); }, "org.jmol.util.Point3fi,org.jmol.util.Point3fi,~N,~B"); Clazz.defineMethod (c$, "drawTicks", ($fz = function (ptA, ptB, dx, length, diameter, formats) { if (dx == 0) return; if (this.g3d.isAntialiased ()) length *= 2; this.vectorT2.set (ptB.screenX, ptB.screenY, 0); this.vectorT.set (ptA.screenX, ptA.screenY, 0); this.vectorT2.sub (this.vectorT); if (this.vectorT2.length () < 50) return; var signFactor = this.tickInfo.signFactor; this.vectorT.setT (ptB); this.vectorT.sub (ptA); var d0 = this.vectorT.length (); if (this.tickInfo.scale != null) { if (Float.isNaN (this.tickInfo.scale.x)) { var a = this.viewer.getUnitCellInfo (0); if (!Float.isNaN (a)) this.vectorT.set (this.vectorT.x / a, this.vectorT.y / this.viewer.getUnitCellInfo (1), this.vectorT.z / this.viewer.getUnitCellInfo (2)); } else { this.vectorT.set (this.vectorT.x * this.tickInfo.scale.x, this.vectorT.y * this.tickInfo.scale.y, this.vectorT.z * this.tickInfo.scale.z); }}var d = this.vectorT.length () + 0.0001 * dx; if (d < dx) return; var f = dx / d * d0 / d; this.vectorT.scale (f); var dz = (ptB.screenZ - ptA.screenZ) / (d / dx); d += this.tickInfo.first; var p = (Clazz.doubleToInt (Math.floor (this.tickInfo.first / dx))) * dx - this.tickInfo.first; this.pointT.scaleAdd2 (p / dx, this.vectorT, ptA); p += this.tickInfo.first; var z = ptA.screenZ; if (diameter < 0) diameter = 1; this.vectorT2.set (-this.vectorT2.y, this.vectorT2.x, 0); this.vectorT2.scale (length / this.vectorT2.length ()); var ptRef = this.tickInfo.reference; if (ptRef == null) { this.pointT3.setT (this.viewer.getBoundBoxCenter ()); if (this.viewer.getAxesMode () === org.jmol.constant.EnumAxesMode.BOUNDBOX) { this.pointT3.x += 1.0; this.pointT3.y += 1.0; this.pointT3.z += 1.0; }} else { this.pointT3.setT (ptRef); }this.viewer.transformPtScr (this.pointT3, this.pt2); var horizontal = (Math.abs (this.vectorT2.x / this.vectorT2.y) < 0.2); var centerX = horizontal; var centerY = !horizontal; var rightJustify = !centerX && (this.vectorT2.x < 0); var drawLabel = (formats != null && formats.length > 0); var x; var y; var val = new Array (1); var i = (this.draw000 ? 0 : -1); while (p < d) { if (p >= this.tickInfo.first) { this.pointT2.setT (this.pointT); this.viewer.transformPt3f (this.pointT2, this.pointT2); this.drawLine (Clazz.doubleToInt (Math.floor (this.pointT2.x)), Clazz.doubleToInt (Math.floor (this.pointT2.y)), Clazz.floatToInt (z), (x = Clazz.doubleToInt (Math.floor (this.pointT2.x + this.vectorT2.x))), (y = Clazz.doubleToInt (Math.floor (this.pointT2.y + this.vectorT2.y))), Clazz.floatToInt (z), diameter); if (drawLabel && (this.draw000 || p != 0)) { val[0] = new Float ((p == 0 ? 0 : p * signFactor)); var s = org.jmol.util.TextFormat.sprintf (formats[i % formats.length], "f", val); this.drawString (x, y, Clazz.floatToInt (z), 4, rightJustify, centerX, centerY, Clazz.doubleToInt (Math.floor (this.pointT2.y)), s); }}this.pointT.add (this.vectorT); p += dx; z += dz; i++; } }, $fz.isPrivate = true, $fz), "org.jmol.util.Point3fi,org.jmol.util.Point3fi,~N,~N,~N,~A"); Clazz.defineMethod (c$, "drawLine", function (x1, y1, z1, x2, y2, z2, diameter) { this.pt0.set (x1, y1, z1); this.pt1.set (x2, y2, z2); if (diameter < 0) { this.g3d.drawDashedLine (4, 2, this.pt0, this.pt1); return 1; }this.g3d.fillCylinder (2, diameter, this.pt0, this.pt1); return Clazz.doubleToInt ((diameter + 1) / 2); }, "~N,~N,~N,~N,~N,~N,~N"); Clazz.defineMethod (c$, "drawString", function (x, y, z, radius, rightJustify, centerX, centerY, yRef, sVal) { if (sVal == null) return; var width = this.font3d.stringWidth (sVal); var height = this.font3d.getAscent (); var xT = x; if (rightJustify) xT -= Clazz.doubleToInt (radius / 2) + 2 + width; else if (centerX) xT -= Clazz.doubleToInt (radius / 2) + 2 + Clazz.doubleToInt (width / 2); else xT += Clazz.doubleToInt (radius / 2) + 2; var yT = y; if (centerY) yT += Clazz.doubleToInt (height / 2); else if (yRef == 0 || yRef < y) yT += height; else yT -= Clazz.doubleToInt (radius / 2); var zT = z - radius - 2; if (zT < 1) zT = 1; this.g3d.drawString (sVal, this.font3d, xT, yT, zT, zT, 0); }, "~N,~N,~N,~N,~B,~B,~B,~N,~S"); });
ksripathi/edx-demo-course
static/jsmol/j2s/org/jmol/render/FontLineShapeRenderer.js
JavaScript
agpl-3.0
7,166
import validateComponentConfig from '../validation/validateComponentConfig'; import normalizeComponentConfig from '../helper/normalizeComponentConfig'; import createFactory from '../helper/createFactory'; import printError from '../helper/printError'; export default function adaptDefineComponentFunction({ createComponentType, createElement, Adapter }) { function defineComponent(config) { const error = validateComponentConfig(config); if (error) { const errorMsg = prettifyErrorMsg(error.message, config); printError(errorMsg); throw new TypeError(errorMsg); } const normalizedConfig = normalizeComponentConfig(config), componentType = createComponentType(normalizedConfig), factory = createFactory(componentType, normalizedConfig, Adapter); return factory; } defineComponent._jsx = createElement; defineComponent._jsxFrag = null; return defineComponent; } function prettifyErrorMsg(errorMsg, config) { return config && typeof config === 'object' && typeof config.displayName === 'string' && config.displayName.trim().length > 0 ? '[defineComponent] Invalid configuration for component ' + `"${config.displayName}": ${errorMsg} ` : `[defineComponent] Invalid component configuration: ${errorMsg}`; }
mcjazzyfunky/js-surface
boxroom/archive/js-surface-2018-05-05-important/src/main/adaption/adaptDefineComponentFunction.js
JavaScript
lgpl-3.0
1,404
import dt from 'datatables.net-bs'; import 'datatables.net-bs/css/dataTables.bootstrap.css'; import $ from 'jquery'; import { d3format, fixDataTableBodyHeight } from '../javascripts/modules/utils'; import './pivot_table.css'; dt(window, $); module.exports = function (slice, payload) { const container = slice.container; const fd = slice.formData; const height = container.height(); let cols = payload.data.columns; if (Array.isArray(cols[0])) { cols = cols.map(col => col[0]); } // payload data is a string of html with a single table element container.html(payload.data.html); // jQuery hack to set verbose names in headers const replaceCell = function () { const s = $(this)[0].textContent; $(this)[0].textContent = slice.datasource.verbose_map[s] || s; }; slice.container.find('thead tr:first th').each(replaceCell); slice.container.find('thead tr th:first-child').each(replaceCell); // jQuery hack to format number slice.container.find('tbody tr').each(function () { $(this).find('td').each(function (i) { const metric = cols[i]; const format = slice.datasource.column_formats[metric] || fd.number_format || '.3s'; const tdText = $(this)[0].textContent; if (!isNaN(tdText) && tdText !== '') { $(this)[0].textContent = d3format(format, tdText); } }); }); if (fd.groupby.length === 1) { // When there is only 1 group by column, // we use the DataTable plugin to make the header fixed. // The plugin takes care of the scrolling so we don't need // overflow: 'auto' on the table. container.css('overflow', 'hidden'); const table = container.find('table').DataTable({ paging: false, searching: false, bInfo: false, scrollY: `${height}px`, scrollCollapse: true, scrollX: true, }); table.column('-1').order('desc').draw(); fixDataTableBodyHeight(container.find('.dataTables_wrapper'), height); } else { // When there is more than 1 group by column we just render the table, without using // the DataTable plugin, so we need to handle the scrolling ourselves. // In this case the header is not fixed. container.css('overflow', 'auto'); container.css('height', `${height + 10}px`); } };
alanmcruickshank/superset-dev
superset/assets/visualizations/pivot_table.js
JavaScript
apache-2.0
2,278
// ---------------------------------------------------------------------------- // To provide some additional features for OpenLayers, portions of the OpenLayers support // have been copied from 'mapstraction.js' [www.mapstraction.com] which includes the // copyright included below. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Copyright (c) 2006-7, Tom Carden, Steve Coast, Mikel Maron, Andrew Turner, Henri Bergius // 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 the Mapstraction 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. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Required funtions defined by this module: // new JSMap(String mapID) // JSClearLayers() // JSSetCenter(JSMapPoint center) // JSDrawPushpins(JSMapPushpin pushPin[], int recenterMode, int replay) // JSDrawPOI(JSMapPushpin pushPin[]) // JSDrawRoute(JSMapPoint points[], String color) // JSDrawShape(String type, double radius, JSMapPoint points[], String color, boolean zoomTo) // JSDrawGeozone(int type, double radius, JSMapPoint points[], String color, int primaryIndex) // JSShowPushpin(JSMapPushpin pushPin, boolean center) // JSPauseReplay(int replay) // JSUnload() // ---------------------------------------------------------------------------- // UserAgents: // - "/MSIE/.test(navigator.userAgent)" // - "/Firefox/.test(navigator.userAgent)" // - "/Safari/.test(navigator.userAgent)" // ---------------------------------------------------------------------------- // References: // - http://openlayers.org/dev/examples/ // OpenLayers Modify Feature Example // Popup Matrix // Drawing Simple Vector Features Example // Wrapping the Date Line // OpenLayers.Handler.Point // ---------------------------------------------------------------------------- // Change History: // 2008/07/08 Martin D. Flynn // -Initial release // 2008/07/27 Martin D. Flynn // -Modified 'JSMap.prototype._addPushpin' to set the proper 'iconAnchor' value // 2008/08/08 Martin D. Flynn // -Added support for Geozones // 2008/08/15 Martin D. Flynn // -Many changes to make this work better with MS IE. // 2008/08/24 Martin D. Flynn // -Added 'replay' support. // 2008/09/01 Martin D. Flynn // -Modified Geozome mouse behavior (click to recenter, shift-drag to resize). // 2008/10/16 Martin D. Flynn // -Initial support for GeoServer // 2008/12/01 Martin D. Flynn // -Removed the 'short' zoom control display (both the zoom-drag bar and the // short zoom bar were previously displayed on the map simultaneously). // 2009/08/23 Martin D. Flynn // -Added color argument to JSDrawRoute // -Added option for drawing multiple points per device on fleet map // 2010/04/11 Martin D. Flynn // -Added support for drawing polygon and corridor geozones. However, in the // case of corridor geozones, additional GTS features may be required to // fully utilize this type of geozone. // ---------------------------------------------------------------------------- var DRAG_NONE = 0x00; var DRAG_RULER = 0x01; var DRAG_GEOZONE = 0x10; var DRAG_GEOZONE_CENTER = 0x11; var DRAG_GEOZONE_RADIUS = 0x12; // ---------------------------------------------------------------------------- function OpenLayersColorStyle(borderColor, borderOpacity, fillColor, fillOpacity) { this.strokeColor = borderColor; this.strokeOpacity = borderOpacity; this.strokeWidth = 1; this.fillColor = fillColor; this.fillOpacity = fillOpacity; }; var GEOZONE_STYLE = [ new OpenLayersColorStyle("#CC1111", 0.80, "#11CC22", 0.28), /* primary */ new OpenLayersColorStyle("#11CC11", 0.80, "#11CC22", 0.18) ]; function GetGeozoneStyle(isPrimary, fillColor) { var s = GEOZONE_STYLE[isPrimary? 0 : 1]; if (fillColor && (fillColor != "")) { return new OpenLayersColorStyle( s.strokeColor, s.strokeOpacity, fillColor, s.fillOpacity); } else { return s; } }; //var DRAW_ZONE_POINT_RADIUS_POLYGON = false; // ---------------------------------------------------------------------------- /** *** JSMap constructor **/ function JSMap(mapElement) { /* custom fix for MSIE */ this.userAgent_MSIE = /MSIE/.test(navigator.userAgent); /* crosshair mouse cursor */ mapElement.style.cursor = "crosshair"; /* OpenStreetMaps */ if (GEOSERVER_enable) { this._initGeoServerCustom(mapElement); } else { this._initOpenStreetMaps(mapElement); } /* pan/zoom bar */ //this.openLayersMap.addControl(new OpenLayers.Control.PanZoomBar()); /* disable double-click zoom */ // this seems to also disable the shift-drag zoom. var nav = new OpenLayers.Control.Navigation({ defaultDblClick: function(e) {/*no-op*/} }); this.openLayersMap.addControl(nav); /* "ruler" layer */ this.rulerFeatures = null; this.rulerLayer = new OpenLayers.Layer.Vector('rulerLayer'); this.openLayersMap.addLayer(this.rulerLayer); /* POI layer */ this.poiLayer = new OpenLayers.Layer.Markers('poiLayer'); this.openLayersMap.addLayer(this.poiLayer); /* route/zone layer */ this.routeLines = []; // JSMapPoint[] this.primaryIndex = -1; this.primaryCenter = null; // OpenLayers.LonLat this.geozonePoints = null; // JSMapPoint[] this.dragZoneOffsetLat = 0.0; this.dragZoneOffsetLon = 0.0; this.drawFeatures = null; this.drawShapes = []; this.drawLayer = []; // drawLayer0 this.drawLayer.push(new OpenLayers.Layer.Vector('drawLayer0')); this.openLayersMap.addLayer(this.drawLayer[this.drawLayer.length - 1]); // drawLayer1 //this.drawLayer.push(new OpenLayers.Layer.Vector('drawLayer0')); //this.openLayersMap.addLayer(this.drawLayer[this.drawLayer.length - 1); /* marker/pushpin layer */ this.markerLayer = new OpenLayers.Layer.Markers('markerLayer'); this.openLayersMap.addLayer(this.markerLayer); this.visiblePopupInfoBox = null; // JSMapPushpin /* replay vars */ this.replayTimer = null; this.replayIndex = 0; this.replayInterval = (REPLAY_INTERVAL < 100)? 100 : REPLAY_INTERVAL; this.replayInProgress = false; this.replayPushpins = []; /* mouse event handlers */ this.dragType = DRAG_NONE; this.dragRulerStart = null; this.dragRulerEnd = null; try { this.openLayersMap.events.registerPriority("mousemove", this, this._event_OnMouseMove ); this.openLayersMap.events.registerPriority("mousedown", this, this._event_OnMouseDown ); this.openLayersMap.events.registerPriority("mouseup" , this, this._event_OnMouseUp ); } catch (e) { //alert("Error: " + e); } /* "click" handler to recenter geozones */ try { this.openLayersMap.events.register("click", this, this._event_OnClick); } catch (e) { //alert("Error: " + e); } /* init lat/lon display */ jsmSetLatLonDisplay(0,0); /* zoom event */ this.lastMapZoom = 0; this.lastMapSize = new OpenLayers.Size(0,0); try { //this.openLayersMap.events.register("zoomend", this, this._event_ZoomEnd); this.openLayersMap.events.register("moveend", this, this._event_MoveEnd); } catch (e) { //alert("Error: " + e); } }; // ---------------------------------------------------------------------------- /* init OpenLayers with OpenStreetMaps */ JSMap.prototype._initOpenStreetMaps = function(mapElement) { /* bounds */ var bounds = new OpenLayers.Bounds( -20037508.34, -20037508.34, 20037508.34, 20037508.34 ); /* see "http://wiki.openstreetmap.org/index.php/OpenLayers_Simple_Example" */ this.openLayersMap = new OpenLayers.Map(mapElement.id, { maxExtent: bounds, maxResolution: 156543, numZoomLevels: 18, units: "meters", projection: "EPSG:41001", controls: [ //new OpenLayers.Control.MousePosition(), //new OpenLayers.Control.OverviewMap(), //new OpenLayers.Control.ScaleLine(), //new OpenLayers.Control() new OpenLayers.Control.PanZoomBar() ] } ); this.openLayersMap.addLayer(new OpenLayers.Layer.TMS( "OSM Mapnik", [ "http://a.tile.openstreetmap.org/", "http://b.tile.openstreetmap.org/", "http://c.tile.openstreetmap.org/" ], { type: 'png', getURL: function (bounds) { var res = this.map.getResolution(); var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w)); var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h)); var z = this.map.getZoom(); var limit = Math.pow(2, z); if ((y < 0) || (y >= limit)) { return null; } else { x = ((x % limit) + limit) % limit; var path = z + "/" + x + "/" + y + "." + this.type; var url = this.url; if (url instanceof Array) { url = this.selectUrl(path, url); } return url + path; } }, displayOutsideMaxExtent: true } )); this.openLayersMap.addLayer(new OpenLayers.Layer.TMS( "OSM", [ "http://a.tah.openstreetmap.org/Tiles/tile.php/", "http://b.tah.openstreetmap.org/Tiles/tile.php/", "http://c.tah.openstreetmap.org/Tiles/tile.php/" ], { type: 'png', getURL: function (bounds) { var res = this.map.getResolution(); var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w)); var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h)); var z = this.map.getZoom(); var limit = Math.pow(2, z); if ((y < 0) || (y >= limit)) { return null; } else { x = ((x % limit) + limit) % limit; var path = z + "/" + x + "/" + y + "." + this.type; var url = this.url; if (url instanceof Array) { url = this.selectUrl(path, url); } return url + path; } }, displayOutsideMaxExtent: true } )); /* convert OpenLayers point to JSMapPoint */ JSMap.prototype._toJSMapPointLatLon = function(olLat, olLon) { var lon = olLon * (180.0 / 20037508.34); var lat = olLat * (180.0 / 20037508.34); lat = (180.0 / Math.PI) * (2.0 * Math.atan(Math.exp(lat * Math.PI / 180.0)) - (Math.PI / 2.0)); return new JSMapPoint(lat,lon); }; /* convert OpenLayers point to JSMapPoint */ JSMap.prototype._toJSMapPoint = function(point) { return this._toJSMapPointLatLon(point.lat, point.lon); }; /* convert JSMapPoint to OpenLayers point */ JSMap.prototype._toOpenLayerPointLatLon = function(lat, lon) { var ollon = lon * (20037508.34 / 180.0); var ollat = Math.log(Math.tan((90.0 + lat) * Math.PI / 360.0)) / (Math.PI / 180.0); ollat *= 20037508.34 / 180.0; return new OpenLayers.LonLat(ollon, ollat); }; /* convert JSMapPoint to OpenLayers point */ JSMap.prototype._toOpenLayerPoint = function(point) { return this._toOpenLayerPointLatLon(point.lat, point.lon); }; /* return map object */ return this.openLayersMap; }; // ---------------------------------------------------------------------------- /* init OpenLayers with GeoServer */ JSMap.prototype._initGeoServerCustom = function(mapElement) { var GEOSERVER_TITLE = GEOSERVER_title; var GEOSERVER_URL = GEOSERVER_url; // "http://localhost:8085/geoserver/wms"; var MAX_RESOLUTION = GEOSERVER_maxResolution; // 0.0007907421875; var MAP_WIDTH = GEOSERVER_size.width; // "431"; var MAP_HEIGHT = GEOSERVER_size.height; // "550"; var MAP_STYLES = ""; var MAP_BOUNDS = new OpenLayers.Bounds(GEOSERVER_bounds.left, GEOSERVER_bounds.bottom, GEOSERVER_bounds.right, GEOSERVER_bounds.top); // -74.047185, 40.679648, -73.907005, 40.882078); var TILE_ORIGIN = MAP_BOUNDS.left + "," + MAP_BOUNDS.bottom; // "-74.047185,40.679648" var PROJECTION = GEOSERVER_projection; // "EPSG:4326"; var TILE_FORMAT = "image/png"; var TILE_STATE = "true"; // may need to be "false" ??? var DATA_LAYERS = GEOSERVER_layers; // "tiger-ny"; var COORD_UNITS = (GEOSERVER_units != "")? GEOSERVER_units : "degrees"; var LAYER_TYPE = GEOSERVER_layerType; /* map */ this.openLayersMap = new OpenLayers.Map( mapElement.id, { maxExtent: MAP_BOUNDS, maxResolution: MAX_RESOLUTION, projection: PROJECTION, units: COORD_UNITS, controls: [ //new OpenLayers.Control.MousePosition(), //new OpenLayers.Control.OverviewMap(), //new OpenLayers.Control.ScaleLine(), new OpenLayers.Control.PanZoomBar() ] } ); /* simple layer */ if (LAYER_TYPE == "simple") { this.openLayersMap.addLayer(new OpenLayers.Layer.WMS( GEOSERVER_TITLE, GEOSERVER_URL, { layers: DATA_LAYERS } )); } /* tiled layer */ if (LAYER_TYPE == "tiled") { this.openLayersMap.addLayer(new OpenLayers.Layer.WMS( GEOSERVER_TITLE, // + " (tiled)", GEOSERVER_URL, { width: MAP_WIDTH, height: MAP_HEIGHT, styles: MAP_STYLES, layers: DATA_LAYERS, srs: PROJECTION, format: TILE_FORMAT, tiled: TILE_STATE, tilesOrigin: TILE_ORIGIN }, { buffer: 0 } )); } /* untiled layer */ if (LAYER_TYPE == "untiled") { this.openLayersMap.addLayer(new OpenLayers.Layer.WMS( GEOSERVER_TITLE, // + " (untiled)", GEOSERVER_URL, { width: MAP_WIDTH, styles: MAP_STYLES, height: MAP_HEIGHT, layers: DATA_LAYERS, srs: PROJECTION, format: TILE_FORMAT }, { singleTile: true, ratio: 1 } )); } /* initial zoom */ this.openLayersMap.zoomToExtent(MAP_BOUNDS); /* convert OpenLayers point to JSMapPoint */ JSMap.prototype._toJSMapPoint = function(point) { var lon = point.lon; var lat = point.lat; return new JSMapPoint(lat,lon); }; /* convert JSMapPoint to OpenLayers point */ JSMap.prototype._toOpenLayerPointLatLon = function(lat, lon) { var ollon = lon; var ollat = lat; return new OpenLayers.LonLat(ollon, ollat); }; /* convert JSMapPoint to OpenLayers point */ JSMap.prototype._toOpenLayerPoint = function(point) { return this._toOpenLayerPointLatLon(point.lat, point.lon); }; /* return map object */ return this.openLayersMap; }; // ---------------------------------------------------------------------------- /** *** Unload/release resources **/ JSMap.prototype.JSUnload = function() { // nothing to do? }; // ---------------------------------------------------------------------------- /** *** Clear all pushpins and drawn lines **/ JSMap.prototype.JSClearLayers = function() { this._clearPoiLayer(); this._clearMarkerLayer(); this._clearDrawLayer(); this._clearRulerLayer(true); this.centerBounds = new OpenLayers.Bounds(); this.routeLines = []; }; /** *** Clear the POI layer **/ JSMap.prototype._clearPoiLayer = function() { if (this.poiLayer !== null) { try { this.poiLayer.clearMarkers(); } catch (e) {} try { this.openLayersMap.removeLayer(this.poiLayer); } catch (e) {} } }; /** *** Clear the marker layer **/ JSMap.prototype._clearMarkerLayer = function() { if (this.markerLayer !== null) { try { this.markerLayer.clearMarkers(); } catch (e) {} try { this.openLayersMap.removeLayer(this.markerLayer); } catch (e) {} } this._clearReplay(); }; // ---------------------------------------------------------------------------- /** *** Pause/Resume replay **/ JSMap.prototype.JSPauseReplay = function(replay) { /* stop replay? */ if (!replay || (replay <= 0) || !this.replayInProgress) { // stopping replay this._clearReplay(); return REPLAY_STOPPED; } else { // replay currently in progress if (this.replayTimer === null) { // replay is "PAUSED" ... resuming replay this._hidePushpinPopup(this.visiblePopupInfoBox); jsmHighlightDetailRow(-1, false); this._startReplayTimer(replay, 100); return REPLAY_RUNNING; } else { // replaying "RUNNING" ... pausing replay this._stopReplayTimer(); return REPLAY_PAUSED; } } }; /** *** Start the replay timer *** @param replay 0=off, 1=pushpin_only, 2=pushpin&balloon **/ JSMap.prototype._startReplayTimer = function(replay, interval) { if (this.replayInProgress) { this.replayTimer = setTimeout("jsmap._replayPushpins("+replay+")", interval); } jsmSetReplayState(REPLAY_RUNNING); }; /** *** Stop the current replay timer **/ JSMap.prototype._stopReplayTimer = function() { if (this.replayTimer !== null) { clearTimeout(this.replayTimer); this.replayTimer = null; } jsmSetReplayState(this.replayInProgress? REPLAY_PAUSED : REPLAY_STOPPED); }; /** *** Clear any current replay in process **/ JSMap.prototype._clearReplay = function() { this.replayPushpins = []; this.replayInProgress = false; this._stopReplayTimer(); this.replayIndex = 0; jsmHighlightDetailRow(-1, false); }; /** *** Gets the current replay state **/ JSMap.prototype._getReplayState = function() { if (this.replayInProgress) { if (this.replayTimer === null) { return REPLAY_PAUSED; } else { return REPLAY_RUNNING; } } else { return REPLAY_STOPPED; } }; // ---------------------------------------------------------------------------- /** *** Clear the draw layer **/ JSMap.prototype._clearRulerLayer = function(clearStart) { if ((this.rulerLayer !== null) && (this.rulerFeatures !== null)) { try { this.rulerLayer.removeFeatures(this.rulerFeatures); } catch (e) {} this.rulerFeatures = null; } if (clearStart) { this.dragRulerStart = null; this.dragRulerEnd = null; } }; /** *** Draw Ruler **/ JSMap.prototype._drawRuler = function(features) { this._clearRulerLayer(false); this.rulerFeatures = features; if (this.rulerFeatures !== null) { if (this.rulerLayer === null) { this.rulerLayer = new OpenLayers.Layer.Vector('rulerLayer'); this.openLayersMap.addLayer(this.rulerLayer); } this.rulerLayer.addFeatures(this.rulerFeatures); //this.rulerLayer.display(true); //this.rulerLayer.drawFeature(this.rulerFeatures[0]); } }; /** *** Create/return ruler feature **/ JSMap.prototype._createRulerFeature = function(lat, lon) { if ((lat !== null) && (lon !== null)) { var rulerStyle = { strokeColor: "#FF6422", strokeOpacity: 1, strokeWidth: 2, fillColor: "#FF2222", fillOpacity: 0.2 }; var rulerPoints = []; rulerPoints.push(this._createGeometryPoint(this._toOpenLayerPoint(lat))); rulerPoints.push(this._createGeometryPoint(this._toOpenLayerPoint(lon))); var line = new OpenLayers.Geometry.LineString(rulerPoints); return new OpenLayers.Feature.Vector(line, null, rulerStyle); } else { return null; } }; // ---------------------------------------------------------------------------- /** *** Clear the draw layer **/ JSMap.prototype._clearDrawLayer = function() { if (this.drawFeatures !== null) { try { this.drawLayer[0].removeFeatures(this.drawFeatures); } catch (e) {} this.drawFeatures = null; } }; /** *** Draw Feature **/ JSMap.prototype._drawFeatures = function(clear, features) { /* clear existing features */ if (clear) { this._clearDrawLayer(); } /* add features */ if (features) { if (!this.drawFeatures) { this.drawFeatures = []; } for (var i = 0; i < features.length; i++) { this.drawFeatures.push(features[i]); } } /* draw features */ if (this.drawFeatures && (this.drawFeatures.length > 0)) { //if (this.drawLayer === null) { // this.drawLayer = new OpenLayers.Layer.Vector('drawLayer0'); // this.openLayersMap.addLayer(this.drawLayer); //} this.drawLayer[0].addFeatures(this.drawFeatures); //this.drawLayer[0].display(true); //this.drawLayer[0].drawFeature(this.drawFeatures[0]); } }; // ---------------------------------------------------------------------------- /** *** Sets the center of the map **/ JSMap.prototype.JSSetCenter = function(center) { try { this.openLayersMap.setCenter(this._toOpenLayerPoint(center)); } catch (e) { // } }; /** *** Draw the specified pushpins on the map *** @param pushPins An array of JSMapPushpin objects *** @param recenter 0=no-recenter, 1=last-pushpin, 2=all-pushpins *** @param replay 0=off, 1=pushpin_only, 2=pushpin&balloon **/ JSMap.prototype.JSDrawPushpins = function(pushPins, recenterMode, replay) { /* reset pushpin layer */ //this.markerLayer.display(false); this._hidePushpinPopup(this.visiblePopupInfoBox); /* drawn pushpins */ var drawPushpins = []; /* recenter map on points */ var pointCount = 0; if ((pushPins !== null) && (pushPins.length > 0)) { for (var i = 0; i < pushPins.length; i++) { var pp = pushPins[i]; // JSMapPushpin if ((pp.lat != 0.0) || (pp.lon != 0.0)) { pointCount++; this.centerBounds.extend(this._toOpenLayerPoint(pp)); drawPushpins.push(pp); } } } if (recenterMode > 0) { try { if (pointCount <= 0) { var centerPt = this._toOpenLayerPoint(DEFAULT_CENTER); var zoomFactor = DEFAULT_ZOOM; this.openLayersMap.setCenter(centerPt, zoomFactor); } else if (recenterMode == RECENTER_LAST) { // center on last point var pp = drawPushpins[drawPushpins.length - 1]; var centerPt = this._toOpenLayerPoint(pp); this.openLayersMap.setCenter(centerPt); } else if (recenterMode == RECENTER_PAN) { // pan to last point var pp = drawPushpins[drawPushpins.length - 1]; var centerPt = this._toOpenLayerPoint(pp); this.openLayersMap.setCenter(centerPt); } else { var centerPt = this.centerBounds.getCenterLonLat(); var zoomFactor = this.openLayersMap.getZoomForExtent(this.centerBounds); this.openLayersMap.setCenter(centerPt, zoomFactor); } } catch (e) { //alert("Error: [JSDrawPushpins] " + e); return; } } if (pointCount <= 0) { return; } /* replay pushpins? */ if (replay && (replay >= 1)) { this.openLayersMap.addLayer(this.markerLayer); // must re-add layer this.replayIndex = 0; this.replayInProgress = true; this.replayPushpins = drawPushpins; this._startReplayTimer(replay, 100); return; } /* draw pushpins now */ var pushpinErr = null; for (var i = 0; i < drawPushpins.length; i++) { var pp = drawPushpins[i]; // JSMapPushpin try { pp.hoverPopup = true; this._addPushpin(pp, this.markerLayer); } catch (e) { if (pushpinErr === null) { pushpinErr = e; } } } try { this.openLayersMap.addLayer(this.markerLayer); // must re-add layer //this.markerLayer.display(true); } catch (e) { if (pushpinErr === null) { pushpinErr = e; } } if (pushpinErr !== null) { alert("Error: adding pushpins:\n" + pushpinErr); } }; /** *** Draw the specified PointsOfInterest pushpins on the map *** @param pushPins An array of JSMapPushpin objects **/ JSMap.prototype.JSDrawPOI = function(pushPins) { /* reset pushpin layer */ this._clearPoiLayer(); //this.poiLayer.display(false); this._hidePushpinPopup(this.visiblePopupInfoBox); /* draw pushpins */ if ((pushPins !== null) && (pushPins.length > 0)) { var pushpinErr = null; for (var i = 0; i < pushPins.length; i++) { var pp = pushPins[i]; // JSMapPushpin try { pp.hoverPopup = true; this._addPushpin(pp, this.poiLayer); } catch (e) { if (pushpinErr === null) { pushpinErr = e; } } } try { this.openLayersMap.addLayer(this.poiLayer); // must re-add layer //this.poiLayer.display(true); } catch (e) { if (pushpinErr === null) { pushpinErr = e; } } if (pushpinErr !== null) { alert("Error: adding pushpins:\n" + pushpinErr); } } }; /** *** Adds a single pushpin to the map *** @param pp The JSMapPushpin object to add to the map **/ JSMap.prototype._addPushpin = function(pp, layer) { try { var self = this; pp.map = this.openLayersMap; var size = new OpenLayers.Size(pp.iconSize[0], pp.iconSize[1]); var anchor = new OpenLayers.Pixel(-pp.iconOffset[0], -pp.iconOffset[1]); var icon = new OpenLayers.Icon(pp.iconUrl, size, anchor); var marker = new OpenLayers.Marker(this._toOpenLayerPoint(pp), icon); if (pp.html) { pp.popup = new OpenLayers.Popup(null, this._toOpenLayerPoint(pp), new OpenLayers.Size(100,100), pp.html, true); pp.popup.autoSize = true; if (pp.hoverPopup) { marker.events.register("mouseover", marker, function(event) { self._showPushpinPopup(pp); }); marker.events.register("mouseout", marker, function(event) { self._hidePushpinPopup(pp); }); } else { marker.events.register("mousedown", marker, function(event) { if (pp.popupShown) { self._hidePushpinPopup(pp); } else { self._showPushpinPopup(pp); } }); } } pp.marker = marker; layer.addMarker(marker); /* if (pp.label) { var labelPopup = new OpenLayers.Popup(null, this._toOpenLayerPoint(pp), new OpenLayers.Size(30,12), "<span>"+pp.label+"</span>", false); labelPopup.autoSize = true; this.openLayersMap.addPopup(labelPopup); labelPopup.show(); } */ } catch(e) { //alert("Error: " + e); } }; /** *** Replays the list of pushpins on the map *** @param replay 0=off, 1=pushpin_only, 2=pushpin&balloon **/ JSMap.prototype._replayPushpins = function(replay) { /* no replay pushpins? */ if (this.replayPushpins === null) { this._clearReplay(); jsmHighlightDetailRow(-1, false); return; // stop } /* advance to next valid point */ while (true) { if (this.replayIndex >= this.replayPushpins.length) { this._clearReplay(); jsmHighlightDetailRow(-1, false); return; // stop } var pp = this.replayPushpins[this.replayIndex]; // JSMapPushpin if ((pp.lat != 0.0) || (pp.lon != 0.0)) { break; // valid point } this.replayIndex++; } /* add pushpin */ try { var lastNdx = this.replayIndex - 1; var pp = this.replayPushpins[this.replayIndex++]; // JSMapPushpin pp.hoverPopup = true; if (REPLAY_SINGLE && (lastNdx >= 0)) { try { this.markerLayer.clearMarkers(); } catch (e) {} } this._addPushpin(pp, this.markerLayer); if (replay && (replay >= 2)) { this._showPushpinPopup(pp); } else { jsmHighlightDetailRow(pp.rcdNdx, true); } this._startReplayTimer(replay, this.replayInterval); } catch (e) { // ignore } }; // ---------------------------------------------------------------------------- /** *** This method should cause the info-bubble popup for the specified pushpin to display *** @param pp The JSMapPushpin object to popup its info-bubble **/ JSMap.prototype.JSShowPushpin = function(pp, center) { if (pp) { if (pp.popupShown) { this._hidePushpinPopup(pp); } else { if (center || !this._isPointOnMap(pp.lat,pp.lon,7,7,50,100)) { this.JSSetCenter(new JSMapPoint(pp.lat, pp.lon)); } this._showPushpinPopup(pp); } } }; JSMap.prototype._isPointOnMap = function(lat, lon, margTop, margLeft, margBott, margRght) { var size = this.openLayersMap.getSize(); var top = 0 + margTop; var left = 0 + margLeft; var bott = top + size.h - margBott; var rght = left + size.w - margRght; var TL = this._toJSMapPoint(this.openLayersMap.getLonLatFromViewPortPx(new OpenLayers.Pixel(left, top ))); var BR = this._toJSMapPoint(this.openLayersMap.getLonLatFromViewPortPx(new OpenLayers.Pixel(rght, bott))); //alert("_isPointOnMap "+lat+"/"+lon+", TL:"+TL.lat+"/"+TL.lon+", BR:"+BR.lat+"/"+BR.lon); if ((lat > TL.lat) || (lat < BR.lat)) { return false; } else if ((lon < TL.lon) || (lon > BR.lon)) { return false; } else { return true; } }; JSMap.prototype._showPushpinPopup = function(pp) { this._hidePushpinPopup(this.visiblePopupInfoBox); if (pp && !pp.popupShown && pp.map) { pp.map.addPopup(pp.popup); pp.popup.show(); pp.popupShown = true; this.visiblePopupInfoBox = pp; jsmHighlightDetailRow(pp.rcdNdx, true); } else { this.visiblePopupInfoBox = null; } }; JSMap.prototype._hidePushpinPopup = function(pp) { if (pp && pp.popupShown) { pp.popup.hide(); pp.map.removePopup(pp.popup); pp.popupShown = false; jsmHighlightDetailRow(pp.rcdNdx, false); } }; // ---------------------------------------------------------------------------- /** *** Draws a line between the specified points on the map. *** @param points An array of JSMapPoint objects **/ JSMap.prototype.JSDrawRoute = function(points, color) { if ((points !== null) && (points.length > 0)) { var route = { points: points, color: color }; this.routeLines.push(route); var routeFeatures = []; for (var i = 0; i < this.routeLines.length; i++) { var r = this.routeLines[i]; routeFeatures.push(this._createRouteFeature(r.points,r.color)); } this._drawFeatures(true, routeFeatures); } else { //this.routeLines = []; //this._clearDrawLayer(); } }; /** *** Create/Return route feature **/ JSMap.prototype._createRouteFeature = function(points, color) // JSMapPoint { if ((points !== null) && (points.length > 0)) { var routeStyle = { strokeColor: color, strokeOpacity: 1, strokeWidth: 2, fillColor: color, fillOpacity: 0.2 }; var rp = []; for (var i = 0; i < points.length; i++) { var olpt = this._toOpenLayerPoint(points[i]); // OpenLayers.LonLat rp.push(this._createGeometryPoint(olpt)); } var line = new OpenLayers.Geometry.LineString(rp); return new OpenLayers.Feature.Vector(line, null, routeStyle); } else { return null; } }; // ---------------------------------------------------------------------------- /** *** Remove previously drawn shapes **/ JSMap.prototype._removeShapes = function() { this._clearDrawLayer(); this.drawShapes = []; }; /** *** Draws a Shape on the map at the specified location *** @param type The Geozone shape type *** @param radiusM The circle radius, in meters *** @param points An array of points (JSMapPoint[]) *** @param color shape color *** @param zoomTo rue to zoom to drawn shape *** @return True if shape was drawn, false otherwise **/ JSMap.prototype.JSDrawShape = function(type, radiusM, verticePts, color, zoomTo) { /* no type? */ if (!type || (type == "") || (type == "!")) { this._removeShapes(); return false; } /* clear existing shapes? */ if (type.startsWith("!")) { this._removeShapes(); type = type.substr(1); } /* no geopoints? */ if (!verticePts || (verticePts.length == 0)) { return false; } /* color */ if (!color || (color == "")) { color = "#0000FF"; } /* zoom bounds */ var mapBounds = zoomTo? new OpenLayers.Bounds() : null; /* color/style */ var colorStyle = new OpenLayersColorStyle(color, 0.75, color, 0.08); /* draw shape */ var didDrawShape = false; if (type == "circle") { // ZONE_POINT_RADIUS var circleList = []; for (var p = 0; p < verticePts.length; p++) { var jsPt = verticePts[p]; // JSMapPoint var center = this._toOpenLayerPoint(jsPt); // OpenLayers.LonLat var circle = this._createCircleFeature(center, radiusM, colorStyle); if (mapBounds) { mapBounds.extend(center); mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(jsPt, radiusM, 0.0))); mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(jsPt, radiusM, 90.0))); mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(jsPt, radiusM, 180.0))); mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(jsPt, radiusM, 270.0))); } this.drawShapes.push(circle); } if (this.drawShapes.length > 0) { this._drawFeatures(false, this.drawShapes); didDrawShape = true; } } else if (type == "rectangle") { // ZONE_BOUNDED_RECT if (verticePts.length >= 2) { /* create rectangle */ var vp0 = verticePts[0]; var vp1 = verticePts[1]; var TL = this._toOpenLayerPointLatLon(((vp0.lat>vp1.lat)?vp0.lat:vp1.lat),((vp0.lon<vp1.lon)?vp0.lon:vp1.lon)); var TR = this._toOpenLayerPointLatLon(((vp0.lat>vp1.lat)?vp0.lat:vp1.lat),((vp0.lon>vp1.lon)?vp0.lon:vp1.lon)); var BL = this._toOpenLayerPointLatLon(((vp0.lat<vp1.lat)?vp0.lat:vp1.lat),((vp0.lon<vp1.lon)?vp0.lon:vp1.lon)); var BR = this._toOpenLayerPointLatLon(((vp0.lat<vp1.lat)?vp0.lat:vp1.lat),((vp0.lon>vp1.lon)?vp0.lon:vp1.lon)); var crPts = [ TL, TR, BR, BL, TL ]; var poly = this._createPolygonFeature(crPts, colorStyle); if (mapBounds) { for (var b = 0; b < crPts.length; b++) { mapBounds.extend(crPts[b]); } } this.drawShapes.push(poly); this._drawFeatures(false, this.drawShapes); didDrawShape = true; } } else if (type == "polygon") { // ZONE_POLYGON if (verticePts.length >= 3) { var crPts = []; for (var p = 0; p < verticePts.length; p++) { var olPt = this._toOpenLayerPointLatLon(verticePts[p].lat, verticePts[p].lon); crPts.push(olPt); if (mapBounds) { mapBounds.extend(olPt); } } var poly = this._createPolygonFeature(crPts, colorStyle); this.drawShapes.push(poly); this._drawFeatures(false, this.drawShapes); didDrawShape = true; } } else if (type == "corridor") { // ZONE_SWEPT_POINT_RADIUS // TODO: } else if (type == "center") { if (mapBounds) { for (var p = 0; p < verticePts.length; p++) { var olPt = this._toOpenLayerPointLatLon(verticePts[p].lat, verticePts[p].lon); mapBounds.extend(olPt); } didDrawShape = true; } } /* center on shape */ if (didDrawShape && zoomTo && mapBounds) { var centerPt = mapBounds.getCenterLonLat(); // OpenLayers.LonLat var zoomFactor = this.openLayersMap.getZoomForExtent(mapBounds); try { this.openLayersMap.setCenter(centerPt, zoomFactor); } catch (e) { /*alert("Error[JSDrawGeozone]:"+e);*/ } } /* shape not supported */ return didDrawShape; }; // ---------------------------------------------------------------------------- /** *** Draws a Geozone on the map at the specified location *** @param type The Geozone type *** @param radiusM The circle radius, in meters *** @param points An array of JSMapPoints *** @return An object representing the Circle. **/ JSMap.prototype.JSDrawGeozone = function(type, radiusM, points, color, primNdx) { // type: // 0 - ZONE_POINT_RADIUS // 1 - ZONE_BOUNDED_RECT // 2 - ZONE_SWEPT_POINT_RADIUS // 3 - ZONE_POLYGON // (type ZONE_POINT_RADIUS may only be currently supported) this._JSDrawGeozone(type, radiusM, points, color, primNdx, false) }; /** *** Draws a Geozone on the map at the specified location *** @param type The Geozone type *** @param radiusM The circle radius, in meters *** @param points An array of JSMapPoints *** @return An object representing the Circle. **/ JSMap.prototype._JSDrawGeozone = function(type, radiusM, points, color, primNdx, isDragging) { // (type ZONE_POINT_RADIUS may only be currently supported) /* Geozone mode */ jsvGeozoneMode = true; /* remove old primary */ if (!isDragging) { this.primaryCenter = null; this.primaryIndex = primNdx; } /* save geozone points */ this.geozonePoints = points; /* no points? */ if ((points === null) || (points.length <= 0)) { //alert("No Zone center!"); this._clearDrawLayer(); return null; } /* point-radius */ if (type == ZONE_POINT_RADIUS) { /* adjust radius */ if (isNaN(radiusM)) { radiusM = 5000; } if (radiusM > MAX_ZONE_RADIUS_M) { radiusM = MAX_ZONE_RADIUS_M; } if (radiusM < MIN_ZONE_RADIUS_M) { radiusM = MIN_ZONE_RADIUS_M; } jsvZoneRadiusMeters = radiusM; /* draw points */ var count = 0; var zoneFeatures = new Array(); var mapBounds = new OpenLayers.Bounds(); var polyPts = []; for (var i = 0; i < points.length; i++) { var c = points[i]; // JSMapPoint if ((c.lat != 0.0) || (c.lon != 0.0)) { var isPrimary = (i == primNdx); var center = (isPrimary && isDragging)? this.primaryCenter : this._toOpenLayerPoint(c); // OpenLayers.LonLat var circStyle = GetGeozoneStyle(isPrimary,color); zoneFeatures.push(this._createCircleFeature(center, radiusM, circStyle)); if (isPrimary && !isDragging) { this.primaryCenter = center; // OpenLayers.LonLat } polyPts.push(center); mapBounds.extend(center); mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 0.0))); mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 90.0))); mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 180.0))); mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 270.0))); count++; } } //if (DRAW_ZONE_POINT_RADIUS_POLYGON && (polyPts.length >= 3)) { // var style = new OpenLayersColorStyle("#1111CC", 0.15, "#1111CC", 0.04); // zoneFeatures.push(this._createPolygonFeature(polyPts, style)); //} /* center on geozone */ if (!isDragging) { var centerPt = this._toOpenLayerPoint(DEFAULT_CENTER); // OpenLayers.LonLat var zoomFactor = DEFAULT_ZOOM; if (count > 0) { centerPt = mapBounds.getCenterLonLat(); // OpenLayers.LonLat zoomFactor = this.openLayersMap.getZoomForExtent(mapBounds); } try { this.openLayersMap.setCenter(centerPt, zoomFactor); } catch (e) { /*alert("Error[JSDrawGeozone]:"+e);*/ } } /* create zone feature */ this._drawFeatures(true, zoneFeatures); /* var self = this; var m = new OpenLayers.Marker(olpt); this.markerLayer.addMarker(m); var dragMarkers = this.markerLayer; var dragging = false; m.events.register("mousedown", m, function(e) { dragging = true; }); m.events.register("mousemove", m, function(e) { if (dragging) { m.moveTo(self.openLayersMap.getLayerPxFromViewPortPx(e.xy)); } }); m.events.register("mouseup", m, function(e) { dragging = false; }); */ /* var controls = { drag: new OpenLayers.Control.DragMarker(dragMarkers, { 'onComplete': function() { alert('foo'); } }) } for(var key in controls) { this.openLayersMap.addControl(controls[key]); } */ } else if (type == ZONE_POLYGON) { /* set radius (should be about 30 pixels radius) */ jsvZoneRadiusMeters = radiusM; /* draw points */ var count = 0; var zoneFeatures = new Array(); var mapBounds = new OpenLayers.Bounds(); var polyPts = []; var polyPtPrim = -1; for (var i = 0; i < points.length; i++) { var c = points[i]; // JSMapPoint if ((c.lat != 0.0) || (c.lon != 0.0)) { var isPrimary = (i == primNdx); var center = (isPrimary && isDragging)? this.primaryCenter : this._toOpenLayerPoint(c); // OpenLayers.LonLat if (isPrimary) { this.primaryCenter = center; // OpenLayers.LonLat polyPtsPrim = polyPts.length; } polyPts.push(center); mapBounds.extend(center); count++; } } if (polyPts.length >= 3) { zoneFeatures.push(this._createPolygonFeature(polyPts, GetGeozoneStyle(false,color))); } /* center on geozone */ if (!isDragging) { var centerPt = this._toOpenLayerPoint(DEFAULT_CENTER); // OpenLayers.LonLat var zoomFactor = DEFAULT_ZOOM; if (count > 0) { centerPt = mapBounds.getCenterLonLat(); // OpenLayers.LonLat zoomFactor = this.openLayersMap.getZoomForExtent(mapBounds); } try { this.openLayersMap.setCenter(centerPt, zoomFactor); } catch (e) { /*alert("Error[JSDrawGeozone]:"+e);*/ } } /* current MPP */ //var zoom = this.openLayersMap.getZoom(); //var DPP = this.openLayersMap.getResolution(); // degrees per pixel radiusM = 10.0 * this.openLayersMap.getResolution(); //alert("Radius = "+radiusM + ", Zoom="+this.openLayersMap.getZoom() + ", Resolution="+this.openLayersMap.getResolution()); jsvZoneRadiusMeters = radiusM; /* draw drag circles at vertices */ for (var i = 0; i < polyPts.length; i++) { var center = polyPts[i]; // OpenLayers.LonLat var dragStyle = GetGeozoneStyle((i == polyPtsPrim), color); zoneFeatures.push(this._createCircleFeature(center, radiusM, dragStyle)); } /* create zone feature */ this._drawFeatures(true, zoneFeatures); } else if (type == ZONE_SWEPT_POINT_RADIUS) { /* adjust radius */ if (isNaN(radiusM)) { radiusM = 1000; } if (radiusM > MAX_ZONE_RADIUS_M) { radiusM = MAX_ZONE_RADIUS_M; } if (radiusM < MIN_ZONE_RADIUS_M) { radiusM = MIN_ZONE_RADIUS_M; } jsvZoneRadiusMeters = radiusM; /* draw vertices */ var count = 0; var zoneFeatures = new Array(); var mapBounds = new OpenLayers.Bounds(); var polyPts = []; // OpenLayers.LonLat[] for (var i = 0; i < points.length; i++) { var c = points[i]; // JSMapPoint if ((c.lat != 0.0) || (c.lon != 0.0)) { var isPrimary = (i == primNdx); var center = (isPrimary && isDragging)? this.primaryCenter : this._toOpenLayerPoint(c); // OpenLayers.LonLat var circStyle = GetGeozoneStyle(isPrimary,color); zoneFeatures.push(this._createCircleFeature(center, radiusM, circStyle)); if (isPrimary && !isDragging) { this.primaryCenter = center; // OpenLayers.LonLat } polyPts.push(center); // OpenLayers.LonLat mapBounds.extend(center); mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 0.0))); mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 90.0))); mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 180.0))); mapBounds.extend(this._toOpenLayerPoint(this._calcRadiusPoint(c, radiusM, 270.0))); count++; } } /* draw corridors */ if (polyPts.length >= 2) { // routeline "_createRouteFeature" for (var i = 0; i < (polyPts.length - 1); i++) { var ptA = this._toJSMapPoint(polyPts[i ]); var ptB = this._toJSMapPoint(polyPts[i+1]); var hAB = geoHeading(ptA.lat, ptA.lon, ptB.lat, ptB.lon) - 90.0; // perpendicular var rp1 = this._toOpenLayerPoint(this._calcRadiusPoint(ptA, radiusM, hAB )); var rp2 = this._toOpenLayerPoint(this._calcRadiusPoint(ptB, radiusM, hAB )); var rp3 = this._toOpenLayerPoint(this._calcRadiusPoint(ptB, radiusM, hAB + 180.0)); var rp4 = this._toOpenLayerPoint(this._calcRadiusPoint(ptA, radiusM, hAB + 180.0)); var rectPts = [ rp1, rp2, rp3, rp4 ]; zoneFeatures.push(this._createPolygonFeature(rectPts, GetGeozoneStyle(false,color))); } } /* center on geozone */ if (!isDragging) { var centerPt = this._toOpenLayerPoint(DEFAULT_CENTER); // OpenLayers.LonLat var zoomFactor = DEFAULT_ZOOM; if (count > 0) { centerPt = mapBounds.getCenterLonLat(); // OpenLayers.LonLat zoomFactor = this.openLayersMap.getZoomForExtent(mapBounds); } try { this.openLayersMap.setCenter(centerPt, zoomFactor); } catch (e) { /*alert("Error[JSDrawGeozone]:"+e);*/ } } /* create zone feature */ this._drawFeatures(true, zoneFeatures); } else { alert("Geozone type not supported: " + type); } return null; }; // ---------------------------------------------------------------------------- /** *** Returns a circle shape (OpenLayers.Feature.Vector) *** @param center The center point (OpenLayers.LonLat) of the circle *** @param radiusM The radius of the circle in meters *** @return The circle OpenLayers.Feature.Vector object **/ JSMap.prototype._createCircleFeature = function(center, radiusM, circleStyle) { if ((center !== null) && (radiusM > 0)) { //var circleShape = OpenLayers.Geometry.Polygon.createRegularPolygpm(center, radiusM, 30, 0); var circlePoints = this._getCirclePoints(center, radiusM); // OpenLayers.Geometry.Point[] var circleShape = new OpenLayers.Geometry.LinearRing(circlePoints); return new OpenLayers.Feature.Vector(circleShape, null, circleStyle); } else { return null; } }; /** *** Returns an array of points (OpenLayers.LonLat) representing a circle polygon *** @param center The center point (OpenLayers.LonLat) of the circle *** @param radiusM The radius of the circle in meters *** @return An array of points (OpenLayers.LonLat) representing a circle polygon **/ JSMap.prototype._getCirclePoints = function(center, radiusM) { var jspt = this._toJSMapPoint(center); var rLat = geoRadians(jspt.lat); // radians var rLon = geoRadians(jspt.lon); // radians var d = radiusM / EARTH_RADIUS_METERS; var circlePoints = new Array(); for (x = 0; x <= 360; x += 12) { var xrad = geoRadians(x); var tLat = Math.asin(Math.sin(rLat) * Math.cos(d) + Math.cos(rLat) * Math.sin(d) * Math.cos(xrad)); var tLon = rLon + Math.atan2(Math.sin(xrad) * Math.sin(d) * Math.cos(rLat), Math.cos(d) - Math.sin(rLat) * Math.sin(tLat)); var olpt = this._toOpenLayerPointLatLon(geoDegrees(tLat),geoDegrees(tLon)); circlePoints.push(this._createGeometryPoint(olpt)); } return circlePoints; }; /** *** Calculate the lat/lon on the radius of the circle in the 'heading' direction **/ JSMap.prototype._calcRadiusPoint = function(center/*JSMapPoint*/, radiusM, heading) { var pt = geoRadiusPoint(center.lat, center.lon, radiusM, heading); // { lat: <>, lon: <> } return new JSMapPoint(pt.lat, pt.lon); }; // ---------------------------------------------------------------------------- /** *** Returns a polygon shape (OpenLayers.Feature.Vector) *** @param vertices An array of polygon vertice points (OpenLayers.LonLat) of the circle *** @return The polygon OpenLayers.Feature.Vector object **/ JSMap.prototype._createPolygonFeature = function(vertices, colorStyle) { if ((vertices !== null) && (vertices.length >= 3)) { var polyStyle = colorStyle; var polyPoints = []; for (var i = 0; i < vertices.length; i++) { polyPoints.push(this._createGeometryPoint(vertices[i])); } var polyShape = new OpenLayers.Geometry.LinearRing(polyPoints); return new OpenLayers.Feature.Vector(polyShape, null, polyStyle); } else { return null; } }; // ---------------------------------------------------------------------------- /** *** Create/Adjust feature points *** @param olpt The OpenLayers.LonLat point **/ JSMap.prototype._createGeometryPoint = function(olpt) // OpenLayers.LonLat { /* This seems to be fixed (as of 2008/09/28) if (this.userAgent_MSIE) { // TODO: find out why this is needed and fix it at the source. var px = this.openLayersMap.getViewPortPxFromLonLat(olpt); px.x -= (this.openLayersMap.size.w / 2); olpt = this.openLayersMap.getLonLatFromViewPortPx(px); } */ return new OpenLayers.Geometry.Point(olpt.lon, olpt.lat); }; // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Mouse modifier keys: e.shiftKey, e.altKey, e.ctrlKey // Mouse buttons: OpenLayers.Event.isLeftClick(e) /** *** Retrun adjusted mouse cursor hotspot **/ JSMap.prototype._mouseLocation = function(xy) { if (this.userAgent_MSIE) { // the "crosshair" cursor hotpsot is off by 4px return new OpenLayers.Pixel(xy.x - 4, xy.y - 4); } else { return xy; } }; /** *** Mouse event handler to draw circles/lines on the map *** @param e The mouse event **/ JSMap.prototype._event_OnMouseDown = function(e) { /* quick exits */ if (!OpenLayers.Event.isLeftClick(e) || e.altKey || (e.ctrlKey && e.shiftKey)) { return true; } /* mouse down point */ var LL = this._toJSMapPoint(this.openLayersMap.getLonLatFromViewPortPx(this._mouseLocation(e.xy))); jsmapElem.style.cursor = 'crosshair'; /* start distance ruler drag */ if (e.ctrlKey) { this.dragType = DRAG_RULER; this._clearRulerLayer(true); this.dragRulerStart = LL; // JSMapPoint jsmSetDistanceDisplay(0); OpenLayers.Event.stop(e); return false; } /* geozone mode */ if (jsvGeozoneMode && jsvZoneEditable) { var radiusM = zoneMapGetRadius(false); // check primary point if (this.primaryCenter !== null) { var CC = this._toJSMapPoint(this.primaryCenter); if (geoDistanceMeters(CC.lat, CC.lon, LL.lat, LL.lon) <= radiusM) { if (e.shiftKey) { // resize this.dragType = DRAG_GEOZONE_RADIUS; this._clearRulerLayer(true); } else { // inside geozone, move this.dragType = DRAG_GEOZONE_CENTER; this.dragZoneOffsetLat = LL.lat - CC.lat; this.dragZoneOffsetLon = LL.lon - CC.lon; } OpenLayers.Event.stop(e); return false; } } // check other points if (!e.shiftKey && this.geozonePoints && (this.geozonePoints.length > 0)) { for (var i = 0; i < this.geozonePoints.length; i++) { if (geoDistanceMeters(this.geozonePoints[i].lat, this.geozonePoints[i].lon, LL.lat, LL.lon) <= radiusM) { this.primaryIndex = i; this.primaryCenter = this.geozonePoints[i]; zoneMapSetIndex(this.primaryIndex); this._JSDrawGeozone(jsvZoneType, jsvZoneRadiusMeters, this.geozonePoints, jsvZoneColor, this.primaryIndex, false); // inside geozone, move CC = this._toJSMapPoint(this.primaryCenter); this.dragType = DRAG_GEOZONE_CENTER; this.dragZoneOffsetLat = LL.lat - CC.lat; this.dragZoneOffsetLon = LL.lon - CC.lon; OpenLayers.Event.stop(e); return false; } } } } this.dragType = DRAG_NONE; return true; }; /** *** Mouse event handler to draw circles on the map *** @param e The mouse event **/ JSMap.prototype._event_OnMouseUp = function(e) { /* geozone mode */ if (jsvGeozoneMode && ((this.dragType & DRAG_GEOZONE) != 0)) { var CC = this._toJSMapPoint(this.primaryCenter); var radiusM = zoneMapGetRadius(false); jsmSetPointZoneValue(CC.lat, CC.lon, radiusM); this.dragType = DRAG_NONE; mapProviderParseZones(jsvZoneList); OpenLayers.Event.stop(e); return false; } /* normal mode */ this.dragType = DRAG_NONE; return true; }; /** *** Mouse event handler to detect lat/lon changes and draw circles/lines on the map *** @param e The mouse event **/ JSMap.prototype._event_OnMouseMove = function(e) { var olpt = this.openLayersMap.getLonLatFromViewPortPx(this._mouseLocation(e.xy)); if (!olpt) { return true; } var LL = this._toJSMapPoint(olpt); /* Latitude/Longitude change */ jsmSetLatLonDisplay(LL.lat, LL.lon); jsmapElem.style.cursor = 'crosshair'; /* distance ruler */ if (this.dragType == DRAG_RULER) { this.dragRulerEnd = LL; var CC = this.dragRulerStart; jsmSetDistanceDisplay(geoDistanceMeters(CC.lat, CC.lon, LL.lat, LL.lon)); this._drawRuler([ this._createRulerFeature(this.dragRulerStart, this.dragRulerEnd) ]); OpenLayers.Event.stop(e); return false; } /* geozone mode */ if (this.dragType == DRAG_GEOZONE_RADIUS) { var CC = this._toJSMapPoint(this.primaryCenter); jsvZoneRadiusMeters = Math.round(geoDistanceMeters(CC.lat, CC.lon, LL.lat, LL.lon)); if (jsvZoneRadiusMeters > MAX_ZONE_RADIUS_M) { jsvZoneRadiusMeters = MAX_ZONE_RADIUS_M; } if (jsvZoneRadiusMeters < MIN_ZONE_RADIUS_M) { jsvZoneRadiusMeters = MIN_ZONE_RADIUS_M; } var features = [ this._createCircleFeature(this.primaryCenter,jsvZoneRadiusMeters,GetGeozoneStyle(true,jsvZoneColor)) ]; this._drawFeatures(true, features); jsmSetDistanceDisplay(jsvZoneRadiusMeters); //mapProviderParseZones(jsvZoneList); OpenLayers.Event.stop(e); return false; } /* geozone mode */ if (this.dragType == DRAG_GEOZONE_CENTER) { var CC = new JSMapPoint(LL.lat - this.dragZoneOffsetLat, LL.lon - this.dragZoneOffsetLon); this.primaryCenter = this._toOpenLayerPoint(CC); var REDRAW_GEOZONE = true; if (REDRAW_GEOZONE) { // redraw the entire Geozone this._JSDrawGeozone(jsvZoneType, jsvZoneRadiusMeters, this.geozonePoints, jsvZoneColor, this.primaryIndex, true); //mapProviderParseZones(jsvZoneList); } else { // just draw the single point-radius [zoneFeatures] var feature = [ this._createCircleFeature(this.primaryCenter, jsvZoneRadiusMeters, GetGeozoneStyle(true,jsvZoneColor)) ]; this._drawFeatures(true, feature); } OpenLayers.Event.stop(e); return false; } return true; }; /** *** Mouse event handler to recenter map *** @param e The mouse event **/ JSMap.prototype._event_OnClick = function(e) { /* geozone mode */ if (jsvGeozoneMode && jsvZoneEditable && !e.ctrlKey && !e.shiftKey && !e.altKey) { var LL = this._toJSMapPoint(this.openLayersMap.getLonLatFromViewPortPx(this._mouseLocation(e.xy))); // where you clicked var CC = (this.primaryCenter !== null)? this._toJSMapPoint(this.primaryCenter) : new JSMapPoint(0.0,0.0); // where the primary center is var CCIsValid = ((CC.lat != 0.0) || (CC.lon != 0.0)); var CCLLDistKM = geoDistanceMeters(CC.lat, CC.lon, LL.lat, LL.lon); if (jsvZoneType == ZONE_POINT_RADIUS) { var radiusM = zoneMapGetRadius(false); // inside primary zone? if (CCLLDistKM <= radiusM) { return false; } // inside any zone? if (this.geozonePoints && (this.geozonePoints.length > 0)) { for (var i = 0; i < this.geozonePoints.length; i++) { if (i == this.primaryIndex) { continue; } var gpt = this.geozonePoints[i]; if (geoDistanceMeters(gpt.lat, gpt.lon, LL.lat, LL.lon) <= radiusM) { return false; } } } // outside geozone, recenter jsmSetPointZoneValue(LL.lat, LL.lon, radiusM); mapProviderParseZones(jsvZoneList); OpenLayers.Event.stop(e); return true; } else if (jsvZoneType == ZONE_POLYGON) { var radiusM = jsvZoneRadiusMeters; // inside primary zone? if (CCLLDistKM <= radiusM) { return false; } // inside any zone? if (this.geozonePoints && (this.geozonePoints.length > 0)) { for (var i = 0; i < this.geozonePoints.length; i++) { if (i == this.primaryIndex) { continue; } var gpt = this.geozonePoints[i]; if (geoDistanceMeters(gpt.lat, gpt.lon, LL.lat, LL.lon) <= radiusM) { return false; } } } // count number of valid points var count = 0; for (var z = 0; z < jsvZoneList.length; z++) { if ((jsvZoneList[z].lat != 0.0) || (jsvZoneList[z].lon != 0.0)) { count++; } } if (count == 0) { // no valid points - create default polygon var radiusM = 450; var crLat = geoRadians(LL.lat); // radians var crLon = geoRadians(LL.lon); // radians for (x = 0; x < jsvZoneList.length; x++) { var deg = x * (360.0 / jsvZoneList.length); var radM = radiusM / EARTH_RADIUS_METERS; if ((deg == 0.0) || ((deg > 170.0) && (deg < 190.0))) { radM *= 0.8; } var xrad = geoRadians(deg); // radians var rrLat = Math.asin(Math.sin(crLat) * Math.cos(radM) + Math.cos(crLat) * Math.sin(radM) * Math.cos(xrad)); var rrLon = crLon + Math.atan2(Math.sin(xrad) * Math.sin(radM) * Math.cos(crLat), Math.cos(radM)-Math.sin(crLat) * Math.sin(rrLat)); _jsmSetPointZoneValue(x, geoDegrees(rrLat), geoDegrees(rrLon), 0); } } else { // move valid points to new location var deltaLat = LL.lat - CC.lat; var deltaLon = LL.lon - CC.lon; for (var x = 0; x < jsvZoneList.length; x++) { var pt = jsvZoneList[x]; if ((pt.lat != 0.0) || (pt.lon != 0.0)) { _jsmSetPointZoneValue(x, (pt.lat + deltaLat), (pt.lon + deltaLon), 0); } } } mapProviderParseZones(jsvZoneList); OpenLayers.Event.stop(e); return true; } else if (jsvZoneType == ZONE_SWEPT_POINT_RADIUS) { var radiusM = jsvZoneRadiusMeters; // inside primary zone? if (CCLLDistKM <= radiusM) { return false; } // inside any zone? if (this.geozonePoints && (this.geozonePoints.length > 0)) { for (var i = 0; i < this.geozonePoints.length; i++) { if (i == this.primaryIndex) { continue; } var gpt = this.geozonePoints[i]; if (geoDistanceMeters(gpt.lat, gpt.lon, LL.lat, LL.lon) <= radiusM) { return false; } } } // count number of valid points var count = 0; var maxDistKM = 0.0; var lastPT = null; for (var z = 0; z < jsvZoneList.length; z++) { if ((jsvZoneList[z].lat != 0.0) || (jsvZoneList[z].lon != 0.0)) { count++; if (lastPT !== null) { var dkm = geoDistanceMeters(lastPT.lat, lastPT.lon, jsvZoneList[z].lat, jsvZoneList[z].lon); if (dkm > maxDistKM) { maxDistKM = dkm; } } else { lastPT = jsvZoneList[z]; // first valid point } } } var maxDeltaKM = ((maxDistKM > 5000)? maxDistKM : 5000) * 1.5; if (!CCIsValid || (count <= 0) || (CCLLDistKM <= maxDeltaKM)) { jsmSetPointZoneValue(LL.lat, LL.lon, radiusM); } // reparse zone mapProviderParseZones(jsvZoneList); OpenLayers.Event.stop(e); return true; } else { return false; } } }; // ---------------------------------------------------------------------------- /** *** map zoomed **/ JSMap.prototype._event_ZoomEnd = function() { this._event_MoveEnd(); }; /** *** map zoomed/panned **/ JSMap.prototype._event_MoveEnd = function() { if (this.userAgent_MSIE) { var zm = this.openLayersMap.getZoom(); var sz = this.openLayersMap.getSize(); if ((this.lastMapZoom != zm) || (sz.w != this.lastMapSize.w) || (sz.h != this.lastMapSize.h)) { // TODO: (see '_createGeometryPoint' above) This is necessary because everything seems to be // shifted by MapWidth/2 pixels. if (jsvGeozoneMode) { // redraw the Geozone var features = [ this._createCircleFeature(this.primaryCenter, jsvZoneRadiusMeters, GetGeozoneStyle(true,jsvZoneColor)) ]; this._drawFeatures(true, features); } else if (this.routeLines && (this.routeLines.length > 0)) { // redraw the route var routeFeatures = []; for (var i = 0; i < this.routeLines.length; i++) { var r = this.routeLines[i]; routeFeatures.push(this._createRouteFeature(r.points,r.color)); } this._drawFeatures(true, routeFeatures); } if ((this.dragRulerStart !== null) && (this.dragRulerEnd !== null)) { // redraw the ruler this._drawRuler([ this._createRulerFeature(this.dragRulerStart, this.dragRulerEnd) ]); } this.lastMapZoom = zm; this.lastMapSize = sz; } } }; // ----------------------------------------------------------------------------
aldridged/gtg-gts-bhp
war/track/js/maps/OpenLayers.js
JavaScript
apache-2.0
68,376
var FormFileUpload = function () { return { //main function to initiate the module init: function () { // Initialize the jQuery File Upload widget: $('#fileupload').fileupload({ disableImageResize: false, autoUpload: false, disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent), maxFileSize: 5000000, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, }); // Enable iframe cross-domain access via redirect option: $('#fileupload').fileupload( 'option', 'redirect', window.location.href.replace( /\/[^\/]*$/, '/cors/result.html?%s' ) ); // Upload server status check for browsers with CORS support: if ($.support.cors) { $.ajax({ type: 'HEAD' }).fail(function () { $('<div class="alert alert-danger"/>') .text('Upload server currently unavailable - ' + new Date()) .appendTo('#fileupload'); }); } // Load & display existing files: $('#fileupload').addClass('fileupload-processing'); $.ajax({ // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, url: $('#fileupload').fileupload('option', 'url'), dataType: 'json', context: $('#fileupload')[0] }).always(function () { $(this).removeClass('fileupload-processing'); }).done(function (result) { $(this).fileupload('option', 'done') .call(this, $.Event('done'), {result: result}); }); } }; }();
zeickan/Infected-Engine
static/admin/pages/scripts/form-fileupload.js
JavaScript
apache-2.0
2,203
๏ปฟ/** enyo.ScrollStrategy is a helper kind which implements a default scrolling strategy for an <a href="#enyo.Scroller">enyo.Scroller</a>. enyo.ScrollStrategy is not typically created in application code. */ enyo.kind({ name: "enyo.ScrollStrategy", noDom: true, events: { onScroll: "doScroll" }, published: { /** Specifies how to horizontally scroll. Acceptable values are: * "scroll": always shows a scrollbar; sets overflow: scroll * "auto": scrolls only if needed; sets overflow: auto * "hidden": never scrolls; sets overflow: hidden * "default": same as auto. */ vertical: "default", /** Specifies how to vertically scroll. Acceptable values are: * "scroll": always shows a scrollbar; sets overflow: scroll * "auto": scrolls only if needed; sets overflow: auto * "hidden": never scrolls; sets overflow: hidden * "default": same as auto. */ horizontal: "default", scrollLeft: 0, scrollTop: 0 }, //* @protected handlers: { onscroll: "scroll", ondown: "down", onmove: "move" }, create: function() { this.inherited(arguments); this.horizontalChanged(); this.verticalChanged(); this.container.setAttribute("onscroll", enyo.bubbler); }, rendered: function() { this.inherited(arguments); this.scrollNode = this.calcScrollNode(); }, teardownRender: function() { this.inherited(arguments); this.scrollNode = null; }, calcScrollNode: function() { return this.container.hasNode(); }, horizontalChanged: function() { this.container.applyStyle("overflow-x", this.horizontal == "default" ? "auto" : this.horizontal); }, verticalChanged: function() { this.container.applyStyle("overflow-y", this.vertical == "default" ? "auto" : this.vertical); }, scroll: function(inSender, e) { return this.doScroll(e); }, scrollTo: function(inX, inY) { if (this.scrollNode) { this.setScrollLeft(inX); this.setScrollTop(inY); } }, scrollIntoView: function(inControl, inAlignWithTop) { if (inControl.hasNode()) { inControl.node.scrollIntoView(inAlignWithTop); } }, setScrollTop: function(inTop) { this.scrollTop = inTop; if (this.scrollNode) { this.scrollNode.scrollTop = this.scrollTop; } }, setScrollLeft: function(inLeft) { this.scrollLeft = inLeft; if (this.scrollNode) { this.scrollNode.scrollLeft = this.scrollLeft; } }, getScrollLeft: function() { return this.scrollNode ? this.scrollNode.scrollLeft : this.scrollLeft; }, getScrollTop: function() { return this.scrollNode ? this.scrollNode.scrollTop : this.scrollTop; }, getScrollBounds: function() { var n = this.scrollNode; var b = { left: this.getScrollLeft(), top: this.getScrollTop(), height: n ? n.scrollHeight : 0, width: n ? n.scrollWidth : 0 }; b.maxLeft = Math.max(0, b.width - n.clientWidth); b.maxTop = Math.max(0, b.height - n.clientHeight); return b; }, // NOTE: down, move handlers are needed only for native touch scrollers // avoid allowing scroll when starting at a vertical boundary to prevent ios from window scrolling. down: function(inSender, inEvent) { // if we start on a boundary, need to check direction of first move var y = this.getScrollTop(); this.atTopEdge = (y == 0); var sb = this.getScrollBounds(); this.atBottomEdge = y == sb.maxTop; this.downY = inEvent.pageY; this.downX = inEvent.pageX; this.canVertical = sb.maxTop > 0 && this.vertical != "hidden"; this.canHorizontal = sb.maxLeft > 0 && this.horizontal != "hidden"; }, // NOTE: mobile native scrollers need touchmove. Indicate this by // setting the requireTouchmove property to true (must do this in move event // because must respond to first move or native action fails). move: function(inSender, inEvent) { var dy = inEvent.pageY - this.downY; var dx = inEvent.pageX - this.downX; var v = this.canVertical, h = this.canHorizontal; // check to see if it is dragging vertically which would trigger window scrolling var isV = (Math.abs(dy) > 10) && (Math.abs(dy) > Math.abs(dx)); // abort scroll if dragging oob from vertical edge if (isV && (v || h) && (this.atTopEdge || this.atBottomEdge)) { var oob = (this.atTopEdge && (dy >= 0) || this.atBottomEdge && (dy <= 0)); // we only need to abort 1 event to prevent window native scrolling, but we // perform oob check around a small radius because a small in bounds move may // not trigger scrolling for this scroller meaning the window might still scroll. if (Math.abs(dy) > 25) { this.atTopEdge = this.atBottomEdge = false; } if (oob) { return; } } inEvent.requireTouchmove = (v || h); } });
pierotofy/glassomium
src/server/WebRoot/apps/Youtube/enyo/source/touch/ScrollStrategy.js
JavaScript
apache-2.0
4,637
/* jshint unused: false */ /* global beforeEach, afterEach */ /* global describe, it, expect, jasmine */ /* global runs, spyOn, waitsFor, waits */ /* global window, eb, loadFixtures, document */ /* global $, _, d3*/ /* global describeInterface, describeIntegeration*/ /* global PreviewAdapter*/ // ////////////////////////////////////////////////////////////////////////////// // / @brief Graph functionality // / // / @file // / // / DISCLAIMER // / // / Copyright 2010-2012 triagens GmbH, Cologne, Germany // / // / Licensed under the Apache License, Version 2.0 (the "License") // / you may not use this file except in compliance with the License. // / You may obtain a copy of the License at // / // / http://www.apache.org/licenses/LICENSE-2.0 // / // / Unless required by applicable law or agreed to in writing, software // / distributed under the License is distributed on an "AS IS" BASIS, // / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // / See the License for the specific language governing permissions and // / limitations under the License. // / // / Copyright holder is triAGENS GmbH, Cologne, Germany // / // / @author Michael Hackstein // / @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany // ////////////////////////////////////////////////////////////////////////////// (function () { 'use strict'; describe('Preview Adapter', function () { describeInterface(new PreviewAdapter([], [], {})); /* describeIntegeration(function() { spyOn($, "ajax").andCallFake(function(req) { var node1 = {_id: 1}, node2 = {_id: 2}, edge = {_id: "1-2", _from: 1, _to: 2} switch(req.type) { case "DELETE": req.success() break case "POST": if (req.url.match(/nodes$/)) { req.success({_id: 1}) } else if (req.url.match(/edges/)) { req.success({_id: "1-2"}) } break case "GET": req.success({ first: {_id: 1}, nodes: { "1": {_id: 1}, "2": {_id: 2} }, edges: { "1-2": {_id: "1-2", _from: 1, _to: 2} } }) break default: req.success() } }) return new FoxxAdapter([], [], "foxx/route") }) */ var adapter, nodes, edges; beforeEach(function () { nodes = []; edges = []; }); it('should throw an error if no nodes are given', function () { expect( function () { var t = new PreviewAdapter(); } ).toThrow('The nodes have to be given.'); }); it('should throw an error if no edges are given', function () { expect( function () { var t = new PreviewAdapter([]); } ).toThrow('The edges have to be given.'); }); it('should not throw an error if necessary info is given', function () { expect( function () { var t = new PreviewAdapter([], []); } ).toThrow('A reference to the graph viewer has to be given.'); }); it('should not throw an error if necessary info is given', function () { expect( function () { var t = new PreviewAdapter([], [], {}); } ).not.toThrow(); }); it('should create a nodeReducer instance', function () { spyOn(window, 'NodeReducer'); var adapter = new PreviewAdapter( nodes, edges, {} ); expect(window.NodeReducer).wasCalledWith(); }); describe('setup correctly', function () { var viewer; beforeEach(function () { var self = this; viewer = { cleanUp: function () {} }; self.fakeReducerRequest = function () {}; self.fakeReducerBucketRequest = function () {}; spyOn(window, 'NodeReducer').andCallFake(function () { return { getCommunity: function (limit, focus) { if (focus !== undefined) { return self.fakeReducerRequest(limit, focus); } return self.fakeReducerRequest(limit); }, bucketNodes: function (toSort, numBuckets) { return self.fakeReducerBucketRequest(toSort, numBuckets); } }; }); adapter = new PreviewAdapter( nodes, edges, viewer ); }); it('should be load a graph of 5 nodes and 5 edges', function () { var called, id; runs(function () { called = false; id = 1; var callback = function () { called = true; }; adapter.loadNode(id, callback); }); waitsFor(function () { return called; }, 1000); runs(function () { expect(nodes.length).toEqual(5); expect(edges.length).toEqual(5); }); }); it('nodes should offer a label', function () { var called, id; runs(function () { called = false; id = 1; var callback = function () { called = true; }; adapter.loadNode(id, callback); }); waitsFor(function () { return called; }, 1000); runs(function () { _.each(nodes, function (n) { expect(n._data.label).toBeDefined(); }); }); }); it('node one should offer an image', function () { var called, id; runs(function () { called = false; id = 1; var callback = function () { called = true; }; adapter.loadNode(id, callback); }); waitsFor(function () { return called; }, 1000); runs(function () { _.each(nodes, function (n) { if (n._id === 1) { expect(n._data.image).toBeDefined(); expect(n._data.image).toEqual('img/stored.png'); } else { expect(n._data.image).toBeUndefined(); } }); }); }); it('edges should offer a label', function () { var called, id; runs(function () { called = false; id = 1; var callback = function () { called = true; }; adapter.loadNode(id, callback); }); waitsFor(function () { return called; }, 1000); runs(function () { _.each(edges, function (e) { expect(e._data.label).toBeDefined(); }); }); }); it('should alert insertion of a node', function () { spyOn(window, 'alert'); var node = {_id: 1}; adapter.createNode(node); expect(window.alert).wasCalledWith('Server-side: createNode was triggered.'); }); it('should alert change of a node', function () { spyOn(window, 'alert'); var toPatch = {_id: 1}, data = {name: 'Alice'}; adapter.patchNode(toPatch, data); expect(window.alert).wasCalledWith('Server-side: patchNode was triggered.'); }); it('should alert deletion of a node', function () { spyOn(window, 'alert'); var node = {_id: 1}; adapter.deleteNode(node); expect(window.alert).wasCalledWith('Server-side: deleteNode was triggered.'); expect(window.alert).wasCalledWith('Server-side: onNodeDelete was triggered.'); }); it('should be able to insert an edge', function () { spyOn(window, 'alert'); var source = {_id: 1}, target = {_id: 2}, edge = { source: source, target: target, label: 'Foxx' }; adapter.createEdge(edge); expect(window.alert).wasCalledWith('Server-side: createEdge was triggered.'); }); it('should be able to change an edge', function () { spyOn(window, 'alert'); var source = {_id: 1}, target = {_id: 2}, edge = { _id: '1-2', source: source, target: target }, patch = { label: 'Foxx' }; adapter.patchEdge(edge, patch); expect(window.alert).wasCalledWith('Server-side: patchEdge was triggered.'); }); it('should be able to delete an edge', function () { spyOn(window, 'alert'); var source = {_id: 1}, target = {_id: 2}, edge = { _id: '1-2', source: source, target: target }; adapter.deleteEdge(edge); expect(window.alert).wasCalledWith('Server-side: deleteEdge was triggered.'); }); }); }); }());
hkernbach/arangodb
js/apps/system/_admin/aardvark/APP/test/specs/graphViewer/specAdapter/previewAdapterSpec.js
JavaScript
apache-2.0
8,929
/* @licstart The following is the entire license notice for the JavaScript code in this file. Copyright (C) 1997-2019 by Dimitri van Heesch This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. @licend The above is the entire license notice for the JavaScript code in this file */ var menudata={children:[ {text:"Introduction",url:"index.html"}, {text:"Tutorial",url:"quick_guide.html"}, {text:"Guides",url:"pages.html"}, {text:"Reference",url:"modules.html"}, {text:"Files",url:"files.html"}]}
marwac-9/myframework
code/exts/glfw/docs/html/menudata.js
JavaScript
apache-2.0
1,065
/* * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ CLASS({ name: 'ErrorDAO', package: 'foam.core.dao', extends: 'AbstractDAO', methods: { put: function(obj, sink) { sink && sink.error && sink.error('put', obj); }, remove: function(obj, sink) { sink && sink.error && sink.error('remove', obj); } } });
mdittmer/foam
js/foam/core/dao/ErrorDAO.js
JavaScript
apache-2.0
917
import Ember from 'ember'; import Sortable from 'ui/mixins/sortable'; export default Ember.Controller.extend(Sortable, { sortBy: 'name', sorts: { state: ['stateSort','name','id'], name: ['name','id'], ip: ['displayIp','name','id'], image: ['imageUuid','id'], }, });
ubiquityhosting/rancher_ui
app/virtualmachines/index/controller.js
JavaScript
apache-2.0
305
/* * Copyright 2013 The Polymer Authors. All rights reserved. * Use of this source code is goverened by a BSD-style * license that can be found in the LICENSE file. */ suite('HTMLShadowElement', function() { var unwrap = ShadowDOMPolyfill.unwrap; test('olderShadowRoot', function() { var host = document.createElement('div'); host.innerHTML = '<a>a</a><b>b</b>'; var a = host.firstChild; var b = host.lastChild; var sr = host.createShadowRoot(); sr.innerHTML = 'a<shadow>b</shadow>c'; var shadow = sr.firstElementChild; host.offsetWidth; assert.isTrue(shadow instanceof HTMLShadowElement); assert.isNull(shadow.olderShadowRoot); var sr2 = host.createShadowRoot(); sr2.innerHTML = 'd<shadow>e</shadow>f'; var shadow2 = sr2.firstElementChild; host.offsetWidth; assert.isTrue(shadow instanceof HTMLShadowElement); assert.isNull(shadow.olderShadowRoot); assert.isTrue(shadow2 instanceof HTMLShadowElement); assert.equal(shadow2.olderShadowRoot, sr); assert.equal(unwrap(host).innerHTML, 'dabcf'); }); });
passiweinberger/passiweinberger.github.io
webgl-globe/polymer-globe/polymer/polymer-all/ShadowDOM/test/js/HTMLShadowElement.js
JavaScript
apache-2.0
1,096
function infostart_rate(ob_id, vote) { $.get("/bitrix/components/infostart/objects_new.list/ajax_rate.php", {ID:ob_id, TYPE:vote}, function(answer) { alert(answer); }); }
allustin/one-c-connectors
OldDemo/1c-transaction/Article/ะ“ะปะพะฑะฐะปัŒะฝั‹ะต ั‚ั€ะฐะฝะทะฐะบั†ะธะธ ะฒ ัะตั€ะฒะธั-ะพั€ะธะตะฝั‚ะธั€ะพะฒะฐะฝะฝะพะน ะฐั€ั…ะธั‚ะตะบั‚ัƒั€ะต ะธ... 1ะก_files/scripts.js
JavaScript
apache-2.0
200
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { CKEDITOR.dialog.add( 'pastetext', function( editor ) { return { title : editor.lang.pasteText.title, minWidth : CKEDITOR.env.ie && CKEDITOR.env.quirks ? 368 : 350, minHeight : 240, onShow : function(){ this.setupContent(); }, onOk : function(){ this.commitContent(); }, contents : [ { label : editor.lang.common.generalTab, id : 'general', elements : [ { type : 'html', id : 'pasteMsg', html : '<div style="white-space:normal;width:340px;">' + editor.lang.clipboard.pasteMsg + '</div>' }, { type : 'textarea', id : 'content', className : 'cke_pastetext', onLoad : function() { var label = this.getDialog().getContentElement( 'general', 'pasteMsg' ).getElement(), input = this.getElement().getElementsByTag( 'textarea' ).getItem( 0 ); input.setAttribute( 'aria-labelledby', label.$.id ); input.setStyle( 'direction', editor.config.contentsLangDirection ); }, focus : function() { this.getElement().focus(); }, setup : function() { this.setValue( '' ); }, commit : function() { var value = this.getValue(); setTimeout( function() { editor.fire( 'paste', { 'text' : value } ); }, 0 ); } } ] } ] }; }); })();
taobataoma/saivi
cms/editor/ckeditor/_source/plugins/pastetext/dialogs/pastetext.js
JavaScript
apache-2.0
1,694
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 15.2.3.13-2-5 description: Object.isExtensible returns true for all built-in objects (String) ---*/ var e = Object.isExtensible(String); assert.sameValue(e, true, 'e');
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Object/isExtensible/15.2.3.13-2-5.js
JavaScript
bsd-2-clause
320
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 15.2.3.12-3-8 description: Object.isFrozen returns false for all built-in objects (String) ---*/ var b = Object.isFrozen(String); assert.sameValue(b, false, 'b');
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Object/isFrozen/15.2.3.12-3-8.js
JavaScript
bsd-2-clause
314
// Copyright (C) 2015 Andrรฉ Bargull. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-string.prototype.valueof description: > String.prototype.valueOf.length is 0. info: | String.prototype.valueOf ( ) 17 ECMAScript Standard Built-in Objects: Every built-in Function object, including constructors, has a length property whose value is an integer. Unless otherwise specified, this value is equal to the largest number of named arguments shown in the subclause headings for the function description, including optional parameters. However, rest parameters shown using the form โ€œ...nameโ€ are not included in the default argument count. Unless otherwise specified, the length property of a built-in Function object has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }. includes: [propertyHelper.js] ---*/ verifyProperty(String.prototype.valueOf, 'length', { value: 0, writable: false, enumerable: false, configurable: true, });
sebastienros/jint
Jint.Tests.Test262/test/built-ins/String/prototype/valueOf/length.js
JavaScript
bsd-2-clause
1,079
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 15.2.3.6-4-542 description: > ES5 Attributes - property ([[Get]] is a Function, [[Set]] is a Function, [[Enumerable]] is true, [[Configurable]] is false) is undeletable includes: [propertyHelper.js] ---*/ var obj = {}; var getFunc = function() { return 1001; }; var verifySetFunc = "data"; var setFunc = function(value) { verifySetFunc = value; }; Object.defineProperty(obj, "prop", { get: getFunc, set: setFunc, enumerable: true, configurable: false }); assert(obj.hasOwnProperty("prop")); verifyNotConfigurable(obj, "prop");
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Object/defineProperty/15.2.3.6-4-542.js
JavaScript
bsd-2-clause
705
// Copyright (C) 2017 Mozilla Corporation. All rights reserved. // This code is governed by the license found in the LICENSE file. /*--- esid: sec-atomics.islockfree description: Testing descriptor property of Atomics.add includes: [propertyHelper.js] features: [Atomics] ---*/ verifyProperty(Atomics, 'add', { enumerable: false, writable: true, configurable: true, });
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Atomics/isLockFree/descriptor.js
JavaScript
bsd-2-clause
378
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule View * @flow */ 'use strict'; const EdgeInsetsPropType = require('EdgeInsetsPropType'); const NativeMethodsMixin = require('NativeMethodsMixin'); const NativeModules = require('NativeModules'); const Platform = require('Platform'); const React = require('React'); const ReactNativeStyleAttributes = require('ReactNativeStyleAttributes'); const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); const StyleSheetPropType = require('StyleSheetPropType'); const ViewStylePropTypes = require('ViewStylePropTypes'); const invariant = require('fbjs/lib/invariant'); const { AccessibilityComponentTypes, AccessibilityTraits, } = require('ViewAccessibility'); var TVViewPropTypes = {}; if (Platform.isTVOS) { TVViewPropTypes = require('TVViewPropTypes'); } const requireNativeComponent = require('requireNativeComponent'); const PropTypes = React.PropTypes; const stylePropType = StyleSheetPropType(ViewStylePropTypes); const forceTouchAvailable = (NativeModules.IOSConstants && NativeModules.IOSConstants.forceTouchAvailable) || false; const statics = { AccessibilityTraits, AccessibilityComponentType: AccessibilityComponentTypes, /** * Is 3D Touch / Force Touch available (i.e. will touch events include `force`) * @platform ios */ forceTouchAvailable, }; /** * The most fundamental component for building a UI, `View` is a container that supports layout with * [flexbox](docs/flexbox.html), [style](docs/style.html), * [some touch handling](docs/handling-touches.html), and * [accessibility](docs/accessibility.html) controls. `View` maps directly to the * native view equivalent on whatever platform React Native is running on, whether that is a * `UIView`, `<div>`, `android.view`, etc. * * `View` is designed to be nested inside other views and can have 0 to many children of any type. * * This example creates a `View` that wraps two colored boxes and a text component in a row with * padding. * * ```javascript * class ViewColoredBoxesWithText extends Component { * render() { * return ( * <View style={{flexDirection: 'row', height: 100, padding: 20}}> * <View style={{backgroundColor: 'blue', flex: 0.3}} /> * <View style={{backgroundColor: 'red', flex: 0.5}} /> * <Text>Hello World!</Text> * </View> * ); * } * } * ``` * * > `View`s are designed to be used with [`StyleSheet`](docs/style.html) for clarity * > and performance, although inline styles are also supported. * * ### Synthetic Touch Events * * For `View` responder props (e.g., `onResponderMove`), the synthetic touch event passed to them * are of the following form: * * - `nativeEvent` * - `changedTouches` - Array of all touch events that have changed since the last event. * - `identifier` - The ID of the touch. * - `locationX` - The X position of the touch, relative to the element. * - `locationY` - The Y position of the touch, relative to the element. * - `pageX` - The X position of the touch, relative to the root element. * - `pageY` - The Y position of the touch, relative to the root element. * - `target` - The node id of the element receiving the touch event. * - `timestamp` - A time identifier for the touch, useful for velocity calculation. * - `touches` - Array of all current touches on the screen. */ const View = React.createClass({ // TODO: We should probably expose the mixins, viewConfig, and statics publicly. For example, // one of the props is of type AccessibilityComponentType. That is defined as a const[] above, // but it is not rendered by the docs, since `statics` below is not rendered. So its Possible // values had to be hardcoded. mixins: [NativeMethodsMixin], /** * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We * make `this` look like an actual native component class. */ viewConfig: { uiViewClassName: 'RCTView', validAttributes: ReactNativeViewAttributes.RCTView }, statics: { ...statics, }, propTypes: { ...TVViewPropTypes, /** * When `true`, indicates that the view is an accessibility element. By default, * all the touchable elements are accessible. */ accessible: PropTypes.bool, /** * Overrides the text that's read by the screen reader when the user interacts * with the element. By default, the label is constructed by traversing all the * children and accumulating all the `Text` nodes separated by space. */ accessibilityLabel: PropTypes.node, /** * Indicates to accessibility services to treat UI component like a * native one. Works for Android only. * * Possible values are one of: * * - `'none'` * - `'button'` * - `'radiobutton_checked'` * - `'radiobutton_unchecked'` * * @platform android */ accessibilityComponentType: PropTypes.oneOf(AccessibilityComponentTypes), /** * Indicates to accessibility services whether the user should be notified * when this view changes. Works for Android API >= 19 only. * Possible values: * * - `'none'` - Accessibility services should not announce changes to this view. * - `'polite'`- Accessibility services should announce changes to this view. * - `'assertive'` - Accessibility services should interrupt ongoing speech to immediately announce changes to this view. * * See the [Android `View` docs](http://developer.android.com/reference/android/view/View.html#attr_android:accessibilityLiveRegion) * for reference. * * @platform android */ accessibilityLiveRegion: PropTypes.oneOf([ 'none', 'polite', 'assertive', ]), /** * Controls how view is important for accessibility which is if it * fires accessibility events and if it is reported to accessibility services * that query the screen. Works for Android only. * * Possible values: * * - `'auto'` - The system determines whether the view is important for accessibility - * default (recommended). * - `'yes'` - The view is important for accessibility. * - `'no'` - The view is not important for accessibility. * - `'no-hide-descendants'` - The view is not important for accessibility, * nor are any of its descendant views. * * See the [Android `importantForAccessibility` docs](http://developer.android.com/reference/android/R.attr.html#importantForAccessibility) * for reference. * * @platform android */ importantForAccessibility: PropTypes.oneOf([ 'auto', 'yes', 'no', 'no-hide-descendants', ]), /** * Provides additional traits to screen reader. By default no traits are * provided unless specified otherwise in element. * * You can provide one trait or an array of many traits. * * Possible values for `AccessibilityTraits` are: * * - `'none'` - The element has no traits. * - `'button'` - The element should be treated as a button. * - `'link'` - The element should be treated as a link. * - `'header'` - The element is a header that divides content into sections. * - `'search'` - The element should be treated as a search field. * - `'image'` - The element should be treated as an image. * - `'selected'` - The element is selected. * - `'plays'` - The element plays sound. * - `'key'` - The element should be treated like a keyboard key. * - `'text'` - The element should be treated as text. * - `'summary'` - The element provides app summary information. * - `'disabled'` - The element is disabled. * - `'frequentUpdates'` - The element frequently changes its value. * - `'startsMedia'` - The element starts a media session. * - `'adjustable'` - The element allows adjustment over a range of values. * - `'allowsDirectInteraction'` - The element allows direct touch interaction for VoiceOver users. * - `'pageTurn'` - Informs VoiceOver that it should scroll to the next page when it finishes reading the contents of the element. * * See the [Accessibility guide](docs/accessibility.html#accessibilitytraits-ios) * for more information. * * @platform ios */ accessibilityTraits: PropTypes.oneOfType([ PropTypes.oneOf(AccessibilityTraits), PropTypes.arrayOf(PropTypes.oneOf(AccessibilityTraits)), ]), /** * When `accessible` is true, the system will try to invoke this function * when the user performs accessibility tap gesture. */ onAccessibilityTap: PropTypes.func, /** * When `accessible` is `true`, the system will invoke this function when the * user performs the magic tap gesture. */ onMagicTap: PropTypes.func, /** * Used to locate this view in end-to-end tests. * * > This disables the 'layout-only view removal' optimization for this view! */ testID: PropTypes.string, /** * For most touch interactions, you'll simply want to wrap your component in * `TouchableHighlight` or `TouchableOpacity`. Check out `Touchable.js`, * `ScrollResponder.js` and `ResponderEventPlugin.js` for more discussion. */ /** * The View is now responding for touch events. This is the time to highlight and show the user * what is happening. * * `View.props.onResponderGrant: (event) => {}`, where `event` is a synthetic touch event as * described above. */ onResponderGrant: PropTypes.func, /** * The user is moving their finger. * * `View.props.onResponderMove: (event) => {}`, where `event` is a synthetic touch event as * described above. */ onResponderMove: PropTypes.func, /** * Another responder is already active and will not release it to that `View` asking to be * the responder. * * `View.props.onResponderReject: (event) => {}`, where `event` is a synthetic touch event as * described above. */ onResponderReject: PropTypes.func, /** * Fired at the end of the touch. * * `View.props.onResponderRelease: (event) => {}`, where `event` is a synthetic touch event as * described above. */ onResponderRelease: PropTypes.func, /** * The responder has been taken from the `View`. Might be taken by other views after a call to * `onResponderTerminationRequest`, or might be taken by the OS without asking (e.g., happens * with control center/ notification center on iOS) * * `View.props.onResponderTerminate: (event) => {}`, where `event` is a synthetic touch event as * described above. */ onResponderTerminate: PropTypes.func, /** * Some other `View` wants to become responder and is asking this `View` to release its * responder. Returning `true` allows its release. * * `View.props.onResponderTerminationRequest: (event) => {}`, where `event` is a synthetic touch * event as described above. */ onResponderTerminationRequest: PropTypes.func, /** * Does this view want to become responder on the start of a touch? * * `View.props.onStartShouldSetResponder: (event) => [true | false]`, where `event` is a * synthetic touch event as described above. */ onStartShouldSetResponder: PropTypes.func, /** * If a parent `View` wants to prevent a child `View` from becoming responder on a touch start, * it should have this handler which returns `true`. * * `View.props.onStartShouldSetResponderCapture: (event) => [true | false]`, where `event` is a * synthetic touch event as described above. */ onStartShouldSetResponderCapture: PropTypes.func, /** * Does this view want to "claim" touch responsiveness? This is called for every touch move on * the `View` when it is not the responder. * * `View.props.onMoveShouldSetResponder: (event) => [true | false]`, where `event` is a * synthetic touch event as described above. */ onMoveShouldSetResponder: PropTypes.func, /** * If a parent `View` wants to prevent a child `View` from becoming responder on a move, * it should have this handler which returns `true`. * * `View.props.onMoveShouldSetResponderCapture: (event) => [true | false]`, where `event` is a * synthetic touch event as described above. */ onMoveShouldSetResponderCapture: PropTypes.func, /** * This defines how far a touch event can start away from the view. * Typical interface guidelines recommend touch targets that are at least * 30 - 40 points/density-independent pixels. * * For example, if a touchable view has a height of 20 the touchable height can be extended to * 40 with `hitSlop={{top: 10, bottom: 10, left: 0, right: 0}}` * * > The touch area never extends past the parent view bounds and the Z-index * > of sibling views always takes precedence if a touch hits two overlapping * > views. */ hitSlop: EdgeInsetsPropType, /** * Invoked on mount and layout changes with: * * `{nativeEvent: { layout: {x, y, width, height}}}` * * This event is fired immediately once the layout has been calculated, but * the new layout may not yet be reflected on the screen at the time the * event is received, especially if a layout animation is in progress. */ onLayout: PropTypes.func, /** * Controls whether the `View` can be the target of touch events. * * - `'auto'`: The View can be the target of touch events. * - `'none'`: The View is never the target of touch events. * - `'box-none'`: The View is never the target of touch events but it's * subviews can be. It behaves like if the view had the following classes * in CSS: * ``` * .box-none { * pointer-events: none; * } * .box-none * { * pointer-events: all; * } * ``` * - `'box-only'`: The view can be the target of touch events but it's * subviews cannot be. It behaves like if the view had the following classes * in CSS: * ``` * .box-only { * pointer-events: all; * } * .box-only * { * pointer-events: none; * } * ``` * > Since `pointerEvents` does not affect layout/appearance, and we are * > already deviating from the spec by adding additional modes, we opt to not * > include `pointerEvents` on `style`. On some platforms, we would need to * > implement it as a `className` anyways. Using `style` or not is an * > implementation detail of the platform. */ pointerEvents: PropTypes.oneOf([ 'box-none', 'none', 'box-only', 'auto', ]), style: stylePropType, /** * This is a special performance property exposed by `RCTView` and is useful * for scrolling content when there are many subviews, most of which are * offscreen. For this property to be effective, it must be applied to a * view that contains many subviews that extend outside its bound. The * subviews must also have `overflow: hidden`, as should the containing view * (or one of its superviews). */ removeClippedSubviews: PropTypes.bool, /** * Whether this `View` should render itself (and all of its children) into a * single hardware texture on the GPU. * * On Android, this is useful for animations and interactions that only * modify opacity, rotation, translation, and/or scale: in those cases, the * view doesn't have to be redrawn and display lists don't need to be * re-executed. The texture can just be re-used and re-composited with * different parameters. The downside is that this can use up limited video * memory, so this prop should be set back to false at the end of the * interaction/animation. * * @platform android */ renderToHardwareTextureAndroid: PropTypes.bool, /** * Whether this `View` should be rendered as a bitmap before compositing. * * On iOS, this is useful for animations and interactions that do not * modify this component's dimensions nor its children; for example, when * translating the position of a static view, rasterization allows the * renderer to reuse a cached bitmap of a static view and quickly composite * it during each frame. * * Rasterization incurs an off-screen drawing pass and the bitmap consumes * memory. Test and measure when using this property. * * @platform ios */ shouldRasterizeIOS: PropTypes.bool, /** * Views that are only used to layout their children or otherwise don't draw * anything may be automatically removed from the native hierarchy as an * optimization. Set this property to `false` to disable this optimization and * ensure that this `View` exists in the native view hierarchy. * * @platform android */ collapsable: PropTypes.bool, /** * Whether this `View` needs to rendered offscreen and composited with an alpha * in order to preserve 100% correct colors and blending behavior. The default * (`false`) falls back to drawing the component and its children with an alpha * applied to the paint used to draw each element instead of rendering the full * component offscreen and compositing it back with an alpha value. This default * may be noticeable and undesired in the case where the `View` you are setting * an opacity on has multiple overlapping elements (e.g. multiple overlapping * `View`s, or text and a background). * * Rendering offscreen to preserve correct alpha behavior is extremely * expensive and hard to debug for non-native developers, which is why it is * not turned on by default. If you do need to enable this property for an * animation, consider combining it with renderToHardwareTextureAndroid if the * view **contents** are static (i.e. it doesn't need to be redrawn each frame). * If that property is enabled, this View will be rendered off-screen once, * saved in a hardware texture, and then composited onto the screen with an alpha * each frame without having to switch rendering targets on the GPU. * * @platform android */ needsOffscreenAlphaCompositing: PropTypes.bool, }, contextTypes: { isInAParentText: React.PropTypes.bool, }, render: function() { invariant( !(this.context.isInAParentText && Platform.OS === 'android'), 'Nesting of <View> within <Text> is not supported on Android.'); // WARNING: This method will not be used in production mode as in that mode we // replace wrapper component View with generated native wrapper RCTView. Avoid // adding functionality this component that you'd want to be available in both // dev and prod modes. return <RCTView {...this.props} />; }, }); const RCTView = requireNativeComponent('RCTView', View, { nativeOnly: { nativeBackgroundAndroid: true, nativeForegroundAndroid: true, } }); if (__DEV__) { const UIManager = require('UIManager'); const viewConfig = UIManager.viewConfigs && UIManager.viewConfigs.RCTView || {}; for (const prop in viewConfig.nativeProps) { const viewAny: any = View; // Appease flow if (!viewAny.propTypes[prop] && !ReactNativeStyleAttributes[prop]) { throw new Error( 'View is missing propType for native prop `' + prop + '`' ); } } } let ViewToExport = RCTView; if (__DEV__) { ViewToExport = View; } else { Object.assign(RCTView, statics); } module.exports = ViewToExport;
htc2u/react-native
Libraries/Components/View/View.js
JavaScript
bsd-3-clause
20,196
function setupTest( target, event, dataToPaste, externalPassCondition ){ var logNode=document.getElementsByTagName('p')[0].firstChild; logNode.data=''; if( typeof target==='string' ){ if( target.indexOf('.')>-1 ){ // for example "myElementID.firstChild" var tmp=target.split('.'); target=document.getElementById(tmp[0])[tmp[1]]; }else{ target=document.getElementById(target); } } /* */ if( target.addEventListener ){ target.addEventListener(event, intermediateListener, false); }else if(target.attachEvent){ target.attachEvent('on'+event, intermediateListener); } if( dataToPaste || event==='paste' ){ logNode.data+='Please place the following text on the clipboard before continuing the test: "'+(dataToPaste || 'clipboard text' )+'"\n'; logNode.parentNode.style.whiteSpace='pre'; if(dataToPaste.indexOf('{')==0){ // sorry about the content sniffing, this is likely a JSON string with alternate clipboard formats if(dataToPaste.indexOf('text/html')>-1){ logNode.parentNode.appendChild(document.createElement('br')); logNode.parentNode.appendChild(document.createTextNode('Note: copy all body text from ')); var tmp=logNode.parentNode.appendChild(document.createElement('a')); tmp.href='support/html_file.htm'; tmp.appendChild(document.createTextNode('this support file')); logNode.parentNode.appendChild(document.createTextNode(' for this test.')); } } } if(typeof triggerTestManually==='function'){ logNode.parentNode.appendChild(document.createTextNode(' ')); var btn=logNode.parentNode.appendChild(document.createElement('button')) btn.type='button'; btn.onclick=function(){ triggerTestManually(); btn.parentNode.removeChild(btn); } btn.appendChild(document.createTextNode(' Click here to run test: ')); }else{ logNode.data+='Test in progress, waiting for '+event+' event'; } if(typeof onTestSetupReady==='function'){ onTestSetupReady(event); } function intermediateListener(e){ e=e||window.event; if(!e.target)e.target=e.srcElement; if(typeof window.clipboardData != 'undefined' && typeof e.clipboardData=='undefined' )e.clipboardData=window.clipboardData; try{ var testResult=test(e); result(testResult); }catch(e){ result('exception: '+e); } } /* if @autofocus isn't supported.. */ if( document.getElementsByTagName('input').length >1 && document.activeElement == document.body ){ for(var inp, i=0, inputs=document.getElementsByTagName('input');inp=inputs[i];i++){ if(inp.hasAttribute('autofocus'))inp.focus(); } } } function result(testResult, msg){ var logNode=document.getElementsByTagName('p')[0].firstChild; if( testResult === true || testResult === false ){ logNode.data= testResult ? 'PASSED' : 'FAILED'; }else if( typeof testResult ==='string' ){ logNode.data=testResult; }else if( typeof externalPassCondition==='string' ){ logNode.data='\nThis test passes if this text is now on the system clipboard: "'+externalPassCondition+'"'; } if( msg )logNode.data+='\n'+msg; /* another return value - or no return - from test() indicates that it is asyncronous and will call testResult() from a timeout or something */ }
frivoal/presto-testo
core/standards/scripts/clipboard-events/tests/_lib.js
JavaScript
bsd-3-clause
3,277
var n = require('./nodejs'); n.a; n.b.c; exports.a2 = n.a; exports.b2 = n.b; exports.c2 = n.b.c;
sourcegraph/jsg
testdata/nodejs_require.js
JavaScript
bsd-3-clause
98
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule AutodocsLayout */ var DocsSidebar = require('DocsSidebar'); var H = require('Header'); var Header = require('Header'); var HeaderWithGithub = require('HeaderWithGithub'); var Marked = require('Marked'); var Prism = require('Prism'); var React = require('React'); var Site = require('Site'); var slugify = require('slugify'); var styleReferencePattern = /^[^.]+\.propTypes\.style$/; function renderEnumValue(value) { // Use single quote strings even when we are given double quotes if (value.match(/^"(.+)"$/)) { return "'" + value.slice(1, -1) + "'"; } return value; } function renderType(type) { if (type.name === 'enum') { if (typeof type.value === 'string') { return type.value; } return 'enum(' + type.value.map((v) => renderEnumValue(v.value)).join(', ') + ')'; } if (type.name === '$Enum') { if (type.elements[0].signature.properties) { return type.elements[0].signature.properties.map(p => `'${p.key}'`).join(' | '); } return type.name; } if (type.name === 'shape') { return '{' + Object.keys(type.value).map((key => key + ': ' + renderType(type.value[key]))).join(', ') + '}'; } if (type.name === 'union') { if (type.value) { return type.value.map(renderType).join(', '); } return type.elements.map(renderType).join(' | '); } if (type.name === 'arrayOf') { return <span>[{renderType(type.value)}]</span>; } if (type.name === 'instanceOf') { return type.value; } if (type.name === 'custom') { if (styleReferencePattern.test(type.raw)) { var name = type.raw.substring(0, type.raw.indexOf('.')); return <a href={'docs/' + slugify(name) + '.html#style'}>{name}#style</a>; } if (type.raw === 'ColorPropType') { return <a href={'docs/colors.html'}>color</a>; } if (type.raw === 'EdgeInsetsPropType') { return '{top: number, left: number, bottom: number, right: number}'; } return type.raw; } if (type.name === 'stylesheet') { return 'style'; } if (type.name === 'func') { return 'function'; } if (type.name === 'signature') { return type.raw; } return type.name; } function sortByPlatform(props, nameA, nameB) { var a = props[nameA]; var b = props[nameB]; if (a.platforms && !b.platforms) { return 1; } if (b.platforms && !a.platforms) { return -1; } // Cheap hack: use < on arrays of strings to compare the two platforms if (a.platforms < b.platforms) { return -1; } if (a.platforms > b.platforms) { return 1; } if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } return 0; } function removeCommentsFromDocblock(docblock) { return docblock .trim('\n ') .replace(/^\/\*+/, '') .replace(/\*\/$/, '') .split('\n') .map(function(line) { return line.trim().replace(/^\* ?/, ''); }) .join('\n'); } var ComponentDoc = React.createClass({ renderProp: function(name, prop) { return ( <div className="prop" key={name}> <Header level={4} className="propTitle" toSlug={name}> {prop.platforms && prop.platforms.map(platform => <span className="platform">{platform}</span> )} {name} {' '} {prop.type && <span className="propType"> {renderType(prop.type)} </span>} </Header> {prop.deprecationMessage && <div className="deprecated"> <div className="deprecatedTitle"> <img className="deprecatedIcon" src="img/Warning.png" /> <span>Deprecated</span> </div> <div className="deprecatedMessage"> <Marked>{prop.deprecationMessage}</Marked> </div> </div>} {prop.type && prop.type.name === 'stylesheet' && this.renderStylesheetProps(prop.type.value)} {prop.description && <Marked>{prop.description}</Marked>} </div> ); }, renderCompose: function(name) { return ( <div className="prop" key={name}> <Header level={4} className="propTitle" toSlug={name}> <a href={'docs/' + slugify(name) + '.html#props'}>{name} props...</a> </Header> </div> ); }, renderStylesheetProp: function(name, prop) { return ( <div className="prop" key={name}> <h6 className="propTitle"> {prop.platforms && prop.platforms.map(platform => <span className="platform">{platform}</span> )} {name} {' '} {prop.type && <span className="propType"> {renderType(prop.type)} </span>} {' '} {prop.description && <Marked>{prop.description}</Marked>} </h6> </div> ); }, renderStylesheetProps: function(stylesheetName) { var style = this.props.content.styles[stylesheetName]; this.extractPlatformFromProps(style.props); return ( <div className="compactProps"> {(style.composes || []).map((name) => { var link; if (name === 'LayoutPropTypes') { name = 'Flexbox'; link = <a href={'docs/' + slugify(name) + '.html#proptypes'}>{name}...</a>; } else if (name === 'TransformPropTypes') { name = 'Transforms'; link = <a href={'docs/' + slugify(name) + '.html#proptypes'}>{name}...</a>; } else { name = name.replace('StylePropTypes', ''); link = <a href={'docs/' + slugify(name) + '.html#style'}>{name}#style...</a>; } return ( <div className="prop" key={name}> <h6 className="propTitle">{link}</h6> </div> ); })} {Object.keys(style.props) .sort(sortByPlatform.bind(null, style.props)) .map((name) => this.renderStylesheetProp(name, style.props[name])) } </div> ); }, renderProps: function(props, composes) { return ( <div className="props"> {(composes || []).map((name) => this.renderCompose(name) )} {Object.keys(props) .sort(sortByPlatform.bind(null, props)) .map((name) => this.renderProp(name, props[name])) } </div> ); }, extractPlatformFromProps: function(props) { for (var key in props) { var prop = props[key]; var description = prop.description || ''; var platforms = description.match(/\@platform (.+)/); platforms = platforms && platforms[1].replace(/ /g, '').split(','); description = description.replace(/\@platform (.+)/, ''); prop.description = description; prop.platforms = platforms; } }, renderMethod: function(method) { return ( <Method key={method.name} name={method.name} description={method.description} params={method.params} modifiers={method.modifiers} returns={method.returns} /> ); }, renderMethods: function(methods) { if (!methods || !methods.length) { return null; } return ( <span> <H level={3}>Methods</H> <div className="props"> {methods.filter((method) => { return method.name[0] !== '_'; }).map(this.renderMethod)} </div> </span> ); }, render: function() { var content = this.props.content; this.extractPlatformFromProps(content.props); return ( <div> <Marked> {content.description} </Marked> <H level={3}>Props</H> {this.renderProps(content.props, content.composes)} {this.renderMethods(content.methods)} </div> ); } }); var APIDoc = React.createClass({ renderMethod: function(method) { return ( <Method key={method.name} name={method.name} description={method.docblock && removeCommentsFromDocblock(method.docblock)} params={method.params} modifiers={method.modifiers} /> ); }, renderMethods: function(methods) { if (!methods.length) { return null; } return ( <span> <H level={3}>Methods</H> <div className="props"> {methods.filter((method) => { return method.name[0] !== '_'; }).map(this.renderMethod)} </div> </span> ); }, renderProperty: function(property) { return ( <div className="prop" key={property.name}> <Header level={4} className="propTitle" toSlug={property.name}> {property.name} {property.type && <span className="propType"> {': ' + renderType(property.type)} </span> } </Header> {property.docblock && <Marked> {removeCommentsFromDocblock(property.docblock)} </Marked>} </div> ); }, renderProperties: function(properties) { if (!properties || !properties.length) { return null; } return ( <span> <H level={3}>Properties</H> <div className="props"> {properties.filter((property) => { return property.name[0] !== '_'; }).map(this.renderProperty)} </div> </span> ); }, renderClasses: function(classes) { if (!classes || !classes.length) { return null; } return ( <span> <div> {classes.filter((cls) => { return cls.name[0] !== '_' && cls.ownerProperty[0] !== '_'; }).map((cls) => { return ( <span key={cls.name}> <Header level={2} toSlug={cls.name}> class {cls.name} </Header> <ul> {cls.docblock && <Marked> {removeCommentsFromDocblock(cls.docblock)} </Marked>} {this.renderMethods(cls.methods)} {this.renderProperties(cls.properties)} </ul> </span> ); })} </div> </span> ); }, render: function() { var content = this.props.content; if (!content.methods) { throw new Error( 'No component methods found for ' + content.componentName ); } return ( <div> <Marked> {removeCommentsFromDocblock(content.docblock)} </Marked> {this.renderMethods(content.methods)} {this.renderProperties(content.properties)} {this.renderClasses(content.classes)} </div> ); } }); var Method = React.createClass({ renderTypehintRec: function(typehint) { if (typehint.type === 'simple') { return typehint.value; } if (typehint.type === 'generic') { return this.renderTypehintRec(typehint.value[0]) + '<' + this.renderTypehintRec(typehint.value[1]) + '>'; } return JSON.stringify(typehint); }, renderTypehint: function(typehint) { if (typeof typehint === 'object' && typehint.name) { return renderType(typehint); } try { var typehint = JSON.parse(typehint); } catch (e) { return typehint; } return this.renderTypehintRec(typehint); }, render: function() { return ( <div className="prop"> <Header level={4} className="propTitle" toSlug={this.props.name}> {this.props.modifiers.length && <span className="propType"> {this.props.modifiers.join(' ') + ' '} </span> || ''} {this.props.name} <span className="propType"> ({this.props.params .map((param) => { var res = param.name; if (param.type) { res += ': ' + this.renderTypehint(param.type); } return res; }) .join(', ')}) {this.props.returns && ': ' + this.renderTypehint(this.props.returns.type)} </span> </Header> {this.props.description && <Marked> {this.props.description} </Marked>} </div> ); }, }); var EmbeddedSimulator = React.createClass({ render: function() { if (!this.props.shouldRender) { return null; } var metadata = this.props.metadata; var imagePreview = metadata.platform === 'android' ? <img alt="Run example in simulator" width="170" height="338" src="img/uiexplorer_main_android.png" /> : <img alt="Run example in simulator" width="170" height="356" src="img/uiexplorer_main_ios.png" />; return ( <div className="column-left"> <p><a className="modal-button-open"><strong>Run this example</strong></a></p> <div className="modal-button-open modal-button-open-img"> {imagePreview} </div> <Modal metadata={metadata} /> </div> ); } }); var Modal = React.createClass({ render: function() { var metadata = this.props.metadata; var appParams = {route: metadata.title}; var encodedParams = encodeURIComponent(JSON.stringify(appParams)); var url = metadata.platform === 'android' ? `https://appetize.io/embed/q7wkvt42v6bkr0pzt1n0gmbwfr?device=nexus5&scale=65&autoplay=false&orientation=portrait&deviceColor=white&params=${encodedParams}` : `https://appetize.io/embed/7vdfm9h3e6vuf4gfdm7r5rgc48?device=iphone6s&scale=60&autoplay=false&orientation=portrait&deviceColor=white&params=${encodedParams}`; return ( <div> <div className="modal"> <div className="modal-content"> <button className="modal-button-close">&times;</button> <div className="center"> <iframe className="simulator" src={url} width="256" height="550" frameborder="0" scrolling="no"></iframe> <p>Powered by <a target="_blank" href="https://appetize.io">appetize.io</a></p> </div> </div> </div> <div className="modal-backdrop" /> </div> ); } }); var Autodocs = React.createClass({ childContextTypes: { permalink: React.PropTypes.string }, getChildContext: function() { return {permalink: this.props.metadata.permalink}; }, renderFullDescription: function(docs) { if (!docs.fullDescription) { return; } return ( <div> <HeaderWithGithub title="Description" path={'docs/' + docs.componentName + '.md'} /> <Marked> {docs.fullDescription} </Marked> </div> ); }, renderExample: function(docs, metadata) { if (!docs.example) { return; } return ( <div> <HeaderWithGithub title="Examples" path={docs.example.path} metadata={metadata} /> <Prism> {docs.example.content.replace(/^[\s\S]*?\*\//, '').trim()} </Prism> </div> ); }, render: function() { var metadata = this.props.metadata; var docs = JSON.parse(this.props.children); var content = docs.type === 'component' || docs.type === 'style' ? <ComponentDoc content={docs} /> : <APIDoc content={docs} apiName={metadata.title} />; return ( <Site section="docs" title={metadata.title}> <section className="content wrap documentationContent"> <DocsSidebar metadata={metadata} /> <div className="inner-content"> <a id="content" /> <HeaderWithGithub title={metadata.title} level={1} path={metadata.path} /> {content} {this.renderFullDescription(docs)} {this.renderExample(docs, metadata)} <div className="docs-prevnext"> {metadata.previous && <a className="docs-prev" href={'docs/' + metadata.previous + '.html#content'}>&larr; Prev</a>} {metadata.next && <a className="docs-next" href={'docs/' + metadata.next + '.html#content'}>Next &rarr;</a>} </div> </div> <EmbeddedSimulator shouldRender={metadata.runnable} metadata={metadata} /> </section> </Site> ); } }); module.exports = Autodocs;
jeffchienzabinet/react-native
website/layout/AutodocsLayout.js
JavaScript
bsd-3-clause
16,538
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** @constructor */ function TaskManager() { } cr.addSingletonGetter(TaskManager); TaskManager.prototype = { /** * Handle window close. * @this */ onClose: function() { if (!this.disabled_) { this.disabled_ = true; commands.disableTaskManager(); } }, /** * Handles selection changes. * This is also called when data of tasks are refreshed, even if selection * has not been changed. * @this */ onSelectionChange: function() { var sm = this.selectionModel_; var dm = this.dataModel_; var selectedIndexes = sm.selectedIndexes; var is_end_process_enabled = true; if (selectedIndexes.length == 0) is_end_process_enabled = false; for (var i = 0; i < selectedIndexes.length; i++) { var index = selectedIndexes[i]; var task = dm.item(index); if (task['type'] == 'BROWSER') is_end_process_enabled = false; } if (this.is_end_process_enabled_ != is_end_process_enabled) { if (is_end_process_enabled) $('kill-process').removeAttribute('disabled'); else $('kill-process').setAttribute('disabled', 'true'); this.is_end_process_enabled_ = is_end_process_enabled; } }, /** * Closes taskmanager dialog. * After this function is called, onClose() will be called. * @this */ close: function() { window.close(); }, /** * Sends commands to kill selected processes. * @this */ killSelectedProcesses: function() { var selectedIndexes = this.selectionModel_.selectedIndexes; var dm = this.dataModel_; var uniqueIds = []; for (var i = 0; i < selectedIndexes.length; i++) { var index = selectedIndexes[i]; var task = dm.item(index); uniqueIds.push(task['uniqueId'][0]); } commands.killSelectedProcesses(uniqueIds); }, /** * Initializes taskmanager. * @this */ initialize: function(dialogDom, opt) { if (!dialogDom) { console.log('ERROR: dialogDom is not defined.'); return; } measureTime.startInterval('Load.DOM'); this.opt_ = opt; this.initialized_ = true; this.elementsCache_ = {}; this.dialogDom_ = dialogDom; this.document_ = dialogDom.ownerDocument; this.localized_column_ = []; for (var i = 0; i < DEFAULT_COLUMNS.length; i++) { var column_label_id = DEFAULT_COLUMNS[i][1]; this.localized_column_[i] = loadTimeData.getString(column_label_id); } this.initElements_(); this.initColumnModel_(); this.selectionModel_ = new cr.ui.ListSelectionModel(); this.dataModel_ = new cr.ui.ArrayDataModel([]); this.selectionModel_.addEventListener('change', this.onSelectionChange.bind(this)); // Initializes compare functions for column sort. var dm = this.dataModel_; // List of columns to sort by its numerical value as opposed to the // formatted value, e.g., 20480 vs. 20KB. var COLUMNS_SORTED_BY_VALUE = [ 'cpuUsage', 'physicalMemory', 'sharedMemory', 'privateMemory', 'networkUsage', 'webCoreImageCacheSize', 'webCoreScriptsCacheSize', 'webCoreCSSCacheSize', 'fps', 'videoMemory', 'sqliteMemoryUsed', 'goatsTeleported', 'v8MemoryAllocatedSize']; for (var i = 0; i < DEFAULT_COLUMNS.length; i++) { var columnId = DEFAULT_COLUMNS[i][0]; var compareFunc = (function() { var columnIdToSort = columnId; if (COLUMNS_SORTED_BY_VALUE.indexOf(columnId) != -1) columnIdToSort += 'Value'; return function(a, b) { var aValues = a[columnIdToSort]; var bValues = b[columnIdToSort]; var aValue = aValues && aValues[0] || 0; var bvalue = bValues && bValues[0] || 0; return dm.defaultValuesCompareFunction(aValue, bvalue); }; })(); dm.setCompareFunction(columnId, compareFunc); } if (isColumnEnabled(DEFAULT_SORT_COLUMN)) dm.sort(DEFAULT_SORT_COLUMN, DEFAULT_SORT_DIRECTION); this.initTable_(); commands.enableTaskManager(); // Populate the static localized strings. i18nTemplate.process(this.document_, loadTimeData); measureTime.recordInterval('Load.DOM'); measureTime.recordInterval('Load.Total'); loadDelayedIncludes(this); }, /** * Initializes the visibilities and handlers of the elements. * This method is called by initialize(). * @private * @this */ initElements_: function() { // <if expr="pp_ifdef('chromeos')"> // The 'close-window' element exists only on ChromeOS. // This <if ... /if> section is removed while flattening HTML if chrome is // built as Desktop Chrome. if (!this.opt_['isShowCloseButton']) $('close-window').style.display = 'none'; $('close-window').addEventListener('click', this.close.bind(this)); // </if> $('kill-process').addEventListener('click', this.killSelectedProcesses.bind(this)); $('about-memory-link').addEventListener('click', commands.openAboutMemory); }, /** * Additional initialization of taskmanager. This function is called when * the loading of delayed scripts finished. * @this */ delayedInitialize: function() { this.initColumnMenu_(); this.initTableMenu_(); var dm = this.dataModel_; for (var i = 0; i < dm.length; i++) { var processId = dm.item(i)['processId'][0]; for (var j = 0; j < DEFAULT_COLUMNS.length; j++) { var columnId = DEFAULT_COLUMNS[j][0]; var row = dm.item(i)[columnId]; if (!row) continue; for (var k = 0; k < row.length; k++) { var labelId = 'detail-' + columnId + '-pid' + processId + '-' + k; var label = $(labelId); // Initialize a context-menu, if the label exists and its context- // menu is not initialized yet. if (label && !label.contextMenu) cr.ui.contextMenuHandler.setContextMenu(label, this.tableContextMenu_); } } } this.isFinishedInitDelayed_ = true; this.table_.redraw(); }, initColumnModel_: function() { var table_columns = new Array(); for (var i = 0; i < DEFAULT_COLUMNS.length; i++) { var column = DEFAULT_COLUMNS[i]; var columnId = column[0]; if (!isColumnEnabled(columnId)) continue; table_columns.push(new cr.ui.table.TableColumn(columnId, this.localized_column_[i], column[2])); } for (var i = 0; i < table_columns.length; i++) { table_columns[i].renderFunction = this.renderColumn_.bind(this); } this.columnModel_ = new cr.ui.table.TableColumnModel(table_columns); }, initColumnMenu_: function() { this.column_menu_commands_ = []; this.commandsElement_ = this.document_.createElement('commands'); this.document_.body.appendChild(this.commandsElement_); this.columnSelectContextMenu_ = this.document_.createElement('menu'); for (var i = 0; i < DEFAULT_COLUMNS.length; i++) { var column = DEFAULT_COLUMNS[i]; // Creates command element to receive event. var command = this.document_.createElement('command'); command.id = COMMAND_CONTEXTMENU_COLUMN_PREFIX + '-' + column[0]; cr.ui.Command.decorate(command); this.column_menu_commands_[command.id] = command; this.commandsElement_.appendChild(command); // Creates menuitem element. var item = this.document_.createElement('menuitem'); item.command = command; command.menuitem = item; item.textContent = this.localized_column_[i]; if (isColumnEnabled(column[0])) item.setAttributeNode(this.document_.createAttribute('checked')); this.columnSelectContextMenu_.appendChild(item); } this.document_.body.appendChild(this.columnSelectContextMenu_); cr.ui.Menu.decorate(this.columnSelectContextMenu_); cr.ui.contextMenuHandler.setContextMenu(this.table_.header, this.columnSelectContextMenu_); cr.ui.contextMenuHandler.setContextMenu(this.table_.list, this.columnSelectContextMenu_); this.document_.addEventListener('command', this.onCommand_.bind(this)); this.document_.addEventListener('canExecute', this.onCommandCanExecute_.bind(this)); }, initTableMenu_: function() { this.table_menu_commands_ = []; this.tableContextMenu_ = this.document_.createElement('menu'); var addMenuItem = function(tm, command_id, string_id) { // Creates command element to receive event. var command = tm.document_.createElement('command'); command.id = COMMAND_CONTEXTMENU_TABLE_PREFIX + '-' + command_id; cr.ui.Command.decorate(command); tm.table_menu_commands_[command.id] = command; tm.commandsElement_.appendChild(command); // Creates menuitem element. var item = tm.document_.createElement('menuitem'); item.command = command; command.menuitem = item; item.textContent = loadTimeData.getString(string_id); tm.tableContextMenu_.appendChild(item); }; addMenuItem(this, 'inspect', 'inspect'); addMenuItem(this, 'activate', 'activate'); this.document_.body.appendChild(this.tableContextMenu_); cr.ui.Menu.decorate(this.tableContextMenu_); }, initTable_: function() { if (!this.dataModel_ || !this.selectionModel_ || !this.columnModel_) { console.log('ERROR: some models are not defined.'); return; } this.table_ = this.dialogDom_.querySelector('.detail-table'); cr.ui.Table.decorate(this.table_); this.table_.dataModel = this.dataModel_; this.table_.selectionModel = this.selectionModel_; this.table_.columnModel = this.columnModel_; // Expands height of row when a process has some tasks. this.table_.fixedHeight = false; this.table_.list.addEventListener('contextmenu', this.onTableContextMenuOpened_.bind(this), true); // Sets custom row render function. this.table_.setRenderFunction(this.getRow_.bind(this)); }, /** * Returns a list item element of the list. This method trys to reuse the * cached element, or creates a new element. * @return {cr.ui.ListItem} list item element which contains the given data. * @private * @this */ getRow_: function(data, table) { // Trys to reuse the cached row; var listItemElement = this.renderRowFromCache_(data, table); if (listItemElement) return listItemElement; // Initializes the cache. var pid = data['processId'][0]; this.elementsCache_[pid] = { listItem: null, cell: [], icon: [], columns: {} }; // Create new row. return this.renderRow_(data, table); }, /** * Returns a list item element with re-using the previous cached element, or * returns null if failed. * @return {cr.ui.ListItem} cached un-used element to be reused. * @private * @this */ renderRowFromCache_: function(data, table) { var pid = data['processId'][0]; // Checks whether the cache exists or not. var cache = this.elementsCache_[pid]; if (!cache) return null; var listItemElement = cache.listItem; var cm = table.columnModel; // Checks whether the number of columns has been changed or not. if (cache.cachedColumnSize != cm.size) return null; // Checks whether the number of childlen tasks has been changed or not. if (cache.cachedChildSize != data['uniqueId'].length) return null; // Updates informations of the task if necessary. for (var i = 0; i < cm.size; i++) { var columnId = cm.getId(i); var columnData = data[columnId]; var oldColumnData = listItemElement.data[columnId]; var columnElements = cache.columns[columnId]; if (!columnData || !oldColumnData || !columnElements) return null; // Sets new width of the cell. var cellElement = cache.cell[i]; cellElement.style.width = cm.getWidth(i) + '%'; for (var j = 0; j < columnData.length; j++) { // Sets the new text, if the text has been changed. if (oldColumnData[j] != columnData[j]) { var textElement = columnElements[j]; textElement.textContent = columnData[j]; } } } // Updates icon of the task if necessary. var oldIcons = listItemElement.data['icon']; var newIcons = data['icon']; if (oldIcons && newIcons) { for (var j = 0; j < columnData.length; j++) { var oldIcon = oldIcons[j]; var newIcon = newIcons[j]; if (oldIcon != newIcon) { var iconElement = cache.icon[j]; iconElement.src = newIcon; } } } listItemElement.data = data; // Removes 'selected' and 'lead' attributes. listItemElement.removeAttribute('selected'); listItemElement.removeAttribute('lead'); return listItemElement; }, /** * Create a new list item element. * @return {cr.ui.ListItem} created new list item element. * @private * @this */ renderRow_: function(data, table) { var pid = data['processId'][0]; var cm = table.columnModel; var listItem = new cr.ui.ListItem({label: ''}); listItem.className = 'table-row'; if (this.opt_.isBackgroundMode && data.isBackgroundResource) listItem.className += ' table-background-row'; for (var i = 0; i < cm.size; i++) { var cell = document.createElement('div'); cell.style.width = cm.getWidth(i) + '%'; cell.className = 'table-row-cell'; cell.id = 'column-' + pid + '-' + cm.getId(i); cell.appendChild( cm.getRenderFunction(i).call(null, data, cm.getId(i), table)); listItem.appendChild(cell); // Stores the cell element to the dictionary. this.elementsCache_[pid].cell[i] = cell; } // Specifies the height of the row. The height of each row is // 'num_of_tasks * HEIGHT_OF_TASK' px. listItem.style.height = (data['uniqueId'].length * HEIGHT_OF_TASK) + 'px'; listItem.data = data; // Stores the list item element, the number of columns and the number of // childlen. this.elementsCache_[pid].listItem = listItem; this.elementsCache_[pid].cachedColumnSize = cm.size; this.elementsCache_[pid].cachedChildSize = data['uniqueId'].length; return listItem; }, /** * Create a new element of the cell. * @return {HTMLDIVElement} created cell * @private * @this */ renderColumn_: function(entry, columnId, table) { var container = this.document_.createElement('div'); container.className = 'detail-container-' + columnId; var pid = entry['processId'][0]; var cache = []; var cacheIcon = []; if (entry && entry[columnId]) { container.id = 'detail-container-' + columnId + '-pid' + entry.processId; for (var i = 0; i < entry[columnId].length; i++) { var label = document.createElement('div'); if (columnId == 'title') { // Creates a page title element with icon. var image = this.document_.createElement('img'); image.className = 'detail-title-image'; image.src = entry['icon'][i]; image.id = 'detail-title-icon-pid' + pid + '-' + i; label.appendChild(image); var text = this.document_.createElement('div'); text.className = 'detail-title-text'; text.id = 'detail-title-text-pid' + pid + '-' + i; text.textContent = entry['title'][i]; label.appendChild(text); // Chech if the delayed scripts (included in includes.js) have been // loaded or not. If the delayed scripts ware not loaded yet, a // context menu could not be initialized. In such case, it will be // initialized at delayedInitialize() just after loading of delayed // scripts instead of here. if (this.isFinishedInitDelayed_) cr.ui.contextMenuHandler.setContextMenu(label, this.tableContextMenu_); label.addEventListener('dblclick', (function(uniqueId) { commands.activatePage(uniqueId); }).bind(this, entry['uniqueId'][i])); label.data = entry; label.index_in_group = i; cache[i] = text; cacheIcon[i] = image; } else { label.textContent = entry[columnId][i]; cache[i] = label; } label.id = 'detail-' + columnId + '-pid' + pid + '-' + i; label.className = 'detail-' + columnId + ' pid' + pid; container.appendChild(label); } this.elementsCache_[pid].columns[columnId] = cache; if (columnId == 'title') this.elementsCache_[pid].icon = cacheIcon; } return container; }, /** * Updates the task list with the supplied task. * @private * @this */ processTaskChange: function(task) { var dm = this.dataModel_; var sm = this.selectionModel_; if (!dm || !sm) return; this.table_.list.startBatchUpdates(); sm.beginChange(); var type = task.type; var start = task.start; var length = task.length; var tasks = task.tasks; // We have to store the selected pids and restore them after // splice(), because it might replace some items but the replaced // items would lose the selection. var oldSelectedIndexes = sm.selectedIndexes; // Create map of selected PIDs. var selectedPids = {}; for (var i = 0; i < oldSelectedIndexes.length; i++) { var item = dm.item(oldSelectedIndexes[i]); if (item) selectedPids[item['processId'][0]] = true; } var args = tasks.slice(); args.unshift(start, dm.length); dm.splice.apply(dm, args); // Create new array of selected indexes from map of old PIDs. var newSelectedIndexes = []; for (var i = 0; i < dm.length; i++) { if (selectedPids[dm.item(i)['processId'][0]]) newSelectedIndexes.push(i); } sm.selectedIndexes = newSelectedIndexes; var pids = []; for (var i = 0; i < dm.length; i++) { pids.push(dm.item(i)['processId'][0]); } // Sweeps unused caches, which elements no longer exist on the list. for (var pid in this.elementsCache_) { if (pids.indexOf(pid) == -1) delete this.elementsCache_[pid]; } sm.endChange(); this.table_.list.endBatchUpdates(); }, /** * Respond to a command being executed. * @this */ onCommand_: function(event) { var command = event.command; var command_id = command.id.split('-', 2); var main_command = command_id[0]; var sub_command = command_id[1]; if (main_command == COMMAND_CONTEXTMENU_COLUMN_PREFIX) { this.onColumnContextMenu_(sub_command, command); } else if (main_command == COMMAND_CONTEXTMENU_TABLE_PREFIX) { var target_unique_id = this.currentContextMenuTarget_; if (!target_unique_id) return; if (sub_command == 'inspect') commands.inspect(target_unique_id); else if (sub_command == 'activate') commands.activatePage(target_unique_id); this.currentContextMenuTarget_ = undefined; } }, onCommandCanExecute_: function(event) { event.canExecute = true; }, /** * Store resourceIndex of target resource of context menu, because resource * will be replaced when it is refreshed. * @this */ onTableContextMenuOpened_: function(e) { if (!this.isFinishedInitDelayed_) return; var mc = this.table_menu_commands_; var inspect_menuitem = mc[COMMAND_CONTEXTMENU_TABLE_PREFIX + '-inspect'].menuitem; var activate_menuitem = mc[COMMAND_CONTEXTMENU_TABLE_PREFIX + '-activate'].menuitem; // Disabled by default. inspect_menuitem.disabled = true; activate_menuitem.disabled = true; var target = e.target; for (;; target = target.parentNode) { if (!target) return; var classes = target.classList; if (classes && Array.prototype.indexOf.call(classes, 'detail-title') != -1) break; } var index_in_group = target.index_in_group; // Sets the uniqueId for current target page under the mouse corsor. this.currentContextMenuTarget_ = target.data['uniqueId'][index_in_group]; // Enables if the page can be inspected. if (target.data['canInspect'][index_in_group]) inspect_menuitem.disabled = false; // Enables if the page can be activated. if (target.data['canActivate'][index_in_group]) activate_menuitem.disabled = false; }, onColumnContextMenu_: function(columnId, command) { var menuitem = command.menuitem; var checkedItemCount = 0; var checked = isColumnEnabled(columnId); // Leaves a item visible when user tries making invisible but it is the // last one. var enabledColumns = getEnabledColumns(); for (var id in enabledColumns) { if (enabledColumns[id]) checkedItemCount++; } if (checkedItemCount == 1 && checked) return; // Toggles the visibility of the column. var newChecked = !checked; menuitem.checked = newChecked; setColumnEnabled(columnId, newChecked); this.initColumnModel_(); this.table_.columnModel = this.columnModel_; this.table_.redraw(); }, }; // |taskmanager| has been declared in preload.js. taskmanager = TaskManager.getInstance(); function init() { var params = parseQueryParams(window.location); var opt = {}; opt['isBackgroundMode'] = params.background; opt['isShowCloseButton'] = params.showclose; taskmanager.initialize(document.body, opt); } document.addEventListener('DOMContentLoaded', init); document.addEventListener('Close', taskmanager.onClose.bind(taskmanager));
leighpauls/k2cro4
chrome/browser/resources/task_manager/main.js
JavaScript
bsd-3-clause
22,270
//When change in default attribute: // Make code revision and check all values working with the default HTML attribute name 'gridindex' and or the variable `attribute` var navigationItem, attribute; var navigationActive = false; var gridindex = "1-2"; var backupGridindex = "1-2"; var lastGridindex_col = {}; var attributes = ["nav-gridindex"] function getElem(col, row) { if (attribute == undefined) { return document.querySelector("[gridindex='" + String(col) + "-" + String(row) + "']"); } else { return document.querySelector("[" + attribute + "='" + String(col) + "-" + String(row) + "']"); } } function getAttribute(elem) { var i; for (i in attributes) { if (elem.getAttribute(attributes[i]) != null) { attribute = attributes[i]; break } else { attribute = undefined; } i += 1; } if (attribute == undefined) { gridindex = String(elem.getAttribute("gridindex")); console.log("%cFocus event: Calling element with id: " + gridindex, "color:orange;"); } else { gridindex = String(elem.getAttribute(attribute)); } } function getIndex(elem) { if (attribute == undefined) { gridindex = String(elem.getAttribute("gridindex")); if (gridindex == "null") { getAttribute(elem); } else { console.log("%cFocus event: Calling element with id: " + gridindex, "color:orange;"); } } else { getAttribute(elem); } } function down() { var elem, col, row; var navelem = false; var tmp = gridindex.split("-"); col = parseInt(tmp[0]); row = parseInt(tmp[1]); row += 1; while (true) { elem = getElem(col, row); console.log("%cCalling element with id: " + String(col) + "-" + String(row), "color:darkblue;"); if (elem != undefined) { if (elem.parentNode.parentNode.className.indexOf("nav-children") > -1 ) { elem.parentNode.parentNode.style.display = "block"; navigationItem = elem.parentNode.parentNode; navelem = true; } else { if (navigationItem != undefined) { navigationItem.style = ""; } } if (elem.offsetHeight > 0 || navelem) { elem.focus(); gridindex = String(col) + "-" + String(row); navelem = false; break; } else { row += 1; } } else { lastGridindex_col[String(col)] = String(row); col += 1; if (getElem(col, 1) != null) { gridindex = String(col) + "-0"; down(); } break; } } } function up() { var elem, col, row; var tmp = gridindex.split("-"); col = parseInt(tmp[0]); row = parseInt(tmp[1]); row -= 1; while (true) { elem = getElem(col, row); console.log("%cCalling element with id: " + String(col) + "-" + String(row), "color:darkblue;"); if (elem != undefined) { if (elem.parentNode.parentNode.className.indexOf("nav-children") > -1 ) { elem.parentNode.parentNode.style.display = "block"; navigationItem = elem.parentNode.parentNode; navelem = true; } else { if (navigationItem != undefined) { navigationItem.style = ""; } } if (elem.offsetHeight > 0) { elem.focus(); gridindex = String(col) + "-" + String(row); break; } else { row -= 1; } } else { if (getElem(col-1, 1) != null) { if (lastGridindex_col[String(col-1)] == undefined) { lastGridindex_col[String(col-1)] = "1"; } gridindex = String(col-1) + "-" + lastGridindex_col[String(col-1)]; if (lastGridindex_col[String(col-1)] == 1) { gridindex = String(col-1) + "-" + String(parseInt(lastGridindex_col[String(col-1)])+1); } up(); } break; } } } function left() { var elem, col, row; var tmp = gridindex.split("-"); col = parseInt(tmp[0]); row = parseInt(tmp[1]); col -= 1; while (true) { elem = getElem(col, row); console.log("%cCalling element with id: " + String(col) + "-" + String(row), "color:darkblue;"); if (elem != undefined) { if (elem.offsetHeight > 0) { elem.focus(); gridindex = String(col) + "-" + String(row); break; } else { col -= 1; } } else { col += 1; break; } } } function right() { var elem, col, row; var tmp = gridindex.split("-"); col = parseInt(tmp[0]); row = parseInt(tmp[1]); col += 1; while (true) { elem = getElem(col, row); console.log("%cCalling element with id: " + String(col) + "-" + String(row), "color:darkblue;"); if (elem != undefined) { if (elem.offsetHeight > 0) { elem.focus(); gridindex = String(col) + "-" + String(row); break; } else { col += 1; } } else { col -= 1; break; } } } document.body.addEventListener("keydown", function(event) { var key = event.keyCode || event.which; if (event.altKey) { var col, row; if (key == 78) { // key 'n' // activate/deactivate navigation (toggling) if (navigationActive) { // deactivate navigation attribute = undefined; navigationActive = false; gridindex = backupGridindex; row = gridindex.split("-"); col = parseInt(row[0]); row = parseInt(row[1]); getElem(col, row).focus(); } else { // activate navigation attribute = "nav-gridindex"; navigationActive = true; backupGridindex = gridindex; gridindex = "1-1"; row = gridindex.split("-"); col = parseInt(row[0]); row = parseInt(row[1]); getElem(col, row).focus(); } } else if (key == 27) { // escape // escape key attribute = undefined; navigationActive = false; gridindex = backupGridindex; row = gridindex.split("-"); col = parseInt(row[0]); row = parseInt(row[1]); getElem(col, row).focus(); } } else { if (key == 38 || key == 121) { // arrow up, F10 up(); event.preventDefault(); } else if (key == 40 || key == 120) { // arrow down, F9 down(); event.preventDefault(); } else if (key == 37 || key == 122) { // arrow left, F11 left(); event.preventDefault(); } else if (key == 39 || key == 123) { // arrow right, F12 right(); event.preventDefault(); } } }) getElem(1, 2).focus();
ValorNaram/isl
templates/sitemap/_files/gridcontrol.js
JavaScript
mit
5,585
// @ts-check const { ESLintUtils } = require('@typescript-eslint/experimental-utils') const RuleTester = ESLintUtils.RuleTester const rule = require('../react-proper-lifecycle-methods') // ------------------------------------------------------------------------------ // Tests // ------------------------------------------------------------------------------ const ruleTester = new RuleTester({ parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 2015, sourceType: 'module', }, }) ruleTester.run('react-proper-lifecycle-methods', rule, { valid: [ // component without lifecycle methods passes without errors { filename: 'app/src/component-no-state.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps> { public render() { return null } } `, }, { filename: 'app/src/component-lifecycle-events-no-state.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps> { public componentWillMount() {} public componentDidMount() {} public componentWillUnmount() {} public componentWillUpdate(nextProps: ICloningRepositoryProps) {} public componentDidUpdate(prevProps: ICloningRepositoryProps) {} public render() { return null } } `, }, { filename: 'app/src/component-lifecycle-events-with-state.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} interface ICloningRepositoryState {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps,ICloningRepositoryState> { public componentWillMount() {} public componentDidMount() {} public componentWillUnmount() {} public componentWillUpdate(nextProps: ICloningRepositoryProps, nextState: ICloningRepositoryState) {} public componentDidUpdate(prevProps: ICloningRepositoryProps, prevState: ICloningRepositoryState) {} public render() { return null } } `, }, { filename: 'app/src/pure-component-lifecycle-events-with-state.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} interface ICloningRepositoryState {} export class CloningRepositoryView extends React.PureComponent<ICloningRepositoryProps,ICloningRepositoryState> { public componentWillMount() {} public componentDidMount() {} public componentWillUnmount() {} public componentWillUpdate(nextProps: ICloningRepositoryProps, nextState: ICloningRepositoryState) {} public componentDidUpdate(prevProps: ICloningRepositoryProps, prevState: ICloningRepositoryState) {} public render() { return null } } `, }, { filename: 'app/src/component-lifecycle-events-with-type-literal.tsx', code: ` import * as React from 'react' interface IWindowControlState {} export class WindowControls extends React.Component<{}, IWindowControlState> { public shouldComponentUpdate(nextProps: {}, nextState: IWindowControlState) { return nextState.windowState !== this.state.windowState } public componentWillUpdate(nextProps: {}, nextState: IWindowControlState) { } public render() { return null } } `, }, { filename: 'app/src/component-lifecycle-events-with-type-literal.tsx', code: ` import * as React from 'react' interface IWindowControlState {} export class WindowControls extends React.Component { public shouldComponentUpdate(nextProps: {}) { return nextState.windowState !== this.state.windowState } public componentWillUpdate(nextProps: {}) { } public render() { return null } } `, }, // a regular class with the same method name is ignored { filename: 'app/src/ui/other.tsx', code: ` class Something { public componentWillUpdate(foo: string) { } } `, }, ], invalid: [ // // shouldComponentUpdate expects the first parameter to be nextProps and match the component's prop type // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps> { public shouldComponentUpdate(foo: string) { return true } public render() { return null } } `, errors: [ { messageId: 'nameMismatch', data: { methodName: 'shouldComponentUpdate', parameterName: 'foo', expectedName: 'nextProps', }, }, { messageId: 'typeMismatch', data: { methodName: 'shouldComponentUpdate', parameterName: 'foo', expectedType: 'ICloningRepositoryProps', }, }, ], }, // // shouldComponentUpdate expects the second parameter to be nextState and match the component's state type // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} interface ICloningRepositoryState {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps,ICloningRepositoryState> { public shouldComponentUpdate(nextProps: ICloningRepositoryProps, foo: string) { return true } public render() { return null } } `, errors: [ { messageId: 'nameMismatch', data: { methodName: 'shouldComponentUpdate', parameterName: 'foo', expectedName: 'nextState', }, }, { messageId: 'typeMismatch', data: { methodName: 'shouldComponentUpdate', parameterName: 'foo', expectedType: 'ICloningRepositoryState', }, }, ], }, // // shouldComponentUpdate is not permitted to have any additional parameters // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} interface ICloningRepositoryState {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps,ICloningRepositoryState> { public shouldComponentUpdate(nextProps: ICloningRepositoryProps, nextState: ICloningRepositoryState, additionalParam: void) { return true } public render() { return null } } `, errors: [ { messageId: 'unknownParameter', data: { methodName: 'shouldComponentUpdate', parameterName: 'additionalParam', }, }, ], }, // // componentWillUpdate expects the first parameter to be nextProps and match the component's prop type // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps> { public componentWillUpdate(bar: string) { } public render() { return null } } `, errors: [ { messageId: 'nameMismatch', data: { methodName: 'componentWillUpdate', parameterName: 'bar', expectedName: 'nextProps', }, }, { messageId: 'typeMismatch', data: { methodName: 'componentWillUpdate', parameterName: 'bar', expectedType: 'ICloningRepositoryProps', }, }, ], }, // // componentWillUpdate expects the first parameter to be nextProps and match the component's type literal // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface IWindowControlState {} export class CloningRepositoryView extends React.Component<{}, IWindowControlState> { public componentWillUpdate(bar: string) { } public render() { return null } } `, errors: [ { messageId: 'nameMismatch', data: { methodName: 'componentWillUpdate', parameterName: 'bar', expectedName: 'nextProps', }, }, { messageId: 'typeMismatch', data: { methodName: 'componentWillUpdate', parameterName: 'bar', expectedType: '{}', }, }, ], }, // // componentWillUpdate expects the second parameter to be nextState and match the component's state type // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} interface ICloningRepositoryState {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps,ICloningRepositoryState> { public componentWillUpdate(nextProps: ICloningRepositoryProps, foo: string) { } public render() { return null } } `, errors: [ { messageId: 'nameMismatch', data: { methodName: 'componentWillUpdate', parameterName: 'foo', expectedName: 'nextState', }, }, { messageId: 'typeMismatch', data: { methodName: 'componentWillUpdate', parameterName: 'foo', expectedType: 'ICloningRepositoryState', }, }, ], }, // // componentWillUpdate expects the first parameter to be nextProps and match the component's type // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface IWindowControlProps {} interface IWindowControlState {} export class CloningRepositoryView extends React.Component<IWindowControlProps, IWindowControlState> { public componentDidUpdate(bar: string) { } public render() { return null } } `, errors: [ { messageId: 'nameMismatch', data: { methodName: 'componentDidUpdate', parameterName: 'bar', expectedName: 'prevProps', }, }, { messageId: 'typeMismatch', data: { methodName: 'componentDidUpdate', parameterName: 'bar', expectedType: 'IWindowControlProps', }, }, ], }, // // componentDidUpdate expects the second parameter to be nextState and match the component's state type // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} interface ICloningRepositoryState {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps,ICloningRepositoryState> { public componentDidUpdate(prevProps: ICloningRepositoryProps, foo: string) { } public render() { return null } } `, errors: [ { messageId: 'nameMismatch', data: { methodName: 'componentDidUpdate', parameterName: 'foo', expectedName: 'prevState', }, }, { messageId: 'typeMismatch', data: { methodName: 'componentDidUpdate', parameterName: 'foo', expectedType: 'ICloningRepositoryState', }, }, ], }, // // Methods inside a component following the `component*` or `shouldComponent*` pattern should be rejected // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' interface ICloningRepositoryProps {} interface ICloningRepositoryState {} export class CloningRepositoryView extends React.Component<ICloningRepositoryProps,ICloningRepositoryState> { public componentWillDoSomething() { } public shouldComponentFoo() { return false } public render() { return null } } `, errors: [ { messageId: 'reservedMethodName', data: { methodName: 'componentWillDoSomething', }, }, { messageId: 'reservedMethodName', data: { methodName: 'shouldComponentFoo', }, }, ], }, // // Methods inside a non-generic component following the `component*` or `shouldComponent*` pattern should be rejected // { filename: 'app/src/component.tsx', code: ` import * as React from 'react' export class CloningRepositoryView extends React.Component { public componentWillDoSomething() { } public shouldComponentFoo() { return false } public render() { return null } } `, errors: [ { messageId: 'reservedMethodName', data: { methodName: 'componentWillDoSomething', }, }, { messageId: 'reservedMethodName', data: { methodName: 'shouldComponentFoo', }, }, ], }, ], })
j-f1/forked-desktop
eslint-rules/tests/react-proper-lifecycle-methods.test.js
JavaScript
mit
13,201
angular.module('ui.bootstrap.alert', []) .controller('UibAlertController', ['$scope', '$attrs', '$timeout', function($scope, $attrs, $timeout) { $scope.closeable = !!$attrs.close; if (angular.isDefined($attrs.dismissOnTimeout)) { $timeout(function() { $scope.close(); }, parseInt($attrs.dismissOnTimeout, 10)); } }]) .directive('uibAlert', function() { return { controller: 'UibAlertController', controllerAs: 'alert', templateUrl: function(element, attrs) { return attrs.templateUrl || 'template/alert/alert.html'; }, transclude: true, replace: true, scope: { type: '@', close: '&' } }; }); /* Deprecated alert below */ angular.module('ui.bootstrap.alert') .value('$alertSuppressWarning', false) .controller('AlertController', ['$scope', '$attrs', '$controller', '$log', '$alertSuppressWarning', function($scope, $attrs, $controller, $log, $alertSuppressWarning) { if (!$alertSuppressWarning) { $log.warn('AlertController is now deprecated. Use UibAlertController instead.'); } angular.extend(this, $controller('UibAlertController', { $scope: $scope, $attrs: $attrs })); }]) .directive('alert', ['$log', '$alertSuppressWarning', function($log, $alertSuppressWarning) { return { controller: 'AlertController', controllerAs: 'alert', templateUrl: function(element, attrs) { return attrs.templateUrl || 'template/alert/alert.html'; }, transclude: true, replace: true, scope: { type: '@', close: '&' }, link: function() { if (!$alertSuppressWarning) { $log.warn('alert is now deprecated. Use uib-alert instead.'); } } }; }]);
tmcgee123/bootstrap
src/alert/alert.js
JavaScript
mit
1,768
/* * This file contains generic tests that are run against every rule. Early on, * we found some common rule patterns that would cause errors under certain * conditions. Instead of tracking them down individually, this file runs * the same tests on every defined rule to track down these patterns. * * When run in addition to the other tests, this causes the Rhino CLI test * to fail due to Java stack overflow. This must be run separate from other tests. */ (function() { "use strict"; var Assert = YUITest.Assert, suite = new YUITest.TestSuite("General Tests for all Rules"), rules = CSSLint.getRules(), len = rules.length, i; function testAll(i, rules) { suite.add(new YUITest.TestCase({ name: "General Tests for " + rules[i].id, setUp: function() { this.options = {}; this.options[rules[i].id] = 1; }, "Using @viewport should not result in an error": function() { var result = CSSLint.verify("@viewport { width: auto; }", this.options); Assert.areEqual(0, result.messages.length); }, "Using @keyframes should not result in an error": function() { var result = CSSLint.verify("@keyframes resize { 0% {padding: 0;} 50% {padding: 0;} 100% {padding: 0;}}", this.options); Assert.areEqual(0, result.messages.length); }, "Using @page should not result in an error": function() { var result = CSSLint.verify("@page { width: 100px; }", this.options); Assert.areEqual(0, result.messages.length); }, "Using @page @top-left should not result in an error": function() { var result = CSSLint.verify("@page { @top-left { content: ''; } }", this.options); Assert.areEqual(0, result.messages.length); }, "Using a regular rule should not result in an error": function() { var result = CSSLint.verify("body { margin: 0; }", this.options); Assert.areEqual(0, result.messages.length); } })); } for (i = 0; i < len; i++) { testAll(i, rules); } YUITest.TestRunner.add(suite); })();
sergeychernyshev/csslint
tests/all-rules.js
JavaScript
mit
2,325
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const { SyncWaterfallHook } = require("tapable"); const Template = require("../Template"); class JsonpMainTemplatePlugin { apply(mainTemplate) { const needChunkOnDemandLoadingCode = chunk => { for (const chunkGroup of chunk.groupsIterable) { if (chunkGroup.getNumberOfChildren() > 0) return true; } return false; }; const needChunkLoadingCode = chunk => { for (const chunkGroup of chunk.groupsIterable) { if (chunkGroup.chunks.length > 1) return true; if (chunkGroup.getNumberOfChildren() > 0) return true; } return false; }; const needEntryDeferringCode = chunk => { for (const chunkGroup of chunk.groupsIterable) { if (chunkGroup.chunks.length > 1) return true; } return false; }; const needPrefetchingCode = chunk => { const allPrefetchChunks = chunk.getChildIdsByOrdersMap(true).prefetch; return allPrefetchChunks && Object.keys(allPrefetchChunks).length; }; // TODO webpack 5, no adding to .hooks, use WeakMap and static methods ["jsonpScript", "linkPreload", "linkPrefetch"].forEach(hook => { if (!mainTemplate.hooks[hook]) { mainTemplate.hooks[hook] = new SyncWaterfallHook([ "source", "chunk", "hash" ]); } }); const getScriptSrcPath = (hash, chunk, chunkIdExpression) => { const chunkFilename = mainTemplate.outputOptions.chunkFilename; const chunkMaps = chunk.getChunkMaps(); return mainTemplate.getAssetPath(JSON.stringify(chunkFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, chunk: { id: `" + ${chunkIdExpression} + "`, hash: `" + ${JSON.stringify( chunkMaps.hash )}[${chunkIdExpression}] + "`, hashWithLength(length) { const shortChunkHashMap = Object.create(null); for (const chunkId of Object.keys(chunkMaps.hash)) { if (typeof chunkMaps.hash[chunkId] === "string") { shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr( 0, length ); } } return `" + ${JSON.stringify( shortChunkHashMap )}[${chunkIdExpression}] + "`; }, name: `" + (${JSON.stringify( chunkMaps.name )}[${chunkIdExpression}]||${chunkIdExpression}) + "`, contentHash: { javascript: `" + ${JSON.stringify( chunkMaps.contentHash.javascript )}[${chunkIdExpression}] + "` }, contentHashWithLength: { javascript: length => { const shortContentHashMap = {}; const contentHash = chunkMaps.contentHash.javascript; for (const chunkId of Object.keys(contentHash)) { if (typeof contentHash[chunkId] === "string") { shortContentHashMap[chunkId] = contentHash[chunkId].substr( 0, length ); } } return `" + ${JSON.stringify( shortContentHashMap )}[${chunkIdExpression}] + "`; } } }, contentHashType: "javascript" }); }; mainTemplate.hooks.localVars.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { const extraCode = []; if (needChunkLoadingCode(chunk)) { extraCode.push( "", "// object to store loaded and loading chunks", "// undefined = chunk not loaded, null = chunk preloaded/prefetched", "// Promise = chunk loading, 0 = chunk loaded", "var installedChunks = {", Template.indent( chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n") ), "};", "", needEntryDeferringCode(chunk) ? "var deferredModules = [];" : "" ); } if (needChunkOnDemandLoadingCode(chunk)) { extraCode.push( "", "// script path function", "function jsonpScriptSrc(chunkId) {", Template.indent([ `return ${mainTemplate.requireFn}.p + ${getScriptSrcPath( hash, chunk, "chunkId" )}` ]), "}" ); } if (extraCode.length === 0) return source; return Template.asString([source, ...extraCode]); } ); mainTemplate.hooks.jsonpScript.tap( "JsonpMainTemplatePlugin", (_, chunk, hash) => { const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; const chunkLoadTimeout = mainTemplate.outputOptions.chunkLoadTimeout; const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType; return Template.asString([ "var script = document.createElement('script');", "var onScriptComplete;", jsonpScriptType ? `script.type = ${JSON.stringify(jsonpScriptType)};` : "", "script.charset = 'utf-8';", `script.timeout = ${chunkLoadTimeout / 1000};`, `if (${mainTemplate.requireFn}.nc) {`, Template.indent( `script.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` ), "}", "script.src = jsonpScriptSrc(chunkId);", crossOriginLoading ? Template.asString([ "if (script.src.indexOf(window.location.origin + '/') !== 0) {", Template.indent( `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` ), "}" ]) : "", "onScriptComplete = function (event) {", Template.indent([ "// avoid mem leaks in IE.", "script.onerror = script.onload = null;", "clearTimeout(timeout);", "var chunk = installedChunks[chunkId];", "if(chunk !== 0) {", Template.indent([ "if(chunk) {", Template.indent([ "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", "var realSrc = event && event.target && event.target.src;", "var error = new Error('Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')');", "error.type = errorType;", "error.request = realSrc;", "chunk[1](error);" ]), "}", "installedChunks[chunkId] = undefined;" ]), "}" ]), "};", "var timeout = setTimeout(function(){", Template.indent([ "onScriptComplete({ type: 'timeout', target: script });" ]), `}, ${chunkLoadTimeout});`, "script.onerror = script.onload = onScriptComplete;" ]); } ); mainTemplate.hooks.linkPreload.tap( "JsonpMainTemplatePlugin", (_, chunk, hash) => { const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType; return Template.asString([ "var link = document.createElement('link');", jsonpScriptType ? `link.type = ${JSON.stringify(jsonpScriptType)};` : "", "link.charset = 'utf-8';", `if (${mainTemplate.requireFn}.nc) {`, Template.indent( `link.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` ), "}", 'link.rel = "preload";', 'link.as = "script";', "link.href = jsonpScriptSrc(chunkId);", crossOriginLoading ? Template.asString([ "if (link.href.indexOf(window.location.origin + '/') !== 0) {", Template.indent( `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` ), "}" ]) : "" ]); } ); mainTemplate.hooks.linkPrefetch.tap( "JsonpMainTemplatePlugin", (_, chunk, hash) => { const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; return Template.asString([ "var link = document.createElement('link');", crossOriginLoading ? `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` : "", `if (${mainTemplate.requireFn}.nc) {`, Template.indent( `link.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` ), "}", 'link.rel = "prefetch";', 'link.as = "script";', "link.href = jsonpScriptSrc(chunkId);" ]); } ); mainTemplate.hooks.requireEnsure.tap( "JsonpMainTemplatePlugin load", (source, chunk, hash) => { return Template.asString([ source, "", "// JSONP chunk loading for javascript", "", "var installedChunkData = installedChunks[chunkId];", 'if(installedChunkData !== 0) { // 0 means "already installed".', Template.indent([ "", '// a Promise means "currently loading".', "if(installedChunkData) {", Template.indent(["promises.push(installedChunkData[2]);"]), "} else {", Template.indent([ "// setup Promise in chunk cache", "var promise = new Promise(function(resolve, reject) {", Template.indent([ "installedChunkData = installedChunks[chunkId] = [resolve, reject];" ]), "});", "promises.push(installedChunkData[2] = promise);", "", "// start chunk loading", mainTemplate.hooks.jsonpScript.call("", chunk, hash), "document.head.appendChild(script);" ]), "}" ]), "}" ]); } ); mainTemplate.hooks.requireEnsure.tap( { name: "JsonpMainTemplatePlugin preload", stage: 10 }, (source, chunk, hash) => { const chunkMap = chunk.getChildIdsByOrdersMap().preload; if (!chunkMap || Object.keys(chunkMap).length === 0) return source; return Template.asString([ source, "", "// chunk preloadng for javascript", "", `var chunkPreloadMap = ${JSON.stringify(chunkMap, null, "\t")};`, "", "var chunkPreloadData = chunkPreloadMap[chunkId];", "if(chunkPreloadData) {", Template.indent([ "chunkPreloadData.forEach(function(chunkId) {", Template.indent([ "if(installedChunks[chunkId] === undefined) {", Template.indent([ "installedChunks[chunkId] = null;", mainTemplate.hooks.linkPreload.call("", chunk, hash), "document.head.appendChild(link);" ]), "}" ]), "});" ]), "}" ]); } ); mainTemplate.hooks.requireExtensions.tap( "JsonpMainTemplatePlugin", (source, chunk) => { if (!needChunkOnDemandLoadingCode(chunk)) return source; return Template.asString([ source, "", "// on error function for async loading", `${ mainTemplate.requireFn }.oe = function(err) { console.error(err); throw err; };` ]); } ); mainTemplate.hooks.bootstrap.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { if (needChunkLoadingCode(chunk)) { const withDefer = needEntryDeferringCode(chunk); const withPrefetch = needPrefetchingCode(chunk); return Template.asString([ source, "", "// install a JSONP callback for chunk loading", "function webpackJsonpCallback(data) {", Template.indent([ "var chunkIds = data[0];", "var moreModules = data[1];", withDefer ? "var executeModules = data[2];" : "", withPrefetch ? "var prefetchChunks = data[3] || [];" : "", '// add "moreModules" to the modules object,', '// then flag all "chunkIds" as loaded and fire callback', "var moduleId, chunkId, i = 0, resolves = [];", "for(;i < chunkIds.length; i++) {", Template.indent([ "chunkId = chunkIds[i];", "if(installedChunks[chunkId]) {", Template.indent("resolves.push(installedChunks[chunkId][0]);"), "}", "installedChunks[chunkId] = 0;" ]), "}", "for(moduleId in moreModules) {", Template.indent([ "if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {", Template.indent( mainTemplate.renderAddModule( hash, chunk, "moduleId", "moreModules[moduleId]" ) ), "}" ]), "}", "if(parentJsonpFunction) parentJsonpFunction(data);", withPrefetch ? Template.asString([ "// chunk prefetching for javascript", "prefetchChunks.forEach(function(chunkId) {", Template.indent([ "if(installedChunks[chunkId] === undefined) {", Template.indent([ "installedChunks[chunkId] = null;", mainTemplate.hooks.linkPrefetch.call("", chunk, hash), "document.head.appendChild(link);" ]), "}" ]), "});" ]) : "", "while(resolves.length) {", Template.indent("resolves.shift()();"), "}", withDefer ? Template.asString([ "", "// add entry modules from loaded chunk to deferred list", "deferredModules.push.apply(deferredModules, executeModules || []);", "", "// run deferred modules when all chunks ready", "return checkDeferredModules();" ]) : "" ]), "};", withDefer ? Template.asString([ "function checkDeferredModules() {", Template.indent([ "var result;", "for(var i = 0; i < deferredModules.length; i++) {", Template.indent([ "var deferredModule = deferredModules[i];", "var fulfilled = true;", "for(var j = 1; j < deferredModule.length; j++) {", Template.indent([ "var depId = deferredModule[j];", "if(installedChunks[depId] !== 0) fulfilled = false;" ]), "}", "if(fulfilled) {", Template.indent([ "deferredModules.splice(i--, 1);", "result = " + mainTemplate.requireFn + "(" + mainTemplate.requireFn + ".s = deferredModule[0]);" ]), "}" ]), "}", "return result;" ]), "}" ]) : "" ]); } return source; } ); mainTemplate.hooks.beforeStartup.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { if (needChunkLoadingCode(chunk)) { var jsonpFunction = mainTemplate.outputOptions.jsonpFunction; var globalObject = mainTemplate.outputOptions.globalObject; return Template.asString([ `var jsonpArray = ${globalObject}[${JSON.stringify( jsonpFunction )}] = ${globalObject}[${JSON.stringify(jsonpFunction)}] || [];`, "var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);", "jsonpArray.push = webpackJsonpCallback;", "jsonpArray = jsonpArray.slice();", "for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);", "var parentJsonpFunction = oldJsonpFunction;", "", source ]); } return source; } ); mainTemplate.hooks.beforeStartup.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { const prefetchChunks = chunk.getChildIdsByOrders().prefetch; if ( needChunkLoadingCode(chunk) && prefetchChunks && prefetchChunks.length ) { return Template.asString([ source, `webpackJsonpCallback([[], {}, 0, ${JSON.stringify( prefetchChunks )}]);` ]); } return source; } ); mainTemplate.hooks.startup.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { if (needEntryDeferringCode(chunk)) { if (chunk.hasEntryModule()) { const entries = [chunk.entryModule].filter(Boolean).map(m => [m.id].concat( Array.from(chunk.groupsIterable)[0] .chunks.filter(c => c !== chunk) .map(c => c.id) ) ); return Template.asString([ "// add entry module to deferred list", `deferredModules.push(${entries .map(e => JSON.stringify(e)) .join(", ")});`, "// run deferred modules when ready", "return checkDeferredModules();" ]); } else { return Template.asString([ "// run deferred modules from other chunks", "checkDeferredModules();" ]); } } return source; } ); mainTemplate.hooks.hotBootstrap.tap( "JsonpMainTemplatePlugin", (source, chunk, hash) => { const globalObject = mainTemplate.outputOptions.globalObject; const hotUpdateChunkFilename = mainTemplate.outputOptions.hotUpdateChunkFilename; const hotUpdateMainFilename = mainTemplate.outputOptions.hotUpdateMainFilename; const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; const hotUpdateFunction = mainTemplate.outputOptions.hotUpdateFunction; const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( JSON.stringify(hotUpdateChunkFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, chunk: { id: '" + chunkId + "' } } ); const currentHotUpdateMainFilename = mainTemplate.getAssetPath( JSON.stringify(hotUpdateMainFilename), { hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` } ); const runtimeSource = Template.getFunctionContent( require("./JsonpMainTemplate.runtime") ) .replace(/\/\/\$semicolon/g, ";") .replace(/\$require\$/g, mainTemplate.requireFn) .replace( /\$crossOriginLoading\$/g, crossOriginLoading ? JSON.stringify(crossOriginLoading) : "null" ) .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) .replace(/\$hash\$/g, JSON.stringify(hash)); return `${source} function hotDisposeChunk(chunkId) { delete installedChunks[chunkId]; } var parentHotUpdateCallback = ${globalObject}[${JSON.stringify( hotUpdateFunction )}]; ${globalObject}[${JSON.stringify(hotUpdateFunction)}] = ${runtimeSource}`; } ); mainTemplate.hooks.hash.tap("JsonpMainTemplatePlugin", hash => { hash.update("jsonp"); hash.update("6"); }); } } module.exports = JsonpMainTemplatePlugin;
marchefk/marchefk.github.io
node_modules/webpack/lib/web/JsonpMainTemplatePlugin.js
JavaScript
mit
18,103
// from https://gist.github.com/mathewbyrne/1280286 slugify = function(text){ return text.toString().toLowerCase() .replace(/\s+/g, '-') // Replace spaces with - .replace(/[^\w\-]+/g, '') // Remove all non-word chars .replace(/\-\-+/g, '-') // Replace multiple - with single - .replace(/^-+/, '') // Trim - from start of text .replace(/-+$/, ''); // Trim - from end of text } var render = function(data) { var data = data.data; var out = '* [' + data.title + '](https://github.com/git-tips/tips#' + slugify(data.title) + ')\n'; return out; }; module.exports = render;
ejmr/tips
.doxie.render.toc.js
JavaScript
mit
647
define(function() { "use strict"; function RangeFilter(columnKey, isMinEnabled, minValue, isMaxEnabled, maxValue) { InputValidator.validateNotNull("columnKey", columnKey); InputValidator.validateNotNull("isMinEnabled", isMinEnabled); InputValidator.validateNotNull("minValue", minValue); InputValidator.validateNotNull("isMaxEnabled", isMaxEnabled); InputValidator.validateNotNull("maxValue", maxValue); this.columnKey = function() { return columnKey; }; this.isMinEnabled = function() { return isMinEnabled; }; this.minValue = function() { return minValue; }; this.isMaxEnabled = function() { return isMaxEnabled; }; this.maxValue = function() { return maxValue; }; this.passes = function(data) { InputValidator.validateNotNull("data", data); var value = data[columnKey]; return (!isMinEnabled || minValue <= value) && (!isMaxEnabled || value <= maxValue); }; this.toObject = function() { return ( { type: "RangeFilter", columnKey: columnKey, isMinEnabled: isMinEnabled, minValue: minValue, isMaxEnabled: isMaxEnabled, maxValue: maxValue, }); }; this.toString = function() { return "RangeFilter (" + isMinEnabled + " " + minValue + "\u2264" + columnKey + "\u2264" + isMaxEnabled + " " + maxValue + ")"; }; } RangeFilter.fromObject = function(object) { InputValidator.validateNotNull("object", object); var columnKey = object.columnKey; var isMinEnabled = object.isMinEnabled; var minValue = object.minValue; var isMaxEnabled = object.isMaxEnabled; var maxValue = object.maxValue; return new RangeFilter(columnKey, isMinEnabled, minValue, isMaxEnabled, maxValue); }; return RangeFilter; });
jmthompson2015/vizzini
game/starfightersquadrons/src/main/js/upgradestats/RangeFilter.js
JavaScript
mit
2,166
const debug = require('ghost-ignition').debug('api:canary:utils:serializers:input:authors'); const slugFilterOrder = require('./utils/slug-filter-order'); const utils = require('../../index'); function setDefaultOrder(frame) { if (!frame.options.order && frame.options.filter) { frame.options.autoOrder = slugFilterOrder('users', frame.options.filter); } if (!frame.options.order && !frame.options.autoOrder) { frame.options.order = 'name asc'; } } module.exports = { browse(apiConfig, frame) { debug('browse'); if (utils.isContentAPI(frame)) { setDefaultOrder(frame); } }, read(apiConfig, frame) { debug('read'); if (utils.isContentAPI(frame)) { setDefaultOrder(frame); } } };
e10/Ghost
core/server/api/canary/utils/serializers/input/authors.js
JavaScript
mit
804
(function() { 'use strict'; /* * This feature allows you to specify a grid over a portion or the entire chart area. * * @name grid */ d4.feature('grid', function(name) { var xAxis = d3.svg.axis(); var yAxis = d3.svg.axis(); return { accessors: { formatXAxis: function(xAxis) { return xAxis.orient('bottom'); }, formatYAxis: function(yAxis) { return yAxis.orient('left'); } }, proxies: [{ target: xAxis, prefix: 'x' }, { target: yAxis, prefix: 'y' }], render: function(scope, data, selection) { xAxis.scale(this.x); yAxis.scale(this.y); var formattedXAxis = d4.functor(scope.accessors.formatXAxis).bind(this)(xAxis); var formattedYAxis = d4.functor(scope.accessors.formatYAxis).bind(this)(yAxis); var grid = d4.appendOnce(selection, 'g.grid.border.' + name); var gridBg = d4.appendOnce(grid, 'rect'); var gridX = d4.appendOnce(grid, 'g.x.grid.' + name); var gridY = d4.appendOnce(grid, 'g.y.grid.' + name); gridBg .attr('transform', 'translate(0,0)') .attr('x', 0) .attr('y', 0) .attr('width', this.width) .attr('height', this.height); gridX .attr('transform', 'translate(0,' + this.height + ')') .call(formattedXAxis .tickSize(-this.height, 0, 0) .tickFormat('')); gridY .attr('transform', 'translate(0,0)') .call(formattedYAxis .tickSize(-this.width, 0, 0) .tickFormat('')); return grid; } }; }); }).call(this);
heavysixer/d4
src/features/grid.js
JavaScript
mit
1,718
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; import { NgModule, Component, ContentChildren, Directive, ElementRef, Renderer, EventEmitter, HostBinding, Input, Optional, Output, QueryList, ViewChild, ViewEncapsulation, forwardRef } from '@angular/core'; import { NG_VALUE_ACCESSOR, FormsModule } from '@angular/forms'; import { Observable } from 'rxjs/Observable'; import { MdUniqueSelectionDispatcher, coerceBooleanProperty, DefaultStyleCompatibilityModeModule } from '../core'; /** * Provider Expression that allows md-button-toggle-group to register as a ControlValueAccessor. * This allows it to support [(ngModel)]. */ export var MD_BUTTON_TOGGLE_GROUP_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(function () { return MdButtonToggleGroup; }), multi: true }; var _uniqueIdCounter = 0; /** A simple change event emitted by either MdButtonToggle or MdButtonToggleGroup. */ export var MdButtonToggleChange = (function () { function MdButtonToggleChange() { } return MdButtonToggleChange; }()); /** Exclusive selection button toggle group that behaves like a radio-button group. */ export var MdButtonToggleGroup = (function () { function MdButtonToggleGroup() { /** The value for the button toggle group. Should match currently selected button toggle. */ this._value = null; /** The HTML name attribute applied to toggles in this group. */ this._name = "md-radio-group-" + _uniqueIdCounter++; /** Disables all toggles in the group. */ this._disabled = null; /** Whether the button toggle group should be vertical. */ this._vertical = false; /** The currently selected button toggle, should match the value. */ this._selected = null; /** Whether the button toggle group is initialized or not. */ this._isInitialized = false; /** * The method to be called in order to update ngModel. * Now `ngModel` binding is not supported in multiple selection mode. */ this._controlValueAccessorChangeFn = function (value) { }; /** onTouch function registered via registerOnTouch (ControlValueAccessor). */ this.onTouched = function () { }; /** Event emitted when the group's value changes. */ this._change = new EventEmitter(); /** Child button toggle buttons. */ this._buttonToggles = null; } Object.defineProperty(MdButtonToggleGroup.prototype, "change", { get: function () { return this._change.asObservable(); }, enumerable: true, configurable: true }); /** TODO: internal */ MdButtonToggleGroup.prototype.ngAfterViewInit = function () { this._isInitialized = true; }; Object.defineProperty(MdButtonToggleGroup.prototype, "name", { get: function () { return this._name; }, set: function (value) { this._name = value; this._updateButtonToggleNames(); }, enumerable: true, configurable: true }); Object.defineProperty(MdButtonToggleGroup.prototype, "disabled", { get: function () { return this._disabled; }, set: function (value) { this._disabled = coerceBooleanProperty(value); }, enumerable: true, configurable: true }); Object.defineProperty(MdButtonToggleGroup.prototype, "vertical", { get: function () { return this._vertical; }, set: function (value) { this._vertical = coerceBooleanProperty(value); }, enumerable: true, configurable: true }); Object.defineProperty(MdButtonToggleGroup.prototype, "value", { get: function () { return this._value; }, set: function (newValue) { if (this._value != newValue) { this._value = newValue; this._updateSelectedButtonToggleFromValue(); // Only emit a change event if the view is completely initialized. // We don't want to emit a change event for the initial values. if (this._isInitialized) { this._emitChangeEvent(); } } }, enumerable: true, configurable: true }); Object.defineProperty(MdButtonToggleGroup.prototype, "selected", { get: function () { return this._selected; }, set: function (selected) { this._selected = selected; this.value = selected ? selected.value : null; if (selected && !selected.checked) { selected.checked = true; } }, enumerable: true, configurable: true }); MdButtonToggleGroup.prototype._updateButtonToggleNames = function () { var _this = this; if (this._buttonToggles) { this._buttonToggles.forEach(function (toggle) { toggle.name = _this._name; }); } }; // TODO: Refactor into shared code with radio. MdButtonToggleGroup.prototype._updateSelectedButtonToggleFromValue = function () { var _this = this; var isAlreadySelected = this._selected != null && this._selected.value == this._value; if (this._buttonToggles != null && !isAlreadySelected) { var matchingButtonToggle = this._buttonToggles.filter(function (buttonToggle) { return buttonToggle.value == _this._value; })[0]; if (matchingButtonToggle) { this.selected = matchingButtonToggle; } else if (this.value == null) { this.selected = null; this._buttonToggles.forEach(function (buttonToggle) { buttonToggle.checked = false; }); } } }; /** Dispatch change event with current selection and group value. */ MdButtonToggleGroup.prototype._emitChangeEvent = function () { var event = new MdButtonToggleChange(); event.source = this._selected; event.value = this._value; this._controlValueAccessorChangeFn(event.value); this._change.emit(event); }; /** * Implemented as part of ControlValueAccessor. * TODO: internal */ MdButtonToggleGroup.prototype.writeValue = function (value) { this.value = value; }; /** * Implemented as part of ControlValueAccessor. * TODO: internal */ MdButtonToggleGroup.prototype.registerOnChange = function (fn) { this._controlValueAccessorChangeFn = fn; }; /** * Implemented as part of ControlValueAccessor. * TODO: internal */ MdButtonToggleGroup.prototype.registerOnTouched = function (fn) { this.onTouched = fn; }; __decorate([ Output(), __metadata('design:type', Observable) ], MdButtonToggleGroup.prototype, "change", null); __decorate([ ContentChildren(forwardRef(function () { return MdButtonToggle; })), __metadata('design:type', QueryList) ], MdButtonToggleGroup.prototype, "_buttonToggles", void 0); __decorate([ Input(), __metadata('design:type', String) ], MdButtonToggleGroup.prototype, "name", null); __decorate([ Input(), __metadata('design:type', Boolean) ], MdButtonToggleGroup.prototype, "disabled", null); __decorate([ Input(), __metadata('design:type', Boolean) ], MdButtonToggleGroup.prototype, "vertical", null); __decorate([ Input(), __metadata('design:type', Object) ], MdButtonToggleGroup.prototype, "value", null); __decorate([ Input(), __metadata('design:type', Object) ], MdButtonToggleGroup.prototype, "selected", null); MdButtonToggleGroup = __decorate([ Directive({ selector: 'md-button-toggle-group:not([multiple])', providers: [MD_BUTTON_TOGGLE_GROUP_VALUE_ACCESSOR], host: { 'role': 'radiogroup', '[class.md-button-toggle-vertical]': 'vertical' }, exportAs: 'mdButtonToggleGroup', }), __metadata('design:paramtypes', []) ], MdButtonToggleGroup); return MdButtonToggleGroup; }()); /** Multiple selection button-toggle group. `ngModel` is not supported in this mode. */ export var MdButtonToggleGroupMultiple = (function () { function MdButtonToggleGroupMultiple() { /** Disables all toggles in the group. */ this._disabled = null; /** Whether the button toggle group should be vertical. */ this._vertical = false; } Object.defineProperty(MdButtonToggleGroupMultiple.prototype, "disabled", { get: function () { return this._disabled; }, set: function (value) { this._disabled = (value != null && value !== false) ? true : null; }, enumerable: true, configurable: true }); Object.defineProperty(MdButtonToggleGroupMultiple.prototype, "vertical", { get: function () { return this._vertical; }, set: function (value) { this._vertical = coerceBooleanProperty(value); }, enumerable: true, configurable: true }); __decorate([ Input(), __metadata('design:type', Boolean) ], MdButtonToggleGroupMultiple.prototype, "disabled", null); __decorate([ Input(), __metadata('design:type', Boolean) ], MdButtonToggleGroupMultiple.prototype, "vertical", null); MdButtonToggleGroupMultiple = __decorate([ Directive({ selector: 'md-button-toggle-group[multiple]', exportAs: 'mdButtonToggleGroup', host: { '[class.md-button-toggle-vertical]': 'vertical' } }), __metadata('design:paramtypes', []) ], MdButtonToggleGroupMultiple); return MdButtonToggleGroupMultiple; }()); export var MdButtonToggle = (function () { function MdButtonToggle(toggleGroup, toggleGroupMultiple, buttonToggleDispatcher, _renderer) { var _this = this; this.buttonToggleDispatcher = buttonToggleDispatcher; this._renderer = _renderer; /** Whether or not this button toggle is checked. */ this._checked = false; /** Whether or not this button toggle is disabled. */ this._disabled = null; /** Value assigned to this button toggle. */ this._value = null; /** Whether or not the button toggle is a single selection. */ this._isSingleSelector = null; /** Event emitted when the group value changes. */ this._change = new EventEmitter(); this.buttonToggleGroup = toggleGroup; this.buttonToggleGroupMultiple = toggleGroupMultiple; if (this.buttonToggleGroup) { buttonToggleDispatcher.listen(function (id, name) { if (id != _this.id && name == _this.name) { _this.checked = false; } }); this._type = 'radio'; this.name = this.buttonToggleGroup.name; this._isSingleSelector = true; } else { // Even if there is no group at all, treat the button toggle as a checkbox so it can be // toggled on or off. this._type = 'checkbox'; this._isSingleSelector = false; } } Object.defineProperty(MdButtonToggle.prototype, "change", { get: function () { return this._change.asObservable(); }, enumerable: true, configurable: true }); MdButtonToggle.prototype.ngOnInit = function () { if (this.id == null) { this.id = "md-button-toggle-" + _uniqueIdCounter++; } if (this.buttonToggleGroup && this._value == this.buttonToggleGroup.value) { this._checked = true; } }; Object.defineProperty(MdButtonToggle.prototype, "inputId", { get: function () { return this.id + "-input"; }, enumerable: true, configurable: true }); Object.defineProperty(MdButtonToggle.prototype, "checked", { get: function () { return this._checked; }, set: function (newCheckedState) { if (this._isSingleSelector) { if (newCheckedState) { // Notify all button toggles with the same name (in the same group) to un-check. this.buttonToggleDispatcher.notify(this.id, this.name); } } this._checked = newCheckedState; if (newCheckedState && this._isSingleSelector && this.buttonToggleGroup.value != this.value) { this.buttonToggleGroup.selected = this; } }, enumerable: true, configurable: true }); Object.defineProperty(MdButtonToggle.prototype, "value", { /** MdButtonToggleGroup reads this to assign its own value. */ get: function () { return this._value; }, set: function (value) { if (this._value != value) { if (this.buttonToggleGroup != null && this.checked) { this.buttonToggleGroup.value = value; } this._value = value; } }, enumerable: true, configurable: true }); /** Dispatch change event with current value. */ MdButtonToggle.prototype._emitChangeEvent = function () { var event = new MdButtonToggleChange(); event.source = this; event.value = this._value; this._change.emit(event); }; Object.defineProperty(MdButtonToggle.prototype, "disabled", { get: function () { return this._disabled || (this.buttonToggleGroup != null && this.buttonToggleGroup.disabled) || (this.buttonToggleGroupMultiple != null && this.buttonToggleGroupMultiple.disabled); }, set: function (value) { this._disabled = (value != null && value !== false) ? true : null; }, enumerable: true, configurable: true }); /** Toggle the state of the current button toggle. */ MdButtonToggle.prototype._toggle = function () { this.checked = !this.checked; }; /** Checks the button toggle due to an interaction with the underlying native input. */ MdButtonToggle.prototype._onInputChange = function (event) { event.stopPropagation(); if (this._isSingleSelector) { // Propagate the change one-way via the group, which will in turn mark this // button toggle as checked. this.checked = true; this.buttonToggleGroup.selected = this; this.buttonToggleGroup.onTouched(); } else { this._toggle(); } // Emit a change event when the native input does. this._emitChangeEvent(); }; /** TODO: internal */ MdButtonToggle.prototype._onInputClick = function (event) { // We have to stop propagation for click events on the visual hidden input element. // By default, when a user clicks on a label element, a generated click event will be // dispatched on the associated input element. Since we are using a label element as our // root container, the click event on the `slide-toggle` will be executed twice. // The real click event will bubble up, and the generated click event also tries to bubble up. // This will lead to multiple click events. // Preventing bubbling for the second event will solve that issue. event.stopPropagation(); }; MdButtonToggle.prototype.focus = function () { this._renderer.invokeElementMethod(this._inputElement.nativeElement, 'focus'); }; __decorate([ HostBinding(), Input(), __metadata('design:type', String) ], MdButtonToggle.prototype, "id", void 0); __decorate([ Input(), __metadata('design:type', String) ], MdButtonToggle.prototype, "name", void 0); __decorate([ Output(), __metadata('design:type', Observable) ], MdButtonToggle.prototype, "change", null); __decorate([ ViewChild('input'), __metadata('design:type', ElementRef) ], MdButtonToggle.prototype, "_inputElement", void 0); __decorate([ HostBinding('class.md-button-toggle-checked'), Input(), __metadata('design:type', Boolean) ], MdButtonToggle.prototype, "checked", null); __decorate([ Input(), __metadata('design:type', Object) ], MdButtonToggle.prototype, "value", null); __decorate([ HostBinding('class.md-button-toggle-disabled'), Input(), __metadata('design:type', Boolean) ], MdButtonToggle.prototype, "disabled", null); MdButtonToggle = __decorate([ Component({selector: 'md-button-toggle', template: "<label [attr.for]=\"inputId\" class=\"md-button-toggle-label\"> <input #input class=\"md-button-toggle-input md-visually-hidden\" [type]=\"_type\" [id]=\"inputId\" [checked]=\"checked\" [disabled]=\"disabled\" [name]=\"name\" (change)=\"_onInputChange($event)\" (click)=\"_onInputClick($event)\"> <div class=\"md-button-toggle-label-content\"> <ng-content></ng-content> </div> </label> ", styles: ["md-button-toggle-group { box-shadow: 0px 3px 1px -2px rgba(0, 0, 0, 0.2), 0px 2px 2px 0px rgba(0, 0, 0, 0.14), 0px 1px 5px 0px rgba(0, 0, 0, 0.12); position: relative; display: inline-flex; flex-direction: row; border-radius: 2px; cursor: pointer; white-space: nowrap; } .md-button-toggle-vertical { flex-direction: column; } .md-button-toggle-vertical .md-button-toggle-label-content { display: block; } .md-button-toggle-disabled .md-button-toggle-label-content { cursor: default; } md-button-toggle { white-space: nowrap; } .md-button-toggle-label-content { display: inline-block; line-height: 36px; padding: 0 16px; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .md-button-toggle-label-content > * { vertical-align: middle; } /*# sourceMappingURL=button-toggle.css.map */ "], encapsulation: ViewEncapsulation.None, }), __param(0, Optional()), __param(1, Optional()), __metadata('design:paramtypes', [MdButtonToggleGroup, MdButtonToggleGroupMultiple, MdUniqueSelectionDispatcher, Renderer]) ], MdButtonToggle); return MdButtonToggle; }()); export var MdButtonToggleModule = (function () { function MdButtonToggleModule() { } MdButtonToggleModule.forRoot = function () { return { ngModule: MdButtonToggleModule, providers: [MdUniqueSelectionDispatcher] }; }; MdButtonToggleModule = __decorate([ NgModule({ imports: [FormsModule, DefaultStyleCompatibilityModeModule], exports: [ MdButtonToggleGroup, MdButtonToggleGroupMultiple, MdButtonToggle, DefaultStyleCompatibilityModeModule, ], declarations: [MdButtonToggleGroup, MdButtonToggleGroupMultiple, MdButtonToggle], }), __metadata('design:paramtypes', []) ], MdButtonToggleModule); return MdButtonToggleModule; }()); //# sourceMappingURL=button-toggle.js.map
HipsterZipster/angular2-webpack-starter
node_modules/@angular/material/button-toggle/button-toggle.js
JavaScript
mit
20,521
var searchData= [ ['get_5fmodel_5fhandle',['GET_MODEL_HANDLE',['../serializer_8h.html#a887590f4b40f78bf359c8e56f03c56fe',1,'serializer.h']]] ];
fsautomata/azure-iot-sdks
c/doc/api_reference/search/defines_3.js
JavaScript
mit
146
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('../../SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ContentLowPriority = function ContentLowPriority(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M14 5h8v2h-8zm0 5.5h8v2h-8zm0 5.5h8v2h-8zM2 11.5C2 15.08 4.92 18 8.5 18H9v2l3-3-3-3v2h-.5C6.02 16 4 13.98 4 11.5S6.02 7 8.5 7H12V5H8.5C4.92 5 2 7.92 2 11.5z' }) ); }; ContentLowPriority = (0, _pure2.default)(ContentLowPriority); ContentLowPriority.displayName = 'ContentLowPriority'; exports.default = ContentLowPriority;
myfintech/material-ui
svg-icons/content/low-priority.js
JavaScript
mit
943
import { Mesh, OrthographicCamera, PerspectiveCamera, PlaneGeometry, Scene, ShaderMaterial, UniformsUtils, WebGLRenderTarget } from 'three'; import { BokehShader } from '../shaders/BokehShader2.js'; import { BokehDepthShader } from '../shaders/BokehShader2.js'; class CinematicCamera extends PerspectiveCamera { constructor( fov, aspect, near, far ) { super( fov, aspect, near, far ); this.type = 'CinematicCamera'; this.postprocessing = { enabled: true }; this.shaderSettings = { rings: 3, samples: 4 }; const depthShader = BokehDepthShader; this.materialDepth = new ShaderMaterial( { uniforms: depthShader.uniforms, vertexShader: depthShader.vertexShader, fragmentShader: depthShader.fragmentShader } ); this.materialDepth.uniforms[ 'mNear' ].value = near; this.materialDepth.uniforms[ 'mFar' ].value = far; // In case of cinematicCamera, having a default lens set is important this.setLens(); this.initPostProcessing(); } // providing fnumber and coc(Circle of Confusion) as extra arguments // In case of cinematicCamera, having a default lens set is important // if fnumber and coc are not provided, cinematicCamera tries to act as a basic PerspectiveCamera setLens( focalLength = 35, filmGauge = 35, fNumber = 8, coc = 0.019 ) { this.filmGauge = filmGauge; this.setFocalLength( focalLength ); this.fNumber = fNumber; this.coc = coc; // fNumber is focalLength by aperture this.aperture = focalLength / this.fNumber; // hyperFocal is required to calculate depthOfField when a lens tries to focus at a distance with given fNumber and focalLength this.hyperFocal = ( focalLength * focalLength ) / ( this.aperture * this.coc ); } linearize( depth ) { const zfar = this.far; const znear = this.near; return - zfar * znear / ( depth * ( zfar - znear ) - zfar ); } smoothstep( near, far, depth ) { const x = this.saturate( ( depth - near ) / ( far - near ) ); return x * x * ( 3 - 2 * x ); } saturate( x ) { return Math.max( 0, Math.min( 1, x ) ); } // function for focusing at a distance from the camera focusAt( focusDistance = 20 ) { const focalLength = this.getFocalLength(); // distance from the camera (normal to frustrum) to focus on this.focus = focusDistance; // the nearest point from the camera which is in focus (unused) this.nearPoint = ( this.hyperFocal * this.focus ) / ( this.hyperFocal + ( this.focus - focalLength ) ); // the farthest point from the camera which is in focus (unused) this.farPoint = ( this.hyperFocal * this.focus ) / ( this.hyperFocal - ( this.focus - focalLength ) ); // the gap or width of the space in which is everything is in focus (unused) this.depthOfField = this.farPoint - this.nearPoint; // Considering minimum distance of focus for a standard lens (unused) if ( this.depthOfField < 0 ) this.depthOfField = 0; this.sdistance = this.smoothstep( this.near, this.far, this.focus ); this.ldistance = this.linearize( 1 - this.sdistance ); this.postprocessing.bokeh_uniforms[ 'focalDepth' ].value = this.ldistance; } initPostProcessing() { if ( this.postprocessing.enabled ) { this.postprocessing.scene = new Scene(); this.postprocessing.camera = new OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, - 10000, 10000 ); this.postprocessing.scene.add( this.postprocessing.camera ); this.postprocessing.rtTextureDepth = new WebGLRenderTarget( window.innerWidth, window.innerHeight ); this.postprocessing.rtTextureColor = new WebGLRenderTarget( window.innerWidth, window.innerHeight ); const bokeh_shader = BokehShader; this.postprocessing.bokeh_uniforms = UniformsUtils.clone( bokeh_shader.uniforms ); this.postprocessing.bokeh_uniforms[ 'tColor' ].value = this.postprocessing.rtTextureColor.texture; this.postprocessing.bokeh_uniforms[ 'tDepth' ].value = this.postprocessing.rtTextureDepth.texture; this.postprocessing.bokeh_uniforms[ 'manualdof' ].value = 0; this.postprocessing.bokeh_uniforms[ 'shaderFocus' ].value = 0; this.postprocessing.bokeh_uniforms[ 'fstop' ].value = 2.8; this.postprocessing.bokeh_uniforms[ 'showFocus' ].value = 1; this.postprocessing.bokeh_uniforms[ 'focalDepth' ].value = 0.1; //console.log( this.postprocessing.bokeh_uniforms[ "focalDepth" ].value ); this.postprocessing.bokeh_uniforms[ 'znear' ].value = this.near; this.postprocessing.bokeh_uniforms[ 'zfar' ].value = this.near; this.postprocessing.bokeh_uniforms[ 'textureWidth' ].value = window.innerWidth; this.postprocessing.bokeh_uniforms[ 'textureHeight' ].value = window.innerHeight; this.postprocessing.materialBokeh = new ShaderMaterial( { uniforms: this.postprocessing.bokeh_uniforms, vertexShader: bokeh_shader.vertexShader, fragmentShader: bokeh_shader.fragmentShader, defines: { RINGS: this.shaderSettings.rings, SAMPLES: this.shaderSettings.samples, DEPTH_PACKING: 1 } } ); this.postprocessing.quad = new Mesh( new PlaneGeometry( window.innerWidth, window.innerHeight ), this.postprocessing.materialBokeh ); this.postprocessing.quad.position.z = - 500; this.postprocessing.scene.add( this.postprocessing.quad ); } } renderCinematic( scene, renderer ) { if ( this.postprocessing.enabled ) { const currentRenderTarget = renderer.getRenderTarget(); renderer.clear(); // Render scene into texture scene.overrideMaterial = null; renderer.setRenderTarget( this.postprocessing.rtTextureColor ); renderer.clear(); renderer.render( scene, this ); // Render depth into texture scene.overrideMaterial = this.materialDepth; renderer.setRenderTarget( this.postprocessing.rtTextureDepth ); renderer.clear(); renderer.render( scene, this ); // Render bokeh composite renderer.setRenderTarget( null ); renderer.render( this.postprocessing.scene, this.postprocessing.camera ); renderer.setRenderTarget( currentRenderTarget ); } } } export { CinematicCamera };
donmccurdy/three.js
examples/jsm/cameras/CinematicCamera.js
JavaScript
mit
6,106
import Social from './Social' export default Social
luisma1989/portfolio-react
src/components/Social/index.js
JavaScript
mit
53
๏ปฟ/* Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'colorbutton', 'ja', { auto: '่‡ชๅ‹•', bgColorTitle: '่ƒŒๆ™ฏ่‰ฒ', colors: { '000': 'Black', '800000': 'Maroon', '8B4513': 'Saddle Brown', '2F4F4F': 'Dark Slate Gray', '008080': 'Teal', '000080': 'Navy', '4B0082': 'Indigo', '696969': 'Dark Gray', B22222: 'Fire Brick', A52A2A: 'Brown', DAA520: 'Golden Rod', '006400': 'Dark Green', '40E0D0': 'Turquoise', '0000CD': 'Medium Blue', '800080': 'Purple', '808080': 'Gray', F00: 'Red', FF8C00: 'Dark Orange', FFD700: 'Gold', '008000': 'Green', '0FF': 'Cyan', '00F': 'Blue', EE82EE: 'Violet', A9A9A9: 'Dim Gray', FFA07A: 'Light Salmon', FFA500: 'Orange', FFFF00: 'Yellow', '00FF00': 'Lime', AFEEEE: 'Pale Turquoise', ADD8E6: 'Light Blue', DDA0DD: 'Plum', D3D3D3: 'Light Grey', FFF0F5: 'Lavender Blush', FAEBD7: 'Antique White', FFFFE0: 'Light Yellow', F0FFF0: 'Honeydew', F0FFFF: 'Azure', F0F8FF: 'Alice Blue', E6E6FA: 'Lavender', FFF: 'White', '1ABC9C': 'Strong Cyan', '2ECC71': 'Emerald', '3498DB': 'Bright Blue', '9B59B6': 'Amethyst', '4E5F70': 'Grayish Blue', 'F1C40F': 'Vivid Yellow', '16A085': 'Dark Cyan', '27AE60': 'Dark Emerald', '2980B9': 'Strong Blue', '8E44AD': 'Dark Violet', '2C3E50': 'Desaturated Blue', 'F39C12': 'Orange', 'E67E22': 'Carrot', 'E74C3C': 'Pale Red', 'ECF0F1': 'Bright Silver', '95A5A6': 'Light Grayish Cyan', 'DDD': 'Light Gray', 'D35400': 'Pumpkin', 'C0392B': 'Strong Red', 'BDC3C7': 'Silver', '7F8C8D': 'Grayish Cyan', '999': 'Dark Gray' }, more: 'ใใฎไป–ใฎ่‰ฒ...', panelTitle: '่‰ฒ', textColorTitle: 'ๆ–‡ๅญ—่‰ฒ' } );
zweidner/hubzero-cms
core/plugins/editors/ckeditor/assets/plugins/colorbutton/lang/ja.js
JavaScript
mit
1,819
var parent = require('../../actual/array-buffer'); module.exports = parent;
zloirock/core-js
packages/core-js/features/array-buffer/index.js
JavaScript
mit
77
/*! * gumshoe v4.0.1 * A simple, framework-agnostic scrollspy script. * (c) 2019 Chris Ferdinandi * MIT License * http://github.com/cferdinandi/gumshoe */ (function (root, factory) { if ( typeof define === 'function' && define.amd ) { define([], (function () { return factory(root); })); } else if ( typeof exports === 'object' ) { module.exports = factory(root); } else { root.Gumshoe = factory(root); } })(typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this, (function (window) { 'use strict'; // // Defaults // var defaults = { // Active classes navClass: 'active', contentClass: 'active', // Nested navigation nested: false, nestedClass: 'active', // Offset & reflow offset: 0, reflow: false, // Event support events: true }; // // Methods // /** * Merge two or more objects together. * @param {Object} objects The objects to merge together * @returns {Object} Merged values of defaults and options */ var extend = function () { var merged = {}; Array.prototype.forEach.call(arguments, (function (obj) { for (var key in obj) { if (!obj.hasOwnProperty(key)) return; merged[key] = obj[key]; } })); return merged; }; /** * Emit a custom event * @param {String} type The event type * @param {Node} elem The element to attach the event to * @param {Object} detail Any details to pass along with the event */ var emitEvent = function (type, elem, detail) { // Make sure events are enabled if (!detail.settings.events) return; // Create a new event var event = new CustomEvent(type, { bubbles: true, cancelable: true, detail: detail }); // Dispatch the event elem.dispatchEvent(event); }; /** * Get an element's distance from the top of the Document. * @param {Node} elem The element * @return {Number} Distance from the top in pixels */ var getOffsetTop = function (elem) { var location = 0; if (elem.offsetParent) { while (elem) { location += elem.offsetTop; elem = elem.offsetParent; } } return location >= 0 ? location : 0; }; /** * Sort content from first to last in the DOM * @param {Array} contents The content areas */ var sortContents = function (contents) { contents.sort((function (item1, item2) { var offset1 = getOffsetTop(item1.content); var offset2 = getOffsetTop(item2.content); if (offset1 < offset2) return -1; return 1; })); }; /** * Get the offset to use for calculating position * @param {Object} settings The settings for this instantiation * @return {Float} The number of pixels to offset the calculations */ var getOffset = function (settings) { // if the offset is a function run it if (typeof settings.offset === 'function') { return parseFloat(settings.offset()); } // Otherwise, return it as-is return parseFloat(settings.offset); }; /** * Determine if an element is in the viewport * @param {Node} elem The element * @param {Object} settings The settings for this instantiation * @return {Boolean} Returns true if element is in the viewport */ var isInViewport = function (elem, settings) { var bounds = elem.getBoundingClientRect(); var offset = getOffset(settings); return parseInt(bounds.top, 10) <= offset && parseInt(bounds.bottom, 10) > offset; }; /** * Get the active content * @param {Array} contents The content areas * @param {Object} settings The settings for this instantiation * @return {Object} The content area and matching navigation link */ var getActive = function (contents, settings) { for (var i = contents.length - 1; i >= 0; i--) { if (isInViewport(contents[i].content, settings)) return contents[i]; } }; /** * Deactivate parent navs in a nested navigation * @param {Node} nav The starting navigation element * @param {Object} settings The settings for this instantiation */ var deactivateNested = function (nav, settings) { // If nesting isn't activated, bail if (!settings.nested) return; // Get the parent navigation var li = nav.parentNode.closest('li'); if (!li) return; // Remove the active class li.classList.remove(settings.nestedClass); // Apply recursively to any parent navigation elements deactivateNested(li, settings); }; /** * Deactivate a nav and content area * @param {Object} items The nav item and content to deactivate * @param {Object} settings The settings for this instantiation */ var deactivate = function (items, settings) { // Make sure their are items to deactivate if (!items) return; // Get the parent list item var li = items.nav.closest('li'); if (!li) return; // Remove the active class from the nav and content li.classList.remove(settings.navClass); items.content.classList.remove(settings.contentClass); // Deactivate any parent navs in a nested navigation deactivateNested(li, settings); // Emit a custom event emitEvent('gumshoeDeactivate', li, { link: items.nav, content: items.content, settings: settings }); }; /** * Activate parent navs in a nested navigation * @param {Node} nav The starting navigation element * @param {Object} settings The settings for this instantiation */ var activateNested = function (nav, settings) { // If nesting isn't activated, bail if (!settings.nested) return; // Get the parent navigation var li = nav.parentNode.closest('li'); if (!li) return; // Add the active class li.classList.add(settings.nestedClass); // Apply recursively to any parent navigation elements activateNested(li, settings); }; /** * Activate a nav and content area * @param {Object} items The nav item and content to activate * @param {Object} settings The settings for this instantiation */ var activate = function (items, settings) { // Make sure their are items to activate if (!items) return; // Get the parent list item var li = items.nav.closest('li'); if (!li) return; // Add the active class to the nav and content li.classList.add(settings.navClass); items.content.classList.add(settings.contentClass); // Activate any parent navs in a nested navigation activateNested(li, settings); // Emit a custom event emitEvent('gumshoeActivate', li, { link: items.nav, content: items.content, settings: settings }); }; /** * Create the Constructor object * @param {String} selector The selector to use for navigation items * @param {Object} options User options and settings */ var Constructor = function (selector, options) { // // Variables // var publicAPIs = {}; var navItems, contents, current, timeout, settings; // // Methods // /** * Set variables from DOM elements */ publicAPIs.setup = function () { // Get all nav items navItems = document.querySelectorAll(selector); // Create contents array contents = []; // Loop through each item, get it's matching content, and push to the array Array.prototype.forEach.call(navItems, (function (item) { // Get the content for the nav item var content = document.getElementById(decodeURIComponent(item.hash.substr(1))); if (!content) return; // Push to the contents array contents.push({ nav: item, content: content }); })); // Sort contents by the order they appear in the DOM sortContents(contents); }; /** * Detect which content is currently active */ publicAPIs.detect = function () { // Get the active content var active = getActive(contents, settings); // if there's no active content, deactivate and bail if (!active) { if (current) { deactivate(current, settings); current = null; } return; } // If the active content is the one currently active, do nothing if (current && active.content === current.content) return; // Deactivate the current content and activate the new content deactivate(current, settings); activate(active, settings); // Update the currently active content current = active; }; /** * Detect the active content on scroll * Debounced for performance */ var scrollHandler = function (event) { // If there's a timer, cancel it if (timeout) { window.cancelAnimationFrame(timeout); } // Setup debounce callback timeout = window.requestAnimationFrame(publicAPIs.detect); }; /** * Update content sorting on resize * Debounced for performance */ var resizeHandler = function (event) { // If there's a timer, cancel it if (timeout) { window.cancelAnimationFrame(timeout); } // Setup debounce callback timeout = window.requestAnimationFrame((function () { sortContents(); publicAPIs.detect(); })); }; /** * Destroy the current instantiation */ publicAPIs.destroy = function () { // Undo DOM changes if (current) { deactivate(current); } // Remove event listeners window.removeEventListener('scroll', scrollHandler, false); if (settings.reflow) { window.removeEventListener('resize', resizeHandler, false); } // Reset variables contents = null; navItems = null; current = null; timeout = null; settings = null; }; /** * Initialize the current instantiation * @param {Object} options User options and settings */ publicAPIs.init = function (options) { // Merge user options into defaults settings = extend(defaults, options || {}); // Setup variables based on the current DOM publicAPIs.setup(); // Find the currently active content publicAPIs.detect(); // Setup event listeners window.addEventListener('scroll', scrollHandler, false); if (settings.reflow) { window.addEventListener('resize', resizeHandler, false); } }; // // Initialize and return the public APIs // publicAPIs.init(options); return publicAPIs; }; // // Return the Constructor // return Constructor; }));
jolantis/altair
assets/javascript/lib/plugins/gumshoe/gumshoe.js
JavaScript
mit
10,130
var Mocks = require("mocks"); var AssistantToTheTransportManager = require('core/transports/assistant_to_the_transport_manager').default; var Util = require('core/util').default; describe("AssistantToTheTransportManager", function() { var transport, transportClass; var manager; beforeEach(function() { jasmine.Clock.useMock(); spyOn(Util, "now").andReturn(1); transport = Mocks.getTransport(true); transportManager = Mocks.getTransportManager(); transportClass = Mocks.getTransportClass(true, transport); assistant = new AssistantToTheTransportManager( transportManager, transportClass, { minPingDelay: 10000, maxPingDelay: 120000 } ); }); describe("#isSupported", function() { it("should return true when transport is supported", function() { var assistant = new AssistantToTheTransportManager( transportManager, Mocks.getTransportClass(true), { minPingDelay: 10000, maxPingDelay: 50000 } ); expect(assistant.isSupported()).toBe(true); }); it("should return false when transport is not supported", function() { var assistant = new AssistantToTheTransportManager( transportManager, Mocks.getTransportClass(false), { minPingDelay: 10000, maxPingDelay: 50000 } ); expect(assistant.isSupported()).toBe(false); }); it("should return true if transport is alive", function() { transportManager.isAlive.andReturn(true); expect(assistant.isSupported()).toBe(true); }); it("should return false if transport is not alive", function() { transportManager.isAlive.andReturn(false); expect(assistant.isSupported()).toBe(false); }); }); describe("#createConnection", function() { it("should pass parameters to the transport", function() { assistant.createConnection("foo", 66, "abc", { test: true }); expect(transportClass.createConnection) .toHaveBeenCalledWith("foo", 66, "abc", { test: true }); }); it("should return the transport instance", function() { var connection = assistant.createConnection("x", 1, "a", {}); expect(connection).toBe(transport); }); }); describe("after an opened connection closed with a protocol error (code 1002)", function() { var connection; beforeEach(function() { connection = assistant.createConnection("x", 1, "a", {}); Util.now.andReturn(1); connection.emit("open"); Util.now.andReturn(100001); connection.emit("closed", { wasClean: true, code: 1002 }); }); it("should report its death to the manager", function() { expect(transportManager.reportDeath).toHaveBeenCalled(); }); }); describe("after an opened connection closed with a unsupported error (code 1003)", function() { var connection; beforeEach(function() { connection = assistant.createConnection("x", 1, "a", {}); Util.now.andReturn(1); connection.emit("open"); Util.now.andReturn(100001); connection.emit("closed", { wasClean: true, code: 1003 }); }); it("should report its death to the manager", function() { expect(transportManager.reportDeath).toHaveBeenCalled(); }); }); describe("after an opened connection died after less than 2*maxPingDelay", function() { var connection; var assistant; beforeEach(function() { assistant = new AssistantToTheTransportManager( transportManager, transportClass, { minPingDelay: 10000, maxPingDelay: 100000 } ); connection = assistant.createConnection("x", 1, "a", {}); Util.now.andReturn(1); connection.emit("open"); Util.now.andReturn(190001); connection.emit("closed", { wasClean: false }); }); it("should report its death once to the manager", function() { expect(transportManager.reportDeath.calls.length).toEqual(1); }); it("should set the activity timeout on the next connection to lifetime/2 ms", function() { var connection = assistant.createConnection("x", 1, "a", {}); expect(transportClass.createConnection).toHaveBeenCalledWith( "x", 1, "a", { activityTimeout: 95000 } ); }); }); describe("after an opened connection died after more than 2*maxPingDelay", function() { var connection; var assistant; beforeEach(function() { assistant = new AssistantToTheTransportManager( transportManager, transportClass, { minPingDelay: 10000, maxPingDelay: 50000 } ); connection = assistant.createConnection("x", 1, "a", {}); Util.now.andReturn(1); connection.emit("open"); Util.now.andReturn(100002); connection.emit("closed", { wasClean: false }); }); it("should not report its death to the manager", function() { expect(transportManager.reportDeath).not.toHaveBeenCalled(); }); it("should not set the activity timeout on the next connection", function() { var connection = assistant.createConnection("x", 1, "a", {}); expect(transportClass.createConnection).toHaveBeenCalledWith( "x", 1, "a", {} ); }); }); describe("after an opened connection died after less than 2*minPingDelay", function() { var connection; var assistant; beforeEach(function() { assistant = new AssistantToTheTransportManager( transportManager, transportClass, { minPingDelay: 20000, maxPingDelay: 100000 } ); connection = assistant.createConnection("x", 1, "a", {}); Util.now.andReturn(1); connection.emit("open"); Util.now.andReturn(32001); connection.emit("closed", { wasClean: false }); }); it("should report its death once to the manager", function() { expect(transportManager.reportDeath.calls.length).toEqual(1); }); it("should set the activity timeout on the next connection to minPingDelay ms", function() { var connection = assistant.createConnection("x", 1, "a", {}); expect(transportClass.createConnection).toHaveBeenCalledWith( "x", 1, "a", { activityTimeout: 20000 } ); }); }); describe("after an opened connection closed cleanly", function() { var connection; beforeEach(function() { connection = assistant.createConnection("x", 1, "a", {}); Util.now.andReturn(1); connection.emit("open"); Util.now.andReturn(100001); connection.emit("closed", { wasClean: true }); }); it("should not report its death to the manager", function() { expect(transportManager.reportDeath).not.toHaveBeenCalled(); }); it("should not set the activity timeout on the next connection", function() { var connection = assistant.createConnection("x", 1, "a", {}); expect(transportClass.createConnection).toHaveBeenCalledWith( "x", 1, "a", {} ); }); }); });
pmaxit/DJANGO_IOT
node_modules/pusher-js/spec/javascripts/unit/core/transports/assistant_to_the_transport_manager_spec.js
JavaScript
mit
6,935
const React = require('react') module.exports = () => <div>test2</div>
flybayer/next.js
test/integration/auto-export/pages/commonjs2.js
JavaScript
mit
72
/*! * Waves v0.5.3 * http://fian.my.id/Waves * * Copyright 2014 Alfiana E. Sibuea and other contributors * Released under the MIT license * https://github.com/fians/Waves/blob/master/LICENSE */ ;(function(window) { 'use strict'; var Waves = Waves || {}; var $$ = document.querySelectorAll.bind(document); // Find exact position of element function isWindow(obj) { return obj !== null && obj === obj.window; } function getWindow(elem) { return isWindow(elem) ? elem : elem.nodeType === 9 && elem.defaultView; } function offset(elem) { var docElem, win, box = {top: 0, left: 0}, doc = elem && elem.ownerDocument; docElem = doc.documentElement; if (typeof elem.getBoundingClientRect !== typeof undefined) { box = elem.getBoundingClientRect(); } win = getWindow(doc); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; } function convertStyle(obj) { var style = ''; for (var a in obj) { if (obj.hasOwnProperty(a)) { style += (a + ':' + obj[a] + ';'); } } return style; } var Effect = { // Effect delay duration: 500, show: function(e) { // Disable right click if (e.button === 2) { return false; } var el = this; // Create ripple var ripple = document.createElement('div'); ripple.className = 'waves-ripple'; el.appendChild(ripple); // Get click coordinate and element witdh var pos = offset(el); var relativeY = (e.pageY - pos.top) - 10; var relativeX = (e.pageX - pos.left) - 10; // var scale = 'scale('+((el.clientWidth / 100) * 2.5)+')'; var scale = 'scale(15)'; // Support for touch devices if ('touches' in e) { relativeY = (e.touches[0].pageY - pos.top) - 45; relativeX = (e.touches[0].pageX - pos.left) - 45; } // Attach data to element ripple.setAttribute('data-hold', Date.now()); ripple.setAttribute('data-scale', scale); ripple.setAttribute('data-x', relativeX); ripple.setAttribute('data-y', relativeY); // Set ripple position var rippleStyle = { 'top': relativeY+'px', 'left': relativeX+'px' }; ripple.className = ripple.className + ' waves-notransition'; ripple.setAttribute('style', convertStyle(rippleStyle)); ripple.className = ripple.className.replace('waves-notransition', ''); // Scale the ripple rippleStyle['-webkit-transform'] = scale; rippleStyle['-moz-transform'] = scale; rippleStyle['-ms-transform'] = scale; rippleStyle['-o-transform'] = scale; rippleStyle.transform = scale; rippleStyle.opacity = '1'; rippleStyle['-webkit-transition-duration'] = Effect.duration + 'ms'; rippleStyle['-moz-transition-duration'] = Effect.duration + 'ms'; rippleStyle['-o-transition-duration'] = Effect.duration + 'ms'; rippleStyle['transition-duration'] = Effect.duration + 'ms'; ripple.setAttribute('style', convertStyle(rippleStyle)); }, hide: function() { var el = this; var width = el.clientWidth * 1.4; // Get first ripple var ripple = null; var childrenLength = el.children.length; for (var a = 0; a < childrenLength; a++) { if (el.children[a].className.indexOf('waves-ripple') !== -1) { ripple = el.children[a]; continue; } } if (!ripple) { return false; } var relativeX = ripple.getAttribute('data-x'); var relativeY = ripple.getAttribute('data-y'); var scale = ripple.getAttribute('data-scale'); // Get delay beetween mousedown and mouse leave var diff = Date.now() - Number(ripple.getAttribute('data-hold')); var delay = 500 - diff; if (delay < 0) { delay = 0; } // Fade out ripple after delay setTimeout(function() { var style = { 'top': relativeY+'px', 'left': relativeX+'px', 'opacity': '0', // Duration '-webkit-transition-duration': Effect.duration + 'ms', '-moz-transition-duration': Effect.duration + 'ms', '-o-transition-duration': Effect.duration + 'ms', 'transition-duration': Effect.duration + 'ms', '-webkit-transform': scale, '-moz-transform': scale, '-ms-transform': scale, '-o-transform': scale, 'transform': scale, }; ripple.setAttribute('style', convertStyle(style)); setTimeout(function() { try { el.removeChild(ripple); } catch(e) { return false; } }, Effect.duration); }, delay); }, // Little hack to make <input> can perform waves effect wrapInput: function(elements) { for (var a = 0; a < elements.length; a++) { var el = elements[a]; if (el.tagName.toLowerCase() === 'input') { var parent = el.parentNode; // If input already have parent just pass through if (parent.tagName.toLowerCase() === 'i' && parent.className.indexOf('waves-effect') !== -1) { return false; } // Put element class and style to the specified parent var wrapper = document.createElement('i'); wrapper.className = el.className + ' waves-input-wrapper'; var elementStyle = el.getAttribute('style'); var dimensionStyle = 'width:'+el.offsetWidth+'px;height:'+el.clientHeight+'px;'; if (!elementStyle) { elementStyle = ''; } wrapper.setAttribute('style', dimensionStyle+elementStyle); el.className = 'waves-button-input'; el.removeAttribute('style'); // Put element as child parent.replaceChild(wrapper, el); wrapper.appendChild(el); } } } }; Waves.displayEffect = function(options) { options = options || {}; if ('duration' in options) { Effect.duration = options.duration; } //Wrap input inside <i> tag Effect.wrapInput($$('.waves-effect')); Array.prototype.forEach.call($$('.waves-effect'), function(i) { if ('ontouchstart' in window) { i.addEventListener('mouseup', Effect.hide, false); i.addEventListener('touchstart', Effect.show, false); i.addEventListener('mouseleave', Effect.hide, false); i.addEventListener('touchend', Effect.hide, false); i.addEventListener('touchcancel', Effect.hide, false); } else { i.addEventListener('mousedown', Effect.show, false); i.addEventListener('mouseup', Effect.hide, false); i.addEventListener('mouseleave', Effect.hide, false); } }); }; window.Waves = Waves; Waves.displayEffect(); })(window);
keithklingen/materialize
js/waves.js
JavaScript
mit
8,319
/* * Copyright (c) 2013 - present Adobe Systems Incorporated. All rights reserved. * * 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. * */ /*jslint vars: true, plusplus: true, nomen: true, regexp: true, maxerr: 50 */ /*global define, brackets, $, window */ define(function (require, exports, module) { "use strict"; var KeyEvent = brackets.getModule("utils/KeyEvent"), Strings = brackets.getModule("strings"), Mustache = brackets.getModule("thirdparty/mustache/mustache"); var TimingFunctionUtils = require("TimingFunctionUtils"); /** Mustache template that forms the bare DOM structure of the UI */ var BezierCurveEditorTemplate = require("text!BezierCurveEditorTemplate.html"); /** @const @type {number} */ var HEIGHT_ABOVE = 75, // extra height above main grid HEIGHT_BELOW = 75, // extra height below main grid HEIGHT_MAIN = 150, // height of main grid WIDTH_MAIN = 150; // width of main grid var animationRequest = null; /** * CubicBezier object constructor * * @param {string|Array.number[4]} coordinates Four parameters passes to cubic-bezier() * either in string or array format. */ function CubicBezier(coordinates) { if (typeof coordinates === "string") { this.coordinates = coordinates.split(","); } else { this.coordinates = coordinates; } if (!this.coordinates) { throw "No offsets were defined"; } this.coordinates = this.coordinates.map(function (n) { return +n; }); var i; for (i = 3; i >= 0; i--) { var xy = this.coordinates[i]; if (isNaN(xy) || (((i % 2) === 0) && (xy < 0 || xy > 1))) { throw "Wrong coordinate at " + i + "(" + xy + ")"; } } } /** * BezierCanvas object constructor * * @param {Element} canvas Inline editor <canvas> element * @param {CubicBezier} bezier Associated CubicBezier object * @param {number|Array.number} padding Element padding */ function BezierCanvas(canvas, bezier, padding) { this.canvas = canvas; this.bezier = bezier; this.padding = this.getPadding(padding); // Convert to a cartesian coordinate system with axes from 0 to 1 var ctx = this.canvas.getContext("2d"), p = this.padding; ctx.scale(canvas.width * (1 - p[1] - p[3]), -canvas.height * 0.5 * (1 - p[0] - p[2])); ctx.translate(p[3] / (1 - p[1] - p[3]), (-1 - p[0] / (1 - p[0] - p[2])) - 0.5); } BezierCanvas.prototype = { /** * Calculates CSS offsets for <canvas> element * * @return {left:string, top:string} */ getOffsets: function () { var p = this.padding, w = this.canvas.width, h = this.canvas.height * 0.5; return [{ left: w * (this.bezier.coordinates[0] * (1 - p[3] - p[1]) - p[3]) + "px", top: h * (1 - this.bezier.coordinates[1] * (1 - p[0] - p[2]) - p[0]) + "px" }, { left: w * (this.bezier.coordinates[2] * (1 - p[3] - p[1]) - p[3]) + "px", top: h * (1 - this.bezier.coordinates[3] * (1 - p[0] - p[2]) - p[0]) + "px" }]; }, /** * Round off number to hundreths place, convert to string, and strip leading zero * * @param {number} v Value * @return {string} */ prettify: function (v) { return (Math.round(v * 100) / 100).toString().replace(/^0\./, "."); }, /** * Get CSS left, top offsets for endpoint handle * * @param {Element} element Endpoint handle <button> element * @return {Array.string[2]} */ offsetsToCoordinates: function (element) { var p = this.padding, w = this.canvas.width, h = this.canvas.height * 0.5; // Convert padding percentage to actual padding p = p.map(function (a, i) { return a * ((i % 2) ? w : h); }); return [ this.prettify((parseInt($(element).css("left"), 10) - p[3]) / (w + p[1] + p[3])), this.prettify((h - parseInt($(element).css("top"), 10) - p[2]) / (h - p[0] - p[2])) ]; }, /** * Paint canvas * * @param {Object} settings Paint settings */ plot: function (settings) { var xy = this.bezier.coordinates, ctx = this.canvas.getContext("2d"), setting; var defaultSettings = { handleTimingFunction: "#2893ef", handleThickness: 0.008, vBorderThickness: 0.02, hBorderThickness: 0.01, bezierTimingFunction: "#2893ef", bezierThickness: 0.03 }; settings = settings || {}; for (setting in defaultSettings) { if (defaultSettings.hasOwnProperty(setting)) { if (!settings.hasOwnProperty(setting)) { settings[setting] = defaultSettings[setting]; } } } ctx.clearRect(-0.5, -0.5, 2, 2); // Draw control handles ctx.beginPath(); ctx.fillStyle = settings.handleTimingFunction; ctx.lineWidth = settings.handleThickness; ctx.strokeStyle = settings.handleTimingFunction; ctx.moveTo(0, 0); ctx.lineTo(xy[0], xy[1]); ctx.moveTo(1, 1); ctx.lineTo(xy[2], xy[3]); ctx.stroke(); ctx.closePath(); ctx.beginPath(); ctx.arc(xy[0], xy[1], 1.5 * settings.handleThickness, 0, 2 * Math.PI, false); ctx.closePath(); ctx.fill(); ctx.beginPath(); ctx.arc(xy[2], xy[3], 1.5 * settings.handleThickness, 0, 2 * Math.PI, false); ctx.closePath(); ctx.fill(); // Draw bezier curve ctx.beginPath(); ctx.lineWidth = settings.bezierThickness; ctx.strokeStyle = settings.bezierColor; ctx.moveTo(0, 0); ctx.bezierCurveTo(xy[0], xy[1], xy[2], xy[3], 1, 1); ctx.stroke(); ctx.closePath(); }, /** * Convert CSS padding shorthand to longhand * * @param {number|Array.number} padding Element padding * @return {Array.number} */ getPadding: function (padding) { var p = (typeof padding === "number") ? [padding] : padding; if (p.length === 1) { p[1] = p[0]; } if (p.length === 2) { p[2] = p[0]; } if (p.length === 3) { p[3] = p[1]; } return p; } }; // Event handlers /** * Handle click in <canvas> element * * @param {Event} e Mouse click event */ function _curveClick(e) { var self = e.target, bezierEditor = self.bezierEditor; var curveBoundingBox = bezierEditor._getCurveBoundingBox(), left = curveBoundingBox.left, top = curveBoundingBox.top, x = e.pageX - left, y = e.pageY - top - HEIGHT_ABOVE, $P1 = $(bezierEditor.P1), $P2 = $(bezierEditor.P2); // Helper function to calculate distance between 2-D points function distance(x1, y1, x2, y2) { return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); } // Find which point is closer var distP1 = distance(x, y, parseInt($P1.css("left"), 10), parseInt($P1.css("top"), 10)), distP2 = distance(x, y, parseInt($P2.css("left"), 10), parseInt($P2.css("top"), 10)), $P = (distP1 < distP2) ? $P1 : $P2; $P.css({ left: x + "px", top: y + "px" }); $P.get(0).focus(); // update coords bezierEditor._cubicBezierCoords = bezierEditor.bezierCanvas .offsetsToCoordinates(bezierEditor.P1) .concat(bezierEditor.bezierCanvas.offsetsToCoordinates(bezierEditor.P2)); bezierEditor._commitTimingFunction(); bezierEditor._updateCanvas(); } /** * Helper function for handling point move * * @param {Event} e Mouse move event * @param {number} x New horizontal position * @param {number} y New vertical position */ function handlePointMove(e, x, y) { var self = e.target, bezierEditor = self.bezierEditor; // Helper function to redraw curve function mouseMoveRedraw() { if (!bezierEditor.dragElement) { animationRequest = null; return; } // Update code bezierEditor._commitTimingFunction(); bezierEditor._updateCanvas(); animationRequest = window.requestAnimationFrame(mouseMoveRedraw); } // This is a dragging state, but left button is no longer down, so mouse // exited element, was released, and re-entered element. Treat like a drop. if (bezierEditor.dragElement && (e.which !== 1)) { bezierEditor.dragElement = null; bezierEditor._commitTimingFunction(); bezierEditor._updateCanvas(); bezierEditor = null; return; } // Constrain time (x-axis) to 0 to 1 range. Progression (y-axis) is // theoretically not constrained, although canvas to drawing curve is // arbitrarily constrained to -0.5 to 1.5 range. x = Math.min(Math.max(0, x), WIDTH_MAIN); if (bezierEditor.dragElement) { $(bezierEditor.dragElement).css({ left: x + "px", top: y + "px" }); } // update coords bezierEditor._cubicBezierCoords = bezierEditor.bezierCanvas .offsetsToCoordinates(bezierEditor.P1) .concat(bezierEditor.bezierCanvas.offsetsToCoordinates(bezierEditor.P2)); if (!animationRequest) { animationRequest = window.requestAnimationFrame(mouseMoveRedraw); } } /** * Update Time (x-axis) and Progression (y-axis) data for mouse position * * @param {Element} canvas <canvas> element * @param {number} x Horizontal position * @param {number} y Vertical position */ function updateTimeProgression(curve, x, y) { var percentX = Math.round(100 * x / WIDTH_MAIN), percentY = Math.round(100 * ((HEIGHT_MAIN - y) / HEIGHT_MAIN)); // Constrain horizontal percentage to [0, 100] range percentX = Math.min(Math.max(0, percentX), 100); curve.parentNode.setAttribute("data-time", percentX); curve.parentNode.setAttribute("data-progression", percentY); } /** * Handle mouse move in <canvas> element * * @param {Event} e Mouse move event */ function _curveMouseMove(e) { var self = e.target, bezierEditor = self.bezierEditor, curveBoundingBox = bezierEditor._getCurveBoundingBox(), left = curveBoundingBox.left, top = curveBoundingBox.top, x = e.pageX - left, y = e.pageY - top - HEIGHT_ABOVE; updateTimeProgression(self, x, y); if (bezierEditor.dragElement) { if (e.pageX === 0 && e.pageY === 0) { return; } handlePointMove(e, x, y); } } /** * Handle mouse move in <button> element * * @param {Event} e Mouse move event */ function _pointMouseMove(e) { var self = e.target, bezierEditor = self.bezierEditor, curveBoundingBox = bezierEditor._getCurveBoundingBox(), left = curveBoundingBox.left, top = curveBoundingBox.top, x = e.pageX - left, y = e.pageY - top - HEIGHT_ABOVE; updateTimeProgression(bezierEditor.curve, x, y); if (e.pageX === 0 && e.pageY === 0) { return; } handlePointMove(e, x, y); } /** * Handle mouse down in <button> element * * @param {Event} e Mouse down event */ function _pointMouseDown(e) { var self = e.target; self.bezierEditor.dragElement = self; } /** * Handle mouse up in <button> element * * @param {Event} e Mouse up event */ function _pointMouseUp(e) { var self = e.target; self.focus(); if (self.bezierEditor.dragElement) { self.bezierEditor.dragElement = null; self.bezierEditor._commitTimingFunction(); self.bezierEditor._updateCanvas(); } } /** * Handle key down in <button> element * * @param {Event} e Key down event */ function _pointKeyDown(e) { var code = e.keyCode, self = e.target, bezierEditor = self.bezierEditor; if (code >= KeyEvent.DOM_VK_LEFT && code <= KeyEvent.DOM_VK_DOWN) { e.preventDefault(); // Arrow keys pressed var $this = $(e.target), left = parseInt($this.css("left"), 10), top = parseInt($this.css("top"), 10), offset = (e.shiftKey ? 15 : 3), newVal; switch (code) { case KeyEvent.DOM_VK_LEFT: newVal = Math.max(0, left - offset); if (left === newVal) { return false; } $this.css({ left: newVal + "px" }); break; case KeyEvent.DOM_VK_UP: newVal = Math.max(-HEIGHT_ABOVE, top - offset); if (top === newVal) { return false; } $this.css({ top: newVal + "px" }); break; case KeyEvent.DOM_VK_RIGHT: newVal = Math.min(WIDTH_MAIN, left + offset); if (left === newVal) { return false; } $this.css({ left: newVal + "px" }); break; case KeyEvent.DOM_VK_DOWN: newVal = Math.min(HEIGHT_MAIN + HEIGHT_BELOW, top + offset); if (top === newVal) { return false; } $this.css({ top: newVal + "px" }); break; } // update coords bezierEditor._cubicBezierCoords = bezierEditor.bezierCanvas .offsetsToCoordinates(bezierEditor.P1) .concat(bezierEditor.bezierCanvas.offsetsToCoordinates(bezierEditor.P2)); bezierEditor._commitTimingFunction(); bezierEditor._updateCanvas(); return true; } else if (code === KeyEvent.DOM_VK_ESCAPE) { return true; } else if (code === KeyEvent.DOM_VK_TAB && !e.ctrlKey && !e.metaKey && !e.altKey) { // Switch between the two points by tabbing if ($(e.target).hasClass("P1")) { $(".P2").focus(); } else { $(".P1").focus(); } e.preventDefault(); return true; } return false; } /** * Constructor for BezierCurveEditor Object. This control may be used standalone * or within an InlineTimingFunctionEditor inline widget. * * @param {!jQuery} $parent DOM node into which to append the root of the bezier curve editor UI * @param {!RegExpMatch} bezierCurve RegExp match object of initially selected bezierCurve * @param {!function(string)} callback Called whenever selected bezierCurve changes */ function BezierCurveEditor($parent, bezierCurve, callback) { // Create the DOM structure, filling in localized strings via Mustache this.$element = $(Mustache.render(BezierCurveEditorTemplate, Strings)); $parent.append(this.$element); this._callback = callback; this.dragElement = null; // current cubic-bezier() function params this._cubicBezierCoords = this._getCubicBezierCoords(bezierCurve); this.hint = {}; this.hint.elem = $(".hint", this.$element); // If function was auto-corrected, then originalString holds the original function, // and an informational message needs to be shown if (bezierCurve.originalString) { TimingFunctionUtils.showHideHint(this.hint, true, bezierCurve.originalString, "cubic-bezier(" + this._cubicBezierCoords.join(", ") + ")"); } else { TimingFunctionUtils.showHideHint(this.hint, false); } this.P1 = this.$element.find(".P1")[0]; this.P2 = this.$element.find(".P2")[0]; this.curve = this.$element.find(".curve")[0]; this.P1.bezierEditor = this.P2.bezierEditor = this.curve.bezierEditor = this; this.bezierCanvas = new BezierCanvas(this.curve, null, [0, 0]); // redraw canvas this._updateCanvas(); $(this.curve) .on("click", _curveClick) .on("mousemove", _curveMouseMove); $(this.P1) .on("mousemove", _pointMouseMove) .on("mousedown", _pointMouseDown) .on("mouseup", _pointMouseUp) .on("keydown", _pointKeyDown); $(this.P2) .on("mousemove", _pointMouseMove) .on("mousedown", _pointMouseDown) .on("mouseup", _pointMouseUp) .on("keydown", _pointKeyDown); } /** * Destructor called by InlineTimingFunctionEditor.onClosed() */ BezierCurveEditor.prototype.destroy = function () { this.P1.bezierEditor = this.P2.bezierEditor = this.curve.bezierEditor = null; $(this.curve) .off("click", _curveClick) .off("mousemove", _curveMouseMove); $(this.P1) .off("mousemove", _pointMouseMove) .off("mousedown", _pointMouseDown) .off("mouseup", _pointMouseUp) .off("keydown", _pointKeyDown); $(this.P2) .off("mousemove", _pointMouseMove) .off("mousedown", _pointMouseDown) .off("mouseup", _pointMouseUp) .off("keydown", _pointKeyDown); }; /** Returns the root DOM node of the BezierCurveEditor UI */ BezierCurveEditor.prototype.getRootElement = function () { return this.$element; }; /** * Default focus needs to go somewhere, so give it to P1 */ BezierCurveEditor.prototype.focus = function () { this.P1.focus(); return true; }; /** * Generates cubic-bezier function based on coords, and updates the doc */ BezierCurveEditor.prototype._commitTimingFunction = function () { var bezierCurveVal = "cubic-bezier(" + this._cubicBezierCoords[0] + ", " + this._cubicBezierCoords[1] + ", " + this._cubicBezierCoords[2] + ", " + this._cubicBezierCoords[3] + ")"; this._callback(bezierCurveVal); TimingFunctionUtils.showHideHint(this.hint, false); }; /** * Handle all matches returned from TimingFunctionUtils.cubicBezierMatch() and * return array of coords * * @param {RegExp.match} match Matches returned from cubicBezierMatch() * @return {Array.number[4]} */ BezierCurveEditor.prototype._getCubicBezierCoords = function (match) { if (match[0].match(/^cubic-bezier/)) { // cubic-bezier() return match.slice(1, 5); } else { // handle special cases of cubic-bezier calls switch (match[0]) { case "linear": return [ "0", "0", "1", "1" ]; case "ease": return [ ".25", ".1", ".25", "1" ]; case "ease-in": return [ ".42", "0", "1", "1" ]; case "ease-out": return [ "0", "0", ".58", "1" ]; case "ease-in-out": return [ ".42", "0", ".58", "1" ]; } } window.console.log("brackets-cubic-bezier: getCubicBezierCoords() passed invalid RegExp match array"); return [ "0", "0", "0", "0" ]; }; /** * Get <canvas> element's bounding box * * @return {left: number, top: number, width: number, height: number} */ BezierCurveEditor.prototype._getCurveBoundingBox = function () { var $canvas = this.$element.find(".curve"), canvasOffset = $canvas.offset(); return { left: canvasOffset.left, top: canvasOffset.top, width: $canvas.width(), height: $canvas.height() }; }; /** * Update <canvas> after a change */ BezierCurveEditor.prototype._updateCanvas = function () { // collect data, build model if (this._cubicBezierCoords) { this.bezierCanvas.bezier = window.bezier = new CubicBezier(this._cubicBezierCoords); var offsets = this.bezierCanvas.getOffsets(); $(this.P1).css({ left: offsets[0].left, top: offsets[0].top }); $(this.P2).css({ left: offsets[1].left, top: offsets[1].top }); this.bezierCanvas.plot(); } }; /** * Handle external update * * @param {!RegExpMatch} bezierCurve RegExp match object of updated bezierCurve */ BezierCurveEditor.prototype.handleExternalUpdate = function (bezierCurve) { this._cubicBezierCoords = this._getCubicBezierCoords(bezierCurve); this._updateCanvas(); // If function was auto-corrected, then originalString holds the original function, // and an informational message needs to be shown if (bezierCurve.originalString) { TimingFunctionUtils.showHideHint(this.hint, true, bezierCurve.originalString, "cubic-bezier(" + this._cubicBezierCoords.join(", ") + ")"); } else { TimingFunctionUtils.showHideHint(this.hint, false); } }; exports.BezierCurveEditor = BezierCurveEditor; });
kolipka/brackets
src/extensions/default/InlineTimingFunctionEditor/BezierCurveEditor.js
JavaScript
mit
23,765
uv.LineGraph = function (graphdef, config) { var self = this; uv.Graph.call(self, graphdef, config).setDefaults().init(); self.linegroups = {}; self.dataset = uv.util.getDataArray(self.graphdef); var linegroup, linepath, linefunc, idx, len = self.categories.length, domainData = self.labels; self.axes[self.config.graph.orientation === 'Horizontal' ? 'ver' : 'hor'].scale.domain(domainData); for (idx = 0; idx < len; idx = idx + 1) { linepath = self.chart.append('g').classed('cg-' + uv.util.formatClassName(self.categories[idx]), true) .append('g').classed('cge-' + uv.util.formatClassName(self.categories[idx]), true).datum(self.dataset[idx]); linegroup = { path: linepath, func: undefined }; self['draw' + self.config.graph.orientation + 'Lines'](linegroup, idx); self.linegroups[self.categories[idx]] = linegroup; } self.finalize(); }; uv.LineGraph.prototype = uv.util.inherits(uv.Graph); uv.LineGraph.prototype.setDefaults = function () { var self = this; self.graphdef.stepup = 'normal'; self.config.scale.ordinality = 0; return this; }; uv.LineGraph.prototype.drawHorizontalLines = function (linegroup, idx) { var self = this, axes = self.axes, config = self.config, color = uv.util.getColorBand(self.config, idx); self.axes.ver.scale.rangePoints([0, self.height()]); linegroup.func = d3.svg.line() .x(function (d) { return axes.hor.scale(d.value); }) .y(function (d) { return axes.ver.scale(d.name) + axes.ver.scale.rangeBand() / 2; }) .interpolate(uv.config.line.interpolation); linegroup.path.append('path') .classed('cr-' + uv.util.formatClassName(self.categories[idx]), true) .attr('d', linegroup.func) .style('fill', 'none') .style('stroke', color) .style('stroke-width', self.config.line.strokewidth) .style('stroke-opacity', self.config.line.strokeopacity) .transition() .duration(3 * self.config.effects.duration) .delay(2 * idx * self.config.effects.duration) .style('stroke-opacity', 1) .call(uv.util.endAll, function (d,i){ d3.select(this.parentNode.parentNode).selectAll('path').on('mouseover', uv.effects.line.mouseover(self, idx)); d3.select(this.parentNode.parentNode).selectAll('path').on('mouseout', uv.effects.line.mouseout(self, idx)); d3.select(this.parentNode.parentNode).selectAll('circle').on('mouseover', uv.effects.line.mouseover(self, idx)); d3.select(this.parentNode.parentNode).selectAll('circle').on('mouseout', uv.effects.line.mouseout(self, idx)); }); if (self.config.line.showcircles) { linegroup.path.selectAll('circle') .data(self.dataset[idx]) .enter().append('circle') .classed('cr-' + uv.util.formatClassName(self.categories[idx]), true) .attr('cx', linegroup.func.x()) .attr('cy', linegroup.func.y()) .attr('r', self.config.line.circleradius) .style('fill', color) .style('fill-opacity', self.config.line.circleopacity) .style('stroke', '#fff') .append('svg:title') .text( function (d, i) { return uv.util.getTooltipText(self, self.categories[idx], self.labels[i], d);}); } linegroup.path.selectAll('text') .data(self.dataset[idx]) .enter().append('text') .attr('x', function (d) { return axes.hor.scale(d.value); }) .attr('y', function(d) { return axes.ver.scale(d.name) + axes.ver.scale.rangeBand()/2; }) .attr('dx', 10) .attr('dy', '.35em') .attr('text-anchor', 'start') .style('opacity', 0) .classed('cr-' + uv.util.formatClassName(self.categories[idx]), true) .style('fill', self.config.label.showlabel ? uv.util.getColorBand(self.config, idx) : 'none') .style('font-family', self.config.line.fontfamily) .style('font-size', self.config.line.fontsize) .style('font-weight', self.config.line.fontweight) .text(function(d) { return uv.util.getLabelValue(self, d); }) .transition() .duration(3 * self.config.effects.duration) .delay(2 * idx * self.config.effects.duration) .style('opacity', 1); return this; }; uv.LineGraph.prototype.drawVerticalLines = function (linegroup, idx) { var self = this, axes = self.axes, config = self.config, color = uv.util.getColorBand(self.config, idx); self.axes.hor.scale.rangePoints([0, self.width()]); linegroup.func = d3.svg.line() .x(function (d) { return axes.hor.scale(d.name) + axes.hor.scale.rangeBand() / 2; }) .y(function (d) { return axes.ver.scale(d.value); }) .interpolate(uv.config.line.interpolation); linegroup.path.append('path') .attr('d', linegroup.func) .classed('cr-' + uv.util.formatClassName(self.categories[idx]), true) .style('fill', 'none') .style('stroke', color) .style('stroke-width', self.config.line.strokewidth) .style('stroke-opacity', self.config.line.strokeopacity) .transition() .duration(self.config.effects.duration) .delay(2 * idx * self.config.effects.duration) .style('stroke-opacity', 1) .call(uv.util.endAll, function (d,i){ d3.select(this.parentNode.parentNode).selectAll('path').on('mouseover', uv.effects.line.mouseover(self, idx)); d3.select(this.parentNode.parentNode).selectAll('path').on('mouseout', uv.effects.line.mouseout(self, idx)); d3.select(this.parentNode.parentNode).selectAll('circle').on('mouseover', uv.effects.line.mouseover(self, idx)); d3.select(this.parentNode.parentNode).selectAll('circle').on('mouseout', uv.effects.line.mouseout(self, idx)); }); if (self.config.line.showcircles) { linegroup.path.selectAll('circle') .data(self.dataset[idx]) .enter().append('circle') .attr('cx', linegroup.func.x()) .attr('cy', linegroup.func.y()) .attr('r', self.config.line.circleradius) .classed('cr-' + uv.util.formatClassName(self.categories[idx]), true) .style('fill', color) .style('fill-opacity', self.config.line.circleopacity) .style('stroke', '#fff') .append('svg:title') .text( function (d, i) { return uv.util.getTooltipText(self, self.categories[idx], self.labels[i], d);}); } linegroup.path.selectAll('text') .data(self.dataset[idx]) .enter().append('text') .attr('x', function (d) { return axes.hor.scale(d.name) + axes.hor.scale.rangeBand() / 2; }) .attr('y', function (d) { return axes.ver.scale(d.value) - 20; }) .attr('dx', 0) .attr('dy', '.71em') .attr('text-anchor', 'middle') .classed('cr-' + uv.util.formatClassName(self.categories[idx]), true) .style('fill', self.config.label.showlabel ? uv.util.getColorBand(self.config, idx) : 'none') .style('font-family', self.config.line.fontfamily) .style('font-size', self.config.line.fontsize) .style('font-weight', self.config.line.fontweight) .style('opacity', 0) .text(function(d) { return uv.util.getLabelValue(self, d); }) .transition() .duration(3 * self.config.effects.duration) .delay(2 * idx * self.config.effects.duration) .style('opacity', 1); return this; };
RobertoMalatesta/uvCharts
src/gfx/line.js
JavaScript
mit
7,531
var _ = require('lodash'), Promise = require('bluebird'), models = require('../../../../models'), utils = require('../../../../utils'), SubscribersImporter = require('./subscribers'), PostsImporter = require('./posts'), TagsImporter = require('./tags'), SettingsImporter = require('./settings'), UsersImporter = require('./users'), RolesImporter = require('./roles'), importers = {}, DataImporter; DataImporter = { type: 'data', preProcess: function preProcess(importData) { importData.preProcessedByData = true; return importData; }, init: function init(importData) { importers.roles = new RolesImporter(importData.data); importers.tags = new TagsImporter(importData.data); importers.users = new UsersImporter(importData.data); importers.subscribers = new SubscribersImporter(importData.data); importers.posts = new PostsImporter(importData.data); importers.settings = new SettingsImporter(importData.data); return importData; }, doImport: function doImport(importData) { var ops = [], errors = [], results = [], options = { importing: true, context: { internal: true } }; this.init(importData); return models.Base.transaction(function (transacting) { options.transacting = transacting; _.each(importers, function (importer) { ops.push(function doModelImport() { return importer.beforeImport(options) .then(function () { return importer.doImport(options) .then(function (_results) { results = results.concat(_results); }); }); }); }); _.each(importers, function (importer) { ops.push(function afterImport() { return importer.afterImport(options); }); }); utils.sequence(ops) .then(function () { results.forEach(function (promise) { if (!promise.isFulfilled()) { errors = errors.concat(promise.reason()); } }); if (errors.length === 0) { transacting.commit(); } else { transacting.rollback(errors); } }); }).then(function () { /** * data: imported data * originalData: data from the json file * problems: warnings */ var toReturn = { data: {}, originalData: importData.data, problems: [] }; _.each(importers, function (importer) { toReturn.problems = toReturn.problems.concat(importer.problems); toReturn.data[importer.dataKeyToImport] = importer.importedData; }); return toReturn; }).catch(function (errors) { return Promise.reject(errors); }); } }; module.exports = DataImporter;
leninhasda/Ghost
core/server/data/importer/importers/data/index.js
JavaScript
mit
3,372
var utils = require('../../../utils'); module.exports = function CodeType(config) { var self = { selector: '.field-type-code[for="' + config.fieldName + '"]', elements: { label: '.FormLabel', lineNumber: '.CodeMirror-linenumber', codeMirror: '.CodeMirror-container', }, commands: [{ assertUI: function() { this .expect.element('@label').to.be.visible; this .expect.element('@label').text.to.equal(utils.titlecase(config.fieldName)); this .expect.element('@lineNumber').to.be.visible; this .expect.element('@lineNumber').text.to.equal('1'); this .expect.element('@codeMirror').to.be.visible; return this; }, fillInput: function(input) { this.api .execute(function (selector, input) { var x = document.querySelector(selector); var y = x.getElementsByClassName('CodeMirror')[0]; y.CodeMirror.setValue(input.value); }, [self.selector, input]); return this; }, assertInput: function(input) { this.api .execute(function (selector) { var x = document.querySelector(selector); var y = x.getElementsByClassName('CodeMirror')[0]; return y.CodeMirror.getValue(); }, [self.selector], function (result) { this.assert.equal(result.value, input.value); }); return this; }, }], }; return self; };
webteckie/keystone
test/e2e/adminUI/pages/fieldTypes/code.js
JavaScript
mit
1,358
// Run if you want to monitor unresolved promises (in properly working // application there should be no promises that are never resolved) 'use strict'; var max = Math.max , callable = require('es5-ext/lib/Object/valid-callable') , isCallable = require('es5-ext/lib/Object/is-callable') , toUint = require('es5-ext/lib/Number/to-uint') , deferred = require('./deferred'); exports = module.exports = function (timeout, cb) { if (timeout === false) { // Cancel monitor delete deferred._monitor; delete exports.timeout; delete exports.callback; return; } exports.timeout = timeout = max(toUint(timeout) || 5000, 50); if (cb == null) { if ((typeof console !== 'undefined') && console && isCallable(console.error)) { cb = function (e) { console.error(((e.stack && e.stack.toString()) || "Unresolved promise: no stack available")); }; } } else { callable(cb); } exports.callback = cb; deferred._monitor = function () { var e = new Error("Unresolved promise"); return setTimeout(function () { if (cb) cb(e); }, timeout); }; };
nateyang/grunt-build_js
tasks/libs/deferred/lib/monitor.js
JavaScript
mit
1,100
define( //begin v1.x content { "field-quarter-short-relative+0": "tento ลกtvrลฅr.", "field-quarter-short-relative+1": "budรบci ลกtvrลฅr.", "dayPeriods-standAlone-abbr-noon": "pol.", "field-tue-relative+-1": "minulรฝ utorok", "field-year": "rok", "dateFormatItem-yw": "w. 'tรฝลพdeลˆ' 'v' 'roku' y", "dayPeriods-format-abbr-afternoon1": "popol.", "dateFormatItem-Hm": "H:mm", "field-wed-relative+0": "tรบto stredu", "field-wed-relative+1": "budรบcu stredu", "dateFormatItem-ms": "mm:ss", "timeFormat-short": "H:mm", "field-minute": "minรบta", "field-tue-narrow-relative+0": "tento ut.", "field-tue-narrow-relative+1": "budรบci ut.", "field-thu-short-relative+0": "tento ลกt.", "dateTimeFormat-short": "{1} {0}", "field-thu-short-relative+1": "budรบci ลกt.", "field-day-relative+0": "dnes", "field-day-relative+1": "zajtra", "field-day-relative+2": "pozajtra", "field-wed-narrow-relative+-1": "minulรบ st.", "field-year-narrow": "r.", "field-tue-relative+0": "tento utorok", "field-tue-relative+1": "budรบci utorok", "field-second-short": "s", "dayPeriods-format-narrow-am": "AM", "dayPeriods-standAlone-abbr-morning1": "rรกno", "dayPeriods-standAlone-abbr-morning2": "dopol.", "dateFormatItem-MMMd": "d. M.", "dayPeriods-format-narrow-morning1": "rรกno", "dayPeriods-format-narrow-morning2": "dop.", "dayPeriods-format-abbr-am": "AM", "field-week-relative+0": "tento tรฝลพdeลˆ", "field-month-relative+0": "tento mesiac", "field-week-relative+1": "budรบci tรฝลพdeลˆ", "field-month-relative+1": "budรบci mesiac", "field-sun-narrow-relative+0": "tรบto ne.", "timeFormat-medium": "H:mm:ss", "field-mon-short-relative+0": "tento pond.", "field-sun-narrow-relative+1": "budรบcu ne.", "field-mon-short-relative+1": "budรบci pond.", "field-second-relative+0": "teraz", "months-standAlone-narrow": [ "j", "f", "m", "a", "m", "j", "j", "a", "s", "o", "n", "d" ], "dayPeriods-standAlone-wide-noon": "poludnie", "eraNames": [ "pred Kristom", "po Kristovi" ], "dayPeriods-standAlone-abbr-pm": "PM", "field-month-short": "mes.", "dateFormatItem-GyMMMEd": "E, d. M. y G", "field-day": "deลˆ", "dayPeriods-standAlone-wide-night1": "noc", "field-year-relative+-1": "minulรฝ rok", "dayPeriods-format-wide-am": "AM", "field-sat-short-relative+-1": "minulรบ so.", "dayPeriods-format-narrow-afternoon1": "pop.", "dayPeriods-format-wide-afternoon1": "popoludnรญ", "field-hour-relative+0": "v tejto hodine", "field-wed-relative+-1": "minulรบ stredu", "dateTimeFormat-medium": "{1}, {0}", "field-sat-narrow-relative+-1": "minulรบ so.", "field-second": "sekunda", "days-standAlone-narrow": [ "n", "p", "u", "s", "ลก", "p", "s" ], "dayPeriods-standAlone-narrow-noon": "pol.", "dayPeriods-standAlone-wide-pm": "PM", "dateFormatItem-Ehms": "E h:mm:ss a", "dateFormat-long": "d. MMMM y", "dateFormatItem-GyMMMd": "d. M. y G", "dayPeriods-standAlone-abbr-midnight": "poln.", "field-quarter": "ลกtvrลฅrok", "field-week-short": "tรฝลพ.", "dayPeriods-format-narrow-midnight": "o poln.", "dateFormatItem-yMMMEd": "E d. M. y", "quarters-standAlone-wide": [ "1. ลกtvrลฅrok", "2. ลกtvrลฅrok", "3. ลกtvrลฅrok", "4. ลกtvrลฅrok" ], "days-format-narrow": [ "n", "p", "u", "s", "ลก", "p", "s" ], "dayPeriods-format-wide-evening1": "veฤer", "dateTimeFormats-appendItem-Timezone": "{0} {1}", "field-tue-short-relative+0": "tento utor.", "field-tue-short-relative+1": "budรบci utor.", "field-mon-relative+-1": "minulรฝ pondelok", "dateFormatItem-GyMMM": "LLLL y G", "field-month": "mesiac", "field-day-narrow": "d.", "dayPeriods-standAlone-abbr-night1": "noc", "dayPeriods-standAlone-narrow-afternoon1": "pop.", "dateFormatItem-MMM": "LLL", "field-minute-short": "min", "field-dayperiod": "ฤasลฅ dลˆa", "field-sat-short-relative+0": "tรบto so.", "field-sat-short-relative+1": "budรบcu so.", "dayPeriods-format-narrow-pm": "PM", "dateFormat-medium": "d. M. y", "eraAbbr": [ "pred Kr.", "po Kr." ], "quarters-standAlone-abbr": [ "Q1", "Q2", "Q3", "Q4" ], "dayPeriods-format-abbr-pm": "PM", "field-second-narrow": "s", "field-mon-relative+0": "tento pondelok", "dayPeriods-standAlone-narrow-night1": "noc", "field-mon-relative+1": "budรบci pondelok", "field-year-short": "r.", "months-format-narrow": [ "j", "f", "m", "a", "m", "j", "j", "a", "s", "o", "n", "d" ], "dayPeriods-format-wide-morning1": "rรกno", "dayPeriods-format-wide-morning2": "dopoludnia", "field-quarter-relative+-1": "minulรฝ ลกtvrลฅrok", "dayPeriods-standAlone-narrow-am": "AM", "days-format-short": [ "ne", "po", "ut", "st", "ลกt", "pi", "so" ], "quarters-format-narrow": [ "1", "2", "3", "4" ], "dayPeriods-format-wide-pm": "PM", "field-sat-relative+-1": "minulรบ sobotu", "dateTimeFormat-long": "{1}, {0}", "dateFormatItem-Md": "d. M.", "field-hour": "hodina", "dateFormatItem-yQQQQ": "QQQQ y", "months-format-wide": [ "januรกra", "februรกra", "marca", "aprรญla", "mรกja", "jรบna", "jรบla", "augusta", "septembra", "oktรณbra", "novembra", "decembra" ], "dayPeriods-format-wide-night1": "v noci", "dateFormat-full": "EEEE, d. MMMM y", "field-month-relative+-1": "minulรฝ mesiac", "dateFormatItem-Hms": "H:mm:ss", "field-quarter-short": "Q", "field-sat-narrow-relative+0": "tรบto so.", "dateFormatItem-Hmv": "H:mm v", "field-fri-relative+0": "tento piatok", "field-sat-narrow-relative+1": "budรบcu so.", "field-fri-relative+1": "budรบci piatok", "dayPeriods-format-narrow-noon": "nap.", "field-sun-short-relative+0": "tรบto ned.", "field-sun-short-relative+1": "budรบcu ned.", "field-week-relative+-1": "minulรฝ tรฝลพdeลˆ", "field-quarter-short-relative+-1": "minulรฝ ลกtvrลฅr.", "dateFormatItem-Ehm": "E h:mm a", "months-format-abbr": [ "jan", "feb", "mar", "apr", "mรกj", "jรบn", "jรบl", "aug", "sep", "okt", "nov", "dec" ], "dayPeriods-format-wide-midnight": "o polnoci", "field-quarter-relative+0": "tento ลกtvrลฅrok", "field-minute-relative+0": "v tejto minรบte", "timeFormat-long": "H:mm:ss z", "field-quarter-relative+1": "budรบci ลกtvrลฅrok", "field-wed-short-relative+-1": "minulรบ str.", "dateFormatItem-yMMM": "M/y", "dateFormat-short": "d. M. y", "field-thu-short-relative+-1": "minulรฝ ลกt.", "dayPeriods-format-abbr-night1": "v noci", "dateFormatItem-MMMMW": "W. 'tรฝลพdeลˆ' 'v' MMM", "days-standAlone-wide": [ "nedeฤพa", "pondelok", "utorok", "streda", "ลกtvrtok", "piatok", "sobota" ], "field-mon-narrow-relative+-1": "minulรฝ po.", "dateFormatItem-MMMMd": "d. MMMM", "field-thu-narrow-relative+-1": "minulรฝ ลกt.", "dateFormatItem-E": "ccc", "dateFormatItem-mmss": "mm:ss", "dateFormatItem-H": "H", "field-tue-narrow-relative+-1": "minulรฝ ut.", "dayPeriods-format-abbr-evening1": "veฤer", "dayPeriods-standAlone-narrow-pm": "PM", "dateFormatItem-M": "L.", "months-standAlone-wide": [ "januรกr", "februรกr", "marec", "aprรญl", "mรกj", "jรบn", "jรบl", "august", "september", "oktรณber", "november", "december" ], "field-wed-short-relative+0": "tรบto str.", "field-wed-short-relative+1": "budรบcu str.", "dateFormatItem-Hmsv": "H:mm:ss v", "field-sun-relative+-1": "minulรบ nedeฤพu", "dateFormatItem-MMMMEd": "E d. MMMM", "days-standAlone-abbr": [ "ne", "po", "ut", "st", "ลกt", "pi", "so" ], "dateTimeFormat-full": "{1}, {0}", "dateFormatItem-hm": "h:mm a", "dateFormatItem-d": "d.", "field-weekday": "deลˆ tรฝลพdลˆa", "dayPeriods-standAlone-wide-evening1": "veฤer", "field-quarter-narrow-relative+0": "tento ลกtvrลฅr.", "field-sat-relative+0": "tรบto sobotu", "dateFormatItem-h": "h a", "field-quarter-narrow-relative+1": "budรบci ลกtvrลฅr.", "field-sat-relative+1": "budรบcu sobotu", "months-standAlone-abbr": [ "jan", "feb", "mar", "apr", "mรกj", "jรบn", "jรบl", "aug", "sep", "okt", "nov", "dec" ], "dateFormatItem-hmsv": "h:mm:ss a v", "dayPeriods-format-abbr-morning1": "rรกno", "dayPeriods-standAlone-narrow-evening1": "veฤ.", "dayPeriods-format-abbr-morning2": "dopol.", "timeFormat-full": "H:mm:ss zzzz", "dateFormatItem-MEd": "E d. M.", "dateFormatItem-y": "y", "field-thu-narrow-relative+0": "tento ลกt.", "field-sun-narrow-relative+-1": "minulรบ ne.", "field-mon-short-relative+-1": "minulรฝ pond.", "field-thu-narrow-relative+1": "budรบci ลกt.", "field-thu-relative+0": "tento ลกtvrtok", "dayPeriods-standAlone-abbr-afternoon1": "popol.", "field-thu-relative+1": "budรบci ลกtvrtok", "dateFormatItem-hms": "h:mm:ss a", "field-fri-short-relative+-1": "minulรฝ pi.", "dateFormatItem-hmv": "h:mm a v", "dayPeriods-format-abbr-noon": "napol.", "field-thu-relative+-1": "minulรฝ ลกtvrtok", "dateFormatItem-yMd": "d. M. y", "quarters-standAlone-narrow": [ "1", "2", "3", "4" ], "field-week": "tรฝลพdeลˆ", "quarters-format-wide": [ "1. ลกtvrลฅrok", "2. ลกtvrลฅrok", "3. ลกtvrลฅrok", "4. ลกtvrลฅrok" ], "dateFormatItem-Ed": "E d.", "field-wed-narrow-relative+0": "tรบto st.", "field-wed-narrow-relative+1": "budรบcu st.", "dayPeriods-standAlone-wide-morning1": "rรกno", "dayPeriods-standAlone-wide-morning2": "dopoludnie", "field-quarter-narrow-relative+-1": "minulรฝ ลกtvrลฅr.", "field-fri-short-relative+0": "tento pi.", "field-fri-short-relative+1": "budรบci pi.", "days-standAlone-short": [ "ne", "po", "ut", "st", "ลกt", "pi", "so" ], "dayPeriods-standAlone-narrow-morning1": "rรกno", "dayPeriods-standAlone-narrow-morning2": "dop.", "dateFormatItem-GyMMMMd": "d. M. y G", "dayPeriods-format-abbr-midnight": "o poln.", "field-hour-short": "h", "quarters-format-abbr": [ "Q1", "Q2", "Q3", "Q4" ], "field-month-narrow": "mes.", "field-hour-narrow": "h", "field-fri-narrow-relative+-1": "minulรฝ pi.", "field-year-relative+0": "tento rok", "field-year-relative+1": "budรบci rok", "field-fri-relative+-1": "minulรฝ piatok", "eraNarrow": [ "pred Kr.", "po Kr." ], "dayPeriods-format-wide-noon": "napoludnie", "field-tue-short-relative+-1": "minulรฝ utor.", "field-minute-narrow": "min", "dayPeriods-standAlone-wide-afternoon1": "popoludnie", "dateFormatItem-yQQQ": "QQQ y", "days-format-wide": [ "nedeฤพa", "pondelok", "utorok", "streda", "ลกtvrtok", "piatok", "sobota" ], "dateFormatItem-yMMMMd": "d. MMMM y", "field-mon-narrow-relative+0": "tento po.", "dateFormatItem-EHm": "E HH:mm", "field-mon-narrow-relative+1": "budรบci po.", "dayPeriods-standAlone-wide-midnight": "polnoc", "dateFormatItem-yM": "M/y", "field-zone": "ฤasovรฉ pรกsmo", "dateFormatItem-yMMMM": "LLLL y", "dateFormatItem-MMMEd": "E d. M.", "dateFormatItem-EHms": "E HH:mm:ss", "dateFormatItem-yMEd": "E d. M. y", "dayPeriods-standAlone-narrow-midnight": "poln.", "field-quarter-narrow": "Q", "dayPeriods-standAlone-abbr-am": "AM", "field-day-relative+-1": "vฤera", "field-sun-short-relative+-1": "minulรบ ned.", "field-day-relative+-2": "predvฤerom", "dayPeriods-format-narrow-night1": "v n.", "days-format-abbr": [ "ne", "po", "ut", "st", "ลกt", "pi", "so" ], "field-sun-relative+0": "tรบto nedeฤพu", "field-sun-relative+1": "budรบcu nedeฤพu", "dateFormatItem-yMMMd": "d. M. y", "dateFormatItem-Gy": "y G", "field-era": "letopoฤet", "field-week-narrow": "tรฝลพ.", "field-day-short": "d.", "dayPeriods-standAlone-abbr-evening1": "veฤer", "field-fri-narrow-relative+0": "tento pi.", "dayPeriods-format-narrow-evening1": "veฤ.", "field-fri-narrow-relative+1": "budรบci pi.", "dayPeriods-standAlone-wide-am": "AM" } //end v1.x content );
cdnjs/cdnjs
ajax/libs/dojo/1.16.3/cldr/nls/sk/gregorian.js
JavaScript
mit
11,650
๏ปฟClazz.declarePackage ("org.eclipse.osgi.framework.internal.core"); Clazz.load (["org.eclipse.osgi.framework.internal.core.BundleLoader"], "org.eclipse.osgi.framework.internal.core.SystemBundleLoader", null, function () { c$ = Clazz.decorateAsClass (function () { this.classLoader = null; Clazz.instantialize (this, arguments); }, org.eclipse.osgi.framework.internal.core, "SystemBundleLoader", org.eclipse.osgi.framework.internal.core.BundleLoader); Clazz.makeConstructor (c$, function (bundle, proxy) { Clazz.superConstructor (this, org.eclipse.osgi.framework.internal.core.SystemBundleLoader, [bundle, proxy]); this.classLoader = this.getClass ().getClassLoader (); }, "org.eclipse.osgi.framework.internal.core.BundleHost,org.eclipse.osgi.framework.internal.core.BundleLoaderProxy"); Clazz.defineMethod (c$, "findClass", function (name) { return this.classLoader.loadClass (name); }, "~S"); Clazz.overrideMethod (c$, "findLibrary", function (name) { return null; }, "~S"); Clazz.overrideMethod (c$, "findLocalClass", function (name) { var clazz = null; try { clazz = this.classLoader.loadClass (name); } catch (e) { if (Clazz.instanceOf (e, ClassNotFoundException)) { } else { throw e; } } return clazz; }, "~S"); Clazz.overrideMethod (c$, "findLocalResource", function (name) { return this.classLoader.getResource (name); }, "~S"); Clazz.overrideMethod (c$, "findLocalResources", function (name) { try { return this.classLoader.getResources (name); } catch (e) { if (Clazz.instanceOf (e, java.io.IOException)) { return null; } else { throw e; } } }, "~S"); Clazz.defineMethod (c$, "findResource", function (name) { return this.classLoader.getResource (name); }, "~S"); Clazz.overrideMethod (c$, "findResources", function (name) { return this.classLoader.getResources (name); }, "~S"); Clazz.overrideMethod (c$, "close", function () { }); });
01org/mayloon-portingtool
sources/net.sf.j2s.lib/j2slib/org/eclipse/osgi/framework/internal/core/SystemBundleLoader.js
JavaScript
epl-1.0
1,857
package test0657; public class X {} class A {}
echoes-tech/eclipse.jsdt.core
org.eclipse.wst.jsdt.core.tests.model/workspace/Converter/src/test0657/X.js
JavaScript
epl-1.0
50
package test0438; import test0438_a.W; class D { }
echoes-tech/eclipse.jsdt.core
org.eclipse.wst.jsdt.core.tests.model/workspace/Converter/src/test0438/D.js
JavaScript
epl-1.0
57
public class X { void bar() { for (final int i; 0 < (i = 1); i = i + 1) { } } } //public class X { // public static void main(String[] args) { // final int i; // for ( ; ; i = 1) // break; // i = 1; // } //} //public class X { // final int blank; // { // while ((null == null || true)) { // blank = 1; // break; // } // } // X(){ // } // public static void main(String[] argv){ // System.out.println("SUCCESS"); // } //} // should fail //class X { // // public static void main(String[] args) { // final boolean b; // do // break; // while ((b = true) && false); // b = true; // } //} // ? //class X { // // public static void main(String[] args) { // final boolean b; // do // break; // while ((b = true) && false); // b = true; // } //}
echoes-tech/eclipse.jsdt.core
org.eclipse.wst.jsdt.core.tests.model/workspace/Formatter/test333/A_out.js
JavaScript
epl-1.0
838
๏ปฟdefine([], function () { function processForgotPasswordResult(result) { if (result.Success) { var msg = Globalize.translate('MessagePasswordResetForUsers'); msg += '<br/>'; msg += '<br/>'; msg += result.UsersReset.join('<br/>'); Dashboard.alert({ message: msg, title: Globalize.translate('HeaderPasswordReset'), callback: function () { window.location.href = 'login.html'; } }); return; } Dashboard.alert({ message: Globalize.translate('MessageInvalidForgotPasswordPin'), title: Globalize.translate('HeaderPasswordReset') }); return; } return function (view, params) { function onSubmit(e) { ApiClient.ajax({ type: 'POST', url: ApiClient.getUrl('Users/ForgotPassword/Pin'), dataType: 'json', data: { Pin: view.querySelector('#txtPin').value } }).then(processForgotPasswordResult); e.preventDefault(); return false; } view.querySelector('form').addEventListener('submit', onSubmit); }; });
solabc16/Emby
MediaBrowser.WebDashboard/dashboard-ui/scripts/forgotpasswordpin.js
JavaScript
gpl-2.0
1,328
๏ปฟ/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'toolbar', 'en', { toolbarCollapse: 'Collapse Toolbar', toolbarExpand: 'Expand Toolbar', toolbarGroups: { document: 'Document', clipboard: 'Clipboard/Undo', editing: 'Editing', forms: 'Forms', basicstyles: 'Basic Styles', paragraph: 'Paragraph', links: 'Links', insert: 'Insert', styles: 'Styles', colors: 'Colors', tools: 'Tools' }, toolbars: 'Editor toolbars' } );
igor-borisov/valamis
learn-portlet/src/main/webapp/js2.0/vendor/ckeditor/plugins/toolbar/lang/en.js
JavaScript
gpl-3.0
566
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; import { Cordova, Plugin } from './plugin'; /** * @name Device Motion * @description * Requires Cordova plugin: `cordova-plugin-device-motion`. For more info, please see the [Device Motion docs](https://github.com/apache/cordova-plugin-device-motion). * * @usage * ```typescript * import { DeviceMotion } from 'ionic-native'; * * * // Get the device current acceleration * DeviceMotion.getCurrentAcceleration().then( * (acceleration: AccelerationData) => console.log(acceleration), * (error: any) => console.log(error) * ); * * // Watch device acceleration * var subscription = DeviceMotion.watchAcceleration().subscribe((acceleration: AccelerationData) => { * console.log(acceleration); * }); * * // Stop watch * subscription.unsubscribe(); * * ``` */ export var DeviceMotion = (function () { function DeviceMotion() { } /** * Get the current acceleration along the x, y, and z axes. * @returns {Promise<AccelerationData>} Returns object with x, y, z, and timestamp properties */ DeviceMotion.getCurrentAcceleration = function () { return; }; /** * Watch the device acceleration. Clear the watch by unsubscribing from the observable. * @param {AccelerometerOptions} options list of options for the accelerometer. * @returns {Observable<AccelerationData>} Observable returns an observable that you can subscribe to */ DeviceMotion.watchAcceleration = function (options) { return; }; __decorate([ Cordova() ], DeviceMotion, "getCurrentAcceleration", null); __decorate([ Cordova({ callbackOrder: 'reverse', observable: true, clearFunction: 'clearWatch' }) ], DeviceMotion, "watchAcceleration", null); DeviceMotion = __decorate([ Plugin({ pluginName: 'DeviceMotion', plugin: 'cordova-plugin-device-motion', pluginRef: 'navigator.accelerometer', repo: 'https://github.com/apache/cordova-plugin-device-motion' }) ], DeviceMotion); return DeviceMotion; }()); //# sourceMappingURL=devicemotion.js.map
chitranshi21/home_service_ionic
node_modules/ionic-native/dist/esm/plugins/devicemotion.js
JavaScript
gpl-3.0
2,774
(function () { // Get values from the substitution engine. // We can't just pull these from the document context // because this script is intended to be transcluded into // another document, and we want the GET values used to request it, // not the values for the including document // XXX these are unencoded, so there's an unavoidable // injection vulnerability in constructing this file... // need to upgrade the template engine. var reportField = "{{GET[reportField]}}"; var reportValue = "{{GET[reportValue]}}"; var reportExists = "{{GET[reportExists]}}"; var noCookies = "{{GET[noCookies]}}"; var reportCookieName = "{{GET[reportCookieName]}}" var testName = "{{GET[testName]}}" var cookiePresent = "{{GET[cookiePresent]}}" var reportCount = "{{GET[reportCount]}}" var location = window.location; if (reportCookieName == "") { // fallback on test file name if cookie name not specified reportCookieName = location.pathname.split('/')[location.pathname.split('/').length - 1].split('.')[0]; } var reportID = "{{GET[reportID]}}"; if (reportID == "") { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookieName = cookies[i].split('=')[0].trim(); var cookieValue = cookies[i].split('=')[1].trim(); if (cookieName == reportCookieName) { reportID = cookieValue; var cookieToDelete = cookieName + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=" + document.location.pathname.substring(0, document.location.pathname.lastIndexOf('/') + 1); document.cookie = cookieToDelete; break; } } } // There is no real way to test (in this particular layer) that a CSP report // has *not* been sent, at least not without some major reworks and // involvement from all the platform participants. So the current "solution" // is to wait for some reasonable amount of time and if no report has been // received to conclude that no report has been generated. These timeouts must // not exceed the test timeouts set by vendors otherwise the test would fail. var timeout = document.querySelector("meta[name=timeout][content=long]") ? 20 : 3; var reportLocation = location.protocol + "//" + location.host + "/content-security-policy/support/report.py?op=retrieve_report&timeout=" + timeout + "&reportID=" + reportID; if (testName == "") testName = "Violation report status OK."; var reportTest = async_test(testName); function assert_field_value(field, value, field_name) { assert_true(field.indexOf(value.split(" ")[0]) != -1, field_name + " value of \"" + field + "\" did not match " + value.split(" ")[0] + "."); } reportTest.step(function () { var report = new XMLHttpRequest(); report.onload = reportTest.step_func(function () { var data = JSON.parse(report.responseText); if (data.error) { assert_equals("false", reportExists, data.error); } else { if(reportExists != "" && reportExists == "false" && data["csp-report"]) { assert_unreached("CSP report sent, but not expecting one: " + JSON.stringify(data["csp-report"])); } // Firefox expands 'self' or origins in a policy to the actual origin value // so "www.example.com" becomes "http://www.example.com:80". // Accomodate this by just testing that the correct directive name // is reported, not the details... if(data["csp-report"] != undefined && data["csp-report"][reportField] != undefined) { assert_field_value(data["csp-report"][reportField], reportValue, reportField); } else if (data[0] != undefined && data[0]["body"] != undefined && data[0]["body"][reportField] != undefined) { assert_field_value(data[0]["body"][reportField], reportValue, reportField); } else { assert_equals("", reportField, "Expected report field could not be found in report"); } } reportTest.done(); }); report.open("GET", reportLocation, true); report.send(); }); if (noCookies || cookiePresent) { var cookieTest = async_test("Test report cookies."); var cookieReport = new XMLHttpRequest(); cookieReport.onload = cookieTest.step_func(function () { var data = JSON.parse(cookieReport.responseText); if (noCookies) { assert_equals(data.reportCookies, "None", "Report should not contain any cookies"); } if (cookiePresent) { assert_true(data.reportCookies.hasOwnProperty(cookiePresent), "Report should contain cookie: " + cookiePresent); } cookieTest.done(); }); var cReportLocation = location.protocol + "//" + location.host + "/content-security-policy/support/report.py?op=retrieve_cookies&timeout=" + timeout + "&reportID=" + reportID; cookieReport.open("GET", cReportLocation, true); cookieReport.send(); } if (reportCount != "") { var reportCountTest = async_test("Test number of sent reports."); var reportCountReport = new XMLHttpRequest(); reportCountReport.onload = reportCountTest.step_func(function () { var data = JSON.parse(reportCountReport.responseText); assert_equals(data.report_count, reportCount, "Report count was not what was expected."); reportCountTest.done(); }); var cReportLocation = location.protocol + "//" + location.host + "/content-security-policy/support/report.py?op=retrieve_count&timeout=" + timeout + "&reportID=" + reportID; reportCountReport.open("GET", cReportLocation, true); reportCountReport.send(); } })();
UK992/servo
tests/wpt/web-platform-tests/content-security-policy/support/checkReport.sub.js
JavaScript
mpl-2.0
5,724
/* * /MathJax/jax/output/HTML-CSS/fonts/STIX-Web/Size1/Regular/Main.js * * Copyright (c) 2009-2015 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.STIXMathJax_Size1 = { directory: "Size1/Regular", family: "STIXMathJax_Size1", testString: "\u00A0\u02C6\u02C7\u02DC\u02F7\u0302\u0303\u0305\u030C\u0330\u0332\u0338\u203E\u20D0\u20D1", 32: [0, 0, 250, 0, 0], 40: [1066, 164, 468, 139, 382], 41: [1066, 164, 468, 86, 329], 47: [1066, 164, 579, 25, 552], 91: [1066, 164, 383, 180, 363], 92: [1066, 164, 579, 27, 552], 93: [1066, 164, 383, 20, 203], 123: [1066, 164, 575, 114, 466], 125: [1066, 164, 575, 109, 461], 160: [0, 0, 250, 0, 0], 710: [767, -554, 560, 0, 560], 711: [767, -554, 560, 0, 560], 732: [750, -598, 558, -2, 558], 759: [-117, 269, 558, -2, 558], 770: [767, -554, 560, 0, 560], 771: [750, -598, 560, 0, 560], 773: [820, -770, 1000, 0, 1000], 780: [767, -554, 560, 0, 560], 816: [-117, 269, 560, 0, 560], 818: [-127, 177, 1000, 0, 1000], 824: [532, 21, 0, -720, -157], 8254: [820, -770, 1000, 0, 1000], 8400: [749, -584, 870, 0, 871], 8401: [749, -584, 871, 0, 871], 8406: [735, -482, 871, 0, 872], 8407: [736, -482, 871, 0, 872], 8428: [-123, 288, 871, 0, 871], 8429: [-123, 288, 871, 0, 871], 8430: [-26, 279, 871, 0, 872], 8431: [-25, 279, 871, 0, 872], 8512: [1500, -50, 1259, 55, 1204], 8719: [1500, -49, 1355, 50, 1305], 8720: [1500, -49, 1355, 50, 1305], 8721: [1499, -49, 1292, 90, 1202], 8730: [1552, 295, 1057, 112, 1089], 8731: [1552, 295, 1057, 112, 1089], 8732: [1552, 295, 1057, 112, 1089], 8747: [2000, 269, 585, 56, 1035], 8748: [2000, 269, 895, 56, 1345], 8749: [2000, 269, 1205, 56, 1655], 8750: [2000, 269, 635, 56, 1035], 8751: [2000, 269, 945, 56, 1345], 8752: [2000, 269, 1255, 56, 1655], 8753: [2000, 269, 635, 56, 1035], 8754: [2000, 269, 635, 56, 1035], 8755: [2000, 269, 635, 56, 1035], 8896: [1500, -49, 1265, 60, 1205], 8897: [1500, -49, 1265, 60, 1205], 8898: [1510, -49, 1265, 118, 1147], 8899: [1500, -39, 1265, 118, 1147], 8968: [1066, 164, 453, 180, 426], 8969: [1066, 164, 453, 25, 273], 8970: [1066, 164, 453, 180, 428], 8971: [1066, 164, 453, 27, 273], 9140: [766, -544, 1063, 69, 994], 9141: [139, 83, 1063, 68, 993], 9168: [676, 14, 200, 67, 133], 9180: [60, 153, 926, 0, 926], 9181: [777, -564, 926, 0, 926], 9182: [136, 89, 926, 0, 925], 9183: [789, -564, 926, 0, 925], 9184: [66, 212, 1460, 0, 1460], 9185: [842, -564, 1460, 0, 1460], 10098: [1066, 164, 566, 205, 539], 10099: [1066, 164, 566, 27, 361], 10214: [1066, 164, 515, 180, 486], 10215: [1066, 164, 515, 29, 335], 10216: [1066, 164, 578, 116, 462], 10217: [1066, 164, 578, 116, 462], 10218: [1066, 164, 798, 116, 670], 10219: [1066, 164, 798, 128, 682], 10627: [1066, 164, 712, 114, 587], 10628: [1066, 164, 712, 114, 587], 10629: [1066, 164, 632, 135, 546], 10630: [1066, 164, 632, 86, 497], 10744: [1566, 279, 806, 25, 781], 10745: [1566, 279, 806, 25, 781], 10752: [1500, -49, 1555, 52, 1503], 10753: [1500, -49, 1555, 52, 1503], 10754: [1500, -49, 1555, 52, 1503], 10755: [1500, -39, 1265, 118, 1147], 10756: [1500, -39, 1265, 118, 1147], 10757: [1500, -49, 1153, 82, 1071], 10758: [1500, -49, 1153, 82, 1071], 10759: [1500, -49, 1530, 60, 1470], 10760: [1500, -49, 1530, 60, 1470], 10761: [1500, -49, 1482, 60, 1422], 10762: [1500, -50, 1292, 90, 1202], 10763: [2000, 269, 914, 56, 1035], 10764: [2000, 269, 1515, 56, 1965], 10765: [2000, 269, 635, 56, 1035], 10766: [2000, 269, 635, 56, 1035], 10767: [2000, 269, 635, 56, 1035], 10768: [2000, 269, 635, 56, 1035], 10769: [2000, 269, 635, 56, 1035], 10770: [2000, 269, 735, 56, 1035], 10771: [2000, 269, 635, 56, 1035], 10772: [2000, 269, 844, 56, 1054], 10773: [2000, 269, 635, 56, 1035], 10774: [2000, 269, 735, 56, 1035], 10775: [2000, 269, 819, 24, 1039], 10776: [2000, 269, 635, 56, 1035], 10777: [2000, 269, 735, 56, 1035], 10778: [2000, 269, 735, 56, 1035], 10779: [2157, 269, 636, 56, 1036], 10780: [2000, 426, 585, 56, 1035], 11004: [867, 363, 690, 133, 557], 11007: [867, 363, 410, 100, 310] }; MathJax.Callback.Queue( ["initFont", MathJax.OutputJax["HTML-CSS"], "STIXMathJax_Size1"], ["loadComplete", MathJax.Ajax, MathJax.OutputJax["HTML-CSS"].fontDir + "/Size1/Regular/Main.js"] );
KWZwickau/KREDA-Sphere
Library/MathJax/2.5.0/jax/output/HTML-CSS/fonts/STIX-Web/Size1/Regular/Main.js
JavaScript
agpl-3.0
5,206
/** * Kendo UI v2018.1.221 (http://www.telerik.com/kendo-ui) * Copyright 2018 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f){ if (typeof define === 'function' && define.amd) { define(["kendo.core"], f); } else { f(); } }(function(){ (function( window, undefined ) { kendo.cultures["lg-UG"] = { name: "lg-UG", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { name: "Ugandan Shilling", abbr: "UGX", pattern: ["-n$","n$"], decimals: 0, ",": ",", ".": ".", groupSize: [3], symbol: "USh" } }, calendars: { standard: { days: { names: ["Sabbiiti","Balaza","Lwakubiri","Lwakusatu","Lwakuna","Lwakutaano","Lwamukaaga"], namesAbbr: ["Sab","Bal","Lw2","Lw3","Lw4","Lw5","Lw6"], namesShort: ["Sab","Bal","Lw2","Lw3","Lw4","Lw5","Lw6"] }, months: { names: ["Janwaliyo","Febwaliyo","Marisi","Apuli","Maayi","Juuni","Julaayi","Agusito","Sebuttemba","Okitobba","Novemba","Desemba"], namesAbbr: ["Jan","Feb","Mar","Apu","Maa","Juu","Jul","Agu","Seb","Oki","Nov","Des"] }, AM: ["AM","am","AM"], PM: ["PM","pm","PM"], patterns: { d: "dd/MM/yyyy", D: "dddd, d MMMM yyyy", F: "dddd, d MMMM yyyy HH:mm:ss", g: "dd/MM/yyyy HH:mm", G: "dd/MM/yyyy HH:mm:ss", m: "MMMM d", M: "MMMM d", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": "/", ":": ":", firstDay: 1 } } } })(this); }));
Memba/Memba-Widgets
src/js/vendor/kendo/cultures/kendo.culture.lg-UG.js
JavaScript
agpl-3.0
6,561
var APIInstall = ServiceCaller.extend( { key_name: 'Install', className: 'APIInstall', getLicense: function() { return this.argumentsHandler( this.className, 'getLicense', arguments ); }, getRequirements: function() { return this.argumentsHandler( this.className, 'getRequirements', arguments ); }, getDatabaseTypeArray: function() { return this.argumentsHandler( this.className, 'getDatabaseTypeArray', arguments ); }, getDatabaseConfig: function() { return this.argumentsHandler( this.className, 'getDatabaseConfig', arguments ); }, createDatabase: function() { return this.argumentsHandler( this.className, 'createDatabase', arguments ); }, getDatabaseSchema: function() { return this.argumentsHandler( this.className, 'getDatabaseSchema', arguments ); }, setDatabaseSchema: function() { return this.argumentsHandler( this.className, 'setDatabaseSchema', arguments ); }, postUpgrade: function() { return this.argumentsHandler( this.className, 'postUpgrade', arguments ); }, installDone: function() { return this.argumentsHandler( this.className, 'installDone', arguments ); }, getSystemSettings: function() { return this.argumentsHandler( this.className, 'getSystemSettings', arguments ); }, setSystemSettings: function() { return this.argumentsHandler( this.className, 'setSystemSettings', arguments ); }, getCompany: function() { return this.argumentsHandler( this.className, 'getCompany', arguments ); }, setCompany: function() { return this.argumentsHandler( this.className, 'setCompany', arguments ); }, getUser: function() { return this.argumentsHandler( this.className, 'getUser', arguments ); }, setUser: function() { return this.argumentsHandler( this.className, 'setUser', arguments ); }, getProvinceOptions: function() { return this.argumentsHandler( this.className, 'getProvinceOptions', arguments ); }, getMaintenanceJobs: function() { return this.argumentsHandler( this.className, 'getMaintenanceJobs', arguments ); }, testConnection: function() { return this.argumentsHandler( this.className, 'testConnection', arguments ); } } );
maestrano/timetrex
interface/html5/services/install/APIInstall.js
JavaScript
agpl-3.0
2,152
(function () { var oLoginViewModel, oSettingsViewModel ; AfterLogicApi.addPluginHook('view-model-defined', function (sViewModelName, oViewModel) { if (oViewModel && ('CLoginViewModel' === sViewModelName)) { oLoginViewModel = oViewModel; } if (oViewModel && ('CSettingsViewModel' === sViewModelName)) { oSettingsViewModel = oViewModel; if (!AfterLogicApi.getAppDataItem('User').CanLoginWithPassword) { oSettingsViewModel.getViewModel('two_factor_authentication').visible(false); } } }); AfterLogicApi.addPluginHook('api-mail-on-password-specified-success', function () { oSettingsViewModel.getViewModel('two_factor_authentication').visible(true); }); AfterLogicApi.addPluginHook('ajax-default-request', function (sAction, oParameters) { if (('SystemLogin' === sAction)) { this.oParams = oParameters; } }); AfterLogicApi.addPluginHook('ajax-default-response', function (sAction, oData) { if (('SystemLogin' === sAction && oData.Result != false && oData.ContinueAuth != true)) { oData['StopExecuteResponse'] = true; AfterLogicApi.showPopup(VerifyTokenPopup, [this.oParams.Email, oLoginViewModel]); } }); }());
jango2015/webmail-lite
data/plugins/two-factor-authentication/js/include.js
JavaScript
agpl-3.0
1,356
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'blockquote', 'is', { toolbar: 'Inndrรกttur' } );
ging/vish
lib/plugins/ediphy/app/assets/javascripts/lib/ckeditor/plugins/blockquote/blockquote/lang/is.js
JavaScript
agpl-3.0
220
odoo.define('payment_stripe.payment_form', function (require) { "use strict"; var ajax = require('web.ajax'); var core = require('web.core'); var Dialog = require('web.Dialog'); var PaymentForm = require('payment.payment_form'); var qweb = core.qweb; var _t = core._t; ajax.loadXML('/payment_stripe/static/src/xml/stripe_templates.xml', qweb); PaymentForm.include({ willStart: function () { return this._super.apply(this, arguments).then(function () { return ajax.loadJS("https://js.stripe.com/v3/"); }) }, //-------------------------------------------------------------------------- // Private //-------------------------------------------------------------------------- /** * called to create payment method object for credit card/debit card. * * @private * @param {Object} stripe * @param {Object} formData * @param {Object} card * @param {Boolean} addPmEvent * @returns {Promise} */ _createPaymentMethod: function (stripe, formData, card, addPmEvent) { if (addPmEvent) { return this._rpc({ route: '/payment/stripe/s2s/create_setup_intent', params: {'acquirer_id': formData.acquirer_id} }).then(function(intent_secret) { return stripe.handleCardSetup(intent_secret, card); }); } else { return stripe.createPaymentMethod({ type: 'card', card: card, }); } }, /** * called when clicking on pay now or add payment event to create token for credit card/debit card. * * @private * @param {Event} ev * @param {DOMElement} checkedRadio * @param {Boolean} addPmEvent */ _createStripeToken: function (ev, $checkedRadio, addPmEvent) { var self = this; if (ev.type === 'submit') { var button = $(ev.target).find('*[type="submit"]')[0] } else { var button = ev.target; } this.disableButton(button); var acquirerID = this.getAcquirerIdFromRadio($checkedRadio); var acquirerForm = this.$('#o_payment_add_token_acq_' + acquirerID); var inputsForm = $('input', acquirerForm); if (this.options.partnerId === undefined) { console.warn('payment_form: unset partner_id when adding new token; things could go wrong'); } var formData = self.getFormData(inputsForm); var stripe = this.stripe; var card = this.stripe_card_element; if (card._invalid) { return; } this._createPaymentMethod(stripe, formData, card, addPmEvent).then(function(result) { if (result.error) { return Promise.reject({"message": {"data": { "arguments": [result.error.message]}}}); } else { const paymentMethod = addPmEvent ? result.setupIntent.payment_method : result.paymentMethod.id; _.extend(formData, {"payment_method": paymentMethod}); return self._rpc({ route: formData.data_set, params: formData, }); } }).then(function(result) { if (addPmEvent) { if (formData.return_url) { window.location = formData.return_url; } else { window.location.reload(); } } else { $checkedRadio.val(result.id); self.el.submit(); } }).guardedCatch(function (error) { // We don't want to open the Error dialog since // we already have a container displaying the error if (error.event) { error.event.preventDefault(); } // if the rpc fails, pretty obvious self.enableButton(button); self.displayError( _t('Unable to save card'), _t("We are not able to add your payment method at the moment. ") + self._parseError(error) ); }); }, /** * called when clicking a Stripe radio if configured for s2s flow; instanciates the card and bind it to the widget. * * @private * @param {DOMElement} checkedRadio */ _bindStripeCard: function ($checkedRadio) { var acquirerID = this.getAcquirerIdFromRadio($checkedRadio); var acquirerForm = this.$('#o_payment_add_token_acq_' + acquirerID); var inputsForm = $('input', acquirerForm); var formData = this.getFormData(inputsForm); var stripe = Stripe(formData.stripe_publishable_key); var element = stripe.elements(); var card = element.create('card', {hidePostalCode: true}); card.mount('#card-element'); card.on('ready', function(ev) { card.focus(); }); card.addEventListener('change', function (event) { var displayError = document.getElementById('card-errors'); displayError.textContent = ''; if (event.error) { displayError.textContent = event.error.message; } }); this.stripe = stripe; this.stripe_card_element = card; }, /** * destroys the card element and any stripe instance linked to the widget. * * @private */ _unbindStripeCard: function () { if (this.stripe_card_element) { this.stripe_card_element.destroy(); } this.stripe = undefined; this.stripe_card_element = undefined; }, /** * @override */ updateNewPaymentDisplayStatus: function () { var $checkedRadio = this.$('input[type="radio"]:checked'); if ($checkedRadio.length !== 1) { return; } var provider = $checkedRadio.data('provider') if (provider === 'stripe') { // always re-init stripe (in case of multiple acquirers for stripe, make sure the stripe instance is using the right key) this._unbindStripeCard(); if (this.isNewPaymentRadio($checkedRadio)) { this._bindStripeCard($checkedRadio); } } return this._super.apply(this, arguments); }, //-------------------------------------------------------------------------- // Handlers //-------------------------------------------------------------------------- /** * @override */ payEvent: function (ev) { ev.preventDefault(); var $checkedRadio = this.$('input[type="radio"]:checked'); // first we check that the user has selected a stripe as s2s payment method if ($checkedRadio.length === 1 && this.isNewPaymentRadio($checkedRadio) && $checkedRadio.data('provider') === 'stripe') { return this._createStripeToken(ev, $checkedRadio); } else { return this._super.apply(this, arguments); } }, /** * @override */ addPmEvent: function (ev) { ev.stopPropagation(); ev.preventDefault(); var $checkedRadio = this.$('input[type="radio"]:checked'); // first we check that the user has selected a stripe as add payment method if ($checkedRadio.length === 1 && this.isNewPaymentRadio($checkedRadio) && $checkedRadio.data('provider') === 'stripe') { return this._createStripeToken(ev, $checkedRadio, true); } else { return this._super.apply(this, arguments); } }, }); });
rven/odoo
addons/payment_stripe/static/src/js/payment_form.js
JavaScript
agpl-3.0
7,614
๏ปฟdefine( ({ _widgetLabel: "์†์„ฑ ํ…Œ์ด๋ธ”", ok: "ํ™•์ธ", cancel: "์ทจ์†Œ", unsupportQueryWarning: "์†์„ฑ ํ…Œ์ด๋ธ” ์œ„์ ฏ์— ํ‘œ์‹œํ•˜๋ ค๋ฉด ๋ ˆ์ด์–ด๊ฐ€ ์ฟผ๋ฆฌ ์ž‘์—…์„ ์ง€์›ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์„œ๋น„์Šค์— ์ฟผ๋ฆฌ ๊ธฐ๋Šฅ์ด ์ผœ์ ธ ์žˆ๋Š”์ง€ ํ™•์ธํ•˜์„ธ์š”.", exportMessage: "๋ฐ์ดํ„ฐ๋ฅผ CSV ํŒŒ์ผ๋กœ ๋‚ด๋ณด๋‚ด์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?", exportFiles: "CSV๋กœ ๋‚ด๋ณด๋‚ด๊ธฐ", exportSelected: "์„ ํƒํ•œ ํ•ญ๋ชฉ์„ CSV๋กœ ๋‚ด๋ณด๋‚ด๊ธฐ", exportAll: "๋ชจ๋“  ํ•ญ๋ชฉ์„ CSV๋กœ ๋‚ด๋ณด๋‚ด๊ธฐ", options: "์˜ต์…˜", zoomto: "ํ™•๋Œ€", highlight: "๊ทธ๋ž˜ํ”ฝ ๊ฐ•์กฐ", selectAll: "๋ชจ๋“  ํŽ˜์ด์ง€์˜ ๋ ˆ์ฝ”๋“œ ์„ ํƒ", selectPage: "ํ˜„์žฌ ํŽ˜์ด์ง€์˜ ๋ ˆ์ฝ”๋“œ ์„ ํƒ", clearSelection: "์„ ํƒ ํ•ญ๋ชฉ ์ง€์šฐ๊ธฐ", filter: "ํ•„ํ„ฐ", setFilterTip: "ํ•„ํ„ฐ๋ฅผ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ์„ค์ •ํ•˜์„ธ์š”.", noFilterTip: "ํ•„ํ„ฐ ์‹์ด ์ •์˜๋˜์ง€ ์•Š์œผ๋ฉด ์ด ์ฟผ๋ฆฌ ์ž‘์—…์€ ์ง€์ •๋œ ๋ฐ์ดํ„ฐ ์›๋ณธ์˜ ๋ชจ๋“  ํ”ผ์ฒ˜๋ฅผ ๋‚˜์—ดํ•ฉ๋‹ˆ๋‹ค.", filterByExtent: "๋งต ๋ฒ”์œ„๋กœ ํ•„ํ„ฐ๋ง", showSelectedRecords: "์„ ํƒํ•œ ๋ ˆ์ฝ”๋“œ ํ‘œ์‹œ", showAllRecords: "๋ชจ๋“  ๋ ˆ์ฝ”๋“œ ๋ณด๊ธฐ", showRelatedRecords: "๋ฆด๋ ˆ์ดํŠธ๋œ ๋ ˆ์ฝ”๋“œ ํ‘œ์‹œ", noRelatedRecords: "๋ฆด๋ ˆ์ดํŠธ๋œ ๋ ˆ์ฝ”๋“œ ์—†์Œ", refresh: "์ƒˆ๋กœ๊ณ ์นจ", features: "ํ”ผ์ฒ˜", selected: "์„ ํƒํ•จ", transparent: "ํˆฌ๋ช… ๋ชจ๋“œ", indicate: "์„ ํƒ ํ•ญ๋ชฉ ์ฐพ๊ธฐ", columns: "์—ด ํ‘œ์‹œ/์ˆจ๊ธฐ๊ธฐ", selectionSymbol: "์„ ํƒ ์‹ฌ๋ณผ", closeMessage: "ํ…Œ์ด๋ธ” ์ˆจ๊ธฐ๊ธฐ(ํ•˜๋‹จ์—์„œ ๋‹ค์‹œ ํ™•์žฅ)", dataNotAvailable: "๋ฐ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.<br>[์ƒˆ๋กœ ๊ณ ์นจ] ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜์—ฌ ๋‹ค์‹œ ์‹œ๋„ํ•˜์„ธ์š”.", openTableTip: "์†์„ฑ ํ…Œ์ด๋ธ” ์—ด๊ธฐ", closeTableTip: "์†์„ฑ ํ…Œ์ด๋ธ” ์ˆจ๊ธฐ๊ธฐ" }) );
cob222/CPG
widgets/AttributeTable/nls/ko/strings.js
JavaScript
apache-2.0
1,777