code
stringlengths
2
1.05M
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * The integration account map filter for odata query. * */ class IntegrationAccountMapFilter { /** * Create a IntegrationAccountMapFilter. * @member {string} mapType The map type of integration account map. Possible * values include: 'NotSpecified', 'Xslt' */ constructor() { } /** * Defines the metadata of IntegrationAccountMapFilter * * @returns {object} metadata of IntegrationAccountMapFilter * */ mapper() { return { required: false, serializedName: 'IntegrationAccountMapFilter', type: { name: 'Composite', className: 'IntegrationAccountMapFilter', modelProperties: { mapType: { required: true, serializedName: 'mapType', type: { name: 'Enum', allowedValues: [ 'NotSpecified', 'Xslt' ] } } } } }; } } module.exports = IntegrationAccountMapFilter;
var assert = require('assert'); var R = require('../source'); describe('toString', function() { it('returns the string representation of null', function() { assert.strictEqual(R.toString(null), 'null'); }); it('returns the string representation of undefined', function() { assert.strictEqual(R.toString(undefined), 'undefined'); }); it('returns the string representation of a Boolean primitive', function() { assert.strictEqual(R.toString(true), 'true'); assert.strictEqual(R.toString(false), 'false'); }); it('returns the string representation of a number primitive', function() { assert.strictEqual(R.toString(0), '0'); assert.strictEqual(R.toString(-0), '-0'); assert.strictEqual(R.toString(1.23), '1.23'); assert.strictEqual(R.toString(-1.23), '-1.23'); assert.strictEqual(R.toString(1e+23), '1e+23'); assert.strictEqual(R.toString(-1e+23), '-1e+23'); assert.strictEqual(R.toString(1e-23), '1e-23'); assert.strictEqual(R.toString(-1e-23), '-1e-23'); assert.strictEqual(R.toString(Infinity), 'Infinity'); assert.strictEqual(R.toString(-Infinity), '-Infinity'); assert.strictEqual(R.toString(NaN), 'NaN'); }); it('returns the string representation of a string primitive', function() { assert.strictEqual(R.toString('abc'), '"abc"'); assert.strictEqual(R.toString('x "y" z'), '"x \\"y\\" z"'); assert.strictEqual(R.toString("' '"), '"\' \'"'); assert.strictEqual(R.toString('" "'), '"\\" \\""'); assert.strictEqual(R.toString('\b \b'), '"\\b \\b"'); assert.strictEqual(R.toString('\f \f'), '"\\f \\f"'); assert.strictEqual(R.toString('\n \n'), '"\\n \\n"'); assert.strictEqual(R.toString('\r \r'), '"\\r \\r"'); assert.strictEqual(R.toString('\t \t'), '"\\t \\t"'); assert.strictEqual(R.toString('\v \v'), '"\\v \\v"'); assert.strictEqual(R.toString('\0 \0'), '"\\0 \\0"'); assert.strictEqual(R.toString('\\ \\'), '"\\\\ \\\\"'); }); it('returns the string representation of a Boolean object', function() { assert.strictEqual(R.toString(new Boolean(true)), 'new Boolean(true)'); assert.strictEqual(R.toString(new Boolean(false)), 'new Boolean(false)'); }); it('returns the string representation of a Number object', function() { assert.strictEqual(R.toString(new Number(0)), 'new Number(0)'); assert.strictEqual(R.toString(new Number(-0)), 'new Number(-0)'); }); it('returns the string representation of a String object', function() { assert.strictEqual(R.toString(new String('abc')), 'new String("abc")'); assert.strictEqual(R.toString(new String('x "y" z')), 'new String("x \\"y\\" z")'); assert.strictEqual(R.toString(new String("' '")), 'new String("\' \'")'); assert.strictEqual(R.toString(new String('" "')), 'new String("\\" \\"")'); assert.strictEqual(R.toString(new String('\b \b')), 'new String("\\b \\b")'); assert.strictEqual(R.toString(new String('\f \f')), 'new String("\\f \\f")'); assert.strictEqual(R.toString(new String('\n \n')), 'new String("\\n \\n")'); assert.strictEqual(R.toString(new String('\r \r')), 'new String("\\r \\r")'); assert.strictEqual(R.toString(new String('\t \t')), 'new String("\\t \\t")'); assert.strictEqual(R.toString(new String('\v \v')), 'new String("\\v \\v")'); assert.strictEqual(R.toString(new String('\0 \0')), 'new String("\\0 \\0")'); assert.strictEqual(R.toString(new String('\\ \\')), 'new String("\\\\ \\\\")'); }); it('returns the string representation of a Date object', function() { assert.strictEqual(R.toString(new Date('2001-02-03T04:05:06.000Z')), 'new Date("2001-02-03T04:05:06.000Z")'); assert.strictEqual(R.toString(new Date('XXX')), 'new Date(NaN)'); }); it('returns the string representation of a RegExp object', function() { assert.strictEqual(R.toString(/(?:)/), '/(?:)/'); assert.strictEqual(R.toString(/\//g), '/\\//g'); }); it('returns the string representation of a function', function() { var add = function add(a, b) { return a + b; }; assert.strictEqual(R.toString(add), add.toString()); }); it('returns the string representation of an array', function() { assert.strictEqual(R.toString([]), '[]'); assert.strictEqual(R.toString([1, 2, 3]), '[1, 2, 3]'); assert.strictEqual(R.toString([1, [2, [3]]]), '[1, [2, [3]]]'); assert.strictEqual(R.toString(['x', 'y']), '["x", "y"]'); }); it('returns the string representation of an array with non-numeric property names', function() { var xs = [1, 2, 3]; xs.foo = 0; xs.bar = 0; xs.baz = 0; assert.strictEqual(R.toString(xs), '[1, 2, 3, "bar": 0, "baz": 0, "foo": 0]'); }); it('returns the string representation of an arguments object', function() { assert.strictEqual(R.toString((function() { return arguments; })()), '(function() { return arguments; }())'); assert.strictEqual(R.toString((function() { return arguments; })(1, 2, 3)), '(function() { return arguments; }(1, 2, 3))'); assert.strictEqual(R.toString((function() { return arguments; })(['x', 'y'])), '(function() { return arguments; }(["x", "y"]))'); }); it('returns the string representation of a plain object', function() { assert.strictEqual(R.toString({}), '{}'); assert.strictEqual(R.toString({foo: 1, bar: 2, baz: 3}), '{"bar": 2, "baz": 3, "foo": 1}'); assert.strictEqual(R.toString({'"quoted"': true}), '{"\\"quoted\\"": true}'); assert.strictEqual(R.toString({a: {b: {c: {}}}}), '{"a": {"b": {"c": {}}}}'); }); it('treats instance without custom `toString` method as plain object', function() { function Point(x, y) { this.x = x; this.y = y; } assert.strictEqual(R.toString(new Point(1, 2)), '{"x": 1, "y": 2}'); }); it('dispatches to custom `toString` method', function() { function Point(x, y) { this.x = x; this.y = y; } Point.prototype.toString = function() { return 'new Point(' + this.x + ', ' + this.y + ')'; }; assert.strictEqual(R.toString(new Point(1, 2)), 'new Point(1, 2)'); function Just(x) { if (!(this instanceof Just)) { return new Just(x); } this.value = x; } Just.prototype.toString = function() { return 'Just(' + R.toString(this.value) + ')'; }; assert.strictEqual(R.toString(Just(42)), 'Just(42)'); assert.strictEqual(R.toString(Just([1, 2, 3])), 'Just([1, 2, 3])'); assert.strictEqual(R.toString(Just(Just(Just('')))), 'Just(Just(Just("")))'); assert.strictEqual(R.toString({toString: R.always('x')}), 'x'); }); it('handles object with no `toString` method', function() { if (typeof Object.create === 'function') { var a = Object.create(null); var b = Object.create(null); b.x = 1; b.y = 2; assert.strictEqual(R.toString(a), '{}'); assert.strictEqual(R.toString(b), '{"x": 1, "y": 2}'); } }); it('handles circular references', function() { var a = []; a[0] = a; assert.strictEqual(R.toString(a), '[<Circular>]'); var o = {}; o.o = o; assert.strictEqual(R.toString(o), '{"o": <Circular>}'); var b = ['bee']; var c = ['see']; b[1] = c; c[1] = b; assert.strictEqual(R.toString(b), '["bee", ["see", <Circular>]]'); assert.strictEqual(R.toString(c), '["see", ["bee", <Circular>]]'); var p = {}; var q = {}; p.q = q; q.p = p; assert.strictEqual(R.toString(p), '{"q": {"p": <Circular>}}'); assert.strictEqual(R.toString(q), '{"p": {"q": <Circular>}}'); var x = []; var y = {}; x[0] = y; y.x = x; assert.strictEqual(R.toString(x), '[{"x": <Circular>}]'); assert.strictEqual(R.toString(y), '{"x": [<Circular>]}'); }); });
/*globals describe, it, expect, ModelList, ModelListMapper */ describe('ModelListMapper', function() { it('returns the model list', function() { expect(ModelListMapper.get()).toBe(ModelList.data); }); });
import isArray from 'lodash/lang/isArray'; import uniqueId from 'lodash/utility/uniqueId'; import React, { PropTypes } from 'react'; import Leaflet from 'leaflet'; import boundsType from './types/bounds'; import latlngType from './types/latlng'; import MapComponent from './MapComponent'; const normalizeCenter = pos => isArray(pos) ? pos : [pos.lat, pos.lng || pos.lon]; export default class Map extends MapComponent { static propTypes = { center: latlngType, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]), className: PropTypes.string, id: PropTypes.string, maxBounds: boundsType, maxZoom: PropTypes.number, minZoom: PropTypes.number, style: PropTypes.object, zoom: PropTypes.number, }; constructor(props) { super(props); this.state = { id: props.id || uniqueId('map'), }; } componentDidMount() { this.leafletElement = Leaflet.map(this.state.id, this.props); super.componentDidMount(); this.setState({map: this.leafletElement}); } componentDidUpdate(prevProps) { const { center, zoom } = this.props; if (center && this.shouldUpdateCenter(center, prevProps.center)) { this.leafletElement.setView(center, zoom, {animate: false}); } else if (zoom && zoom !== prevProps.zoom) { this.leafletElement.setZoom(zoom); } } componentWillUnmount() { super.componentWillUnmount(); this.leafletElement.remove(); } shouldUpdateCenter(next, prev) { if (!prev) return true; next = normalizeCenter(next); prev = normalizeCenter(prev); return next[0] !== prev[0] || next[1] !== prev[1]; } render() { const map = this.leafletElement; const children = map ? React.Children.map(this.props.children, child => { return child ? React.cloneElement(child, {map}) : null; }) : null; return ( <div className={this.props.className} id={this.state.id} style={this.props.style}> {children} </div> ); } }
Clazz.declarePackage ("J.renderspecial"); Clazz.load (["J.render.ShapeRenderer", "JU.P3", "$.P3i", "$.V3"], "J.renderspecial.VectorsRenderer", ["J.shape.Shape", "J.util.Vibration"], function () { c$ = Clazz.decorateAsClass (function () { this.pointVectorEnd = null; this.pointArrowHead = null; this.screenVectorEnd = null; this.screenArrowHead = null; this.headOffsetVector = null; this.diameter = 0; this.headWidthPixels = 0; this.vectorScale = 0; this.vectorSymmetry = false; this.headScale = 0; this.doShaft = false; this.vibTemp = null; Clazz.instantialize (this, arguments); }, J.renderspecial, "VectorsRenderer", J.render.ShapeRenderer); Clazz.prepareFields (c$, function () { this.pointVectorEnd = new JU.P3 (); this.pointArrowHead = new JU.P3 (); this.screenVectorEnd = new JU.P3i (); this.screenArrowHead = new JU.P3i (); this.headOffsetVector = new JU.V3 (); }); $_V(c$, "render", function () { var vectors = this.shape; if (!vectors.isActive) return false; var mads = vectors.mads; if (mads == null) return false; var atoms = vectors.atoms; var colixes = vectors.colixes; var needTranslucent = false; this.vectorScale = this.viewer.getFloat (1649410049); this.vectorSymmetry = this.viewer.getBoolean (603979973); for (var i = this.modelSet.getAtomCount (); --i >= 0; ) { var atom = atoms[i]; if (!atom.isVisible (this.myVisibilityFlag)) continue; var vibrationVector = this.viewer.getVibration (i); if (vibrationVector == null) continue; if (!this.transform (mads[i], atom, vibrationVector)) continue; if (!this.g3d.setColix (J.shape.Shape.getColix (colixes, i, atom))) { needTranslucent = true; continue; }this.renderVector (atom); if (this.vectorSymmetry) { if (this.vibTemp == null) this.vibTemp = new J.util.Vibration (); this.vibTemp.setT (vibrationVector); this.vibTemp.scale (-1); this.transform (mads[i], atom, this.vibTemp); this.renderVector (atom); }} return needTranslucent; }); $_M(c$, "transform", ($fz = function (mad, atom, vibrationVector) { var len = vibrationVector.length (); if (Math.abs (len * this.vectorScale) < 0.01) return false; this.headScale = -0.2; if (this.vectorScale < 0) this.headScale = -this.headScale; this.doShaft = (0.1 + Math.abs (this.headScale / len) < Math.abs (this.vectorScale)); this.headOffsetVector.setT (vibrationVector); this.headOffsetVector.scale (this.headScale / len); this.pointVectorEnd.scaleAdd2 (this.vectorScale, vibrationVector, atom); this.pointArrowHead.setT (this.pointVectorEnd); this.pointArrowHead.add (this.headOffsetVector); this.screenArrowHead.setT (this.viewer.transformPtVib (this.pointArrowHead, vibrationVector)); this.screenVectorEnd.setT (this.viewer.transformPtVib (this.pointVectorEnd, vibrationVector)); this.diameter = Clazz.floatToInt (mad < 1 ? 1 : mad <= 20 ? mad : this.viewer.scaleToScreen (this.screenVectorEnd.z, mad)); this.headWidthPixels = this.diameter << 1; if (this.headWidthPixels < this.diameter + 2) this.headWidthPixels = this.diameter + 2; return true; }, $fz.isPrivate = true, $fz), "~N,J.modelset.Atom,J.util.Vibration"); $_M(c$, "renderVector", ($fz = function (atom) { if (this.doShaft) this.g3d.fillCylinderScreen (1, this.diameter, atom.screenX, atom.screenY, atom.screenZ, this.screenArrowHead.x, this.screenArrowHead.y, this.screenArrowHead.z); this.g3d.fillConeScreen (2, this.headWidthPixels, this.screenArrowHead, this.screenVectorEnd, false); }, $fz.isPrivate = true, $fz), "J.modelset.Atom"); Clazz.defineStatics (c$, "arrowHeadOffset", -0.2); });
$(document).ready(function(){ //$('#comment_page_controller').hide(); $('#text_event_name').text("Error: Invalid event name "); var eventName = getURLParameter("q"); var teamName = getURLParameter("team"); if (eventName != null && eventName !== '' && teamName != null && teamName !== '') { $('#text_event_name').text("Thanks for joining " + eventName); $('#text_team_name').text("Your team is " + teamName); } }); angular.module('teamform-comment-app', ['firebase']) .controller('CommentCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function($scope, $firebaseObject, $firebaseArray) { // Call Firebase initialization code defined in site.js if (firebase.apps.length === 0) { initalizeFirebase(); } // Check is there any current user checkUser(firebase); firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. $scope.currentUserID = user.uid; } else { // No user is signed in. $scope.currentUserID = null; } }); var refPath, ref, eventName, teamName; eventName = getURLParameter("q"); teamName = getURLParameter("team"); // Combine id and skill $scope.combine = []; refPath = "event/" + eventName + "/team/" + teamName + "/teamMembers"; $scope.member = []; $scope.member = $firebaseArray(firebase.database().ref(refPath)); // Wait for the data $scope.member.$loaded().then(function(member) { console.log(member); // Remove user from member list var index = -1; for (i = 0; i < member.length; i++) { if (member[i].$value == $scope.currentUserID) { index = i; break; } } if (index > -1) { member.splice(index, 1); } else { console.log("ERROR"); } var refPath = "user/"; $scope.userList = []; $scope.userList = $firebaseArray(firebase.database().ref(refPath)); // Wait for the data $scope.userList.$loaded().then(function(userList) { console.log(userList); memberName = []; // Get skills // For each member in members for (i = 0; i < member.length; i++) { // Get the name of members in member list var index = userList.$indexFor(member[i].$value); console.log(index); memberName.push(userList[index].name); console.log(memberName); console.log(userList[index].skills); var skillList = $.map(userList[index].skills, function(value, index) { value.key = index; return [value]; }); console.log(skillList); //Initailise seletected to be false and increment 1 to total for (j = 0; j < skillList.length; j++) { skillList[j].selected = false; skillList[j].total += 1; console.log(skillList[j]); } console.log(i); console.log(memberName[i]); //console.log($scope.skillList); // Add an object to combine list $scope.combine.push({id: member[i].$value, name: memberName[i], skillList: skillList}); } }); }); $scope.addPoint = function(s) { if (s.selected == false) { s.agree += 1; s.selected = true; } else { s.agree -= 1; s.selected = false; } console.log(s); } $scope.updateFunc = function() { console.log($scope.combine); for (i = 0; i < $scope.combine.length; i++) { var userID = $.trim($scope.combine[i].id); for (j = 0; j < $scope.combine[i].skillList.length; j++){ var skillName = $.trim($scope.combine[i].skillList[j].key); if ( userID !== '' && skillName !=='') { var newData = { 'agree' : $scope.combine[i].skillList[j].agree, 'total' : $scope.combine[i].skillList[j].total, 'percent' : Math.floor($scope.combine[i].skillList[j].agree / $scope.combine[i].skillList[j].total*100) }; refPath = "user/" + userID + "/skills/" + skillName; console.log(refPath); ref = firebase.database().ref(refPath); ref.update(newData, function(){ // Complete call back //alert("data pushed..."); // Finally, go back to the front-end window.location.href= "index.html"; console.log("Save data"); }); } } } } }]);
/** * Password Template Script * ------------------------------------------------------------------------------ * A file that contains scripts highly couple code to the Password template. * * @namespace password */ theme.customerLogin = (function() { var config = { recoverPasswordForm: '#RecoverPassword', hideRecoverPasswordLink: '#HideRecoverPasswordLink' }; if (!$(config.recoverPasswordForm).length) { return; } checkUrlHash(); resetPasswordSuccess(); $(config.recoverPasswordForm).on('click', onShowHidePasswordForm); $(config.hideRecoverPasswordLink).on('click', onShowHidePasswordForm); function onShowHidePasswordForm(evt) { evt.preventDefault(); toggleRecoverPasswordForm(); } function checkUrlHash() { var hash = window.location.hash; // Allow deep linking to recover password form if (hash === '#recover') { toggleRecoverPasswordForm(); } } /** * Show/Hide recover password form */ function toggleRecoverPasswordForm() { $('#RecoverPasswordForm').toggleClass('hide'); $('#CustomerLoginForm').toggleClass('hide'); } /** * Show reset password success message */ function resetPasswordSuccess() { var $formState = $('.reset-password-success'); // check if reset password form was successfully submited. if (!$formState.length) { return; } // show success message $('#ResetSuccess').removeClass('hide'); } })();
var browserAdapter = { jumpTo : function (url) { window.location.assign(url); } }; var events = { makeRowBodyClickable : function () { $('.event-row').css('cursor', 'pointer'); $('.event-row').on('click', function (event) { var clicked_row = $(this); var href = clicked_row.find('.event-title a')[0].href; browserAdapter.jumpTo(href); }); } } $(document).ready(function () { events.makeRowBodyClickable(); });
'use strict'; describe('Core Tests:', function () { // TODO: Add chat socket tests });
'use strict'; angular .module('softvApp') .controller('NuevaPreguntaCtrl', function ($uibModal, $rootScope, ngNotify, encuestasFactory, $state) { function initialData() { encuestasFactory.GetResOpcMultsList().then(function (data) { console.log(data); vm.Respuestas_ = data.GetResOpcMultsListResult; }); } function cambioTipo() { if (vm.TipoPregunta == 1 || vm.TipoPregunta == 2) { vm.opcionMultiple = false; } else { vm.opcionMultiple = true; } } function AgregaRespuesta() { console.log(vm.selectedResp); if (vm.selectedResp != undefined) { if (vm.selectedResp.originalObject.Id_ResOpcMult != undefined) { if (ExisteRespuesta(vm.selectedResp.originalObject.Id_ResOpcMult) == false) { var object = { 'Id_ResOpcMult': vm.selectedResp.originalObject.Id_ResOpcMult, 'ResOpcMult': vm.selectedResp.originalObject.ResOpcMult } vm.Respuestas.push(object); } else { ngNotify.set('Esta respuesta ya fue ingresada', 'warn'); } } else { var object = { 'Id_ResOpcMult': 0, 'ResOpcMult': vm.selectedResp.originalObject } vm.Respuestas.push(object); } } } function Elimina(index) { vm.Respuestas.splice(index, 1); } function ExisteRespuesta(Id_ResOpcMult) { var count = 0; for (var a = 0; a < vm.Respuestas.length; a++) { if (vm.Respuestas[a].Id_ResOpcMult == Id_ResOpcMult) { count = count + 1; } } return (count > 0) ? true : false; } function AgregarPregunta() { if (vm.TipoPregunta == 3) { console.log("Opciones"); if (vm.Respuestas != undefined && vm.Respuestas.length > 1) { encuestasFactory.GetAddPregunta(vm.Npregunta, vm.TipoPregunta, vm.Respuestas).then(function (resp) { ngNotify.set('La pregunta se ha guardado correctamente', 'success'); $state.go('home.encuestas.preguntas'); }); } else { ngNotify.set('Ingresa las respuestas para tu pregunta ', 'warn'); } } else { encuestasFactory.GetAddPregunta(vm.Npregunta, vm.TipoPregunta, vm.Respuestas).then(function (resp) { ngNotify.set('La pregunta se ha guardado correctamente', 'success'); $state.go('home.encuestas.preguntas'); }); } } var vm = this; initialData(); vm.cambioTipo = cambioTipo; vm.AgregarPregunta = AgregarPregunta; vm.opcionMultiple = false; vm.AgregaRespuesta = AgregaRespuesta; vm.Elimina = Elimina; vm.Respuestas = []; });
// Deflate coverage tests /*global describe, it*/ 'use strict'; var assert = require('assert'); var fs = require('fs'); var path = require('path'); var c = require('../lib/zlib/constants'); var msg = require('../lib/zlib/messages'); var zlib_deflate = require('../lib/zlib/deflate.js'); var zstream = require('../lib/zlib/zstream'); var pako = require('../index'); var short_sample = 'hello world'; var long_sample = fs.readFileSync(path.join(__dirname, 'fixtures/samples/lorem_en_100k.txt')); function testDeflate(data, opts, flush) { var deflator = new pako.Deflate(opts); deflator.push(data, flush); deflator.push(data, true); assert.equal(deflator.err, false, msg[deflator.err]); } describe('Deflate support', function() { it('stored', function() { testDeflate(short_sample, {level: 0, chunkSize: 200}, 0); testDeflate(short_sample, {level: 0, chunkSize: 10}, 5); }); it('fast', function() { testDeflate(short_sample, {level: 1, chunkSize: 10}, 5); testDeflate(long_sample, {level: 1, memLevel: 1, chunkSize: 10}, 0); }); it('slow', function() { testDeflate(short_sample, {level: 4, chunkSize: 10}, 5); testDeflate(long_sample, {level: 9, memLevel: 1, chunkSize: 10}, 0); }); it('rle', function() { testDeflate(short_sample, {strategy: 3}, 0); testDeflate(short_sample, {strategy: 3, chunkSize: 10}, 5); testDeflate(long_sample, {strategy: 3, chunkSize: 10}, 0); }); it('huffman', function() { testDeflate(short_sample, {strategy: 2}, 0); testDeflate(short_sample, {strategy: 2, chunkSize: 10}, 5); testDeflate(long_sample, {strategy: 2, chunkSize: 10}, 0); }); }); describe('Deflate states', function() { //in port checking input parameters was removed it('inflate bad parameters', function () { var ret, strm; ret = zlib_deflate.deflate(null, 0); assert(ret === c.Z_STREAM_ERROR); strm = new zstream(); ret = zlib_deflate.deflateInit(null); assert(ret === c.Z_STREAM_ERROR); ret = zlib_deflate.deflateInit(strm, 6); assert(ret === c.Z_OK); ret = zlib_deflate.deflateSetHeader(null); assert(ret === c.Z_STREAM_ERROR); strm.state.wrap = 1; ret = zlib_deflate.deflateSetHeader(strm, null); assert(ret === c.Z_STREAM_ERROR); strm.state.wrap = 2; ret = zlib_deflate.deflateSetHeader(strm, null); assert(ret === c.Z_OK); ret = zlib_deflate.deflate(strm, c.Z_FINISH); assert(ret === c.Z_BUF_ERROR); ret = zlib_deflate.deflateEnd(null); assert(ret === c.Z_STREAM_ERROR); //BS_NEED_MORE strm.state.status = 5; ret = zlib_deflate.deflateEnd(strm); assert(ret === c.Z_STREAM_ERROR); }); });
/** * @private * * A general {@link Ext.picker.Picker} slot class. Slots are used to organize multiple scrollable slots into * a single {@link Ext.picker.Picker}. * * { * name : 'limit_speed', * title: 'Speed Limit', * data : [ * {text: '50 KB/s', value: 50}, * {text: '100 KB/s', value: 100}, * {text: '200 KB/s', value: 200}, * {text: '300 KB/s', value: 300} * ] * } * * See the {@link Ext.picker.Picker} documentation on how to use slots. */ Ext.define('Ext.picker.Slot', { extend: 'Ext.dataview.DataView', xtype : 'pickerslot', alternateClassName: 'Ext.Picker.Slot', requires: [ 'Ext.XTemplate', 'Ext.data.Store', 'Ext.Component', 'Ext.data.StoreManager' ], /** * @event slotpick * Fires whenever an slot is picked * @param {Ext.picker.Slot} this * @param {Mixed} value The value of the pick * @param {HTMLElement} node The node element of the pick */ isSlot: true, config: { /** * @cfg {String} title The title to use for this slot, or `null` for no title. * @accessor */ title: null, /** * @private * @cfg {Boolean} showTitle * @accessor */ showTitle: true, /** * @private * @cfg {String} cls The main component class * @accessor */ cls: Ext.baseCSSPrefix + 'picker-slot', /** * @cfg {String} name (required) The name of this slot. * @accessor */ name: null, /** * @cfg {Number} value The value of this slot * @accessor */ value: null, /** * @cfg {Number} flex * @accessor * @private */ flex: 1, /** * @cfg {String} align The horizontal alignment of the slot's contents. * * Valid values are: "left", "center", and "right". * @accessor */ align: 'left', /** * @cfg {String} displayField The display field in the store. * @accessor */ displayField: 'text', /** * @cfg {String} valueField The value field in the store. * @accessor */ valueField: 'value', /** * @cfg {String} itemTpl The template to be used in this slot. * If you set this, {@link #displayField} will be ignored. */ itemTpl: null, /** * @cfg {Object} scrollable * @accessor * @hide */ scrollable: { direction: 'vertical', indicators: false, momentumEasing: { minVelocity: 2 }, slotSnapEasing: { duration: 100 } } }, constructor: function() { /** * @property selectedIndex * @type Number * The current `selectedIndex` of the picker slot. * @private */ this.selectedIndex = 0; /** * @property picker * @type Ext.picker.Picker * A reference to the owner Picker. * @private */ this.callParent(arguments); }, /** * Sets the title for this dataview by creating element. * @param {String} title * @return {String} */ applyTitle: function(title) { //check if the title isnt defined if (title) { //create a new title element title = Ext.create('Ext.Component', { cls: Ext.baseCSSPrefix + 'picker-slot-title', docked : 'top', html : title }); } return title; }, updateTitle: function(newTitle, oldTitle) { if (newTitle) { this.add(newTitle); this.setupBar(); } if (oldTitle) { this.remove(oldTitle); } }, updateShowTitle: function(showTitle) { var title = this.getTitle(); if (title) { title[showTitle ? 'show' : 'hide'](); this.setupBar(); } }, updateDisplayField: function(newDisplayField) { if (!this.config.itemTpl) { this.setItemTpl('<div class="' + Ext.baseCSSPrefix + 'picker-item {cls} <tpl if="extra">' + Ext.baseCSSPrefix + 'picker-invalid</tpl>">{' + newDisplayField + '}</div>'); } }, /** * Updates the {@link #align} configuration */ updateAlign: function(newAlign, oldAlign) { var element = this.element; element.addCls(Ext.baseCSSPrefix + 'picker-' + newAlign); element.removeCls(Ext.baseCSSPrefix + 'picker-' + oldAlign); }, /** * Looks at the {@link #data} configuration and turns it into {@link #store}. * @param {Object} data * @return {Object} */ applyData: function(data) { var parsedData = [], ln = data && data.length, i, item, obj; if (data && Ext.isArray(data) && ln) { for (i = 0; i < ln; i++) { item = data[i]; obj = {}; if (Ext.isArray(item)) { obj[this.valueField] = item[0]; obj[this.displayField] = item[1]; } else if (Ext.isString(item)) { obj[this.valueField] = item; obj[this.displayField] = item; } else if (Ext.isObject(item)) { obj = item; } parsedData.push(obj); } } return data; }, // @private initialize: function() { this.callParent(); var scroller = this.getScrollable().getScroller(); this.on({ scope: this, painted: 'onPainted', itemtap: 'doItemTap' }); scroller.on({ scope: this, scrollend: 'onScrollEnd' }); }, // @private onPainted: function() { this.setupBar(); }, /** * Returns an instance of the owner picker. * @return {Object} * @private */ getPicker: function() { if (!this.picker) { this.picker = this.getParent(); } return this.picker; }, // @private setupBar: function() { if (!this.rendered) { //if the component isnt rendered yet, there is no point in calculating the padding just eyt return; } var element = this.element, innerElement = this.innerElement, picker = this.getPicker(), bar = picker.bar, value = this.getValue(), showTitle = this.getShowTitle(), title = this.getTitle(), scrollable = this.getScrollable(), scroller = scrollable.getScroller(), titleHeight = 0, barHeight, padding; barHeight = bar.getHeight(); if (showTitle && title) { titleHeight = title.element.getHeight(); } padding = Math.ceil((element.getHeight() - titleHeight - barHeight) / 2); innerElement.setStyle({ padding: padding + 'px 0 ' + (padding) + 'px' }); scroller.refresh(); scroller.setSlotSnapSize(barHeight); this.setValue(value); }, // @private doItemTap: function(list, index, item, e) { var me = this; me.selectedIndex = index; me.selectedNode = item; me.scrollToItem(item, true); }, // @private scrollToItem: function(item, animated) { var y = item.getY(), parentEl = item.parent(), parentY = parentEl.getY(), scrollView = this.getScrollable(), scroller = scrollView.getScroller(), difference; difference = y - parentY; scroller.scrollTo(0, difference, animated); }, // @private onScrollEnd: function(scroller, x, y) { var me = this, index = Math.round(y / me.picker.bar.getHeight()), viewItems = me.getViewItems(), item = viewItems[index]; if (item) { me.selectedIndex = index; me.selectedNode = item; me.fireEvent('slotpick', me, me.getValue(), me.selectedNode); } }, /** * Returns the value of this slot * @private */ getValue: function(useDom) { var store = this.getStore(), record, value; if (!store) { return; } if (!this.rendered || !useDom) { return this._value; } //if the value is ever false, that means we do not want to return anything if (this._value === false) { return null; } record = store.getAt(this.selectedIndex); value = record ? record.get(this.getValueField()) : null; // this._value = value; return value; }, /** * Sets the value of this slot * @private */ setValue: function(value) { return this.doSetValue(value); }, /** * Sets the value of this slot * @private */ setValueAnimated: function(value) { return this.doSetValue(value, true); }, doSetValue: function(value, animated) { if (!Ext.isDefined(value)) { return; } if (!this.rendered) { //we don't want to call this until the slot has been rendered this._value = value; return; } var store = this.getStore(), viewItems = this.getViewItems(), valueField = this.getValueField(), index, item; index = store.findExact(valueField, value); if (index != -1) { item = Ext.get(viewItems[index]); this.selectedIndex = index; if (item) { this.scrollToItem(item, (animated) ? { duration: 100 } : false); } this._value = value; } } });
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; /* * The purpose of this test is to make sure that when forking a process, * sending a fd representing a UDP socket to the child and sending messages * to this endpoint, these messages are distributed to the parent and the * child process. */ const common = require('../common'); if (common.isWindows) common.skip('Sending dgram sockets to child processes is not supported'); const dgram = require('dgram'); const fork = require('child_process').fork; const assert = require('assert'); if (process.argv[2] === 'child') { let childServer; process.once('message', function(msg, clusterServer) { childServer = clusterServer; childServer.once('message', function() { process.send('gotMessage'); childServer.close(); }); process.send('handleReceived'); }); } else { const parentServer = dgram.createSocket('udp4'); const client = dgram.createSocket('udp4'); const child = fork(__filename, ['child']); const msg = Buffer.from('Some bytes'); let childGotMessage = false; let parentGotMessage = false; parentServer.once('message', function(msg, rinfo) { parentGotMessage = true; parentServer.close(); }); parentServer.on('listening', function() { child.send('server', parentServer); child.on('message', function(msg) { if (msg === 'gotMessage') { childGotMessage = true; } else if (msg = 'handlReceived') { sendMessages(); } }); }); function sendMessages() { const serverPort = parentServer.address().port; const timer = setInterval(function() { /* * Both the parent and the child got at least one message, * test passed, clean up everything. */ if (parentGotMessage && childGotMessage) { clearInterval(timer); client.close(); } else { client.send( msg, 0, msg.length, serverPort, '127.0.0.1', function(err) { assert.ifError(err); } ); } }, 1); } parentServer.bind(0, '127.0.0.1'); process.once('exit', function() { assert(parentGotMessage); assert(childGotMessage); }); }
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import styles from './heading.css'; const Heading = ({ text, headingLines, theme, ...otherProps }) => { const classes = classNames({ [`${styles.heading}`]: true, [`${styles[theme]}`]: true, [`${styles.headingLines}`]: headingLines }); return ( <h2 className={classes} {...otherProps}> {text} </h2> ); }; Heading.propTypes = { id: PropTypes.string, text: PropTypes.string.isRequired, headingLines: PropTypes.bool, theme: PropTypes.string }; Heading.defaultProps = { id: null, headingLines: true, theme: 'dark' }; export default Heading;
import join from "url-join"; import { root } from "../config"; export default function path(str) { return join(root, str); }
/// <reference path="../../observable.ts"/> /// <reference path="../../concurrency/scheduler.ts" /> (function () { var o; var o2; o = o.skipUntilWithTime(new Date()); o = o.skipUntilWithTime(new Date(), Rx.Scheduler.default); o = o.skipUntilWithTime(1000); o = o.skipUntilWithTime(1000, Rx.Scheduler.default); }); //# sourceMappingURL=skipuntilwithtime.js.map
export { default } from 'ember-cli-semantic-ui/components/ui-popup';
class AppHeaderCtrl { constructor(AppConstants, User, $scope) { 'ngInject'; this.appName = AppConstants.appName; this.currentUser = User.current; this.secure = AppConstants.secure; $scope.$watch('User.current', (newUser)=>{ this.currentUser = newUser; }) } } let AppHeader = { controller: AppHeaderCtrl, templateUrl: 'layout/header.html' }; export default AppHeader;
var test = require('../'); var childRan = false; test('parent', function (t) { t.test('child', function (t) { childRan = true; t.pass('child ran'); t.end(); }); t.end(); }); test('uncle', function (t) { t.ok(childRan, 'Child should run before next top-level test'); t.end(); }); var grandParentRan = false; var parentRan = false; var grandChildRan = false; test('grandparent', function (t) { t.ok(!grandParentRan, 'grand parent ran twice'); grandParentRan = true; t.test('parent', function (t) { t.ok(!parentRan, 'parent ran twice'); parentRan = true; t.test('grandchild', function (t) { t.ok(!grandChildRan, 'grand child ran twice'); grandChildRan = true; t.pass('grand child ran'); t.end(); }); t.pass('parent ran'); t.end(); }); t.test('other parent', function (t) { t.ok(parentRan, 'first parent runs before second parent'); t.ok(grandChildRan, 'grandchild runs before second parent'); t.end(); }); t.pass('grandparent ran'); t.end(); }); test('second grandparent', function (t) { t.ok(grandParentRan, 'grandparent ran'); t.ok(parentRan, 'parent ran'); t.ok(grandChildRan, 'grandchild ran'); t.pass('other grandparent ran'); t.end(); }); // vim: set softtabstop=4 shiftwidth=4:
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled'; import experimentalStyled from '../styles/experimentalStyled'; import useThemeProps from '../styles/useThemeProps'; import { getListItemIconUtilityClass } from './listItemIconClasses'; import ListContext from '../List/ListContext'; import { jsx as _jsx } from "react/jsx-runtime"; var useUtilityClasses = function useUtilityClasses(styleProps) { var alignItems = styleProps.alignItems, classes = styleProps.classes; var slots = { root: ['root', alignItems === 'flex-start' && 'alignItemsFlexStart'] }; return composeClasses(slots, getListItemIconUtilityClass, classes); }; var ListItemIconRoot = experimentalStyled('div', {}, { name: 'MuiListItemIcon', slot: 'Root', overridesResolver: function overridesResolver(props, styles) { var styleProps = props.styleProps; return _extends({}, styles.root, styleProps.alignItems === 'flex-start' && styles.alignItemsFlexStart); } })(function (_ref) { var theme = _ref.theme, styleProps = _ref.styleProps; return _extends({ /* Styles applied to the root element. */ minWidth: 56, color: theme.palette.action.active, flexShrink: 0, display: 'inline-flex' }, styleProps.alignItems === 'flex-start' && { marginTop: 8 }); }); /** * A simple wrapper to apply `List` styles to an `Icon` or `SvgIcon`. */ var ListItemIcon = /*#__PURE__*/React.forwardRef(function ListItemIcon(inProps, ref) { var props = useThemeProps({ props: inProps, name: 'MuiListItemIcon' }); var className = props.className, other = _objectWithoutProperties(props, ["className"]); var context = React.useContext(ListContext); var styleProps = _extends({}, props, { alignItems: context.alignItems }); var classes = useUtilityClasses(styleProps); return /*#__PURE__*/_jsx(ListItemIconRoot, _extends({ className: clsx(classes.root, className), styleProps: styleProps, ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? ListItemIcon.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The content of the component, normally `Icon`, `SvgIcon`, * or a `@material-ui/icons` SVG icon element. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object } : void 0; export default ListItemIcon;
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")); var React = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _debounce = _interopRequireDefault(require("../utils/debounce")); var _useForkRef = _interopRequireDefault(require("../utils/useForkRef")); function getStyleValue(computedStyle, property) { return parseInt(computedStyle[property], 10) || 0; } var useEnhancedEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect; var styles = { /* Styles applied to the shadow textarea element. */ shadow: { // Visibility needed to hide the extra text area on iPads visibility: 'hidden', // Remove from the content flow position: 'absolute', // Ignore the scrollbar width overflow: 'hidden', height: 0, top: 0, left: 0, // Create a new layer, increase the isolation of the computed values transform: 'translateZ(0)' } }; var TextareaAutosize = React.forwardRef(function TextareaAutosize(props, ref) { var onChange = props.onChange, rows = props.rows, rowsMax = props.rowsMax, _props$rowsMin = props.rowsMin, rowsMinProp = _props$rowsMin === void 0 ? 1 : _props$rowsMin, style = props.style, value = props.value, other = (0, _objectWithoutProperties2.default)(props, ["onChange", "rows", "rowsMax", "rowsMin", "style", "value"]); var rowsMin = rows || rowsMinProp; var _React$useRef = React.useRef(value != null), isControlled = _React$useRef.current; var inputRef = React.useRef(null); var handleRef = (0, _useForkRef.default)(ref, inputRef); var shadowRef = React.useRef(null); var renders = React.useRef(0); var _React$useState = React.useState({}), state = _React$useState[0], setState = _React$useState[1]; var syncHeight = React.useCallback(function () { var input = inputRef.current; var computedStyle = window.getComputedStyle(input); var inputShallow = shadowRef.current; inputShallow.style.width = computedStyle.width; inputShallow.value = input.value || props.placeholder || 'x'; var boxSizing = computedStyle['box-sizing']; var padding = getStyleValue(computedStyle, 'padding-bottom') + getStyleValue(computedStyle, 'padding-top'); var border = getStyleValue(computedStyle, 'border-bottom-width') + getStyleValue(computedStyle, 'border-top-width'); // The height of the inner content var innerHeight = inputShallow.scrollHeight - padding; // Measure height of a textarea with a single row inputShallow.value = 'x'; var singleRowHeight = inputShallow.scrollHeight - padding; // The height of the outer content var outerHeight = innerHeight; if (rowsMin) { outerHeight = Math.max(Number(rowsMin) * singleRowHeight, outerHeight); } if (rowsMax) { outerHeight = Math.min(Number(rowsMax) * singleRowHeight, outerHeight); } outerHeight = Math.max(outerHeight, singleRowHeight); // Take the box sizing into account for applying this value as a style. var outerHeightStyle = outerHeight + (boxSizing === 'border-box' ? padding + border : 0); var overflow = Math.abs(outerHeight - innerHeight) <= 1; setState(function (prevState) { // Need a large enough difference to update the height. // This prevents infinite rendering loop. if (renders.current < 20 && (outerHeightStyle > 0 && Math.abs((prevState.outerHeightStyle || 0) - outerHeightStyle) > 1 || prevState.overflow !== overflow)) { renders.current += 1; return { overflow: overflow, outerHeightStyle: outerHeightStyle }; } if (process.env.NODE_ENV !== 'production') { if (renders.current === 20) { console.error(['Material-UI: too many re-renders. The layout is unstable.', 'TextareaAutosize limits the number of renders to prevent an infinite loop.'].join('\n')); } } return prevState; }); }, [rowsMax, rowsMin, props.placeholder]); React.useEffect(function () { var handleResize = (0, _debounce.default)(function () { renders.current = 0; syncHeight(); }); window.addEventListener('resize', handleResize); return function () { handleResize.clear(); window.removeEventListener('resize', handleResize); }; }, [syncHeight]); useEnhancedEffect(function () { syncHeight(); }); React.useEffect(function () { renders.current = 0; }, [value]); var handleChange = function handleChange(event) { renders.current = 0; if (!isControlled) { syncHeight(); } if (onChange) { onChange(event); } }; return React.createElement(React.Fragment, null, React.createElement("textarea", (0, _extends2.default)({ value: value, onChange: handleChange, ref: handleRef // Apply the rows prop to get a "correct" first SSR paint , rows: rowsMin, style: (0, _extends2.default)({ height: state.outerHeightStyle, // Need a large enough difference to allow scrolling. // This prevents infinite rendering loop. overflow: state.overflow ? 'hidden' : null }, style) }, other)), React.createElement("textarea", { "aria-hidden": true, className: props.className, readOnly: true, ref: shadowRef, tabIndex: -1, style: (0, _extends2.default)({}, styles.shadow, {}, style) })); }); process.env.NODE_ENV !== "production" ? TextareaAutosize.propTypes = { /** * @ignore */ className: _propTypes.default.string, /** * @ignore */ onChange: _propTypes.default.func, /** * @ignore */ placeholder: _propTypes.default.string, /** * Use `rowsMin` instead. The prop will be removed in v5. * * @deprecated */ rows: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.number]), /** * Maximum number of rows to display. */ rowsMax: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.number]), /** * Minimum number of rows to display. */ rowsMin: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.number]), /** * @ignore */ style: _propTypes.default.object, /** * @ignore */ value: _propTypes.default.any } : void 0; var _default = TextareaAutosize; exports.default = _default;
import extend from '../../../../extend'; import LineSegment from '../geom/LineSegment'; import LineSegmentIndex from './LineSegmentIndex'; import RobustLineIntersector from '../algorithm/RobustLineIntersector'; export default function TaggedLineStringSimplifier() { this.li = new RobustLineIntersector(); this.inputIndex = new LineSegmentIndex(); this.outputIndex = new LineSegmentIndex(); this.line = null; this.linePts = null; this.distanceTolerance = 0.0; let inputIndex = arguments[0], outputIndex = arguments[1]; this.inputIndex = inputIndex; this.outputIndex = outputIndex; } extend(TaggedLineStringSimplifier.prototype, { flatten: function (start, end) { var p0 = this.linePts[start]; var p1 = this.linePts[end]; var newSeg = new LineSegment(p0, p1); this.remove(this.line, start, end); this.outputIndex.add(newSeg); return newSeg; }, hasBadIntersection: function (parentLine, sectionIndex, candidateSeg) { if (this.hasBadOutputIntersection(candidateSeg)) return true; if (this.hasBadInputIntersection(parentLine, sectionIndex, candidateSeg)) return true; return false; }, setDistanceTolerance: function (distanceTolerance) { this.distanceTolerance = distanceTolerance; }, simplifySection: function (i, j, depth) { depth += 1; var sectionIndex = new Array(2).fill(null); if (i + 1 === j) { var newSeg = this.line.getSegment(i); this.line.addToResult(newSeg); return null; } var isValidToSimplify = true; if (this.line.getResultSize() < this.line.getMinimumSize()) { var worstCaseSize = depth + 1; if (worstCaseSize < this.line.getMinimumSize()) isValidToSimplify = false; } var distance = new Array(1).fill(null); var furthestPtIndex = this.findFurthestPoint(this.linePts, i, j, distance); if (distance[0] > this.distanceTolerance) isValidToSimplify = false; var candidateSeg = new LineSegment(); candidateSeg.p0 = this.linePts[i]; candidateSeg.p1 = this.linePts[j]; sectionIndex[0] = i; sectionIndex[1] = j; if (this.hasBadIntersection(this.line, sectionIndex, candidateSeg)) isValidToSimplify = false; if (isValidToSimplify) { var newSeg = this.flatten(i, j); this.line.addToResult(newSeg); return null; } this.simplifySection(i, furthestPtIndex, depth); this.simplifySection(furthestPtIndex, j, depth); }, hasBadOutputIntersection: function (candidateSeg) { var querySegs = this.outputIndex.query(candidateSeg); for (var i = querySegs.iterator(); i.hasNext(); ) { var querySeg = i.next(); if (this.hasInteriorIntersection(querySeg, candidateSeg)) { return true; } } return false; }, findFurthestPoint: function (pts, i, j, maxDistance) { var seg = new LineSegment(); seg.p0 = pts[i]; seg.p1 = pts[j]; var maxDist = -1.0; var maxIndex = i; for (var k = i + 1; k < j; k++) { var midPt = pts[k]; var distance = seg.distance(midPt); if (distance > maxDist) { maxDist = distance; maxIndex = k; } } maxDistance[0] = maxDist; return maxIndex; }, simplify: function (line) { this.line = line; this.linePts = line.getParentCoordinates(); this.simplifySection(0, this.linePts.length - 1, 0); }, remove: function (line, start, end) { for (var i = start; i < end; i++) { var seg = line.getSegment(i); this.inputIndex.remove(seg); } }, hasInteriorIntersection: function (seg0, seg1) { this.li.computeIntersection(seg0.p0, seg0.p1, seg1.p0, seg1.p1); return this.li.isInteriorIntersection(); }, hasBadInputIntersection: function (parentLine, sectionIndex, candidateSeg) { var querySegs = this.inputIndex.query(candidateSeg); for (var i = querySegs.iterator(); i.hasNext(); ) { var querySeg = i.next(); if (this.hasInteriorIntersection(querySeg, candidateSeg)) { if (TaggedLineStringSimplifier.isInLineSection(parentLine, sectionIndex, querySeg)) continue; return true; } } return false; }, interfaces_: function () { return []; }, getClass: function () { return TaggedLineStringSimplifier; } }); TaggedLineStringSimplifier.isInLineSection = function (line, sectionIndex, seg) { if (seg.getParent() !== line.getParent()) return false; var segIndex = seg.getIndex(); if (segIndex >= sectionIndex[0] && segIndex < sectionIndex[1]) return true; return false; };
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M2 22h20V2L2 22z" /><path d="M17 7L2 22h15V7z" /></React.Fragment> , 'NetworkCellOutlined');
import config from '../config'; import gulp from 'gulp'; import gulpif from 'gulp-if'; import sourcemaps from 'gulp-sourcemaps'; import sass from 'gulp-sass'; import handleErrors from '../util/handleErrors'; import browserSync from 'browser-sync'; import autoprefixer from 'gulp-autoprefixer'; gulp.task('styles', function () { const createSourcemap = !global.isProd || config.styles.prodSourcemap; return gulp.src(config.styles.src) .pipe(gulpif(createSourcemap, sourcemaps.init())) .pipe(sass({ sourceComments: !global.isProd, outputStyle: global.isProd ? 'compressed' : 'nested', includePaths: config.styles.sassIncludePaths })) .on('error', handleErrors) .pipe(autoprefixer({ browsers: ['last 2 versions', '> 1%', 'ie 8'] })) .pipe(gulpif( createSourcemap, sourcemaps.write( global.isProd ? './' : null )) ) .pipe(gulp.dest(config.styles.dest)) .pipe(browserSync.stream()); });
/** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ 'use strict'; const throws = () => { expect.assertions(2); expect(false).toBeTruthy(); }; const redeclare = () => { expect.assertions(1); expect(false).toBeTruthy(); expect.assertions(2); }; const noAssertions = () => { expect.assertions(0); expect(true).toBeTruthy(); }; const hasNoAssertions = () => { expect.hasAssertions(); }; describe('.assertions()', () => { it('throws', throws); it('throws on redeclare of assertion count', redeclare); it('throws on assertion', noAssertions); }); describe('.hasAssertions()', () => { it('throws when there are not assertions', hasNoAssertions); });
/*global define*/ /*global describe, it, expect*/ /*global jasmine*/ /*global beforeEach, afterEach*/ /*jslint white: true*/ define([ 'kbaseNarrativeDataList' ], function(Widget) { describe('Test the kbaseNarrativeDataList widget', function() { it('Should do things', function() { }); }); });
version https://git-lfs.github.com/spec/v1 oid sha256:c57e113e6c65c7fca0a5c5b8d409b644397b1521eeab8d08b186d486d2735586 size 4789
Joshfire.define([], function() { //memory cached var cache = {}; return { set:function(key,val) { cache[key]=val; }, get:function(key) { return cache[key]; }, clear:function() { cache = {}; }, remove:function(key) { delete cache[key]; }, disabled:false }; });
module.exports = (state = [], action) => { switch (action.type) { case `CREATE_REDIRECT`: return [...state, action.payload] default: return state } }
/*----------------------------------------------------------------------------- This Bot demonstrates how to implement simple multi-turns using waterfalls. By multi-turn we mean supporting scenarios where a user asks a question about something and then wants to ask a series of follow-up questions. To support this the bot needs to track the current context or topic of the conversation. This sample shows a simple way to use session.dialogState to do just that. In this specific sample we're using a LuisDialog to to give the bot a more natural language interface but there's nothing specific about multi-turn that requires the use of LUIS. The basic idea is that before we can answer a question we need to know the company to answer the question for. This is the “context” of the question. We’re using a LUIS model to identify the question the user would like asked and so for every intent handler we have the same two basic steps which we’re representing using a waterfall. The first step of our waterfall is a function called askCompany(). This function determines the current company in one of 3 ways. First it looks to see if the company was passed to us from an LUIS as an entity. This would be the case for a query like “when did microsoft ipo?”. If there was no company passed from LUIS then we check to see if we just answered a question about a company, if so we’ll use that as the current context. Finally, if the company wasn’t passed in and there is a current context then we’ll ask the user the name of the company to use. In any case the output of askCompany() is passed to the second step of the waterfall which is a function called answerQuestion(). This function checks to see if the company was passed in (the only way it wouldn’t be is if the user said ‘nevermind’ when asked for the company) and then sets that company to be the context for future questions and returns an answer for data that was asked for. # INSTALL THE MODEL The sample is coded to use a version of the LUIS models deployed to our LUIS account. This model is rate limited and intended for sample use only so if you would like to deploy your own copy of the model we've included it in the models folder. Import the model as an Appliction into your LUIS account (http://luis.ai) and assign the models service url to an environment variable called model. set model="MODEL_URL" # RUN THE BOT: Run the bot from the command line using "node app.js" and then try saying the following. Say: who founded google? Say: where are they located? Say: how can I contact microsoft? Say: when did they ipo? -----------------------------------------------------------------------------*/ var builder = require('../../'); var prompts = require('./prompts'); /** Use CrunchBot LUIS model for the root dialog. */ var model = process.env.model || 'https://api.projectoxford.ai/luis/v1/application?id=56c73d36-e6de-441f-b2c2-6ba7ea73a1bf&subscription-key=6d0966209c6e4f6b835ce34492f3e6d9&q='; var dialog = new builder.LuisDialog(model); var crunchBot = new builder.TextBot(); crunchBot.add('/', dialog); crunchBot.listenStdin(); /** Answer help related questions like "what can I say?" */ dialog.on('Help', builder.DialogAction.send(prompts.helpMessage)); /** Answer acquisition related questions like "how many companies has microsoft bought?" */ dialog.on('Acquisitions', [askCompany, answerQuestion('acquisitions', prompts.answerAcquisitions)]); /** Answer IPO date related questions like "when did microsoft go public?" */ dialog.on('IpoDate', [askCompany, answerQuestion('ipoDate', prompts.answerIpoDate)]); /** Answer headquarters related questions like "where is microsoft located?" */ dialog.on('Headquarters', [askCompany, answerQuestion('headquarters', prompts.answerHeadquarters)]); /** Answer description related questions like "tell me about microsoft" */ dialog.on('Description', [askCompany, answerQuestion('description', prompts.answerDescription)]); /** Answer founder related questions like "who started microsoft?" */ dialog.on('Founders', [askCompany, answerQuestion('founders', prompts.answerFounders)]); /** Answer website related questions like "how can I contact microsoft?" */ dialog.on('website', [askCompany, answerQuestion('website', prompts.answerWebsite)]); /** * This function the first step in the waterfall for intent handlers. It will use the company mentioned * in the users question if specified and valid. Otherwise it will use the last company a user asked * about. If it the company is missing it will prompt the user to pick one. */ function askCompany(session, args, next) { // First check to see if we either got a company from LUIS or have a an existing company // that we can multi-turn over. var company; var entity = builder.EntityRecognizer.findEntity(args.entities, 'CompanyName'); if (entity) { // The user specified a company so lets look it up to make sure its valid. // * This calls the underlying function Prompts.choice() uses to match a users response // to a list of choices. When you pass it an object it will use the field names as the // list of choices to match against. company = builder.EntityRecognizer.findBestMatch(data, entity.entity); } else if (session.dialogData.company) { // Just multi-turn over the existing company company = session.dialogData.company; } // Prompt the user to pick a ocmpany if they didn't specify a valid one. if (!company) { // Lets see if the user just asked for a company we don't know about. var txt = entity ? session.gettext(prompts.companyUnknown, { company: entity.entity }) : prompts.companyUnknown; // Prompt the user to pick a company from the list. They can also ask to cancel the operation. builder.Prompts.choice(session, txt, data); } else { // Great! pass the company to the next step in the waterfall which will answer the question. // * This will match the format of the response returned from Prompts.choice(). next({ response: company }) } } /** * This function generates a generic answer step for an intent handlers waterfall. The company to answer * a question about will be passed into the step and the specified field from the data will be returned to * the user using the specified answer template. */ function answerQuestion(field, answerTemplate) { return function (session, results) { // Check to see if we have a company. The user can cancel picking a company so IPromptResult.response // can be null. if (results.response) { // Save company for multi-turn case and compose answer var company = session.dialogData.company = results.response; var answer = { company: company.entity, value: data[company.entity][field] }; session.send(answerTemplate, answer); } else { session.send(prompts.cancel); } }; } /** * Sample data sourced from http://crunchbase.com on 3/18/2016 */ var data = { 'Microsoft': { acquisitions: 170, ipoDate: 'Mar 13, 1986', headquarters: 'Redmond, WA', description: 'Microsoft, a software corporation, develops licensed and support products and services ranging from personal use to enterprise application.', founders: 'Bill Gates and Paul Allen', website: 'http://www.microsoft.com' }, 'Apple': { acquisitions: 72, ipoDate: 'Dec 19, 1980', headquarters: 'Cupertino, CA', description: 'Apple is a multinational corporation that designs, manufactures, and markets consumer electronics, personal computers, and software.', founders: 'Kevin Harvey, Steve Wozniak, Steve Jobs, and Ron Wayne', website: 'http://www.apple.com' }, 'Google': { acquisitions: 39, ipoDate: 'Aug 19, 2004', headquarters: 'Mountain View, CA', description: 'Google is a multinational corporation that is specialized in internet-related services and products.', founders: 'Baris Gultekin, Michoel Ogince, Sergey Brin, and Larry Page', website: 'http://www.google.com' }, 'Amazon': { acquisitions: 58, ipoDate: 'May 15, 1997', headquarters: 'Seattle, WA', description: 'Amazon.com is an international e-commerce website for consumers, sellers, and content creators.', founders: 'Sachin Agarwal and Jeff Bezos', website: 'http://amazon.com' } };
'use strict'; const gulp = require('gulp'); const uglify = require('gulp-uglify'); const concat = require('gulp-concat'); gulp.task('build', ['clean'], function () { return gulp .src(['src/resize.js', 'src/*.js']) .pipe(concat('angular-images-resizer.js')) .pipe(uglify()) .pipe(gulp.dest('./')); }); gulp.task('build:ghPage', ['clean:dist', 'ngdocs', 'build:ghPage:docs', 'build:ghPage:node_modules'], function () { return gulp .src([ 'example/**/*', 'docs', 'angular-images-resizer.js' ]) .pipe(gulp.dest('./dist/')); }); gulp.task('build:ghPage:docs', function () { return gulp .src('docs/**/*') .pipe(gulp.dest('./dist/docs')); }); gulp.task('build:ghPage:node_modules', function () { return gulp .src([ 'node_modules/angular-animate/*', 'node_modules/angular-ui-router/**/*', 'node_modules/angular-material/*', 'node_modules/angular/*', 'node_modules/angular-aria/*' ], { base: './' }) .pipe(gulp.dest('./dist')); });
import { AppRegistry } from 'react-native'; import Basic from './Basic'; AppRegistry.registerComponent('Basic', () => Basic);
function edit_tag(m) { var name, slug, tr; name = jQuery("#name" + m).html(); slug = jQuery("#slug" + m).html(); tr = ' <td id="td_check_'+m+'" ></td> <td id="td_id_'+m+'" ></td> <td id="td_name_'+m+'" class="edit_input"><input id="edit_tagname" name="tagname'+m+'" class="input_th2" type="text" value="'+name+'"></td> <td id="td_slug_'+m+'" class="edit_input"><input id="edit_slug" class="input_th2" name="slug'+m+'" type="text" value="'+slug+'"></td> <td id="td_count_'+m+'" ></td> <td id="td_edit_'+m+'" class="table_big_col"><a class="button-primary button button-small" onclick="save_tag('+m+')" >Save Tag </a></td><td id="td_delete_'+m+'" class="table_big_col" ></td> '; jQuery("#tr_" + m).html(tr); jQuery("#td_id_" + m).attr('class', 'table_big_col'); } function save_tag(tag_id) { var tagname=jQuery('input[name=tagname'+tag_id+']').val(); var slug = jQuery('input[name=slug'+tag_id+']').val(); var datas = "tagname="+tagname+"&"+"slug="+slug+"&"+"tag_id="+tag_id; var td_check,td_name,td_slug,td_count,td_edit,td_delete,massege; jQuery.ajax({ type: "POST", url: ajax_url + "=bwg_edit_tag", data: datas, success: function(html) { var tagname_slug=html; var array = tagname_slug.split("."); if (array[0] == "The slug must be unique.") { massege = array[0]; } else { massege = "Item Succesfully Saved."; jQuery("#td_check_" + tag_id).attr('class', 'table_small_col check-column'); td_check='<input id="check_'+tag_id+'" name="check_'+tag_id+'" type="checkbox" />'; jQuery("#td_check_" + tag_id).html(td_check); jQuery("#td_id_" + tag_id).attr('class', 'table_small_col'); jQuery("#td_id_" + tag_id).html(tag_id); jQuery("#td_name_" + tag_id).removeClass(); td_name='<a class="pointer" id="name'+tag_id+'" onclick="edit_tag('+tag_id+')" title="Edit">'+array[0]+'</a>'; jQuery("#td_name_" + tag_id).html(td_name); jQuery("#td_slug_" + tag_id).removeClass(); td_slug='<a class="pointer" id="slug'+tag_id+'" onclick="edit_tag('+tag_id+')" title="Edit">'+array[1]+'</a>'; jQuery("#td_slug_" + tag_id).html(td_slug); jQuery("#td_count_" + tag_id).attr('class', 'table_big_col'); td_count='<a class="pointer" id="count'+tag_id+'" onclick="edit_tag('+tag_id+')" title="Edit">'+array[2]+'</a>'; jQuery("#td_count_" + tag_id).html(td_count); td_edit='<a class="pointer" onclick="edit_tag('+tag_id+')" >Edit</a>'; jQuery("#td_edit_" + tag_id).html(td_edit); var func1="spider_set_input_value('task', 'delete');"; var func2="spider_set_input_value('current_id', "+tag_id+");"; var func3="spider_form_submit('event', 'tags_form')"; td_delete='<a class="pointer" onclick="'+func1+func2+func3+'" >Delete</a>'; jQuery("#td_delete_" + tag_id).html(td_delete); } if ((jQuery( ".updated" ) && jQuery( ".updated" ).attr("id")!='wordpress_message_2' ) || (jQuery( ".error" ) && jQuery( ".error" ).css("display")=="block")) { if (jQuery( ".updated" ) && jQuery( ".updated" ).attr("id")!='wordpress_message_2' ){ jQuery(".updated").html("<strong><p>"+massege+"</p></strong>"); } else { jQuery(".error").html("<strong><p>"+massege+"</p></strong>"); jQuery(".error").attr('class', 'updated'); } } else { jQuery("#wordpress_message_1").css("display", "block"); } } }); } var bwg_save_count = 50; function spider_ajax_save(form_id, tr_group) { var ajax_task = jQuery("#ajax_task").val(); if (!tr_group) { var tr_group = 1; } else if (ajax_task == 'ajax_apply' || ajax_task == 'ajax_save') { ajax_task = ''; } var bwg_nonce = jQuery("#bwg_nonce").val(); var name = jQuery("#name").val(); var slug = jQuery("#slug").val(); if ((typeof tinyMCE != "undefined") && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden() && tinyMCE.activeEditor.getContent) { var description = tinyMCE.activeEditor.getContent(); } else { var description = jQuery("#description").val(); } var preview_image = jQuery("#preview_image").val(); var published = jQuery("input[name=published]:checked").val(); var search_value = jQuery("#search_value").val(); var current_id = jQuery("#current_id").val(); var page_number = jQuery("#page_number").val(); var search_or_not = jQuery("#search_or_not").val(); var ids_string = jQuery("#ids_string").val(); var image_order_by = jQuery("#image_order_by").val(); var asc_or_desc = jQuery("#asc_or_desc").val(); var image_current_id = jQuery("#image_current_id").val(); ids_array = ids_string.split(","); var tr_count = ids_array.length; if (tr_count > bwg_save_count) { // Remove items form begin and end of array. ids_array.splice(tr_group * bwg_save_count, ids_array.length); ids_array.splice(0, (tr_group - 1) * bwg_save_count); ids_string = ids_array.join(","); } var post_data = {}; post_data["bwg_nonce"] = bwg_nonce; post_data["name"] = name; post_data["slug"] = slug; post_data["description"] = description; post_data["preview_image"] = preview_image; post_data["published"] = published; post_data["search_value"] = search_value; post_data["current_id"] = current_id; post_data["page_number"] = page_number; post_data["image_order_by"] = image_order_by; post_data["asc_or_desc"] = asc_or_desc; post_data["ids_string"] = ids_string; post_data["task"] = "ajax_search"; post_data["ajax_task"] = ajax_task; post_data["image_current_id"] = image_current_id; post_data["image_width"] = jQuery("#image_width").val(); post_data["image_height"] = jQuery("#image_height").val(); var flag = false; if (jQuery("#check_all_items").attr('checked') == 'checked') { post_data["check_all_items"] = jQuery("#check_all_items").val(); post_data["added_tags_select_all"] = jQuery("#added_tags_select_all").val(); flag = true; jQuery('#check_all_items').attr('checked', false); } for (var i in ids_array) { if (ids_array.hasOwnProperty(i) && ids_array[i]) { if (jQuery("#check_" + ids_array[i]).attr('checked') == 'checked') { post_data["check_" + ids_array[i]] = jQuery("#check_" + ids_array[i]).val(); flag = true; } post_data["input_filename_" + ids_array[i]] = jQuery("#input_filename_" + ids_array[i]).val(); post_data["image_url_" + ids_array[i]] = jQuery("#image_url_" + ids_array[i]).val(); post_data["thumb_url_" + ids_array[i]] = jQuery("#thumb_url_" + ids_array[i]).val(); post_data["image_description_" + ids_array[i]] = jQuery("#image_description_" + ids_array[i]).val(); post_data["image_alt_text_" + ids_array[i]] = jQuery("#image_alt_text_" + ids_array[i]).val(); post_data["redirect_url_" + ids_array[i]] = jQuery("#redirect_url_" + ids_array[i]).val(); post_data["input_date_modified_" + ids_array[i]] = jQuery("#input_date_modified_" + ids_array[i]).val(); post_data["input_size_" + ids_array[i]] = jQuery("#input_size_" + ids_array[i]).val(); post_data["input_filetype_" + ids_array[i]] = jQuery("#input_filetype_" + ids_array[i]).val(); post_data["input_resolution_" + ids_array[i]] = jQuery("#input_resolution_" + ids_array[i]).val(); post_data["input_crop_" + ids_array[i]] = jQuery("#input_crop_" + ids_array[i]).val(); post_data["order_input_" + ids_array[i]] = jQuery("#order_input_" + ids_array[i]).val(); post_data["tags_" + ids_array[i]] = jQuery("#tags_" + ids_array[i]).val(); } } // Loading. jQuery('#opacity_div').show(); jQuery('#loading_div').show(); jQuery.post( jQuery('#' + form_id).action, post_data, function (data) { var str = jQuery(data).find("#current_id").val(); jQuery("#current_id").val(str); } ).success(function (data, textStatus, errorThrown) { if (tr_count > bwg_save_count * tr_group) { spider_ajax_save(form_id, ++tr_group); return; } else { var str = jQuery(data).find('#images_table').html(); jQuery('#images_table').html(str); var str = jQuery(data).find('.tablenav.top').html(); jQuery('.tablenav.top').html(str); var str = jQuery(data).find('.tablenav.bottom').html(); jQuery('.tablenav.bottom').html(str); jQuery("#show_hide_weights").val("Hide order column"); spider_show_hide_weights(); spider_run_checkbox(); if (ajax_task == 'ajax_apply') { jQuery('#message_div').html("<strong><p>Items Succesfully Saved.</p></strong>"); jQuery('#message_div').show(); } else if (ajax_task == 'recover') { jQuery('#draganddrop').html("<strong><p>Item Succesfully Recovered.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_publish') { jQuery('#draganddrop').html("<strong><p>Item Succesfully Published.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_unpublish') { jQuery('#draganddrop').html("<strong><p>Item Succesfully Unpublished.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_delete') { jQuery('#draganddrop').html("<strong><p>Item Succesfully Deleted.</p></strong>"); jQuery('#draganddrop').show(); } else if (!flag && ((ajax_task == 'image_publish_all') || (ajax_task == 'image_unpublish_all') || (ajax_task == 'image_delete_all') || (ajax_task == 'image_set_watermark') || (ajax_task == 'image_recover_all') || (ajax_task == 'image_resize'))) { jQuery('#draganddrop').html("<strong><p>You must select at least one item.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_publish_all') { jQuery('#draganddrop').html("<strong><p>Items Succesfully Published.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_unpublish_all') { jQuery('#draganddrop').html("<strong><p>Items Succesfully Unpublished.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_delete_all') { jQuery('#draganddrop').html("<strong><p>Items Succesfully Deleted.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_set_watermark') { jQuery('#draganddrop').html("<strong><p>Watermarks Succesfully Set.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_resize') { jQuery('#draganddrop').html("<strong><p>Images Succesfully Resized.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_recover_all') { jQuery('#draganddrop').html("<strong><p>Items Succesfully Reset.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'search') { jQuery('#message_div').html(""); jQuery('#message_div').hide(); } else { jQuery('#draganddrop').html("<strong><p>Items Succesfully Saved.</p></strong>"); jQuery('#draganddrop').show(); } if (ajax_task == "ajax_save") { jQuery('#' + form_id).submit(); } jQuery('#opacity_div').hide(); jQuery('#loading_div').hide(); } }); // if (event.preventDefault) { // event.preventDefault(); // } // else { // event.returnValue = false; // } return false; } function spider_run_checkbox() { jQuery("tbody").children().children(".check-column").find(":checkbox").click(function (l) { if ("undefined" == l.shiftKey) { return true } if (l.shiftKey) { if (!i) { return true } d = jQuery(i).closest("form").find(":checkbox"); f = d.index(i); j = d.index(this); h = jQuery(this).prop("checked"); if (0 < f && 0 < j && f != j) { d.slice(f, j).prop("checked", function () { if (jQuery(this).closest("tr").is(":visible")) { return h } return false }) } } i = this; var k = jQuery(this).closest("tbody").find(":checkbox").filter(":visible").not(":checked"); jQuery(this).closest("table").children("thead, tfoot").find(":checkbox").prop("checked", function () { return(0 == k.length) }); return true }); jQuery("thead, tfoot").find(".check-column :checkbox").click(function (m) { var n = jQuery(this).prop("checked"), l = "undefined" == typeof toggleWithKeyboard ? false : toggleWithKeyboard, k = m.shiftKey || l; jQuery(this).closest("table").children("tbody").filter(":visible").children().children(".check-column").find(":checkbox").prop("checked", function () { if (jQuery(this).is(":hidden")) { return false } if (k) { return jQuery(this).prop("checked") } else { if (n) { return true } } return false }); jQuery(this).closest("table").children("thead, tfoot").filter(":visible").children().children(".check-column").find(":checkbox").prop("checked", function () { if (k) { return false } else { if (n) { return true } } return false }) }); } // Set value by id. function spider_set_input_value(input_id, input_value) { if (document.getElementById(input_id)) { document.getElementById(input_id).value = input_value; } } // Submit form by id. function spider_form_submit(event, form_id) { if (document.getElementById(form_id)) { document.getElementById(form_id).submit(); } if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } } // Check if required field is empty. function spider_check_required(id, name) { if (jQuery('#' + id).val() == '') { alert(name + '* field is required.'); jQuery('#' + id).attr('style', 'border-color: #FF0000;'); jQuery('#' + id).focus(); jQuery('html, body').animate({ scrollTop:jQuery('#' + id).offset().top - 200 }, 500); return true; } else { return false; } } // Show/hide order column and drag and drop column. function spider_show_hide_weights() { if (jQuery("#show_hide_weights").val() == 'Show order column') { jQuery(".connectedSortable").css("cursor", "default"); jQuery("#tbody_arr").find(".handle").hide(0); jQuery("#th_order").show(0); jQuery("#tbody_arr").find(".spider_order").show(0); jQuery("#show_hide_weights").val("Hide order column"); if (jQuery("#tbody_arr").sortable()) { jQuery("#tbody_arr").sortable("disable"); } } else { jQuery(".connectedSortable").css("cursor", "move"); var page_number; if (jQuery("#page_number") && jQuery("#page_number").val() != '' && jQuery("#page_number").val() != 1) { page_number = (jQuery("#page_number").val() - 1) * 20 + 1; } else { page_number = 1; } jQuery("#tbody_arr").sortable({ handle:".connectedSortable", connectWith:".connectedSortable", update:function (event, tr) { jQuery("#draganddrop").attr("style", ""); jQuery("#draganddrop").html("<strong><p>Changes made in this table should be saved.</p></strong>"); var i = page_number; jQuery('.spider_order').each(function (e) { if (jQuery(this).find('input').val()) { jQuery(this).find('input').val(i++); } }); } });//.disableSelection(); jQuery("#tbody_arr").sortable("enable"); jQuery("#tbody_arr").find(".handle").show(0); jQuery("#tbody_arr").find(".handle").attr('class', 'handle connectedSortable'); jQuery("#th_order").hide(0); jQuery("#tbody_arr").find(".spider_order").hide(0); jQuery("#show_hide_weights").val("Show order column"); } } // Check all items. function spider_check_all_items() { spider_check_all_items_checkbox(); // if (!jQuery('#check_all').attr('checked')) { jQuery('#check_all').trigger('click'); // } } function spider_check_all_items_checkbox() { if (jQuery('#check_all_items').attr('checked')) { jQuery('#check_all_items').attr('checked', false); jQuery('#draganddrop').hide(); } else { var saved_items = (parseInt(jQuery(".displaying-num").html()) ? parseInt(jQuery(".displaying-num").html()) : 0); var added_items = (jQuery('input[id^="check_pr_"]').length ? parseInt(jQuery('input[id^="check_pr_"]').length) : 0); var items_count = added_items + saved_items; jQuery('#check_all_items').attr('checked', true); if (items_count) { jQuery('#draganddrop').html("<strong><p>Selected " + items_count + " item" + (items_count > 1 ? "s" : "") + ".</p></strong>"); jQuery('#draganddrop').show(); } } } function spider_check_all(current) { if (!jQuery(current).attr('checked')) { jQuery('#check_all_items').attr('checked', false); jQuery('#draganddrop').hide(); } } // Set uploader to button class. function spider_uploader(button_id, input_id, delete_id, img_id) { if (typeof img_id == 'undefined') { img_id = ''; } jQuery(function () { var formfield = null; window.original_send_to_editor = window.send_to_editor; window.send_to_editor = function (html) { if (formfield) { var fileurl = jQuery('img', html).attr('src'); if (!fileurl) { var exploded_html; var exploded_html_askofen; exploded_html = html.split('"'); for (i = 0; i < exploded_html.length; i++) { exploded_html_askofen = exploded_html[i].split("'"); } for (i = 0; i < exploded_html.length; i++) { for (j = 0; j < exploded_html_askofen.length; j++) { if (exploded_html_askofen[j].search("href")) { fileurl = exploded_html_askofen[i + 1]; break; } } } if (img_id != '') { alert('You must select an image file.'); tb_remove(); return; } window.parent.document.getElementById(input_id).value = fileurl; window.parent.document.getElementById(button_id).style.display = "none"; window.parent.document.getElementById(input_id).style.display = "inline-block"; window.parent.document.getElementById(delete_id).style.display = "inline-block"; } else { if (img_id == '') { alert('You must select an audio file.'); tb_remove(); return; } window.parent.document.getElementById(input_id).value = fileurl; window.parent.document.getElementById(button_id).style.display = "none"; window.parent.document.getElementById(delete_id).style.display = "inline-block"; if ((img_id != '') && window.parent.document.getElementById(img_id)) { window.parent.document.getElementById(img_id).src = fileurl; window.parent.document.getElementById(img_id).style.display = "inline-block"; } } formfield.val(fileurl); tb_remove(); } else { window.original_send_to_editor(html); } formfield = null; }; formfield = jQuery(this).parent().parent().find(".url_input"); tb_show('', 'media-upload.php?type=image&TB_iframe=true'); jQuery('#TB_overlay,#TB_closeWindowButton').bind("click", function () { formfield = null; }); return false; }); } // Remove uploaded file. function spider_remove_url(button_id, input_id, delete_id, img_id) { if (typeof img_id == 'undefined') { img_id = ''; } if (document.getElementById(button_id)) { document.getElementById(button_id).style.display = ''; } if (document.getElementById(input_id)) { document.getElementById(input_id).value = ''; document.getElementById(input_id).style.display = 'none'; } if (document.getElementById(delete_id)) { document.getElementById(delete_id).style.display = 'none'; } if ((img_id != '') && window.parent.document.getElementById(img_id)) { document.getElementById(img_id).src = ''; document.getElementById(img_id).style.display = 'none'; } } function spider_reorder_items(tbody_id) { jQuery("#" + tbody_id).sortable({ handle:".connectedSortable", connectWith:".connectedSortable", update:function (event, tr) { spider_sortt(tbody_id); } }); } function spider_sortt(tbody_id) { var str = ""; var counter = 0; jQuery("#" + tbody_id).children().each(function () { str += ((jQuery(this).attr("id")).substr(3) + ","); counter++; }); jQuery("#albums_galleries").val(str); if (!counter) { document.getElementById("table_albums_galleries").style.display = "none"; } } function spider_remove_row(tbody_id, event, obj) { var span = obj; var tr = jQuery(span).closest("tr"); jQuery(tr).remove(); spider_sortt(tbody_id); } function spider_jslider(idtaginp) { jQuery(function () { var inpvalue = jQuery("#" + idtaginp).val(); if (inpvalue == "") { inpvalue = 50; } jQuery("#slider-" + idtaginp).slider({ range:"min", value:inpvalue, min:1, max:100, slide:function (event, ui) { jQuery("#" + idtaginp).val("" + ui.value); } }); jQuery("#" + idtaginp).val("" + jQuery("#slider-" + idtaginp).slider("value")); }); } function spider_get_items(e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } var trackIds = []; var titles = []; var types = []; var tbody = document.getElementById('tbody_albums_galleries'); var trs = tbody.getElementsByTagName('tr'); for (j = 0; j < trs.length; j++) { i = trs[j].getAttribute('id').substr(3); if (document.getElementById('check_' + i).checked) { trackIds.push(document.getElementById("id_" + i).innerHTML); titles.push(document.getElementById("a_" + i).innerHTML); types.push(document.getElementById("url_" + i).innerHTML == "Album" ? 1 : 0); } } window.parent.bwg_add_items(trackIds, titles, types); } function bwg_check_checkboxes() { var flag = false; var ids_string = jQuery("#ids_string").val(); ids_array = ids_string.split(","); for (var i in ids_array) { if (ids_array.hasOwnProperty(i) && ids_array[i]) { if (jQuery("#check_" + ids_array[i]).attr('checked') == 'checked') { flag = true; } } } if(flag) { if(jQuery(".buttons_div_right").find("a").hasClass( "thickbox" )) { return true; } else { jQuery(".buttons_div_right").find("a").addClass( "thickbox thickbox-preview" ); jQuery('#draganddrop').hide(); return true; } } else { jQuery(".buttons_div_right").find("a").removeClass( "thickbox thickbox-preview" ); jQuery('#draganddrop').html("<strong><p>You must select at least one item.</p></strong>"); jQuery('#draganddrop').show(); return false; } } function bwg_get_tags(image_id, e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } var tagIds = []; var titles = []; var tbody = document.getElementById('tbody_arr'); var trs = tbody.getElementsByTagName('tr'); for (j = 0; j < trs.length; j++) { i = trs[j].getAttribute('id').substr(3); if (document.getElementById('check_' + i).checked) { tagIds.push(i); titles.push(document.getElementById("a_" + i).innerHTML); } } window.parent.bwg_add_tag(image_id, tagIds, titles); } function bwg_add_tag(image_id, tagIds, titles) { if (image_id == '0') { var flag = false; var ids_string = jQuery("#ids_string").val(); ids_array = ids_string.split(","); if (jQuery("#check_all_items").attr("checked")) { var added_tags = ''; for (i = 0; i < tagIds.length; i++) { added_tags = added_tags + tagIds[i] + ','; } jQuery("#added_tags_select_all").val(added_tags); } } else { image_id = image_id + ','; ids_array = image_id.split(","); var flag = true; } for (var i in ids_array) { if (ids_array.hasOwnProperty(i) && ids_array[i]) { if (jQuery("#check_" + ids_array[i]).attr('checked') == 'checked' || flag) { image_id = ids_array[i]; var tag_ids = document.getElementById('tags_' + image_id).value; tags_array = tag_ids.split(','); var div = document.getElementById('tags_div_' + image_id); var counter = 0; for (i = 0; i < tagIds.length; i++) { if (tags_array.indexOf(tagIds[i]) == -1) { tag_ids = tag_ids + tagIds[i] + ','; var tag_div = document.createElement('div'); tag_div.setAttribute('id', image_id + "_tag_" + tagIds[i]); tag_div.setAttribute('class', "tag_div"); div.appendChild(tag_div); var tag_name_span = document.createElement('span'); tag_name_span.setAttribute('class', "tag_name"); tag_name_span.innerHTML = titles[i]; tag_div.appendChild(tag_name_span); var tag_delete_span = document.createElement('span'); tag_delete_span.setAttribute('class', "spider_delete_img_small"); tag_delete_span.setAttribute('onclick', "bwg_remove_tag('" + tagIds[i] + "', '" + image_id + "')"); tag_delete_span.setAttribute('style', "float:right;"); tag_div.appendChild(tag_delete_span); counter++; } } document.getElementById('tags_' + image_id).value = tag_ids; if (counter) { div.style.display = "block"; } } } } tb_remove(); } function bwg_remove_tag(tag_id, image_id) { if (jQuery('#' + image_id + '_tag_' + tag_id)) { jQuery('#' + image_id + '_tag_' + tag_id).remove(); var tag_ids_string = jQuery("#tags_" + image_id).val(); tag_ids_string = tag_ids_string.replace(tag_id + ',', ''); jQuery("#tags_" + image_id).val(tag_ids_string); if (jQuery("#tags_" + image_id).val() == '') { jQuery("#tags_div_" + image_id).hide(); } } } function preview_watermark() { setTimeout(function() { watermark_type = window.parent.document.getElementById('watermark_type_text').checked; if (watermark_type) { watermark_text = document.getElementById('watermark_text').value; watermark_link = document.getElementById('watermark_link').value; watermark_font_size = document.getElementById('watermark_font_size').value; watermark_font = document.getElementById('watermark_font').value; watermark_color = document.getElementById('watermark_color').value; watermark_opacity = document.getElementById('watermark_opacity').value; watermark_position = jQuery("input[name=watermark_position]:checked").val().split('-'); document.getElementById("preview_watermark").style.verticalAlign = watermark_position[0]; document.getElementById("preview_watermark").style.textAlign = watermark_position[1]; stringHTML = (watermark_link ? '<a href="' + watermark_link + '" target="_blank" style="text-decoration: none;' : '<span style="cursor:default;') + 'margin:4px;font-size:' + watermark_font_size + 'px;font-family:' + watermark_font + ';color:#' + watermark_color + ';opacity:' + (watermark_opacity / 100) + ';" class="non_selectable">' + watermark_text + (watermark_link ? '</a>' : '</span>'); document.getElementById("preview_watermark").innerHTML = stringHTML; } watermark_type = window.parent.document.getElementById('watermark_type_image').checked; if (watermark_type) { watermark_url = document.getElementById('watermark_url').value; watermark_link = document.getElementById('watermark_link').value; watermark_width = document.getElementById('watermark_width').value; watermark_height = document.getElementById('watermark_height').value; watermark_opacity = document.getElementById('watermark_opacity').value; watermark_position = jQuery("input[name=watermark_position]:checked").val().split('-'); document.getElementById("preview_watermark").style.verticalAlign = watermark_position[0]; document.getElementById("preview_watermark").style.textAlign = watermark_position[1]; stringHTML = (watermark_link ? '<a href="' + watermark_link + '" target="_blank">' : '') + '<img class="non_selectable" src="' + watermark_url + '" style="margin:0 4px 0 4px;max-width:' + watermark_width + 'px;max-height:' + watermark_height + 'px;opacity:' + (watermark_opacity / 100) + ';" />' + (watermark_link ? '</a>' : ''); document.getElementById("preview_watermark").innerHTML = stringHTML; } }, 50); } function preview_built_in_watermark() { setTimeout(function(){ watermark_type = window.parent.document.getElementById('built_in_watermark_type_text').checked; if (watermark_type) { watermark_text = document.getElementById('built_in_watermark_text').value; watermark_font_size = document.getElementById('built_in_watermark_font_size').value * 400 / 500; watermark_font = 'bwg_' + document.getElementById('built_in_watermark_font').value.replace('.TTF', '').replace('.ttf', ''); watermark_color = document.getElementById('built_in_watermark_color').value; watermark_opacity = document.getElementById('built_in_watermark_opacity').value; watermark_position = jQuery("input[name=built_in_watermark_position]:checked").val().split('-'); document.getElementById("preview_built_in_watermark").style.verticalAlign = watermark_position[0]; document.getElementById("preview_built_in_watermark").style.textAlign = watermark_position[1]; stringHTML = '<span style="cursor:default;margin:4px;font-size:' + watermark_font_size + 'px;font-family:' + watermark_font + ';color:#' + watermark_color + ';opacity:' + (watermark_opacity / 100) + ';" class="non_selectable">' + watermark_text + '</span>'; document.getElementById("preview_built_in_watermark").innerHTML = stringHTML; } watermark_type = window.parent.document.getElementById('built_in_watermark_type_image').checked; if (watermark_type) { watermark_url = document.getElementById('built_in_watermark_url').value; watermark_size = document.getElementById('built_in_watermark_size').value; watermark_position = jQuery("input[name=built_in_watermark_position]:checked").val().split('-'); document.getElementById("preview_built_in_watermark").style.verticalAlign = watermark_position[0]; document.getElementById("preview_built_in_watermark").style.textAlign = watermark_position[1]; stringHTML = '<img class="non_selectable" src="' + watermark_url + '" style="margin:0 4px 0 4px;max-width:95%;width:' + watermark_size + '%;" />'; document.getElementById("preview_built_in_watermark").innerHTML = stringHTML; } }, 50); } function bwg_watermark(watermark_type) { jQuery("#" + watermark_type).attr('checked', 'checked'); jQuery("#tr_watermark_url").css('display', 'none'); jQuery("#tr_watermark_width_height").css('display', 'none'); jQuery("#tr_watermark_opacity").css('display', 'none'); jQuery("#tr_watermark_text").css('display', 'none'); jQuery("#tr_watermark_link").css('display', 'none'); jQuery("#tr_watermark_font_size").css('display', 'none'); jQuery("#tr_watermark_font").css('display', 'none'); jQuery("#tr_watermark_color").css('display', 'none'); jQuery("#tr_watermark_position").css('display', 'none'); jQuery("#tr_watermark_preview").css('display', 'none'); jQuery("#preview_watermark").css('display', 'none'); switch (watermark_type) { case 'watermark_type_text': { jQuery("#tr_watermark_opacity").css('display', ''); jQuery("#tr_watermark_text").css('display', ''); jQuery("#tr_watermark_link").css('display', ''); jQuery("#tr_watermark_font_size").css('display', ''); jQuery("#tr_watermark_font").css('display', ''); jQuery("#tr_watermark_color").css('display', ''); jQuery("#tr_watermark_position").css('display', ''); jQuery("#tr_watermark_preview").css('display', ''); jQuery("#preview_watermark").css('display', 'table-cell'); break; } case 'watermark_type_image': { jQuery("#tr_watermark_url").css('display', ''); jQuery("#tr_watermark_link").css('display', ''); jQuery("#tr_watermark_width_height").css('display', ''); jQuery("#tr_watermark_opacity").css('display', ''); jQuery("#tr_watermark_position").css('display', ''); jQuery("#tr_watermark_preview").css('display', ''); jQuery("#preview_watermark").css('display', 'table-cell'); break; } } } function bwg_built_in_watermark(watermark_type) { jQuery("#built_in_" + watermark_type).attr('checked', 'checked'); jQuery("#tr_built_in_watermark_url").css('display', 'none'); jQuery("#tr_built_in_watermark_size").css('display', 'none'); jQuery("#tr_built_in_watermark_opacity").css('display', 'none'); jQuery("#tr_built_in_watermark_text").css('display', 'none'); jQuery("#tr_built_in_watermark_font_size").css('display', 'none'); jQuery("#tr_built_in_watermark_font").css('display', 'none'); jQuery("#tr_built_in_watermark_color").css('display', 'none'); jQuery("#tr_built_in_watermark_position").css('display', 'none'); jQuery("#tr_built_in_watermark_preview").css('display', 'none'); jQuery("#preview_built_in_watermark").css('display', 'none'); switch (watermark_type) { case 'watermark_type_text': { jQuery("#tr_built_in_watermark_opacity").css('display', ''); jQuery("#tr_built_in_watermark_text").css('display', ''); jQuery("#tr_built_in_watermark_font_size").css('display', ''); jQuery("#tr_built_in_watermark_font").css('display', ''); jQuery("#tr_built_in_watermark_color").css('display', ''); jQuery("#tr_built_in_watermark_position").css('display', ''); jQuery("#tr_built_in_watermark_preview").css('display', ''); jQuery("#preview_built_in_watermark").css('display', 'table-cell'); break; } case 'watermark_type_image': { jQuery("#tr_built_in_watermark_url").css('display', ''); jQuery("#tr_built_in_watermark_size").css('display', ''); jQuery("#tr_built_in_watermark_position").css('display', ''); jQuery("#tr_built_in_watermark_preview").css('display', ''); jQuery("#preview_built_in_watermark").css('display', 'table-cell'); break; } } } function bwg_change_option_type(type) { type = (type == '' ? 1 : type); document.getElementById('type').value = type; for (var i = 1; i <= 9; i++) { if (i == type) { document.getElementById('div_content_' + i).style.display = 'block'; document.getElementById('div_' + i).style.background = '#C5C5C5'; } else { document.getElementById('div_content_' + i).style.display = 'none'; document.getElementById('div_' + i).style.background = '#F4F4F4'; } } document.getElementById('display_panel').style.display = 'inline-block'; } function bwg_inputs() { jQuery(".spider_int_input").keypress(function (event) { var chCode1 = event.which || event.paramlist_keyCode; if (chCode1 > 31 && (chCode1 < 48 || chCode1 > 57) && (chCode1 != 46) && (chCode1 != 45)) { return false; } return true; }); } function bwg_enable_disable(display, id, current) { jQuery("#" + current).attr('checked', 'checked'); jQuery("#" + id).css('display', display); if(id == 'tr_slideshow_title_position') { jQuery("#tr_slideshow_full_width_title").css('display', display); } } function bwg_popup_fullscreen(num) { if (num) { jQuery("#tr_popup_dimensions").css('display', 'none'); } else { jQuery("#tr_popup_dimensions").css('display', ''); } } function bwg_change_album_view_type(type) { if (type == 'thumbnail') { jQuery("#album_thumb_dimensions").html('Album thumb dimensions: '); jQuery("#album_thumb_dimensions_x").css('display', ''); jQuery("#album_thumb_height").css('display', ''); } else { jQuery("#album_thumb_dimensions").html('Album thumb width: '); jQuery("#album_thumb_dimensions_x").css('display', 'none'); jQuery("#album_thumb_height").css('display', 'none'); } } function spider_check_isnum(e) { var chCode1 = e.which || e.paramlist_keyCode; if (chCode1 > 31 && (chCode1 < 48 || chCode1 > 57) && (chCode1 != 46) && (chCode1 != 45)) { return false; } return true; } function bwg_change_theme_type(type) { var button_name = jQuery("#button_name").val(); jQuery("#Thumbnail").hide(); jQuery("#Masonry").hide(); jQuery("#Mosaic").hide(); jQuery("#Slideshow").hide(); jQuery("#Compact_album").hide(); jQuery("#Extended_album").hide(); jQuery("#Masonry_album").hide(); jQuery("#Image_browser").hide(); jQuery("#Blog_style").hide(); jQuery("#Lightbox").hide(); jQuery("#Navigation").hide(); jQuery("#" + type).show(); jQuery("#type_menu").show(); jQuery(".spider_fieldset").show(); jQuery("#current_type").val(type); jQuery("#type_Thumbnail").attr("style", "background-color: #F4F4F4;"); jQuery("#type_Masonry").attr("style", "background-color: #F4F4F4; opacity: 0.4; filter: Alpha(opacity=40);"); jQuery("#type_Mosaic").attr("style", "background-color: #F4F4F4; opacity: 0.4; filter: Alpha(opacity=40);"); jQuery("#type_Slideshow").attr("style", "background-color: #F4F4F4;"); jQuery("#type_Compact_album").attr("style", "background-color: #F4F4F4;"); jQuery("#type_Extended_album").attr("style", "background-color: #F4F4F4;"); jQuery("#type_Masonry_album").attr("style", "background-color: #F4F4F4; opacity: 0.4; filter: Alpha(opacity=40);"); jQuery("#type_Image_browser").attr("style", "background-color: #F4F4F4;"); jQuery("#type_Blog_style").attr("style", "background-color: #F4F4F4; opacity: 0.4; filter: Alpha(opacity=40);"); jQuery("#type_Lightbox").attr("style", "background-color: #F4F4F4;"); jQuery("#type_Navigation").attr("style", "background-color: #F4F4F4;"); jQuery("#type_" + type).attr("style", "background-color: #CFCBCB;"); } function bwg_gallery_type() { var response = true; var value = jQuery('#gallery_type').val(); response = bwg_change_gallery_type(value, 'change'); return response; } /*returns false if user cancels or impossible to do.*/ /* type_to_set:'' or 'instagram' */ function bwg_change_gallery_type(type_to_set, warning_type) { warning_type = (typeof warning_type === "undefined") ? "default" : warning_type; if(type_to_set == 'instagram'){ jQuery('#gallery_type').val('instagram'); jQuery('#tr_instagram_post_gallery').show(); jQuery('#tr_gallery_source').show(); jQuery('#tr_update_flag').show(); jQuery('#tr_autogallery_image_number').show(); jQuery('#tr_instagram_gallery_add_button').show(); /*hide features of only standard gallery*/ jQuery('.spider_delete_button').hide(); jQuery('#spider_setwatermark_button').hide(); jQuery('#spider_resize_button').hide(); jQuery('#spider_reset_button').hide(); jQuery('#content-add_media').hide(); jQuery('#show_add_embed').hide(); jQuery('#show_bulk_embed').hide(); } else{ var ids_string = jQuery("#ids_string").val(); ids_array = ids_string.split(","); var tr_count = ids_array[0]=='' ? 0: ids_array.length; if(tr_count != 0){ switch(warning_type) { case 'default': var allowed = confirm("This action will reset gallery type to standard and will save that choice. You cannot undo it."); break; case 'change': var allowed = confirm("After pressing save/apply buttons, you cannot change gallery type back to Instagram!"); break; default: var allowed = confirm("This action will reset gallery type to standard and will save that choice. You cannot undo it."); }/*endof switch*/ if (allowed == false) { jQuery('#gallery_type').val('instagram'); return false; } } jQuery('#gallery_type').val(''); jQuery('#tr_instagram_post_gallery').hide(); jQuery('#tr_gallery_source').hide(); jQuery('#tr_update_flag').hide(); jQuery('#tr_autogallery_image_number').hide(); jQuery('#tr_instagram_gallery_add_button').hide(); /*show features of only standard gallery*/ jQuery('.spider_delete_button').show(); jQuery('#spider_setwatermark_button').show(); jQuery('#spider_resize_button').show(); jQuery('#spider_reset_button').show(); jQuery('#content-add_media').show(); jQuery('#show_add_embed').show(); jQuery('#show_bulk_embed').show(); } return true; } function bwg_is_instagram_gallery() { var value = jQuery('#gallery_type').val(); if(value == 'instagram'){ return true; } else{ return false; } } /** * * @param reset:bool true if reset to standard in case of not empty * @param message:bool true if to alert that not empty * @return true if empty, false if not empty */ function bwg_convert_seconds(seconds) { var sec_num = parseInt(seconds, 10); var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - (hours * 3600)) / 60); var seconds = sec_num - (hours * 3600) - (minutes * 60); if (minutes < 10 && hours != 0) {minutes = "0" + minutes;} if (seconds < 10) {seconds = "0" + seconds;} var time = (hours != 0 ? hours + ':' : '') + minutes + ':' + seconds; return time; } function bwg_convert_date(date, separator) { var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); date = date.split(separator); var dateArray = date[0].split("-"); return dateArray[2] + " " + m_names[dateArray[1] - 1] + " " + dateArray[0] + ", " + date[1].substring(0, 5); } /* EMBED handling */ function bwg_get_embed_info(input_id) { jQuery('#opacity_div').show(); jQuery('#loading_div').show(); var url = encodeURI(jQuery("#" + input_id).val()); if (!url) { alert('Please enter url to embed.'); return ''; } var filesValid = []; var data = { 'action': 'addEmbed', 'URL_to_embed': url, 'async':true }; // get from the server data for the url. Here we use the server as a proxy, since Cross-Origin Resource Sharing AJAX is forbidden. jQuery.post(ajax_url, data, function(response) { if(response == false){ alert('Error: cannot get response from the server.'); jQuery('#opacity_div').hide(); jQuery('#loading_div').hide(); return ''; } else{ var index_start = response.indexOf("WD_delimiter_start"); var index_end = response.indexOf("WD_delimiter_end"); if(index_start == -1 || index_end == -1){ alert('Error: something wrong happened at the server.'); jQuery('#opacity_div').hide(); jQuery('#loading_div').hide(); return ''; } /*filter out other echoed characters*/ /*18 is the length of "wd_delimiter_start"*/ response = response.substring(index_start+18,index_end); response_JSON = jQuery.parseJSON(response); /*if indexed array, it means there is error*/ if(typeof response_JSON[0] !== 'undefined'){ alert('Error: ' + jQuery.parseJSON(response)[1]); jQuery('#opacity_div').hide(); jQuery('#loading_div').hide(); return ''; } else{ fileData = response_JSON; filesValid.push(fileData); bwg_add_image(filesValid); document.getElementById(input_id).value = ''; jQuery('#opacity_div').hide(); jQuery('#loading_div').hide(); return 'ok'; } } return ''; }); return 'ok'; }
/* global Promise:true */ import run from "ember-metal/run_loop"; import RSVP from "ember-runtime/ext/rsvp"; QUnit.module('Ember.RSVP'); test('Ensure that errors thrown from within a promise are sent to the console', function(){ var error = new Error('Error thrown in a promise for testing purposes.'); try { run(function(){ new RSVP.Promise(function(resolve, reject){ throw error; }); }); ok(false, 'expected assertion to be thrown'); } catch (e) { equal(e, error, "error was re-thrown"); } }); var asyncStarted = 0; var asyncEnded = 0; var Promise = RSVP.Promise; var EmberTest; var EmberTesting; QUnit.module("Deferred RSVP's async + Testing", { setup: function() { EmberTest = Ember.Test; EmberTesting = Ember.testing; Ember.Test = { adapter: { asyncStart: function() { asyncStarted++; QUnit.stop(); }, asyncEnd: function() { asyncEnded++; QUnit.start(); } } }; }, teardown: function() { asyncStarted = 0; asyncEnded = 0; Ember.testing = EmberTesting; Ember.Test = EmberTest; } }); test("given `Ember.testing = true`, correctly informs the test suite about async steps", function() { expect(19); ok(!run.currentRunLoop, 'expect no run-loop'); Ember.testing = true; equal(asyncStarted, 0); equal(asyncEnded, 0); var user = Promise.resolve({ name: 'tomster' }); equal(asyncStarted, 0); equal(asyncEnded, 0); user.then(function(user){ equal(asyncStarted, 1); equal(asyncEnded, 1); equal(user.name, 'tomster'); return Promise.resolve(1).then(function(){ equal(asyncStarted, 1); equal(asyncEnded, 1); }); }).then(function(){ equal(asyncStarted, 1); equal(asyncEnded, 1); return new Promise(function(resolve){ QUnit.stop(); // raw async, we must inform the test framework manually setTimeout(function(){ QUnit.start(); // raw async, we must inform the test framework manually equal(asyncStarted, 1); equal(asyncEnded, 1); resolve({ name: 'async tomster' }); equal(asyncStarted, 2); equal(asyncEnded, 1); }, 0); }); }).then(function(user){ equal(user.name, 'async tomster'); equal(asyncStarted, 2); equal(asyncEnded, 2); }); }); test('TransitionAborted errors are not re-thrown', function() { expect(1); var fakeTransitionAbort = { name: 'TransitionAborted' }; run(RSVP, 'reject', fakeTransitionAbort); ok(true, 'did not throw an error when dealing with TransitionAborted'); }); test('rejections like jqXHR which have errorThrown property work', function() { expect(2); var wasEmberTesting = Ember.testing; var wasOnError = Ember.onerror; try { Ember.testing = false; Ember.onerror = function(error) { equal(error, actualError, 'expected the real error on the jqXHR'); equal(error.__reason_with_error_thrown__, jqXHR, 'also retains a helpful reference to the rejection reason'); }; var actualError = new Error("OMG what really happend"); var jqXHR = { errorThrown: actualError }; run(RSVP, 'reject', jqXHR); } finally { Ember.onerror = wasOnError; Ember.testing = wasEmberTesting ; } });
asynctest( 'browser.tinymce.ui.data.ObservableObjectTest', [ 'ephox.mcagar.api.LegacyUnit', 'ephox.agar.api.Pipeline', 'tinymce.ui.data.ObservableObject' ], function (LegacyUnit, Pipeline, ObservableObject) { var success = arguments[arguments.length - 2]; var failure = arguments[arguments.length - 1]; var suite = LegacyUnit.createSuite(); suite.test("Constructor", function () { var obj; obj = new ObservableObject(); LegacyUnit.strictEqual(!obj.has('a'), true); obj = new ObservableObject({ a: 1, b: 2 }); LegacyUnit.strictEqual(obj.get('a'), 1); LegacyUnit.strictEqual(obj.get('b'), 2); }); suite.test("set/get and observe all", function () { var obj = new ObservableObject(), events = []; obj.on('change', function (e) { events.push(e); }); obj.set('a', 'a'); obj.set('a', 'a2'); obj.set('a', 'a3'); obj.set('b', 'b'); LegacyUnit.strictEqual(obj.get('a'), 'a3'); LegacyUnit.equal(events[0].type, 'change'); LegacyUnit.equal(events[0].value, 'a'); LegacyUnit.equal(events[1].type, 'change'); LegacyUnit.equal(events[1].value, 'a2'); LegacyUnit.equal(events[2].type, 'change'); LegacyUnit.equal(events[2].value, 'a3'); LegacyUnit.equal(events[3].type, 'change'); LegacyUnit.equal(events[3].value, 'b'); }); suite.test("set/get and observe specific", function () { var obj = new ObservableObject(), events = []; obj.on('change:a', function (e) { events.push(e); }); obj.set('a', 'a'); obj.set('b', 'b'); LegacyUnit.equal(events[0].type, 'change'); LegacyUnit.equal(events[0].value, 'a'); LegacyUnit.equal(events.length, 1); }); Pipeline.async({}, suite.toSteps({}), function () { success(); }, failure); } );
/* eslint-disable */ import Gatsby from "gatsby"; export const query = graphql` query { allSitePages { prefix } } `;
var Utils = require('./../utils') module.exports = (function() { var HasManySingleLinked = function(definition, instance) { this.__factory = definition this.instance = instance } HasManySingleLinked.prototype.injectGetter = function(options) { var where = {}, options = options || {} where[this.__factory.identifier] = this.instance.id options.where = options.where ? Utils._.extend(options.where, where) : where return this.__factory.target.findAll(options) } HasManySingleLinked.prototype.injectSetter = function(emitter, oldAssociations, newAssociations) { var self = this , options = this.__factory.options , chainer = new Utils.QueryChainer() , obsoleteAssociations = oldAssociations.filter(function (old) { return !Utils._.find(newAssociations, function (obj) { return obj.id === old.id }) }) , unassociatedObjects = newAssociations.filter(function (obj) { return !Utils._.find(oldAssociations, function (old) { return obj.id === old.id }) }) // clear the old associations obsoleteAssociations.forEach(function(associatedObject) { associatedObject[self.__factory.identifier] = null chainer.add(associatedObject.save()) }) // set the new associations unassociatedObjects.forEach(function(associatedObject) { associatedObject[self.__factory.identifier] = self.instance.id chainer.add(associatedObject.save()) }) chainer .run() .success(function() { emitter.emit('success', newAssociations) }) .error(function(err) { emitter.emit('error', err) }) } HasManySingleLinked.prototype.injectAdder = function(emitterProxy, newAssociation) { newAssociation[this.__factory.identifier] = this.instance.id newAssociation.save() .success(function() { emitterProxy.emit('success', newAssociation) }) .error(function(err) { emitterProxy.emit('error', err) }) .on('sql', function(sql) { emitterProxy.emit('sql', sql) }) } return HasManySingleLinked })()
var Measure = require('./measure'); var allResults = {}; var totals = {}; var comparator = function(a, b) { return a[this.key] > b[this.key] ? 1 : -1; }; var compareResult = function (result, against) { var compare = {}; result.each(function (key) { compare[key] = { best: false, worst: false }; var sorted = against.slice().sort(comparator.bind({ key: key })); var howMany = sorted.length; if (howMany > 1 && result.equal(key, sorted[howMany - 1]) && !result.equal(key, sorted[0])) compare[key].worst = true; if (howMany && result.equal(key, sorted[0])) compare[key].best = true; }); return compare; }; exports.save = function (file, minifier, stats) { if (!allResults[file]) allResults[file] = {}; allResults[file][minifier] = new Measure(stats); if (!totals[minifier]) totals[minifier] = new Measure(stats); else totals[minifier].add(stats); }; exports.get = function (file, minifier) { var against = []; for (var name in allResults[file]) { var value = allResults[file][name]; if (value.isValid()) against.push(value); } var result = allResults[file][minifier]; return { value: result, compare: compareResult(result, against) }; }; exports.total = function (minifier) { var against = []; for (var name in totals) { var value = totals[name]; if (value.isValid()) against.push(value); } var result = totals[minifier]; return { value: result, compare: compareResult(result, against) }; };
/*global ODSA */ // Written by Jun Yang and Cliff Shaffer //Linked list insertion $(document).ready(function() { "use strict"; var av_name = "llistInsertCON"; // Load the config object with interpreter and code created by odsaUtils.js var config = ODSA.UTILS.loadConfig({av_name: av_name}), interpret = config.interpreter, // get the interpreter code = config.code; // get the code object var av = new JSAV(av_name); var pseudo = av.code(code[0]); // Offsets var leftMargin = 217; var topMargin = 40; // Make the main list var l = av.ds.list({nodegap: 30, top: topMargin, left: leftMargin}); l.addFirst("null").addFirst(12).addFirst(23).addFirst(35).addFirst("null"); l.layout(); av.pointer("head", l.get(0)); av.pointer("curr", l.get(2)); av.pointer("tail", l.get(4)); l.get(2).addVLine(); // Box "it" av.label("it", {left: 20, top: -10}); var itBox = av.ds.array([15], {indexed: false, top: -15, left: 40}); // Create pieces for later steps var arr = av.ds.array([""], {indexed: true}); arr.hide(); //Horizontal arrow in step 4 pointing to item 12 var longArrow = av.g.line(leftMargin + 190, topMargin + 31, leftMargin + 298, topMargin + 31, {"arrow-end": "classic-wide-long", opacity: 0, "stroke-width": 2}); // Slide 1 av.umsg(interpret("sc1")); itBox.highlight(0); pseudo.setCurrentLine("sig"); av.displayInit(); // Slide 2 av.umsg(interpret("sc2")); var newNode = l.newNode(""); // Set the position for the new node newNode.css({top: 50, left: 222}); var node = l.get(2).next(); l.get(2).next(newNode); newNode.next(node); l.get(2).edgeToNext().hide(); l.get(3).edgeToNext().hide(); longArrow.show(); l.layout({updateTop: false}); //Copy 23 to the new link node av.effects.copyValue(arr, 0, newNode); newNode.highlight(); pseudo.setCurrentLine("setnext"); av.step(); // Slide 3 av.umsg(interpret("sc3")); //Copy 10 to the new link node av.effects.copyValue(l.get(2), newNode); av.step(); // Slide 4 av.umsg(interpret("sc4")); l.get(3).edgeToNext().show(); newNode.unhighlight(); l.layout({updateTop: false}); // Do not recalculate top coordinate l.get(3).highlight(); av.step(); // Slide 5 av.umsg(interpret("sc5")); l.get(2).highlight(); l.get(3).unhighlight(); l.get(2).edgeToNext().show(); longArrow.hide(); av.step(); // Slide 6 av.umsg(interpret("sc6")); l.get(2).unhighlight(); l.get(3).highlight(); l.layout(); av.step(); // Slide 7 av.umsg(interpret("sc7")); av.effects.copyValue(itBox, 0, l.get(2)); itBox.unhighlight(0); l.get(3).unhighlight(); l.get(2).highlight(); pseudo.setCurrentLine("setelem"); av.step(); // Slide 8 av.umsg(interpret("sc8")); l.get(2).unhighlight(); pseudo.setCurrentLine("listSize"); av.step(); // Slide 9 av.umsg(interpret("sc9")); pseudo.setCurrentLine("return"); av.recorded(); });
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ * * Version: 5.0.8 (2019-06-18) */ (function (domGlobals) { 'use strict'; var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); function Plugin () { global.add('contextmenu', function () { domGlobals.console.warn('Context menu plugin is now built in to the core editor, please remove it from your editor configuration'); }); } Plugin(); }(window));
version https://git-lfs.github.com/spec/v1 oid sha256:be72cac097c9d0cbd6c8bebf581495945bbf99dffd2e326bdbe97aea79968e10 size 32768
/** * @use 간단 포토 업로드용으로 제작되었습니다. * @author cielo * @See nhn.husky.SE2M_Configuration * @ 팝업 마크업은 SimplePhotoUpload.html과 SimplePhotoUpload_html5.html이 있습니다. */ nhn.husky.SE2M_AttachQuickPhoto = jindo.$Class({ name : "SE2M_AttachQuickPhoto", $init : function(){}, $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_UI_EVENT", ["photo_attach", "click", "ATTACHPHOTO_OPEN_WINDOW"]); }, $LOCAL_BEFORE_FIRST : function(sMsg){ if(!!this.oPopupMgr){ return; } // Popup Manager에서 사용할 param this.htPopupOption = { oApp : this.oApp, sName : this.name, bScroll : false, sProperties : "", sUrl : "" }; this.oPopupMgr = nhn.husky.PopUpManager.getInstance(this.oApp); }, /** * 포토 웹탑 오픈 */ $ON_ATTACHPHOTO_OPEN_WINDOW : function(){ this.htPopupOption.sUrl = this.makePopupURL(); this.htPopupOption.sProperties = "left=0,top=0,width=403,height=359,scrollbars=yes,location=no,status=0,resizable=no"; this.oPopupWindow = this.oPopupMgr.openWindow(this.htPopupOption); // 처음 로딩하고 IE에서 커서가 전혀 없는 경우 // 복수 업로드시에 순서가 바뀜 this.oApp.exec('FOCUS'); return (!!this.oPopupWindow ? true : false); }, /** * 서비스별로 팝업에 parameter를 추가하여 URL을 생성하는 함수 * nhn.husky.SE2M_AttachQuickPhoto.prototype.makePopupURL로 덮어써서 사용하시면 됨. */ makePopupURL : function(){ var sPopupUrl = "./photo_uploader/popup/photo_uploader.html"; return sPopupUrl; }, /** * 팝업에서 호출되는 메세지. */ $ON_SET_PHOTO : function(aPhotoData){ var sContents, aPhotoInfo, htData; if( !aPhotoData ){ return; } try{ sContents = ""; for(var i = 0; i <aPhotoData.length; i++){ htData = aPhotoData[i]; if(!htData.sAlign){ htData.sAlign = ""; } aPhotoInfo = { sName : htData.sFileName || "", sOriginalImageURL : htData.sFileURL, bNewLine : htData.bNewLine || false }; sContents += this._getPhotoTag(aPhotoInfo); } this.oApp.exec("PASTE_HTML", [sContents]); // 위즐 첨부 파일 부분 확인 }catch(e){ // upload시 error발생에 대해서 skip함 return false; } }, /** * @use 일반 포토 tag 생성 */ _getPhotoTag : function(htPhotoInfo){ // id와 class는 썸네일과 연관이 많습니다. 수정시 썸네일 영역도 Test var sTag = '<img src="{=sOriginalImageURL}" title="{=sName}" >'; if(htPhotoInfo.bNewLine){ sTag += '<br style="clear:both;">'; } sTag = jindo.$Template(sTag).process(htPhotoInfo); return sTag; } });
/*global defineSuite*/ defineSuite([ 'Scene/TileCoordinatesImageryProvider', 'Core/defined', 'Core/GeographicTilingScheme', 'Core/WebMercatorTilingScheme', 'Scene/ImageryProvider', 'Specs/waitsForPromise' ], function( TileCoordinatesImageryProvider, defined, GeographicTilingScheme, WebMercatorTilingScheme, ImageryProvider, waitsForPromise) { "use strict"; /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/ it('conforms to ImageryProvider interface', function() { expect(TileCoordinatesImageryProvider).toConformToInterface(ImageryProvider); }); it('returns valid value for hasAlphaChannel', function() { var provider = new TileCoordinatesImageryProvider(); waitsFor(function() { return provider.ready; }, 'imagery provider to become ready'); runs(function() { expect(typeof provider.hasAlphaChannel).toBe('boolean'); }); }); it('can provide a root tile', function() { var provider = new TileCoordinatesImageryProvider(); waitsFor(function() { return provider.ready; }, 'imagery provider to become ready'); runs(function() { expect(provider.tileWidth).toEqual(256); expect(provider.tileHeight).toEqual(256); expect(provider.maximumLevel).toBeUndefined(); expect(provider.tilingScheme).toBeInstanceOf(GeographicTilingScheme); expect(provider.tileDiscardPolicy).toBeUndefined(); expect(provider.rectangle).toEqual(new GeographicTilingScheme().rectangle); waitsForPromise(provider.requestImage(0, 0, 0), function(image) { expect(image).toBeDefined(); }); }); }); it('uses alternate tiling scheme if provided', function() { var tilingScheme = new WebMercatorTilingScheme(); var provider = new TileCoordinatesImageryProvider({ tilingScheme : tilingScheme }); waitsFor(function() { return provider.ready; }, 'imagery provider to become ready'); runs(function() { expect(provider.tilingScheme).toBe(tilingScheme); }); }); it('uses tile width and height if provided', function() { var provider = new TileCoordinatesImageryProvider({ tileWidth : 123, tileHeight : 456 }); waitsFor(function() { return provider.ready; }, 'imagery provider to become ready'); runs(function() { expect(provider.tileWidth).toEqual(123); expect(provider.tileHeight).toEqual(456); }); }); });
import { isFunction, isNumber } from './isType'; export default function debounce(func, wait) { if (isFunction(func)) { let timeoutID = null; const delay = isNumber(wait) ? wait : 1000; const closureDebounce = (...args) => { const delayed = () => { timeoutID = null; func.apply(this, args); }; clearTimeout(timeoutID); timeoutID = setTimeout(delayed, delay); }; closureDebounce.cancel = () => { if (timeoutID) { clearTimeout(timeoutID); return true; } return false; }; return closureDebounce; } return null; }
// Copyright 2006 Google Inc. // All Rights Reserved // // Defines regular expression patterns to extract XML tokens from string. // See <http://www.w3.org/TR/REC-xml/#sec-common-syn>, // <http://www.w3.org/TR/xml11/#sec-common-syn> and // <http://www.w3.org/TR/REC-xml-names/#NT-NCName> for the specifications. // // Author: Junji Takagi <jtakagi@google.com> // Detect whether RegExp supports Unicode characters or not. var REGEXP_UNICODE = function() { var tests = [' ', '\u0120', -1, // Konquerer 3.4.0 fails here. '!', '\u0120', -1, '\u0120', '\u0120', 0, '\u0121', '\u0120', -1, '\u0121', '\u0120|\u0121', 0, '\u0122', '\u0120|\u0121', -1, '\u0120', '[\u0120]', 0, // Safari 2.0.3 fails here. '\u0121', '[\u0120]', -1, '\u0121', '[\u0120\u0121]', 0, // Safari 2.0.3 fails here. '\u0122', '[\u0120\u0121]', -1, '\u0121', '[\u0120-\u0121]', 0, // Safari 2.0.3 fails here. '\u0122', '[\u0120-\u0121]', -1]; for (var i = 0; i < tests.length; i += 3) { if (tests[i].search(new RegExp(tests[i + 1])) != tests[i + 2]) { return false; } } return true; }(); // Common tokens in XML 1.0 and XML 1.1. var XML_S = '[ \t\r\n]+'; var XML_EQ = '(' + XML_S + ')?=(' + XML_S + ')?'; var XML_CHAR_REF = '&#[0-9]+;|&#x[0-9a-fA-F]+;'; // XML 1.0 tokens. var XML10_VERSION_INFO = XML_S + 'version' + XML_EQ + '("1\\.0"|' + "'1\\.0')"; var XML10_BASE_CHAR = (REGEXP_UNICODE) ? '\u0041-\u005a\u0061-\u007a\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff' + '\u0100-\u0131\u0134-\u013e\u0141-\u0148\u014a-\u017e\u0180-\u01c3' + '\u01cd-\u01f0\u01f4-\u01f5\u01fa-\u0217\u0250-\u02a8\u02bb-\u02c1\u0386' + '\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03ce\u03d0-\u03d6\u03da\u03dc' + '\u03de\u03e0\u03e2-\u03f3\u0401-\u040c\u040e-\u044f\u0451-\u045c' + '\u045e-\u0481\u0490-\u04c4\u04c7-\u04c8\u04cb-\u04cc\u04d0-\u04eb' + '\u04ee-\u04f5\u04f8-\u04f9\u0531-\u0556\u0559\u0561-\u0586\u05d0-\u05ea' + '\u05f0-\u05f2\u0621-\u063a\u0641-\u064a\u0671-\u06b7\u06ba-\u06be' + '\u06c0-\u06ce\u06d0-\u06d3\u06d5\u06e5-\u06e6\u0905-\u0939\u093d' + '\u0958-\u0961\u0985-\u098c\u098f-\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2' + '\u09b6-\u09b9\u09dc-\u09dd\u09df-\u09e1\u09f0-\u09f1\u0a05-\u0a0a' + '\u0a0f-\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32-\u0a33\u0a35-\u0a36' + '\u0a38-\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8b\u0a8d' + '\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2-\u0ab3\u0ab5-\u0ab9' + '\u0abd\u0ae0\u0b05-\u0b0c\u0b0f-\u0b10\u0b13-\u0b28\u0b2a-\u0b30' + '\u0b32-\u0b33\u0b36-\u0b39\u0b3d\u0b5c-\u0b5d\u0b5f-\u0b61\u0b85-\u0b8a' + '\u0b8e-\u0b90\u0b92-\u0b95\u0b99-\u0b9a\u0b9c\u0b9e-\u0b9f\u0ba3-\u0ba4' + '\u0ba8-\u0baa\u0bae-\u0bb5\u0bb7-\u0bb9\u0c05-\u0c0c\u0c0e-\u0c10' + '\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c60-\u0c61\u0c85-\u0c8c' + '\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cde\u0ce0-\u0ce1' + '\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d28\u0d2a-\u0d39\u0d60-\u0d61' + '\u0e01-\u0e2e\u0e30\u0e32-\u0e33\u0e40-\u0e45\u0e81-\u0e82\u0e84' + '\u0e87-\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5' + '\u0ea7\u0eaa-\u0eab\u0ead-\u0eae\u0eb0\u0eb2-\u0eb3\u0ebd\u0ec0-\u0ec4' + '\u0f40-\u0f47\u0f49-\u0f69\u10a0-\u10c5\u10d0-\u10f6\u1100\u1102-\u1103' + '\u1105-\u1107\u1109\u110b-\u110c\u110e-\u1112\u113c\u113e\u1140\u114c' + '\u114e\u1150\u1154-\u1155\u1159\u115f-\u1161\u1163\u1165\u1167\u1169' + '\u116d-\u116e\u1172-\u1173\u1175\u119e\u11a8\u11ab\u11ae-\u11af' + '\u11b7-\u11b8\u11ba\u11bc-\u11c2\u11eb\u11f0\u11f9\u1e00-\u1e9b' + '\u1ea0-\u1ef9\u1f00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d' + '\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc' + '\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec' + '\u1ff2-\u1ff4\u1ff6-\u1ffc\u2126\u212a-\u212b\u212e\u2180-\u2182' + '\u3041-\u3094\u30a1-\u30fa\u3105-\u312c\uac00-\ud7a3' : 'A-Za-z'; var XML10_IDEOGRAPHIC = (REGEXP_UNICODE) ? '\u4e00-\u9fa5\u3007\u3021-\u3029' : ''; var XML10_COMBINING_CHAR = (REGEXP_UNICODE) ? '\u0300-\u0345\u0360-\u0361\u0483-\u0486\u0591-\u05a1\u05a3-\u05b9' + '\u05bb-\u05bd\u05bf\u05c1-\u05c2\u05c4\u064b-\u0652\u0670\u06d6-\u06dc' + '\u06dd-\u06df\u06e0-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0901-\u0903\u093c' + '\u093e-\u094c\u094d\u0951-\u0954\u0962-\u0963\u0981-\u0983\u09bc\u09be' + '\u09bf\u09c0-\u09c4\u09c7-\u09c8\u09cb-\u09cd\u09d7\u09e2-\u09e3\u0a02' + '\u0a3c\u0a3e\u0a3f\u0a40-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a70-\u0a71' + '\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0b01-\u0b03' + '\u0b3c\u0b3e-\u0b43\u0b47-\u0b48\u0b4b-\u0b4d\u0b56-\u0b57\u0b82-\u0b83' + '\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0c01-\u0c03\u0c3e-\u0c44' + '\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c82-\u0c83\u0cbe-\u0cc4' + '\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5-\u0cd6\u0d02-\u0d03\u0d3e-\u0d43' + '\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1' + '\u0eb4-\u0eb9\u0ebb-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35\u0f37\u0f39' + '\u0f3e\u0f3f\u0f71-\u0f84\u0f86-\u0f8b\u0f90-\u0f95\u0f97\u0f99-\u0fad' + '\u0fb1-\u0fb7\u0fb9\u20d0-\u20dc\u20e1\u302a-\u302f\u3099\u309a' : ''; var XML10_DIGIT = (REGEXP_UNICODE) ? '\u0030-\u0039\u0660-\u0669\u06f0-\u06f9\u0966-\u096f\u09e6-\u09ef' + '\u0a66-\u0a6f\u0ae6-\u0aef\u0b66-\u0b6f\u0be7-\u0bef\u0c66-\u0c6f' + '\u0ce6-\u0cef\u0d66-\u0d6f\u0e50-\u0e59\u0ed0-\u0ed9\u0f20-\u0f29' : '0-9'; var XML10_EXTENDER = (REGEXP_UNICODE) ? '\u00b7\u02d0\u02d1\u0387\u0640\u0e46\u0ec6\u3005\u3031-\u3035' + '\u309d-\u309e\u30fc-\u30fe' : ''; var XML10_LETTER = XML10_BASE_CHAR + XML10_IDEOGRAPHIC; var XML10_NAME_CHAR = XML10_LETTER + XML10_DIGIT + '\\._:' + XML10_COMBINING_CHAR + XML10_EXTENDER + '-'; var XML10_NAME = '[' + XML10_LETTER + '_:][' + XML10_NAME_CHAR + ']*'; var XML10_ENTITY_REF = '&' + XML10_NAME + ';'; var XML10_REFERENCE = XML10_ENTITY_REF + '|' + XML_CHAR_REF; var XML10_ATT_VALUE = '"(([^<&"]|' + XML10_REFERENCE + ')*)"|' + "'(([^<&']|" + XML10_REFERENCE + ")*)'"; var XML10_ATTRIBUTE = '(' + XML10_NAME + ')' + XML_EQ + '(' + XML10_ATT_VALUE + ')'; // XML 1.1 tokens. // TODO(jtakagi): NameStartChar also includes \u10000-\ueffff. // ECMAScript Language Specifiction defines UnicodeEscapeSequence as // "\u HexDigit HexDigit HexDigit HexDigit" and we may need to use // surrogate pairs, but any browser doesn't support surrogate paris in // character classes of regular expression, so avoid including them for now. var XML11_VERSION_INFO = XML_S + 'version' + XML_EQ + '("1\\.1"|' + "'1\\.1')"; var XML11_NAME_START_CHAR = (REGEXP_UNICODE) ? ':A-Z_a-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02ff\u0370-\u037d' + '\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff' + '\uf900-\ufdcf\ufdf0-\ufffd' : ':A-Z_a-z'; var XML11_NAME_CHAR = XML11_NAME_START_CHAR + ((REGEXP_UNICODE) ? '\\.0-9\u00b7\u0300-\u036f\u203f-\u2040-' : '\\.0-9-'); var XML11_NAME = '[' + XML11_NAME_START_CHAR + '][' + XML11_NAME_CHAR + ']*'; var XML11_ENTITY_REF = '&' + XML11_NAME + ';'; var XML11_REFERENCE = XML11_ENTITY_REF + '|' + XML_CHAR_REF; var XML11_ATT_VALUE = '"(([^<&"]|' + XML11_REFERENCE + ')*)"|' + "'(([^<&']|" + XML11_REFERENCE + ")*)'"; var XML11_ATTRIBUTE = '(' + XML11_NAME + ')' + XML_EQ + '(' + XML11_ATT_VALUE + ')'; // XML Namespace tokens. // Used in XML parser and XPath parser. var XML_NC_NAME_CHAR = XML10_LETTER + XML10_DIGIT + '\\._' + XML10_COMBINING_CHAR + XML10_EXTENDER + '-'; var XML_NC_NAME = '[' + XML10_LETTER + '_][' + XML_NC_NAME_CHAR + ']*';
goog.provide("DateTime"); goog.require("Instant"); /** * JSDoc here * * @author Victor Polischuk * @constructor * @class Class description * @public * @extends Instant */ var DateTime = function () { //TODO<vpolischuk>: implement it } goog.inherits(DateTime, Instant); registerClass(DateTime, "DateTime"); // Instant extends methods /** * Returns {@link DateTime} instance using default {@link DateTimeZone} and {@link Chronology}. * * @return {DateTime} fully operational instance of {@link DateTime}. * @public * @see DateTime */ Instant.prototype.toDateTime = function() { return null; //TODO<vpolischuk>: use DateTime here. };
import * as types from './mutation_types'; export default { [types.SET_LOADING_STACKTRACE](state, data) { state.loadingStacktrace = data; }, [types.SET_STACKTRACE_DATA](state, data) { state.stacktraceData = data; }, };
(function($){ $( document ).ready( function() { var $body = $( 'body' ); $( '.et_dashboard_authorize' ).click( function() { var $this_button = $( this ), $key_field = $this_button.closest( 'ul' ).find( '.api_option_key' ), $spinner = $this_button.closest( 'li' ).find( 'span.spinner' ); authorize_aweber( $key_field, $spinner ); return false; }); function authorize_aweber( $key_field, $spinner ) { var $container = $key_field.closest( '.et_dashboard_form' ); $key_field.css( { 'border' : 'none' } ); if ( $key_field.length && '' == $key_field.val() ) { $key_field.css( { 'border' : '1px solid red' } ); } else { $.ajax({ type: 'POST', url: builder_settings.ajaxurl, data: { action : 'et_builder_authorize_aweber', et_builder_nonce : builder_settings.et_builder_nonce, et_builder_api_key : $key_field.val() }, beforeSend: function( data ) { $spinner.addClass( 'et_dashboard_spinner_visible' ); }, success: function( data ){ $spinner.removeClass( 'et_dashboard_spinner_visible' ); if ( 'success' == data || '' == data ) { $( $container ).find( '.et_dashboard_authorize' ).text( builder_settings.reauthorize_text ); window.et_dashboard_generate_warning( builder_settings.authorization_successflull, '#', '', '', '', '' ); } else { window.et_dashboard_generate_warning( data, '#', '', '', '', '' ); } } }); } return false; } $( '.et_dashboard_get_lists' ).click( function() { var $this_button = $( this ), $this_spinner = $this_button.closest( 'li' ).find( 'span.spinner' ), service_name = $this_button.hasClass( 'et_pb_aweber' ) ? 'aweber' : 'mailchimp', options_fromform = $( '.et_builder #et_dashboard_options' ).serialize(); $.ajax({ type: 'POST', url: builder_settings.ajaxurl, data: { action : 'et_builder_refresh_lists', et_builder_nonce : builder_settings.et_builder_nonce, et_builder_mail_service : service_name, et_builder_form_options : options_fromform }, beforeSend: function( data ) { $this_spinner.addClass( 'et_dashboard_spinner_visible' ); }, success: function( data ) { $this_spinner.removeClass( 'et_dashboard_spinner_visible' ); window.et_dashboard_generate_warning( data, '#', '', '', '', '' ); } }); return false; }); $( '.et_dashboard_updates_save' ).click( function() { var $this_button = $( this ), $this_container = $this_button.closest( 'ul' ), $this_spinner = $this_container.find( 'span.spinner' ), username = $this_container.find( '.updates_option_username' ).val(), api_key = $this_container.find( '.updates_option_api_key' ).val(); $.ajax({ type: 'POST', url: builder_settings.ajaxurl, data: { action : 'et_builder_save_updates_settings', et_builder_nonce : builder_settings.et_builder_nonce, et_builder_updates_username : username, et_builder_updates_api_key : api_key }, beforeSend: function( data ) { $this_spinner.addClass( 'et_dashboard_spinner_visible' ); }, success: function( data ) { $this_spinner.removeClass( 'et_dashboard_spinner_visible' ); } }); return false; }); $( '.et_google_api_save' ).click( function() { var $this_button = $( this ), $this_container = $this_button.closest( 'ul' ), $this_spinner = $this_container.find( 'span.spinner' ), api_key = $this_container.find( '.google_api_key' ).val(); $.ajax({ type: 'POST', url: builder_settings.ajaxurl, data: { action : 'et_builder_save_google_api_settings', et_builder_nonce : builder_settings.et_builder_nonce, et_builder_google_api_key : api_key }, beforeSend: function( data ) { $this_spinner.addClass( 'et_dashboard_spinner_visible' ); }, success: function( data ) { $this_spinner.removeClass( 'et_dashboard_spinner_visible' ); } }); return false; }); $( '#et_pb_save_plugin' ).click( function() { var $loading_animation = $( '#et_pb_loading_animation' ), $success_animation = $( '#et_pb_success_animation' ), options_fromform; tinyMCE.triggerSave(); options_fromform = $( '.' + dashboardSettings.plugin_class + ' #et_dashboard_options' ).serialize(); $.ajax({ type: 'POST', url: builder_settings.ajaxurl, data: { action : 'et_builder_save_settings', options : options_fromform, options_sub_title : '', save_settings_nonce : builder_settings.save_settings }, beforeSend: function ( xhr ) { $loading_animation.removeClass( 'et_pb_hide_loading' ); $success_animation.removeClass( 'et_pb_active_success' ); $loading_animation.show(); }, success: function( data ) { $loading_animation.addClass( 'et_pb_hide_loading' ); $success_animation.addClass( 'et_pb_active_success' ).show(); setTimeout( function(){ $success_animation.fadeToggle(); $loading_animation.fadeToggle(); }, 1000 ); } }); return false; }); $body.append( '<div id="et_pb_loading_animation"></div>' ); $body.append( '<div id="et_pb_success_animation"></div>' ); $( '#et_pb_loading_animation' ).hide(); $( '#et_pb_success_animation' ).hide(); }); })(jQuery)
/*global define*/ /* jshint -W106, -W069*/ define(['jquery', 'underscore', 'backbone', 'templates', 'gauge', 'humanize', 'helpers/animation', 'helpers/gauge-helper', 'marionette'], function($, _, Backbone, JST, Gauge, humanize, animation, gaugeHelper) { 'use strict'; /* UsageView * --------- * This is the view for the usage card widget in the dashboard */ return Backbone.Marionette.ItemView.extend({ className: 'col-lg-3 col-md-3 col-sm-6 col-xs-6 custom-gutter', template: JST['app/scripts/templates/usage.ejs'], cardTitleTemplate: _.template('<%- used %>% Usage'), timer: null, delay: 20000, ui: { cardtitle: '.card-title', number: '.number', totalused: '.totalused', totalcap: '.totalcap', canvas: '.usage-canvas', spinner: '.fa-spinner' }, modelEvents: { 'change': 'updateView' }, serializeData: function() { return { title: this.title }; }, initialize: function(options) { _.bindAll(this, 'updateView', 'set'); // The are defaults for Gauge.js and can be overidden from the contructor this.App = Backbone.Marionette.getOption(this, 'App'); if (this.App) { this.listenTo(this.App.vent, 'usage:update', this.set); } this.opts = {}; _.extend(this.opts, { lines: 10, 'font-size': '0px', percentColors: [ [0.0, '#1ae61a'], [0.60, '#e6e619'], [1.0, '#e61919'] ], generateGradient: true, highDpiSupport: false }); this.title = options.title === undefined ? 'Untitled' : options.title; this.listenToOnce(this, 'render', this.postRender); gaugeHelper(this, 'usage'); }, // Once the render has been executed and has set up the widget // add the canvas based gauge dial postRender: function() { this.gauge = new Gauge(this.ui.canvas[0]).setOptions(this.opts); this.gauge.set(0); this.gauge.maxValue = 100; this.gauge.minValue = 0; this.ui.canvas.css({ 'height': '', 'width': '' }); this.triggerMethod('item:postrender', this); }, warningThreshold: 90, displayWarning: function() { if (this.model.getPercentageUsed() > this.warningThreshold) { this.trigger('status:warn'); } else { this.trigger('status:ok'); } }, updateView: function(model) { var attr = model.toJSON(); var space = attr.space; var used = humanize.filesize(space.used_bytes, undefined, 1); used = used.replace(' ', ''); var total = humanize.filesize(space.capacity_bytes, undefined, 1); total = total.replace(' ', ''); this.ui.number.text(used); this.ui.totalcap.text(total); this.gauge.set(model.getPercentageUsed()); this.displayWarning(); }, set: function(model) { this.model.set(model.toJSON()); } }); });
// unquoted attributes should be ok in non-strict mode // https://github.com/isaacs/sax-js/issues/31 require(__dirname).test ( { xml : "<span class=test hello=world></span>" , expect : [ [ "attribute", { name: "CLASS", value: "test" } ] , [ "attribute", { name: "HELLO", value: "world" } ] , [ "opentag", { name: "SPAN", attributes: { CLASS: "test", HELLO: "world" }, isSelfClosing: false } ] , [ "closetag", "SPAN" ] ] , strict : false , opt : {} } )
import initPanels from './init_panels'; describe('manager.ui.config.init_panels', () => { test('should call the selectDownPanel with first panel name', () => { const actions = { ui: { selectDownPanel: jest.fn(), }, }; const provider = { getPanels() { return { test1: {}, test2: {}, test3: {}, }; }, }; initPanels({ provider }, actions); expect(actions.ui.selectDownPanel).toHaveBeenCalledWith('test1'); }); });
/** * program.js - basic curses-like functionality for blessed. * Copyright (c) 2013-2015, Christopher Jeffrey and contributors (MIT License). * https://github.com/chjj/blessed */ /** * Modules */ var EventEmitter = require('events').EventEmitter , StringDecoder = require('string_decoder').StringDecoder , cp = require('child_process') , util = require('util') , fs = require('fs'); var Tput = require('./tput') , colors = require('./colors') , slice = Array.prototype.slice; var nextTick = global.setImmediate || process.nextTick.bind(process); /** * Program */ function Program(options) { var self = this; if (!(this instanceof Program)) { return new Program(options); } Program.bind(this); EventEmitter.call(this); if (!options || options.__proto__ !== Object.prototype) { options = { input: arguments[0], output: arguments[1] }; } this.options = options; this.input = options.input || process.stdin; this.output = options.output || process.stdout; options.log = options.log || options.dump; if (options.log) { this._logger = fs.createWriteStream(options.log); if (options.dump) this.setupDump(); } this.zero = options.zero !== false; this.useBuffer = options.buffer; this.x = 0; this.y = 0; this.savedX = 0; this.savedY = 0; this.cols = this.output.columns || 1; this.rows = this.output.rows || 1; this.scrollTop = 0; this.scrollBottom = this.rows - 1; this._terminal = options.terminal || options.term || process.env.TERM || (process.platform === 'win32' ? 'windows-ansi' : 'xterm'); this._terminal = this._terminal.toLowerCase(); // OSX this.isOSXTerm = process.env.TERM_PROGRAM === 'Apple_Terminal'; this.isiTerm2 = process.env.TERM_PROGRAM === 'iTerm.app' || !!process.env.ITERM_SESSION_ID; // VTE // NOTE: lxterminal does not provide an env variable to check for. // NOTE: gnome-terminal and sakura use a later version of VTE // which provides VTE_VERSION as well as supports SGR events. this.isXFCE = /xfce/i.test(process.env.COLORTERM); this.isTerminator = !!process.env.TERMINATOR_UUID; this.isLXDE = false; this.isVTE = !!process.env.VTE_VERSION || this.isXFCE || this.isTerminator || this.isLXDE; // xterm and rxvt - not accurate this.isRxvt = /rxvt/i.test(process.env.COLORTERM); this.isXterm = false; this.tmux = !!process.env.TMUX; this.tmuxVersion = (function() { if (!self.tmux) return 2; try { var version = cp.execFileSync('tmux', ['-V'], { encoding: 'utf8' }); return +/^tmux ([\d.]+)/i.exec(version.trim().split('\n')[0])[1]; } catch (e) { return 2; } })(); this._buf = ''; this._flush = this.flush.bind(this); if (options.tput !== false) { this.setupTput(); } this.listen(); } Program.global = null; Program.total = 0; Program.instances = []; Program.bind = function(program) { if (!Program.global) { Program.global = program; } if (!~Program.instances.indexOf(program)) { Program.instances.push(program); program.index = Program.total; Program.total++; } if (Program._bound) return; Program._bound = true; unshiftEvent(process, 'exit', Program._exitHandler = function() { Program.instances.forEach(function(program) { // Potentially reset window title on exit: // if (program._originalTitle) { // program.setTitle(program._originalTitle); // } // Ensure the buffer is flushed (it should // always be at this point, but who knows). program.flush(); // Ensure _exiting is set (could technically // use process._exiting). program._exiting = true; }); }); }; Program.prototype.__proto__ = EventEmitter.prototype; Program.prototype.type = 'program'; Program.prototype.log = function() { return this._log('LOG', util.format.apply(util, arguments)); }; Program.prototype.debug = function() { if (!this.options.debug) return; return this._log('DEBUG', util.format.apply(util, arguments)); }; Program.prototype._log = function(pre, msg) { if (!this._logger) return; return this._logger.write(pre + ': ' + msg + '\n-\n'); }; Program.prototype.setupDump = function() { var self = this , write = this.output.write , decoder = new StringDecoder('utf8'); function stringify(data) { return caret(data .replace(/\r/g, '\\r') .replace(/\n/g, '\\n') .replace(/\t/g, '\\t')) .replace(/[^ -~]/g, function(ch) { if (ch.charCodeAt(0) > 0xff) return ch; ch = ch.charCodeAt(0).toString(16); if (ch.length > 2) { if (ch.length < 4) ch = '0' + ch; return '\\u' + ch; } if (ch.length < 2) ch = '0' + ch; return '\\x' + ch; }); } function caret(data) { return data.replace(/[\0\x80\x1b-\x1f\x7f\x01-\x1a]/g, function(ch) { switch (ch) { case '\0': case '\x80': ch = '@'; break; case '\x1b': ch = '['; break; case '\x1c': ch = '\\'; break; case '\x1d': ch = ']'; break; case '\x1e': ch = '^'; break; case '\x1f': ch = '_'; break; case '\x7f': ch = '?'; break; default: ch = ch.charCodeAt(0); // From ('A' - 64) to ('Z' - 64). if (ch >= 1 && ch <= 26) { ch = String.fromCharCode(ch + 64); } else { return String.fromCharCode(ch); } break; } return '^' + ch; }); } this.input.on('data', function(data) { self._log('IN', stringify(decoder.write(data))); }); this.output.write = function(data) { self._log('OUT', stringify(data)); return write.apply(this, arguments); }; }; Program.prototype.setupTput = function() { if (this._tputSetup) return; this._tputSetup = true; var self = this , options = this.options , write = this._write.bind(this); var tput = this.tput = new Tput({ terminal: this.terminal, padding: options.padding, extended: options.extended, printf: options.printf, termcap: options.termcap, forceUnicode: options.forceUnicode }); if (tput.error) { nextTick(function() { self.emit('warning', tput.error.message); }); } if (tput.padding) { nextTick(function() { self.emit('warning', 'Terminfo padding has been enabled.'); }); } this.put = function() { var args = slice.call(arguments) , cap = args.shift(); if (tput[cap]) { return this._write(tput[cap].apply(tput, args)); } }; Object.keys(tput).forEach(function(key) { if (self[key] == null) { self[key] = tput[key]; } if (typeof tput[key] !== 'function') { self.put[key] = tput[key]; return; } if (tput.padding) { self.put[key] = function() { return tput._print(tput[key].apply(tput, arguments), write); }; } else { self.put[key] = function() { return self._write(tput[key].apply(tput, arguments)); }; } }); }; Program.prototype.__defineGetter__('terminal', function() { return this._terminal; }); Program.prototype.__defineSetter__('terminal', function(terminal) { this.setTerminal(terminal); return this.terminal; }); Program.prototype.setTerminal = function(terminal) { this._terminal = terminal.toLowerCase(); delete this._tputSetup; this.setupTput(); }; Program.prototype.has = function(name) { return this.tput ? this.tput.has(name) : false; }; Program.prototype.term = function(is) { return this.terminal.indexOf(is) === 0; }; Program.prototype.listen = function() { var self = this; // Potentially reset window title on exit: // if (!this.isRxvt) { // if (!this.isVTE) this.setTitleModeFeature(3); // this.manipulateWindow(21, function(err, data) { // if (err) return; // self._originalTitle = data.text; // }); // } // Listen for keys/mouse on input if (!this.input._blessedInput) { this.input._blessedInput = 1; this._listenInput(); } else { this.input._blessedInput++; } this.on('newListener', this._newHandler = function fn(type) { if (type === 'keypress' || type === 'mouse') { self.removeListener('newListener', fn); if (self.input.setRawMode && !self.input.isRaw) { self.input.setRawMode(true); self.input.resume(); } } }); this.on('newListener', function fn(type) { if (type === 'mouse') { self.removeListener('newListener', fn); self.bindMouse(); } }); // Listen for resize on output if (!this.output._blessedOutput) { this.output._blessedOutput = 1; this._listenOutput(); } else { this.output._blessedOutput++; } }; Program.prototype._listenInput = function() { var keys = require('./keys') , self = this; // Input this.input.on('keypress', this.input._keypressHandler = function(ch, key) { key = key || { ch: ch }; if (key.name === 'undefined' && (key.code === '[M' || key.code === '[I' || key.code === '[O')) { // A mouse sequence. The `keys` module doesn't understand these. return; } if (key.name === 'undefined') { // Not sure what this is, but we should probably ignore it. return; } if (key.name === 'enter' && key.sequence === '\n') { key.name = 'linefeed'; } if (key.name === 'return' && key.sequence === '\r') { self.input.emit('keypress', ch, merge({}, key, { name: 'enter' })); } var name = (key.ctrl ? 'C-' : '') + (key.meta ? 'M-' : '') + (key.shift && key.name ? 'S-' : '') + (key.name || ch); key.full = name; Program.instances.forEach(function(program) { if (program.input !== self.input) return; program.emit('keypress', ch, key); program.emit('key ' + name, ch, key); }); }); this.input.on('data', this.input._dataHandler = function(data) { Program.instances.forEach(function(program) { if (program.input !== self.input) return; program.emit('data', data); }); }); keys.emitKeypressEvents(this.input); }; Program.prototype._listenOutput = function() { var self = this; if (!this.output.isTTY) { nextTick(function() { self.emit('warning', 'Output is not a TTY'); }); } // Output function resize() { Program.instances.forEach(function(program) { if (program.output !== self.output) return; program.cols = program.output.columns; program.rows = program.output.rows; program.emit('resize'); }); } this.output.on('resize', this.output._resizeHandler = function() { Program.instances.forEach(function(program) { if (program.output !== self.output) return; if (!program.options.resizeTimeout) { return resize(); } if (program._resizeTimer) { clearTimeout(program._resizeTimer); delete program._resizeTimer; } var time = typeof program.options.resizeTimeout === 'number' ? program.options.resizeTimeout : 300; program._resizeTimer = setTimeout(resize, time); }); }); }; Program.prototype.destroy = function() { var index = Program.instances.indexOf(this); if (~index) { Program.instances.splice(index, 1); Program.total--; this.flush(); this._exiting = true; Program.global = Program.instances[0]; if (Program.total === 0) { Program.global = null; process.removeListener('exit', Program._exitHandler); delete Program._exitHandler; delete Program._bound; } this.input._blessedInput--; this.output._blessedOutput--; if (this.input._blessedInput === 0) { this.input.removeListener('keypress', this.input._keypressHandler); this.input.removeListener('data', this.input._dataHandler); delete this.input._keypressHandler; delete this.input._dataHandler; if (this.input.setRawMode) { if (this.input.isRaw) { this.input.setRawMode(false); } if (!this.input.destroyed) { this.input.pause(); } } } if (this.output._blessedOutput === 0) { this.output.removeListener('resize', this.output._resizeHandler); delete this.output._resizeHandler; } this.removeListener('newListener', this._newHandler); delete this._newHandler; this.destroyed = true; this.emit('destroy'); } }; Program.prototype.key = function(key, listener) { if (typeof key === 'string') key = key.split(/\s*,\s*/); key.forEach(function(key) { return this.on('key ' + key, listener); }, this); }; Program.prototype.onceKey = function(key, listener) { if (typeof key === 'string') key = key.split(/\s*,\s*/); key.forEach(function(key) { return this.once('key ' + key, listener); }, this); }; Program.prototype.unkey = Program.prototype.removeKey = function(key, listener) { if (typeof key === 'string') key = key.split(/\s*,\s*/); key.forEach(function(key) { return this.removeListener('key ' + key, listener); }, this); }; // XTerm mouse events // http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking // To better understand these // the xterm code is very helpful: // Relevant files: // button.c, charproc.c, misc.c // Relevant functions in xterm/button.c: // BtnCode, EmitButtonCode, EditorButton, SendMousePosition // send a mouse event: // regular/utf8: ^[[M Cb Cx Cy // urxvt: ^[[ Cb ; Cx ; Cy M // sgr: ^[[ Cb ; Cx ; Cy M/m // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r // locator: CSI P e ; P b ; P r ; P c ; P p & w // motion example of a left click: // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7< // mouseup, mousedown, mousewheel // left click: ^[[M 3<^[[M#3< // mousewheel up: ^[[M`3> Program.prototype.bindMouse = function() { if (this._boundMouse) return; this._boundMouse = true; var decoder = new StringDecoder('utf8') , self = this; this.on('data', function(data) { var text = decoder.write(data); if (!text) return; self._bindMouse(text, data); }); }; Program.prototype._bindMouse = function(s, buf) { var self = this , key , parts , b , x , y , mod , params , down , page , button; key = { name: undefined, ctrl: false, meta: false, shift: false }; if (Buffer.isBuffer(s)) { if (s[0] > 127 && s[1] === undefined) { s[0] -= 128; s = '\x1b' + s.toString('utf-8'); } else { s = s.toString('utf-8'); } } // if (this.8bit) { // s = s.replace(/\233/g, '\x1b['); // buf = new Buffer(s, 'utf8'); // } // XTerm / X10 for buggy VTE // VTE can only send unsigned chars and no unicode for coords. This limits // them to 0xff. However, normally the x10 protocol does not allow a byte // under 0x20, but since VTE can have the bytes overflow, we can consider // bytes below 0x20 to be up to 0xff + 0x20. This gives a limit of 287. Since // characters ranging from 223 to 248 confuse javascript's utf parser, we // need to parse the raw binary. We can detect whether the terminal is using // a bugged VTE version by examining the coordinates and seeing whether they // are a value they would never otherwise be with a properly implemented x10 // protocol. This method of detecting VTE is only 99% reliable because we // can't check if the coords are 0x00 (255) since that is a valid x10 coord // technically. var bx = s.charCodeAt(4); var by = s.charCodeAt(5); if (buf[0] === 0x1b && buf[1] === 0x5b && buf[2] === 0x4d && (this.isVTE || bx >= 65533 || by >= 65533 || (bx > 0x00 && bx < 0x20) || (by > 0x00 && by < 0x20) || (buf[4] > 223 && buf[4] < 248 && buf.length === 6) || (buf[5] > 223 && buf[5] < 248 && buf.length === 6))) { b = buf[3]; x = buf[4]; y = buf[5]; // unsigned char overflow. if (x < 0x20) x += 0xff; if (y < 0x20) y += 0xff; // Convert the coordinates into a // properly formatted x10 utf8 sequence. s = '\x1b[M' + String.fromCharCode(b) + String.fromCharCode(x) + String.fromCharCode(y); } // XTerm / X10 if (parts = /^\x1b\[M([\x00\u0020-\uffff]{3})/.exec(s)) { b = parts[1].charCodeAt(0); x = parts[1].charCodeAt(1); y = parts[1].charCodeAt(2); key.name = 'mouse'; key.type = 'X10'; key.raw = [b, x, y, parts[0]]; key.buf = buf; key.x = x - 32; key.y = y - 32; if (this.zero) key.x--, key.y--; if (x === 0) key.x = 255; if (y === 0) key.y = 255; mod = b >> 2; key.shift = !!(mod & 1); key.meta = !!((mod >> 1) & 1); key.ctrl = !!((mod >> 2) & 1); b -= 32; if ((b >> 6) & 1) { key.action = b & 1 ? 'wheeldown' : 'wheelup'; key.button = 'middle'; } else if (b === 3) { // NOTE: x10 and urxvt have no way // of telling which button mouseup used. key.action = 'mouseup'; key.button = this._lastButton || 'unknown'; delete this._lastButton; } else { key.action = 'mousedown'; button = b & 3; key.button = button === 0 ? 'left' : button === 1 ? 'middle' : button === 2 ? 'right' : 'unknown'; this._lastButton = key.button; } // Probably a movement. // The *newer* VTE gets mouse movements comepletely wrong. // This presents a problem: older versions of VTE that get it right might // be confused by the second conditional in the if statement. // NOTE: Possibly just switch back to the if statement below. // none, shift, ctrl, alt // gnome: 32, 36, 48, 40 // xterm: 35, _, 51, _ // urxvt: 35, _, _, _ // if (key.action === 'mousedown' && key.button === 'unknown') { if (b === 35 || b === 39 || b === 51 || b === 43 || (this.isVTE && (b === 32 || b === 36 || b === 48 || b === 40))) { delete key.button; key.action = 'mousemove'; } self.emit('mouse', key); return; } // URxvt if (parts = /^\x1b\[(\d+;\d+;\d+)M/.exec(s)) { params = parts[1].split(';'); b = +params[0]; x = +params[1]; y = +params[2]; key.name = 'mouse'; key.type = 'urxvt'; key.raw = [b, x, y, parts[0]]; key.buf = buf; key.x = x; key.y = y; if (this.zero) key.x--, key.y--; mod = b >> 2; key.shift = !!(mod & 1); key.meta = !!((mod >> 1) & 1); key.ctrl = !!((mod >> 2) & 1); // XXX Bug in urxvt after wheelup/down on mousemove // NOTE: This may be different than 128/129 depending // on mod keys. if (b === 128 || b === 129) { b = 67; } b -= 32; if ((b >> 6) & 1) { key.action = b & 1 ? 'wheeldown' : 'wheelup'; key.button = 'middle'; } else if (b === 3) { // NOTE: x10 and urxvt have no way // of telling which button mouseup used. key.action = 'mouseup'; key.button = this._lastButton || 'unknown'; delete this._lastButton; } else { key.action = 'mousedown'; button = b & 3; key.button = button === 0 ? 'left' : button === 1 ? 'middle' : button === 2 ? 'right' : 'unknown'; // NOTE: 0/32 = mousemove, 32/64 = mousemove with left down // if ((b >> 1) === 32) this._lastButton = key.button; } // Probably a movement. // The *newer* VTE gets mouse movements comepletely wrong. // This presents a problem: older versions of VTE that get it right might // be confused by the second conditional in the if statement. // NOTE: Possibly just switch back to the if statement below. // none, shift, ctrl, alt // urxvt: 35, _, _, _ // gnome: 32, 36, 48, 40 // if (key.action === 'mousedown' && key.button === 'unknown') { if (b === 35 || b === 39 || b === 51 || b === 43 || (this.isVTE && (b === 32 || b === 36 || b === 48 || b === 40))) { delete key.button; key.action = 'mousemove'; } self.emit('mouse', key); return; } // SGR if (parts = /^\x1b\[<(\d+;\d+;\d+)([mM])/.exec(s)) { down = parts[2] === 'M'; params = parts[1].split(';'); b = +params[0]; x = +params[1]; y = +params[2]; key.name = 'mouse'; key.type = 'sgr'; key.raw = [b, x, y, parts[0]]; key.buf = buf; key.x = x; key.y = y; if (this.zero) key.x--, key.y--; mod = b >> 2; key.shift = !!(mod & 1); key.meta = !!((mod >> 1) & 1); key.ctrl = !!((mod >> 2) & 1); if ((b >> 6) & 1) { key.action = b & 1 ? 'wheeldown' : 'wheelup'; key.button = 'middle'; } else { key.action = down ? 'mousedown' : 'mouseup'; button = b & 3; key.button = button === 0 ? 'left' : button === 1 ? 'middle' : button === 2 ? 'right' : 'unknown'; } // Probably a movement. // The *newer* VTE gets mouse movements comepletely wrong. // This presents a problem: older versions of VTE that get it right might // be confused by the second conditional in the if statement. // NOTE: Possibly just switch back to the if statement below. // none, shift, ctrl, alt // xterm: 35, _, 51, _ // gnome: 32, 36, 48, 40 // if (key.action === 'mousedown' && key.button === 'unknown') { if (b === 35 || b === 39 || b === 51 || b === 43 || (this.isVTE && (b === 32 || b === 36 || b === 48 || b === 40))) { delete key.button; key.action = 'mousemove'; } self.emit('mouse', key); return; } // DEC // The xterm mouse documentation says there is a // `<` prefix, the DECRQLP says there is no prefix. if (parts = /^\x1b\[<(\d+;\d+;\d+;\d+)&w/.exec(s)) { params = parts[1].split(';'); b = +params[0]; x = +params[1]; y = +params[2]; page = +params[3]; key.name = 'mouse'; key.type = 'dec'; key.raw = [b, x, y, parts[0]]; key.buf = buf; key.x = x; key.y = y; key.page = page; if (this.zero) key.x--, key.y--; key.action = b === 3 ? 'mouseup' : 'mousedown'; key.button = b === 2 ? 'left' : b === 4 ? 'middle' : b === 6 ? 'right' : 'unknown'; self.emit('mouse', key); return; } // vt300 if (parts = /^\x1b\[24([0135])~\[(\d+),(\d+)\]\r/.exec(s)) { b = +parts[1]; x = +parts[2]; y = +parts[3]; key.name = 'mouse'; key.type = 'vt300'; key.raw = [b, x, y, parts[0]]; key.buf = buf; key.x = x; key.y = y; if (this.zero) key.x--, key.y--; key.action = 'mousedown'; key.button = b === 1 ? 'left' : b === 2 ? 'middle' : b === 5 ? 'right' : 'unknown'; self.emit('mouse', key); return; } if (parts = /^\x1b\[(O|I)/.exec(s)) { key.action = parts[1] === 'I' ? 'focus' : 'blur'; self.emit('mouse', key); self.emit(key.action); return; } }; // gpm support for linux vc Program.prototype.enableGpm = function() { var self = this; var gpmclient = require('./gpmclient'); if (this.gpm) return; this.gpm = gpmclient(); this.gpm.on('btndown', function(btn, modifier, x, y) { x--, y--; var key = { name: 'mouse', type: 'GPM', action: 'mousedown', button: self.gpm.ButtonName(btn), raw: [btn, modifier, x, y], x: x, y: y, shift: self.gpm.hasShiftKey(modifier), meta: self.gpm.hasMetaKey(modifier), ctrl: self.gpm.hasCtrlKey(modifier) }; self.emit('mouse', key); }); this.gpm.on('btnup', function(btn, modifier, x, y) { x--, y--; var key = { name: 'mouse', type: 'GPM', action: 'mouseup', button: self.gpm.ButtonName(btn), raw: [btn, modifier, x, y], x: x, y: y, shift: self.gpm.hasShiftKey(modifier), meta: self.gpm.hasMetaKey(modifier), ctrl: self.gpm.hasCtrlKey(modifier) }; self.emit('mouse', key); }); this.gpm.on('move', function(btn, modifier, x, y) { x--, y--; var key = { name: 'mouse', type: 'GPM', action: 'mousemove', button: self.gpm.ButtonName(btn), raw: [btn, modifier, x, y], x: x, y: y, shift: self.gpm.hasShiftKey(modifier), meta: self.gpm.hasMetaKey(modifier), ctrl: self.gpm.hasCtrlKey(modifier) }; self.emit('mouse', key); }); this.gpm.on('drag', function(btn, modifier, x, y) { x--, y--; var key = { name: 'mouse', type: 'GPM', action: 'mousemove', button: self.gpm.ButtonName(btn), raw: [btn, modifier, x, y], x: x, y: y, shift: self.gpm.hasShiftKey(modifier), meta: self.gpm.hasMetaKey(modifier), ctrl: self.gpm.hasCtrlKey(modifier) }; self.emit('mouse', key); }); this.gpm.on('mousewheel', function(btn, modifier, x, y, dx, dy) { var key = { name: 'mouse', type: 'GPM', action: dy > 0 ? 'wheelup' : 'wheeldown', button: self.gpm.ButtonName(btn), raw: [btn, modifier, x, y, dx, dy], x: x, y: y, shift: self.gpm.hasShiftKey(modifier), meta: self.gpm.hasMetaKey(modifier), ctrl: self.gpm.hasCtrlKey(modifier) }; self.emit('mouse', key); }); }; Program.prototype.disableGpm = function() { if (this.gpm) { this.gpm.stop(); delete this.gpm; } }; // All possible responses from the terminal Program.prototype.bindResponse = function() { if (this._boundResponse) return; this._boundResponse = true; var decoder = new StringDecoder('utf8') , self = this; this.on('data', function(data) { data = decoder.write(data); if (!data) return; self._bindResponse(data); }); }; Program.prototype._bindResponse = function(s) { var out = {} , parts; if (Buffer.isBuffer(s)) { if (s[0] > 127 && s[1] === undefined) { s[0] -= 128; s = '\x1b' + s.toString('utf-8'); } else { s = s.toString('utf-8'); } } // CSI P s c // Send Device Attributes (Primary DA). // CSI > P s c // Send Device Attributes (Secondary DA). if (parts = /^\x1b\[(\?|>)(\d*(?:;\d*)*)c/.exec(s)) { parts = parts[2].split(';').map(function(ch) { return +ch || 0; }); out.event = 'device-attributes'; out.code = 'DA'; if (parts[1] === '?') { out.type = 'primary-attribute'; // VT100-style params: if (parts[0] === 1 && parts[2] === 2) { out.term = 'vt100'; out.advancedVideo = true; } else if (parts[0] === 1 && parts[2] === 0) { out.term = 'vt101'; } else if (parts[0] === 6) { out.term = 'vt102'; } else if (parts[0] === 60 && parts[1] === 1 && parts[2] === 2 && parts[3] === 6 && parts[4] === 8 && parts[5] === 9 && parts[6] === 15) { out.term = 'vt220'; } else { // VT200-style params: parts.forEach(function(attr) { switch (attr) { case 1: out.cols132 = true; break; case 2: out.printer = true; break; case 6: out.selectiveErase = true; break; case 8: out.userDefinedKeys = true; break; case 9: out.nationalReplacementCharsets = true; break; case 15: out.technicalCharacters = true; break; case 18: out.userWindows = true; break; case 21: out.horizontalScrolling = true; break; case 22: out.ansiColor = true; break; case 29: out.ansiTextLocator = true; break; } }); } } else { out.type = 'secondary-attribute'; switch (parts[0]) { case 0: out.term = 'vt100'; break; case 1: out.term = 'vt220'; break; case 2: out.term = 'vt240'; break; case 18: out.term = 'vt330'; break; case 19: out.term = 'vt340'; break; case 24: out.term = 'vt320'; break; case 41: out.term = 'vt420'; break; case 61: out.term = 'vt510'; break; case 64: out.term = 'vt520'; break; case 65: out.term = 'vt525'; break; } out.firmwareVersion = parts[1]; out.romCartridgeRegistrationNumber = parts[2]; } // LEGACY out.deviceAttributes = out; this.emit('response', out); this.emit('response ' + out.event, out); return; } // CSI Ps n Device Status Report (DSR). // Ps = 5 -> Status Report. Result (``OK'') is // CSI 0 n // CSI ? Ps n // Device Status Report (DSR, DEC-specific). // Ps = 1 5 -> Report Printer status as CSI ? 1 0 n (ready). // or CSI ? 1 1 n (not ready). // Ps = 2 5 -> Report UDK status as CSI ? 2 0 n (unlocked) // or CSI ? 2 1 n (locked). // Ps = 2 6 -> Report Keyboard status as // CSI ? 2 7 ; 1 ; 0 ; 0 n (North American). // The last two parameters apply to VT400 & up, and denote key- // board ready and LK01 respectively. // Ps = 5 3 -> Report Locator status as // CSI ? 5 3 n Locator available, if compiled-in, or // CSI ? 5 0 n No Locator, if not. if (parts = /^\x1b\[(\?)?(\d+)(?:;(\d+);(\d+);(\d+))?n/.exec(s)) { out.event = 'device-status'; out.code = 'DSR'; if (!parts[1] && parts[2] === '0' && !parts[3]) { out.type = 'device-status'; out.status = 'OK'; // LEGACY out.deviceStatus = out.status; this.emit('response', out); this.emit('response ' + out.event, out); return; } if (parts[1] && (parts[2] === '10' || parts[2] === '11') && !parts[3]) { out.type = 'printer-status'; out.status = parts[2] === '10' ? 'ready' : 'not ready'; // LEGACY out.printerStatus = out.status; this.emit('response', out); this.emit('response ' + out.event, out); return; } if (parts[1] && (parts[2] === '20' || parts[2] === '21') && !parts[3]) { out.type = 'udk-status'; out.status = parts[2] === '20' ? 'unlocked' : 'locked'; // LEGACY out.UDKStatus = out.status; this.emit('response', out); this.emit('response ' + out.event, out); return; } if (parts[1] && parts[2] === '27' && parts[3] === '1' && parts[4] === '0' && parts[5] === '0') { out.type = 'keyboard-status'; out.status = 'OK'; // LEGACY out.keyboardStatus = out.status; this.emit('response', out); this.emit('response ' + out.event, out); return; } if (parts[1] && (parts[2] === '53' || parts[2] === '50') && !parts[3]) { out.type = 'locator-status'; out.status = parts[2] === '53' ? 'available' : 'unavailable'; // LEGACY out.locator = out.status; this.emit('response', out); this.emit('response ' + out.event, out); return; } out.type = 'error'; out.text = 'Unhandled: ' + JSON.stringify(parts); // LEGACY out.error = out.text; this.emit('response', out); this.emit('response ' + out.event, out); return; } // CSI Ps n Device Status Report (DSR). // Ps = 6 -> Report Cursor Position (CPR) [row;column]. // Result is // CSI r ; c R // CSI ? Ps n // Device Status Report (DSR, DEC-specific). // Ps = 6 -> Report Cursor Position (CPR) [row;column] as CSI // ? r ; c R (assumes page is zero). if (parts = /^\x1b\[(\?)?(\d+);(\d+)R/.exec(s)) { out.event = 'device-status'; out.code = 'DSR'; out.type = 'cursor-status'; out.status = { x: +parts[3], y: +parts[2], page: !parts[1] ? undefined : 0 }; out.x = out.status.x; out.y = out.status.y; out.page = out.status.page; // LEGACY out.cursor = out.status; this.emit('response', out); this.emit('response ' + out.event, out); return; } // CSI Ps ; Ps ; Ps t // Window manipulation (from dtterm, as well as extensions). // These controls may be disabled using the allowWindowOps // resource. Valid values for the first (and any additional // parameters) are: // Ps = 1 1 -> Report xterm window state. If the xterm window // is open (non-iconified), it returns CSI 1 t . If the xterm // window is iconified, it returns CSI 2 t . // Ps = 1 3 -> Report xterm window position. Result is CSI 3 // ; x ; y t // Ps = 1 4 -> Report xterm window in pixels. Result is CSI // 4 ; height ; width t // Ps = 1 8 -> Report the size of the text area in characters. // Result is CSI 8 ; height ; width t // Ps = 1 9 -> Report the size of the screen in characters. // Result is CSI 9 ; height ; width t if (parts = /^\x1b\[(\d+)(?:;(\d+);(\d+))?t/.exec(s)) { out.event = 'window-manipulation'; out.code = ''; if ((parts[1] === '1' || parts[1] === '2') && !parts[2]) { out.type = 'window-state'; out.state = parts[1] === '1' ? 'non-iconified' : 'iconified'; // LEGACY out.windowState = out.state; this.emit('response', out); this.emit('response ' + out.event, out); return; } if (parts[1] === '3' && parts[2]) { out.type = 'window-position'; out.position = { x: +parts[2], y: +parts[3] }; out.x = out.position.x; out.y = out.position.y; // LEGACY out.windowPosition = out.position; this.emit('response', out); this.emit('response ' + out.event, out); return; } if (parts[1] === '4' && parts[2]) { out.type = 'window-size-pixels'; out.size = { height: +parts[2], width: +parts[3] }; out.height = out.size.height; out.width = out.size.width; // LEGACY out.windowSizePixels = out.size; this.emit('response', out); this.emit('response ' + out.event, out); return; } if (parts[1] === '8' && parts[2]) { out.type = 'textarea-size'; out.size = { height: +parts[2], width: +parts[3] }; out.height = out.size.height; out.width = out.size.width; // LEGACY out.textAreaSizeCharacters = out.size; this.emit('response', out); this.emit('response ' + out.event, out); return; } if (parts[1] === '9' && parts[2]) { out.type = 'screen-size'; out.size = { height: +parts[2], width: +parts[3] }; out.height = out.size.height; out.width = out.size.width; // LEGACY out.screenSizeCharacters = out.size; this.emit('response', out); this.emit('response ' + out.event, out); return; } out.type = 'error'; out.text = 'Unhandled: ' + JSON.stringify(parts); // LEGACY out.error = out.text; this.emit('response', out); this.emit('response ' + out.event, out); return; } // rxvt-unicode does not support window manipulation // Result Normal: OSC l/L 0xEF 0xBF 0xBD // Result ASCII: OSC l/L 0x1c (file separator) // Result UTF8->ASCII: OSC l/L 0xFD // Test with: // echo -ne '\ePtmux;\e\e[>3t\e\\' // sleep 2 && echo -ne '\ePtmux;\e\e[21t\e\\' & cat -v // - // echo -ne '\e[>3t' // sleep 2 && echo -ne '\e[21t' & cat -v if (parts = /^\x1b\](l|L)([^\x07\x1b]*)$/.exec(s)) { parts[2] = 'rxvt'; s = '\x1b]' + parts[1] + parts[2] + '\x1b\\'; } // CSI Ps ; Ps ; Ps t // Window manipulation (from dtterm, as well as extensions). // These controls may be disabled using the allowWindowOps // resource. Valid values for the first (and any additional // parameters) are: // Ps = 2 0 -> Report xterm window's icon label. Result is // OSC L label ST // Ps = 2 1 -> Report xterm window's title. Result is OSC l // label ST if (parts = /^\x1b\](l|L)([^\x07\x1b]*)(?:\x07|\x1b\\)/.exec(s)) { out.event = 'window-manipulation'; out.code = ''; if (parts[1] === 'L') { out.type = 'window-icon-label'; out.text = parts[2]; // LEGACY out.windowIconLabel = out.text; this.emit('response', out); this.emit('response ' + out.event, out); return; } if (parts[1] === 'l') { out.type = 'window-title'; out.text = parts[2]; // LEGACY out.windowTitle = out.text; this.emit('response', out); this.emit('response ' + out.event, out); return; } out.type = 'error'; out.text = 'Unhandled: ' + JSON.stringify(parts); // LEGACY out.error = out.text; this.emit('response', out); this.emit('response ' + out.event, out); return; } // CSI Ps ' | // Request Locator Position (DECRQLP). // -> CSI Pe ; Pb ; Pr ; Pc ; Pp & w // Parameters are [event;button;row;column;page]. // Valid values for the event: // Pe = 0 -> locator unavailable - no other parameters sent. // Pe = 1 -> request - xterm received a DECRQLP. // Pe = 2 -> left button down. // Pe = 3 -> left button up. // Pe = 4 -> middle button down. // Pe = 5 -> middle button up. // Pe = 6 -> right button down. // Pe = 7 -> right button up. // Pe = 8 -> M4 button down. // Pe = 9 -> M4 button up. // Pe = 1 0 -> locator outside filter rectangle. // ``button'' parameter is a bitmask indicating which buttons are // pressed: // Pb = 0 <- no buttons down. // Pb & 1 <- right button down. // Pb & 2 <- middle button down. // Pb & 4 <- left button down. // Pb & 8 <- M4 button down. // ``row'' and ``column'' parameters are the coordinates of the // locator position in the xterm window, encoded as ASCII deci- // mal. // The ``page'' parameter is not used by xterm, and will be omit- // ted. // NOTE: // This is already implemented in the _bindMouse // method, but it might make more sense here. // The xterm mouse documentation says there is a // `<` prefix, the DECRQLP says there is no prefix. if (parts = /^\x1b\[(\d+(?:;\d+){4})&w/.exec(s)) { parts = parts[1].split(';').map(function(ch) { return +ch; }); out.event = 'locator-position'; out.code = 'DECRQLP'; switch (parts[0]) { case 0: out.status = 'locator-unavailable'; break; case 1: out.status = 'request'; break; case 2: out.status = 'left-button-down'; break; case 3: out.status = 'left-button-up'; break; case 4: out.status = 'middle-button-down'; break; case 5: out.status = 'middle-button-up'; break; case 6: out.status = 'right-button-down'; break; case 7: out.status = 'right-button-up'; break; case 8: out.status = 'm4-button-down'; break; case 9: out.status = 'm4-button-up'; break; case 10: out.status = 'locator-outside'; break; } out.mask = parts[1]; out.row = parts[2]; out.col = parts[3]; out.page = parts[4]; // LEGACY out.locatorPosition = out; this.emit('response', out); this.emit('response ' + out.event, out); return; } // OSC Ps ; Pt BEL // OSC Ps ; Pt ST // Set Text Parameters if (parts = /^\x1b\](\d+);([^\x07\x1b]+)(?:\x07|\x1b\\)/.exec(s)) { out.event = 'text-params'; out.code = 'Set Text Parameters'; out.ps = +s[1]; out.pt = s[2]; this.emit('response', out); this.emit('response ' + out.event, out); } }; Program.prototype.response = function(name, text, callback, noBypass) { var self = this; if (arguments.length === 2) { callback = text; text = name; name = null; } if (!callback) { callback = function() {}; } this.bindResponse(); name = name ? 'response ' + name : 'response'; var onresponse; this.once(name, onresponse = function(event) { if (timeout) clearTimeout(timeout); if (event.type === 'error') { return callback(new Error(event.event + ': ' + event.text)); } return callback(null, event); }); var timeout = setTimeout(function() { self.removeListener(name, onresponse); return callback(new Error('Timeout.')); }, 2000); return noBypass ? this._write(text) : this._twrite(text); }; Program.prototype._owrite = Program.prototype.write = function(text) { if (!this.output.writable) return; return this.output.write(text); }; Program.prototype._buffer = function(text) { if (this._exiting) { this.flush(); this._owrite(text); return; } if (this._buf) { this._buf += text; return; } this._buf = text; nextTick(this._flush); return true; }; Program.prototype.flush = function() { if (!this._buf) return; this._owrite(this._buf); this._buf = ''; }; Program.prototype._write = function(text) { if (this.ret) return text; if (this.useBuffer) { return this._buffer(text); } return this._owrite(text); }; // Example: `DCS tmux; ESC Pt ST` // Real: `DCS tmux; ESC Pt ESC \` Program.prototype._twrite = function(data) { var self = this , iterations = 0 , timer; if (this.tmux) { // Replace all STs with BELs so they can be nested within the DCS code. data = data.replace(/\x1b\\/g, '\x07'); // Wrap in tmux forward DCS: data = '\x1bPtmux;\x1b' + data + '\x1b\\'; // If we've never even flushed yet, it means we're still in // the normal buffer. Wait for alt screen buffer. if (this.output.bytesWritten === 0) { timer = setInterval(function() { if (self.output.bytesWritten > 0 || ++iterations === 50) { clearInterval(timer); self.flush(); self._owrite(data); } }, 100); return true; } // NOTE: Flushing the buffer is required in some cases. // The DCS code must be at the start of the output. this.flush(); // Write out raw now that the buffer is flushed. return this._owrite(data); } return this._write(data); }; Program.prototype.echo = Program.prototype.print = function(text, attr) { return attr ? this._write(this.text(text, attr)) : this._write(text); }; Program.prototype._ncoords = function() { if (this.x < 0) this.x = 0; else if (this.x >= this.cols) this.x = this.cols - 1; if (this.y < 0) this.y = 0; else if (this.y >= this.rows) this.y = this.rows - 1; }; Program.prototype.setx = function(x) { return this.cursorCharAbsolute(x); // return this.charPosAbsolute(x); }; Program.prototype.sety = function(y) { return this.linePosAbsolute(y); }; Program.prototype.move = function(x, y) { return this.cursorPos(y, x); }; // TODO: Fix cud and cuu calls. Program.prototype.omove = function(x, y) { if (!this.zero) { x = (x || 1) - 1; y = (y || 1) - 1; } else { x = x || 0; y = y || 0; } if (y === this.y && x === this.x) { return; } if (y === this.y) { if (x > this.x) { this.cuf(x - this.x); } else if (x < this.x) { this.cub(this.x - x); } } else if (x === this.x) { if (y > this.y) { this.cud(y - this.y); } else if (y < this.y) { this.cuu(this.y - y); } } else { if (!this.zero) x++, y++; this.cup(y, x); } }; Program.prototype.rsetx = function(x) { // return this.HPositionRelative(x); if (!x) return; return x > 0 ? this.forward(x) : this.back(-x); }; Program.prototype.rsety = function(y) { // return this.VPositionRelative(y); if (!y) return; return y > 0 ? this.up(y) : this.down(-y); }; Program.prototype.rmove = function(x, y) { this.rsetx(x); this.rsety(y); }; Program.prototype.simpleInsert = function(ch, i, attr) { return this._write(this.repeat(ch, i), attr); }; Program.prototype.repeat = function(ch, i) { if (!i || i < 0) i = 0; return Array(i + 1).join(ch); }; Program.prototype.__defineGetter__('title', function() { return this._title; }); Program.prototype.__defineSetter__('title', function(title) { this.setTitle(title); return this._title; }); // Specific to iTerm2, but I think it's really cool. // Example: // if (!screen.copyToClipboard(text)) { // execClipboardProgram(text); // } Program.prototype.copyToClipboard = function(text) { if (this.isiTerm2) { this._twrite('\x1b]50;CopyToCliboard=' + text + '\x07'); return true; } return false; }; // Only XTerm and iTerm2. If you know of any others, post them. Program.prototype.cursorShape = function(shape, blink) { if (this.isiTerm2) { switch (shape) { case 'block': if (!blink) { this._twrite('\x1b]50;CursorShape=0;BlinkingCursorEnabled=0\x07'); } else { this._twrite('\x1b]50;CursorShape=0;BlinkingCursorEnabled=1\x07'); } break; case 'underline': if (!blink) { // this._twrite('\x1b]50;CursorShape=n;BlinkingCursorEnabled=0\x07'); } else { // this._twrite('\x1b]50;CursorShape=n;BlinkingCursorEnabled=1\x07'); } break; case 'line': if (!blink) { this._twrite('\x1b]50;CursorShape=1;BlinkingCursorEnabled=0\x07'); } else { this._twrite('\x1b]50;CursorShape=1;BlinkingCursorEnabled=1\x07'); } break; } return true; } else if (this.term('xterm') || this.term('screen')) { switch (shape) { case 'block': if (!blink) { this._twrite('\x1b[0 q'); } else { this._twrite('\x1b[1 q'); } break; case 'underline': if (!blink) { this._twrite('\x1b[2 q'); } else { this._twrite('\x1b[3 q'); } break; case 'line': if (!blink) { this._twrite('\x1b[4 q'); } else { this._twrite('\x1b[5 q'); } break; } return true; } return false; }; Program.prototype.cursorColor = function(color) { if (this.term('xterm') || this.term('rxvt') || this.term('screen')) { this._twrite('\x1b]12;' + color + '\x07'); return true; } return false; }; Program.prototype.cursorReset = Program.prototype.resetCursor = function() { if (this.term('xterm') || this.term('rxvt') || this.term('screen')) { // XXX // return this.resetColors(); this._twrite('\x1b[0 q'); this._twrite('\x1b]112\x07'); // urxvt doesnt support OSC 112 this._twrite('\x1b]12;white\x07'); return true; } return false; }; Program.prototype.getTextParams = function(param, callback) { return this.response('text-params', '\x1b]' + param + ';?\x07', function(err, data) { if (err) return callback(err); return callback(null, data.pt); }); }; Program.prototype.getCursorColor = function(callback) { return this.getTextParams(12, callback); }; /** * Normal */ //Program.prototype.pad = Program.prototype.nul = function() { //if (this.has('pad')) return this.put.pad(); return this._write('\x80'); }; Program.prototype.bel = Program.prototype.bell = function() { if (this.has('bel')) return this.put.bel(); return this._write('\x07'); }; Program.prototype.vtab = function() { this.y++; this._ncoords(); return this._write('\x0b'); }; Program.prototype.ff = Program.prototype.form = function() { if (this.has('ff')) return this.put.ff(); return this._write('\x0c'); }; Program.prototype.kbs = Program.prototype.backspace = function() { this.x--; this._ncoords(); if (this.has('kbs')) return this.put.kbs(); return this._write('\x08'); }; Program.prototype.ht = Program.prototype.tab = function() { this.x += 8; this._ncoords(); if (this.has('ht')) return this.put.ht(); return this._write('\t'); }; Program.prototype.shiftOut = function() { // if (this.has('S2')) return this.put.S2(); return this._write('\x0e'); }; Program.prototype.shiftIn = function() { // if (this.has('S3')) return this.put.S3(); return this._write('\x0f'); }; Program.prototype.cr = Program.prototype.return = function() { this.x = 0; if (this.has('cr')) return this.put.cr(); return this._write('\r'); }; Program.prototype.nel = Program.prototype.newline = Program.prototype.feed = function() { if (this.tput && this.tput.bools.eat_newline_glitch && this.x >= this.cols) { return; } this.x = 0; this.y++; this._ncoords(); if (this.has('nel')) return this.put.nel(); return this._write('\n'); }; /** * Esc */ // ESC D Index (IND is 0x84). Program.prototype.ind = Program.prototype.index = function() { this.y++; this._ncoords(); if (this.tput) return this.put.ind(); return this._write('\x1bD'); }; // ESC M Reverse Index (RI is 0x8d). Program.prototype.ri = Program.prototype.reverse = Program.prototype.reverseIndex = function() { this.y--; this._ncoords(); if (this.tput) return this.put.ri(); return this._write('\x1bM'); }; // ESC E Next Line (NEL is 0x85). Program.prototype.nextLine = function() { this.y++; this.x = 0; this._ncoords(); if (this.has('nel')) return this.put.nel(); return this._write('\x1bE'); }; // ESC c Full Reset (RIS). Program.prototype.reset = function() { this.x = this.y = 0; if (this.has('rs1') || this.has('ris')) { return this.has('rs1') ? this.put.rs1() : this.put.ris(); } return this._write('\x1bc'); }; // ESC H Tab Set (HTS is 0x88). Program.prototype.tabSet = function() { if (this.tput) return this.put.hts(); return this._write('\x1bH'); }; // ESC 7 Save Cursor (DECSC). Program.prototype.sc = Program.prototype.saveCursor = function(key) { if (key) return this.lsaveCursor(key); this.savedX = this.x || 0; this.savedY = this.y || 0; if (this.tput) return this.put.sc(); return this._write('\x1b7'); }; // ESC 8 Restore Cursor (DECRC). Program.prototype.rc = Program.prototype.restoreCursor = function(key, hide) { if (key) return this.lrestoreCursor(key, hide); this.x = this.savedX || 0; this.y = this.savedY || 0; if (this.tput) return this.put.rc(); return this._write('\x1b8'); }; // Save Cursor Locally Program.prototype.lsaveCursor = function(key) { key = key || 'local'; this._saved = this._saved || {}; this._saved[key] = this._saved[key] || {}; this._saved[key].x = this.x; this._saved[key].y = this.y; this._saved[key].hidden = this.cursorHidden; }; // Restore Cursor Locally Program.prototype.lrestoreCursor = function(key, hide) { var pos; key = key || 'local'; if (!this._saved || !this._saved[key]) return; pos = this._saved[key]; //delete this._saved[key]; this.cup(pos.y, pos.x); if (hide && pos.hidden !== this.cursorHidden) { if (pos.hidden) { this.hideCursor(); } else { this.showCursor(); } } }; // ESC # 3 DEC line height/width Program.prototype.lineHeight = function() { return this._write('\x1b#'); }; // ESC (,),*,+,-,. Designate G0-G2 Character Set. Program.prototype.charset = function(val, level) { level = level || 0; // See also: // acs_chars / acsc / ac // enter_alt_charset_mode / smacs / as // exit_alt_charset_mode / rmacs / ae // enter_pc_charset_mode / smpch / S2 // exit_pc_charset_mode / rmpch / S3 switch (level) { case 0: level = '('; break; case 1: level = ')'; break; case 2: level = '*'; break; case 3: level = '+'; break; } var name = typeof val === 'string' ? val.toLowerCase() : val; switch (name) { case 'acs': case 'scld': // DEC Special Character and Line Drawing Set. if (this.tput) return this.put.smacs(); val = '0'; break; case 'uk': // UK val = 'A'; break; case 'us': // United States (USASCII). case 'usascii': case 'ascii': if (this.tput) return this.put.rmacs(); val = 'B'; break; case 'dutch': // Dutch val = '4'; break; case 'finnish': // Finnish val = 'C'; val = '5'; break; case 'french': // French val = 'R'; break; case 'frenchcanadian': // FrenchCanadian val = 'Q'; break; case 'german': // German val = 'K'; break; case 'italian': // Italian val = 'Y'; break; case 'norwegiandanish': // NorwegianDanish val = 'E'; val = '6'; break; case 'spanish': // Spanish val = 'Z'; break; case 'swedish': // Swedish val = 'H'; val = '7'; break; case 'swiss': // Swiss val = '='; break; case 'isolatin': // ISOLatin (actually /A) val = '/A'; break; default: // Default if (this.tput) return this.put.rmacs(); val = 'B'; break; } return this._write('\x1b(' + val); }; Program.prototype.enter_alt_charset_mode = Program.prototype.as = Program.prototype.smacs = function() { return this.charset('acs'); }; Program.prototype.exit_alt_charset_mode = Program.prototype.ae = Program.prototype.rmacs = function() { return this.charset('ascii'); }; // ESC N // Single Shift Select of G2 Character Set // ( SS2 is 0x8e). This affects next character only. // ESC O // Single Shift Select of G3 Character Set // ( SS3 is 0x8f). This affects next character only. // ESC n // Invoke the G2 Character Set as GL (LS2). // ESC o // Invoke the G3 Character Set as GL (LS3). // ESC | // Invoke the G3 Character Set as GR (LS3R). // ESC } // Invoke the G2 Character Set as GR (LS2R). // ESC ~ // Invoke the G1 Character Set as GR (LS1R). Program.prototype.setG = function(val) { // if (this.tput) return this.put.S2(); // if (this.tput) return this.put.S3(); switch (val) { case 1: val = '~'; // GR break; case 2: val = 'n'; // GL val = '}'; // GR val = 'N'; // Next Char Only break; case 3: val = 'o'; // GL val = '|'; // GR val = 'O'; // Next Char Only break; } return this._write('\x1b' + val); }; /** * OSC */ // OSC Ps ; Pt ST // OSC Ps ; Pt BEL // Set Text Parameters. Program.prototype.setTitle = function(title) { this._title = title; // if (this.term('screen')) { // // Tmux pane // // if (this.tmux) { // // return this._write('\x1b]2;' + title + '\x1b\\'); // // } // return this._write('\x1bk' + title + '\x1b\\'); // } return this._twrite('\x1b]0;' + title + '\x07'); }; // OSC Ps ; Pt ST // OSC Ps ; Pt BEL // Reset colors Program.prototype.resetColors = function(param) { if (this.has('Cr')) { return this.put.Cr(param); } return this._twrite('\x1b]112\x07'); //return this._twrite('\x1b]112;' + param + '\x07'); }; // OSC Ps ; Pt ST // OSC Ps ; Pt BEL // Change dynamic colors Program.prototype.dynamicColors = function(param) { if (this.has('Cs')) { return this.put.Cs(param); } return this._twrite('\x1b]12;' + param + '\x07'); }; // OSC Ps ; Pt ST // OSC Ps ; Pt BEL // Sel data Program.prototype.selData = function(a, b) { if (this.has('Ms')) { return this.put.Ms(a, b); } return this._twrite('\x1b]52;' + a + ';' + b + '\x07'); }; /** * CSI */ // CSI Ps A // Cursor Up Ps Times (default = 1) (CUU). Program.prototype.cuu = Program.prototype.up = Program.prototype.cursorUp = function(param) { this.y -= param || 1; this._ncoords(); if (this.tput) { if (!this.tput.strings.parm_up_cursor) { return this._write(this.repeat(this.tput.cuu1(), param)); } return this.put.cuu(param); } return this._write('\x1b[' + (param || '') + 'A'); }; // CSI Ps B // Cursor Down Ps Times (default = 1) (CUD). Program.prototype.cud = Program.prototype.down = Program.prototype.cursorDown = function(param) { this.y += param || 1; this._ncoords(); if (this.tput) { if (!this.tput.strings.parm_down_cursor) { return this._write(this.repeat(this.tput.cud1(), param)); } return this.put.cud(param); } return this._write('\x1b[' + (param || '') + 'B'); }; // CSI Ps C // Cursor Forward Ps Times (default = 1) (CUF). Program.prototype.cuf = Program.prototype.right = Program.prototype.forward = Program.prototype.cursorForward = function(param) { this.x += param || 1; this._ncoords(); if (this.tput) { if (!this.tput.strings.parm_right_cursor) { return this._write(this.repeat(this.tput.cuf1(), param)); } return this.put.cuf(param); } return this._write('\x1b[' + (param || '') + 'C'); }; // CSI Ps D // Cursor Backward Ps Times (default = 1) (CUB). Program.prototype.cub = Program.prototype.left = Program.prototype.back = Program.prototype.cursorBackward = function(param) { this.x -= param || 1; this._ncoords(); if (this.tput) { if (!this.tput.strings.parm_left_cursor) { return this._write(this.repeat(this.tput.cub1(), param)); } return this.put.cub(param); } return this._write('\x1b[' + (param || '') + 'D'); }; // CSI Ps ; Ps H // Cursor Position [row;column] (default = [1,1]) (CUP). Program.prototype.cup = Program.prototype.pos = Program.prototype.cursorPos = function(row, col) { if (!this.zero) { row = (row || 1) - 1; col = (col || 1) - 1; } else { row = row || 0; col = col || 0; } this.x = col; this.y = row; this._ncoords(); if (this.tput) return this.put.cup(row, col); return this._write('\x1b[' + (row + 1) + ';' + (col + 1) + 'H'); }; // CSI Ps J Erase in Display (ED). // Ps = 0 -> Erase Below (default). // Ps = 1 -> Erase Above. // Ps = 2 -> Erase All. // Ps = 3 -> Erase Saved Lines (xterm). // CSI ? Ps J // Erase in Display (DECSED). // Ps = 0 -> Selective Erase Below (default). // Ps = 1 -> Selective Erase Above. // Ps = 2 -> Selective Erase All. Program.prototype.ed = Program.prototype.eraseInDisplay = function(param) { if (this.tput) { switch (param) { case 'above': param = 1; break; case 'all': param = 2; break; case 'saved': param = 3; break; case 'below': default: param = 0; break; } // extended tput.E3 = ^[[3;J return this.put.ed(param); } switch (param) { case 'above': return this._write('\X1b[1J'); case 'all': return this._write('\x1b[2J'); case 'saved': return this._write('\x1b[3J'); case 'below': default: return this._write('\x1b[J'); } }; Program.prototype.clear = function() { this.x = 0; this.y = 0; if (this.tput) return this.put.clear(); return this._write('\x1b[H\x1b[J'); }; // CSI Ps K Erase in Line (EL). // Ps = 0 -> Erase to Right (default). // Ps = 1 -> Erase to Left. // Ps = 2 -> Erase All. // CSI ? Ps K // Erase in Line (DECSEL). // Ps = 0 -> Selective Erase to Right (default). // Ps = 1 -> Selective Erase to Left. // Ps = 2 -> Selective Erase All. Program.prototype.el = Program.prototype.eraseInLine = function(param) { if (this.tput) { //if (this.tput.back_color_erase) ... switch (param) { case 'left': param = 1; break; case 'all': param = 2; break; case 'right': default: param = 0; break; } return this.put.el(param); } switch (param) { case 'left': return this._write('\x1b[1K'); case 'all': return this._write('\x1b[2K'); case 'right': default: return this._write('\x1b[K'); } }; // CSI Pm m Character Attributes (SGR). // Ps = 0 -> Normal (default). // Ps = 1 -> Bold. // Ps = 4 -> Underlined. // Ps = 5 -> Blink (appears as Bold). // Ps = 7 -> Inverse. // Ps = 8 -> Invisible, i.e., hidden (VT300). // Ps = 2 2 -> Normal (neither bold nor faint). // Ps = 2 4 -> Not underlined. // Ps = 2 5 -> Steady (not blinking). // Ps = 2 7 -> Positive (not inverse). // Ps = 2 8 -> Visible, i.e., not hidden (VT300). // Ps = 3 0 -> Set foreground color to Black. // Ps = 3 1 -> Set foreground color to Red. // Ps = 3 2 -> Set foreground color to Green. // Ps = 3 3 -> Set foreground color to Yellow. // Ps = 3 4 -> Set foreground color to Blue. // Ps = 3 5 -> Set foreground color to Magenta. // Ps = 3 6 -> Set foreground color to Cyan. // Ps = 3 7 -> Set foreground color to White. // Ps = 3 9 -> Set foreground color to default (original). // Ps = 4 0 -> Set background color to Black. // Ps = 4 1 -> Set background color to Red. // Ps = 4 2 -> Set background color to Green. // Ps = 4 3 -> Set background color to Yellow. // Ps = 4 4 -> Set background color to Blue. // Ps = 4 5 -> Set background color to Magenta. // Ps = 4 6 -> Set background color to Cyan. // Ps = 4 7 -> Set background color to White. // Ps = 4 9 -> Set background color to default (original). // If 16-color support is compiled, the following apply. Assume // that xterm's resources are set so that the ISO color codes are // the first 8 of a set of 16. Then the aixterm colors are the // bright versions of the ISO colors: // Ps = 9 0 -> Set foreground color to Black. // Ps = 9 1 -> Set foreground color to Red. // Ps = 9 2 -> Set foreground color to Green. // Ps = 9 3 -> Set foreground color to Yellow. // Ps = 9 4 -> Set foreground color to Blue. // Ps = 9 5 -> Set foreground color to Magenta. // Ps = 9 6 -> Set foreground color to Cyan. // Ps = 9 7 -> Set foreground color to White. // Ps = 1 0 0 -> Set background color to Black. // Ps = 1 0 1 -> Set background color to Red. // Ps = 1 0 2 -> Set background color to Green. // Ps = 1 0 3 -> Set background color to Yellow. // Ps = 1 0 4 -> Set background color to Blue. // Ps = 1 0 5 -> Set background color to Magenta. // Ps = 1 0 6 -> Set background color to Cyan. // Ps = 1 0 7 -> Set background color to White. // If xterm is compiled with the 16-color support disabled, it // supports the following, from rxvt: // Ps = 1 0 0 -> Set foreground and background color to // default. // If 88- or 256-color support is compiled, the following apply. // Ps = 3 8 ; 5 ; Ps -> Set foreground color to the second // Ps. // Ps = 4 8 ; 5 ; Ps -> Set background color to the second // Ps. Program.prototype.sgr = Program.prototype.attr = Program.prototype.charAttributes = function(param, val) { return this._write(this._attr(param, val)); }; Program.prototype.text = function(text, attr) { return this._attr(attr, true) + text + this._attr(attr, false); }; // NOTE: sun-color may not allow multiple params for SGR. Program.prototype._attr = function(param, val) { var self = this , parts , color , m; if (Array.isArray(param)) { parts = param; param = parts[0] || 'normal'; } else { param = param || 'normal'; parts = param.split(/\s*[,;]\s*/); } if (parts.length > 1) { var used = {} , out = []; parts.forEach(function(part) { part = self._attr(part, val).slice(2, -1); if (part === '') return; if (used[part]) return; used[part] = true; out.push(part); }); return '\x1b[' + out.join(';') + 'm'; } if (param.indexOf('no ') === 0) { param = param.substring(3); val = false; } else if (param.indexOf('!') === 0) { param = param.substring(1); val = false; } switch (param) { // attributes case 'normal': case 'default': if (val === false) return ''; return '\x1b[m'; case 'bold': return val === false ? '\x1b[22m' : '\x1b[1m'; case 'ul': case 'underline': case 'underlined': return val === false ? '\x1b[24m' : '\x1b[4m'; case 'blink': return val === false ? '\x1b[25m' : '\x1b[5m'; case 'inverse': return val === false ? '\x1b[27m' : '\x1b[7m'; case 'invisible': return val === false ? '\x1b[28m' : '\x1b[8m'; // 8-color foreground case 'black fg': return val === false ? '\x1b[39m' : '\x1b[30m'; case 'red fg': return val === false ? '\x1b[39m' : '\x1b[31m'; case 'green fg': return val === false ? '\x1b[39m' : '\x1b[32m'; case 'yellow fg': return val === false ? '\x1b[39m' : '\x1b[33m'; case 'blue fg': return val === false ? '\x1b[39m' : '\x1b[34m'; case 'magenta fg': return val === false ? '\x1b[39m' : '\x1b[35m'; case 'cyan fg': return val === false ? '\x1b[39m' : '\x1b[36m'; case 'white fg': case 'light grey fg': case 'light gray fg': case 'bright grey fg': case 'bright gray fg': return val === false ? '\x1b[39m' : '\x1b[37m'; case 'default fg': if (val === false) return ''; return '\x1b[39m'; // 8-color background case 'black bg': return val === false ? '\x1b[49m' : '\x1b[40m'; case 'red bg': return val === false ? '\x1b[49m' : '\x1b[41m'; case 'green bg': return val === false ? '\x1b[49m' : '\x1b[42m'; case 'yellow bg': return val === false ? '\x1b[49m' : '\x1b[43m'; case 'blue bg': return val === false ? '\x1b[49m' : '\x1b[44m'; case 'magenta bg': return val === false ? '\x1b[49m' : '\x1b[45m'; case 'cyan bg': return val === false ? '\x1b[49m' : '\x1b[46m'; case 'white bg': case 'light grey bg': case 'light gray bg': case 'bright grey bg': case 'bright gray bg': return val === false ? '\x1b[49m' : '\x1b[47m'; case 'default bg': if (val === false) return ''; return '\x1b[49m'; // 16-color foreground case 'light black fg': case 'bright black fg': case 'grey fg': case 'gray fg': return val === false ? '\x1b[39m' : '\x1b[90m'; case 'light red fg': case 'bright red fg': return val === false ? '\x1b[39m' : '\x1b[91m'; case 'light green fg': case 'bright green fg': return val === false ? '\x1b[39m' : '\x1b[92m'; case 'light yellow fg': case 'bright yellow fg': return val === false ? '\x1b[39m' : '\x1b[93m'; case 'light blue fg': case 'bright blue fg': return val === false ? '\x1b[39m' : '\x1b[94m'; case 'light magenta fg': case 'bright magenta fg': return val === false ? '\x1b[39m' : '\x1b[95m'; case 'light cyan fg': case 'bright cyan fg': return val === false ? '\x1b[39m' : '\x1b[96m'; case 'light white fg': case 'bright white fg': return val === false ? '\x1b[39m' : '\x1b[97m'; // 16-color background case 'light black bg': case 'bright black bg': case 'grey bg': case 'gray bg': return val === false ? '\x1b[49m' : '\x1b[100m'; case 'light red bg': case 'bright red bg': return val === false ? '\x1b[49m' : '\x1b[101m'; case 'light green bg': case 'bright green bg': return val === false ? '\x1b[49m' : '\x1b[102m'; case 'light yellow bg': case 'bright yellow bg': return val === false ? '\x1b[49m' : '\x1b[103m'; case 'light blue bg': case 'bright blue bg': return val === false ? '\x1b[49m' : '\x1b[104m'; case 'light magenta bg': case 'bright magenta bg': return val === false ? '\x1b[49m' : '\x1b[105m'; case 'light cyan bg': case 'bright cyan bg': return val === false ? '\x1b[49m' : '\x1b[106m'; case 'light white bg': case 'bright white bg': return val === false ? '\x1b[49m' : '\x1b[107m'; // non-16-color rxvt default fg and bg case 'default fg bg': if (val === false) return ''; return this.term('rxvt') ? '\x1b[100m' : '\x1b[39;49m'; default: // 256-color fg and bg if (param[0] === '#') { param = param.replace(/#(?:[0-9a-f]{3}){1,2}/i, colors.match); } m = /^(-?\d+) (fg|bg)$/.exec(param); if (m) { color = +m[1]; if (val === false || color === -1) { return this._attr('default ' + m[2]); } color = colors.reduce(color, this.tput.colors); if (color < 16 || (this.tput && this.tput.colors <= 16)) { if (m[2] === 'fg') { if (color < 8) { color += 30; } else if (color < 16) { color -= 8; color += 90; } } else if (m[2] === 'bg') { if (color < 8) { color += 40; } else if (color < 16) { color -= 8; color += 100; } } return '\x1b[' + color + 'm'; } if (m[2] === 'fg') { return '\x1b[38;5;' + color + 'm'; } if (m[2] === 'bg') { return '\x1b[48;5;' + color + 'm'; } } if (/^[\d;]*$/.test(param)) { return '\x1b[' + param + 'm'; } return null; } }; Program.prototype.fg = Program.prototype.setForeground = function(color, val) { color = color.split(/\s*[,;]\s*/).join(' fg, ') + ' fg'; return this.attr(color, val); }; Program.prototype.bg = Program.prototype.setBackground = function(color, val) { color = color.split(/\s*[,;]\s*/).join(' bg, ') + ' bg'; return this.attr(color, val); }; // CSI Ps n Device Status Report (DSR). // Ps = 5 -> Status Report. Result (``OK'') is // CSI 0 n // Ps = 6 -> Report Cursor Position (CPR) [row;column]. // Result is // CSI r ; c R // CSI ? Ps n // Device Status Report (DSR, DEC-specific). // Ps = 6 -> Report Cursor Position (CPR) [row;column] as CSI // ? r ; c R (assumes page is zero). // Ps = 1 5 -> Report Printer status as CSI ? 1 0 n (ready). // or CSI ? 1 1 n (not ready). // Ps = 2 5 -> Report UDK status as CSI ? 2 0 n (unlocked) // or CSI ? 2 1 n (locked). // Ps = 2 6 -> Report Keyboard status as // CSI ? 2 7 ; 1 ; 0 ; 0 n (North American). // The last two parameters apply to VT400 & up, and denote key- // board ready and LK01 respectively. // Ps = 5 3 -> Report Locator status as // CSI ? 5 3 n Locator available, if compiled-in, or // CSI ? 5 0 n No Locator, if not. Program.prototype.dsr = Program.prototype.deviceStatus = function(param, callback, dec, noBypass) { if (dec) { return this.response('device-status', '\x1b[?' + (param || '0') + 'n', callback, noBypass); } return this.response('device-status', '\x1b[' + (param || '0') + 'n', callback, noBypass); }; Program.prototype.getCursor = function(callback) { return this.deviceStatus(6, callback, false, true); }; Program.prototype.saveReportedCursor = function(callback) { var self = this; if (this.tput.strings.user7 === '\x1b[6n' || this.term('screen')) { return this.getCursor(function(err, data) { if (data) { self._rx = data.status.x; self._ry = data.status.y; } if (!callback) return; return callback(err); }); } if (!callback) return; return callback(); }; Program.prototype.restoreReportedCursor = function() { if (this._rx == null) return; return this.cup(this._ry, this._rx); // return this.nel(); }; /** * Additions */ // CSI Ps @ // Insert Ps (Blank) Character(s) (default = 1) (ICH). Program.prototype.ich = Program.prototype.insertChars = function(param) { this.x += param || 1; this._ncoords(); if (this.tput) return this.put.ich(param); return this._write('\x1b[' + (param || 1) + '@'); }; // CSI Ps E // Cursor Next Line Ps Times (default = 1) (CNL). // same as CSI Ps B ? Program.prototype.cnl = Program.prototype.cursorNextLine = function(param) { this.y += param || 1; this._ncoords(); return this._write('\x1b[' + (param || '') + 'E'); }; // CSI Ps F // Cursor Preceding Line Ps Times (default = 1) (CNL). // reuse CSI Ps A ? Program.prototype.cpl = Program.prototype.cursorPrecedingLine = function(param) { this.y -= param || 1; this._ncoords(); return this._write('\x1b[' + (param || '') + 'F'); }; // CSI Ps G // Cursor Character Absolute [column] (default = [row,1]) (CHA). Program.prototype.cha = Program.prototype.cursorCharAbsolute = function(param) { if (!this.zero) { param = (param || 1) - 1; } else { param = param || 0; } this.x = param; this.y = 0; this._ncoords(); if (this.tput) return this.put.hpa(param); return this._write('\x1b[' + (param + 1) + 'G'); }; // CSI Ps L // Insert Ps Line(s) (default = 1) (IL). Program.prototype.il = Program.prototype.insertLines = function(param) { if (this.tput) return this.put.il(param); return this._write('\x1b[' + (param || '') + 'L'); }; // CSI Ps M // Delete Ps Line(s) (default = 1) (DL). Program.prototype.dl = Program.prototype.deleteLines = function(param) { if (this.tput) return this.put.dl(param); return this._write('\x1b[' + (param || '') + 'M'); }; // CSI Ps P // Delete Ps Character(s) (default = 1) (DCH). Program.prototype.dch = Program.prototype.deleteChars = function(param) { if (this.tput) return this.put.dch(param); return this._write('\x1b[' + (param || '') + 'P'); }; // CSI Ps X // Erase Ps Character(s) (default = 1) (ECH). Program.prototype.ech = Program.prototype.eraseChars = function(param) { if (this.tput) return this.put.ech(param); return this._write('\x1b[' + (param || '') + 'X'); }; // CSI Pm ` Character Position Absolute // [column] (default = [row,1]) (HPA). Program.prototype.hpa = Program.prototype.charPosAbsolute = function(param) { this.x = param || 0; this._ncoords(); if (this.tput) { return this.put.hpa.apply(this.put, arguments); } param = slice.call(arguments).join(';'); return this._write('\x1b[' + (param || '') + '`'); }; // 141 61 a * HPR - // Horizontal Position Relative // reuse CSI Ps C ? Program.prototype.hpr = Program.prototype.HPositionRelative = function(param) { if (this.tput) return this.cuf(param); this.x += param || 1; this._ncoords(); // Does not exist: // if (this.tput) return this.put.hpr(param); return this._write('\x1b[' + (param || '') + 'a'); }; // CSI Ps c Send Device Attributes (Primary DA). // Ps = 0 or omitted -> request attributes from terminal. The // response depends on the decTerminalID resource setting. // -> CSI ? 1 ; 2 c (``VT100 with Advanced Video Option'') // -> CSI ? 1 ; 0 c (``VT101 with No Options'') // -> CSI ? 6 c (``VT102'') // -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c (``VT220'') // The VT100-style response parameters do not mean anything by // themselves. VT220 parameters do, telling the host what fea- // tures the terminal supports: // Ps = 1 -> 132-columns. // Ps = 2 -> Printer. // Ps = 6 -> Selective erase. // Ps = 8 -> User-defined keys. // Ps = 9 -> National replacement character sets. // Ps = 1 5 -> Technical characters. // Ps = 2 2 -> ANSI color, e.g., VT525. // Ps = 2 9 -> ANSI text locator (i.e., DEC Locator mode). // CSI > Ps c // Send Device Attributes (Secondary DA). // Ps = 0 or omitted -> request the terminal's identification // code. The response depends on the decTerminalID resource set- // ting. It should apply only to VT220 and up, but xterm extends // this to VT100. // -> CSI > Pp ; Pv ; Pc c // where Pp denotes the terminal type // Pp = 0 -> ``VT100''. // Pp = 1 -> ``VT220''. // and Pv is the firmware version (for xterm, this was originally // the XFree86 patch number, starting with 95). In a DEC termi- // nal, Pc indicates the ROM cartridge registration number and is // always zero. // More information: // xterm/charproc.c - line 2012, for more information. // vim responds with ^[[?0c or ^[[?1c after the terminal's response (?) Program.prototype.da = Program.prototype.sendDeviceAttributes = function(param, callback) { return this.response('device-attributes', '\x1b[' + (param || '') + 'c', callback); }; // CSI Pm d // Line Position Absolute [row] (default = [1,column]) (VPA). // NOTE: Can't find in terminfo, no idea why it has multiple params. Program.prototype.vpa = Program.prototype.linePosAbsolute = function(param) { this.y = param || 1; this._ncoords(); if (this.tput) { return this.put.vpa.apply(this.put, arguments); } param = slice.call(arguments).join(';'); return this._write('\x1b[' + (param || '') + 'd'); }; // 145 65 e * VPR - Vertical Position Relative // reuse CSI Ps B ? Program.prototype.vpr = Program.prototype.VPositionRelative = function(param) { if (this.tput) return this.cud(param); this.y += param || 1; this._ncoords(); // Does not exist: // if (this.tput) return this.put.vpr(param); return this._write('\x1b[' + (param || '') + 'e'); }; // CSI Ps ; Ps f // Horizontal and Vertical Position [row;column] (default = // [1,1]) (HVP). Program.prototype.hvp = Program.prototype.HVPosition = function(row, col) { if (!this.zero) { row = (row || 1) - 1; col = (col || 1) - 1; } else { row = row || 0; col = col || 0; } this.y = row; this.x = col; this._ncoords(); // Does not exist (?): // if (this.tput) return this.put.hvp(row, col); if (this.tput) return this.put.cup(row, col); return this._write('\x1b[' + (row + 1) + ';' + (col + 1) + 'f'); }; // CSI Pm h Set Mode (SM). // Ps = 2 -> Keyboard Action Mode (AM). // Ps = 4 -> Insert Mode (IRM). // Ps = 1 2 -> Send/receive (SRM). // Ps = 2 0 -> Automatic Newline (LNM). // CSI ? Pm h // DEC Private Mode Set (DECSET). // Ps = 1 -> Application Cursor Keys (DECCKM). // Ps = 2 -> Designate USASCII for character sets G0-G3 // (DECANM), and set VT100 mode. // Ps = 3 -> 132 Column Mode (DECCOLM). // Ps = 4 -> Smooth (Slow) Scroll (DECSCLM). // Ps = 5 -> Reverse Video (DECSCNM). // Ps = 6 -> Origin Mode (DECOM). // Ps = 7 -> Wraparound Mode (DECAWM). // Ps = 8 -> Auto-repeat Keys (DECARM). // Ps = 9 -> Send Mouse X & Y on button press. See the sec- // tion Mouse Tracking. // Ps = 1 0 -> Show toolbar (rxvt). // Ps = 1 2 -> Start Blinking Cursor (att610). // Ps = 1 8 -> Print form feed (DECPFF). // Ps = 1 9 -> Set print extent to full screen (DECPEX). // Ps = 2 5 -> Show Cursor (DECTCEM). // Ps = 3 0 -> Show scrollbar (rxvt). // Ps = 3 5 -> Enable font-shifting functions (rxvt). // Ps = 3 8 -> Enter Tektronix Mode (DECTEK). // Ps = 4 0 -> Allow 80 -> 132 Mode. // Ps = 4 1 -> more(1) fix (see curses resource). // Ps = 4 2 -> Enable Nation Replacement Character sets (DECN- // RCM). // Ps = 4 4 -> Turn On Margin Bell. // Ps = 4 5 -> Reverse-wraparound Mode. // Ps = 4 6 -> Start Logging. This is normally disabled by a // compile-time option. // Ps = 4 7 -> Use Alternate Screen Buffer. (This may be dis- // abled by the titeInhibit resource). // Ps = 6 6 -> Application keypad (DECNKM). // Ps = 6 7 -> Backarrow key sends backspace (DECBKM). // Ps = 1 0 0 0 -> Send Mouse X & Y on button press and // release. See the section Mouse Tracking. // Ps = 1 0 0 1 -> Use Hilite Mouse Tracking. // Ps = 1 0 0 2 -> Use Cell Motion Mouse Tracking. // Ps = 1 0 0 3 -> Use All Motion Mouse Tracking. // Ps = 1 0 0 4 -> Send FocusIn/FocusOut events. // Ps = 1 0 0 5 -> Enable Extended Mouse Mode. // Ps = 1 0 1 0 -> Scroll to bottom on tty output (rxvt). // Ps = 1 0 1 1 -> Scroll to bottom on key press (rxvt). // Ps = 1 0 3 4 -> Interpret "meta" key, sets eighth bit. // (enables the eightBitInput resource). // Ps = 1 0 3 5 -> Enable special modifiers for Alt and Num- // Lock keys. (This enables the numLock resource). // Ps = 1 0 3 6 -> Send ESC when Meta modifies a key. (This // enables the metaSendsEscape resource). // Ps = 1 0 3 7 -> Send DEL from the editing-keypad Delete // key. // Ps = 1 0 3 9 -> Send ESC when Alt modifies a key. (This // enables the altSendsEscape resource). // Ps = 1 0 4 0 -> Keep selection even if not highlighted. // (This enables the keepSelection resource). // Ps = 1 0 4 1 -> Use the CLIPBOARD selection. (This enables // the selectToClipboard resource). // Ps = 1 0 4 2 -> Enable Urgency window manager hint when // Control-G is received. (This enables the bellIsUrgent // resource). // Ps = 1 0 4 3 -> Enable raising of the window when Control-G // is received. (enables the popOnBell resource). // Ps = 1 0 4 7 -> Use Alternate Screen Buffer. (This may be // disabled by the titeInhibit resource). // Ps = 1 0 4 8 -> Save cursor as in DECSC. (This may be dis- // abled by the titeInhibit resource). // Ps = 1 0 4 9 -> Save cursor as in DECSC and use Alternate // Screen Buffer, clearing it first. (This may be disabled by // the titeInhibit resource). This combines the effects of the 1 // 0 4 7 and 1 0 4 8 modes. Use this with terminfo-based // applications rather than the 4 7 mode. // Ps = 1 0 5 0 -> Set terminfo/termcap function-key mode. // Ps = 1 0 5 1 -> Set Sun function-key mode. // Ps = 1 0 5 2 -> Set HP function-key mode. // Ps = 1 0 5 3 -> Set SCO function-key mode. // Ps = 1 0 6 0 -> Set legacy keyboard emulation (X11R6). // Ps = 1 0 6 1 -> Set VT220 keyboard emulation. // Ps = 2 0 0 4 -> Set bracketed paste mode. // Modes: // http://vt100.net/docs/vt220-rm/chapter4.html Program.prototype.sm = Program.prototype.setMode = function() { var param = slice.call(arguments).join(';'); return this._write('\x1b[' + (param || '') + 'h'); }; Program.prototype.decset = function() { var param = slice.call(arguments).join(';'); return this.setMode('?' + param); }; Program.prototype.dectcem = Program.prototype.cnorm = Program.prototype.cvvis = Program.prototype.showCursor = function() { this.cursorHidden = false; // NOTE: In xterm terminfo: // cnorm stops blinking cursor // cvvis starts blinking cursor if (this.tput) return this.put.cnorm(); //if (this.tput) return this.put.cvvis(); // return this._write('\x1b[?12l\x1b[?25h'); // cursor_normal // return this._write('\x1b[?12;25h'); // cursor_visible return this.setMode('?25'); }; Program.prototype.alternate = Program.prototype.smcup = Program.prototype.alternateBuffer = function() { this.isAlt = true; if (this.tput) return this.put.smcup(); if (this.term('vt') || this.term('linux')) return; this.setMode('?47'); return this.setMode('?1049'); }; // CSI Pm l Reset Mode (RM). // Ps = 2 -> Keyboard Action Mode (AM). // Ps = 4 -> Replace Mode (IRM). // Ps = 1 2 -> Send/receive (SRM). // Ps = 2 0 -> Normal Linefeed (LNM). // CSI ? Pm l // DEC Private Mode Reset (DECRST). // Ps = 1 -> Normal Cursor Keys (DECCKM). // Ps = 2 -> Designate VT52 mode (DECANM). // Ps = 3 -> 80 Column Mode (DECCOLM). // Ps = 4 -> Jump (Fast) Scroll (DECSCLM). // Ps = 5 -> Normal Video (DECSCNM). // Ps = 6 -> Normal Cursor Mode (DECOM). // Ps = 7 -> No Wraparound Mode (DECAWM). // Ps = 8 -> No Auto-repeat Keys (DECARM). // Ps = 9 -> Don't send Mouse X & Y on button press. // Ps = 1 0 -> Hide toolbar (rxvt). // Ps = 1 2 -> Stop Blinking Cursor (att610). // Ps = 1 8 -> Don't print form feed (DECPFF). // Ps = 1 9 -> Limit print to scrolling region (DECPEX). // Ps = 2 5 -> Hide Cursor (DECTCEM). // Ps = 3 0 -> Don't show scrollbar (rxvt). // Ps = 3 5 -> Disable font-shifting functions (rxvt). // Ps = 4 0 -> Disallow 80 -> 132 Mode. // Ps = 4 1 -> No more(1) fix (see curses resource). // Ps = 4 2 -> Disable Nation Replacement Character sets (DEC- // NRCM). // Ps = 4 4 -> Turn Off Margin Bell. // Ps = 4 5 -> No Reverse-wraparound Mode. // Ps = 4 6 -> Stop Logging. (This is normally disabled by a // compile-time option). // Ps = 4 7 -> Use Normal Screen Buffer. // Ps = 6 6 -> Numeric keypad (DECNKM). // Ps = 6 7 -> Backarrow key sends delete (DECBKM). // Ps = 1 0 0 0 -> Don't send Mouse X & Y on button press and // release. See the section Mouse Tracking. // Ps = 1 0 0 1 -> Don't use Hilite Mouse Tracking. // Ps = 1 0 0 2 -> Don't use Cell Motion Mouse Tracking. // Ps = 1 0 0 3 -> Don't use All Motion Mouse Tracking. // Ps = 1 0 0 4 -> Don't send FocusIn/FocusOut events. // Ps = 1 0 0 5 -> Disable Extended Mouse Mode. // Ps = 1 0 1 0 -> Don't scroll to bottom on tty output // (rxvt). // Ps = 1 0 1 1 -> Don't scroll to bottom on key press (rxvt). // Ps = 1 0 3 4 -> Don't interpret "meta" key. (This disables // the eightBitInput resource). // Ps = 1 0 3 5 -> Disable special modifiers for Alt and Num- // Lock keys. (This disables the numLock resource). // Ps = 1 0 3 6 -> Don't send ESC when Meta modifies a key. // (This disables the metaSendsEscape resource). // Ps = 1 0 3 7 -> Send VT220 Remove from the editing-keypad // Delete key. // Ps = 1 0 3 9 -> Don't send ESC when Alt modifies a key. // (This disables the altSendsEscape resource). // Ps = 1 0 4 0 -> Do not keep selection when not highlighted. // (This disables the keepSelection resource). // Ps = 1 0 4 1 -> Use the PRIMARY selection. (This disables // the selectToClipboard resource). // Ps = 1 0 4 2 -> Disable Urgency window manager hint when // Control-G is received. (This disables the bellIsUrgent // resource). // Ps = 1 0 4 3 -> Disable raising of the window when Control- // G is received. (This disables the popOnBell resource). // Ps = 1 0 4 7 -> Use Normal Screen Buffer, clearing screen // first if in the Alternate Screen. (This may be disabled by // the titeInhibit resource). // Ps = 1 0 4 8 -> Restore cursor as in DECRC. (This may be // disabled by the titeInhibit resource). // Ps = 1 0 4 9 -> Use Normal Screen Buffer and restore cursor // as in DECRC. (This may be disabled by the titeInhibit // resource). This combines the effects of the 1 0 4 7 and 1 0 // 4 8 modes. Use this with terminfo-based applications rather // than the 4 7 mode. // Ps = 1 0 5 0 -> Reset terminfo/termcap function-key mode. // Ps = 1 0 5 1 -> Reset Sun function-key mode. // Ps = 1 0 5 2 -> Reset HP function-key mode. // Ps = 1 0 5 3 -> Reset SCO function-key mode. // Ps = 1 0 6 0 -> Reset legacy keyboard emulation (X11R6). // Ps = 1 0 6 1 -> Reset keyboard emulation to Sun/PC style. // Ps = 2 0 0 4 -> Reset bracketed paste mode. Program.prototype.rm = Program.prototype.resetMode = function() { var param = slice.call(arguments).join(';'); return this._write('\x1b[' + (param || '') + 'l'); }; Program.prototype.decrst = function() { var param = slice.call(arguments).join(';'); return this.resetMode('?' + param); }; Program.prototype.dectcemh = Program.prototype.cursor_invisible = Program.prototype.vi = Program.prototype.civis = Program.prototype.hideCursor = function() { this.cursorHidden = true; if (this.tput) return this.put.civis(); return this.resetMode('?25'); }; Program.prototype.rmcup = Program.prototype.normalBuffer = function() { this.isAlt = false; if (this.tput) return this.put.rmcup(); this.resetMode('?47'); return this.resetMode('?1049'); }; Program.prototype.enableMouse = function() { if (process.env.BLESSED_FORCE_MODES) { var modes = process.env.BLESSED_FORCE_MODES.split(','); var options = {}; for (var n = 0; n < modes.length; ++n) { var pair = modes[n].split('='); var v = pair[1] !== '0'; switch (pair[0].toUpperCase()) { case 'SGRMOUSE': options.sgrMouse = v; break; case 'UTFMOUSE': options.utfMouse = v; break; case 'VT200MOUSE': options.vt200Mouse = v; break; case 'URXVTMOUSE': options.urxvtMouse = v; break; case 'X10MOUSE': options.x10Mouse = v; break; case 'DECMOUSE': options.decMouse = v; break; case 'PTERMMOUSE': options.ptermMouse = v; break; case 'JSBTERMMOUSE': options.jsbtermMouse = v; break; case 'VT200HILITE': options.vt200Hilite = v; break; case 'GPMMOUSE': options.gpmMouse = v; break; case 'CELLMOTION': options.cellMotion = v; break; case 'ALLMOTION': options.allMotion = v; break; case 'SENDFOCUS': options.sendFocus = v; break; } } return this.setMouse(options, true); } // NOTE: // Cell Motion isn't normally need for anything below here, but we'll // activate it for tmux (whether using it or not) in case our all-motion // passthrough does not work. It can't hurt. if (this.term('rxvt-unicode')) { return this.setMouse({ urxvtMouse: true, cellMotion: true, allMotion: true }, true); } // rxvt does not support the X10 UTF extensions if (this.term('rxvt')) { return this.setMouse({ vt200Mouse: true, x10Mouse: true, cellMotion: true, allMotion: true }, true); } // libvte is broken. Older versions do not support the // X10 UTF extension. However, later versions do support // SGR/URXVT. if (this.isVTE) { return this.setMouse({ // NOTE: Could also use urxvtMouse here. sgrMouse: true, cellMotion: true, allMotion: true }, true); } if (this.term('linux')) { return this.setMouse({ vt200Mouse: true, gpmMouse: true }, true); } if (this.term('xterm') || this.term('screen') || (this.tput && this.tput.strings.key_mouse)) { return this.setMouse({ vt200Mouse: true, utfMouse: true, cellMotion: true, allMotion: true }, true); } }; Program.prototype.disableMouse = function() { if (!this._currentMouse) return; var obj = {}; Object.keys(this._currentMouse).forEach(function(key) { obj[key] = false; }); return this.setMouse(obj, false); }; // Set Mouse Program.prototype.setMouse = function(opt, enable) { if (opt.normalMouse != null) { opt.vt200Mouse = opt.normalMouse; opt.allMotion = opt.normalMouse; } if (opt.hiliteTracking != null) { opt.vt200Hilite = opt.hiliteTracking; } if (enable === true) { if (this._currentMouse) { this.setMouse(opt); Object.keys(opt).forEach(function(key) { this._currentMouse[key] = opt[key]; }, this); return; } this._currentMouse = opt; this.mouseEnabled = true; } else if (enable === false) { delete this._currentMouse; this.mouseEnabled = false; } // Ps = 9 -> Send Mouse X & Y on button press. See the sec- // tion Mouse Tracking. // Ps = 9 -> Don't send Mouse X & Y on button press. // x10 mouse if (opt.x10Mouse != null) { if (opt.x10Mouse) this.setMode('?9'); else this.resetMode('?9'); } // Ps = 1 0 0 0 -> Send Mouse X & Y on button press and // release. See the section Mouse Tracking. // Ps = 1 0 0 0 -> Don't send Mouse X & Y on button press and // release. See the section Mouse Tracking. // vt200 mouse if (opt.vt200Mouse != null) { if (opt.vt200Mouse) this.setMode('?1000'); else this.resetMode('?1000'); } // Ps = 1 0 0 1 -> Use Hilite Mouse Tracking. // Ps = 1 0 0 1 -> Don't use Hilite Mouse Tracking. if (opt.vt200Hilite != null) { if (opt.vt200Hilite) this.setMode('?1001'); else this.resetMode('?1001'); } // Ps = 1 0 0 2 -> Use Cell Motion Mouse Tracking. // Ps = 1 0 0 2 -> Don't use Cell Motion Mouse Tracking. // button event mouse if (opt.cellMotion != null) { if (opt.cellMotion) this.setMode('?1002'); else this.resetMode('?1002'); } // Ps = 1 0 0 3 -> Use All Motion Mouse Tracking. // Ps = 1 0 0 3 -> Don't use All Motion Mouse Tracking. // any event mouse if (opt.allMotion != null) { // NOTE: Latest versions of tmux seem to only support cellMotion (not // allMotion). We pass all motion through to the terminal. if (this.tmux && this.tmuxVersion >= 2) { if (opt.allMotion) this._twrite('\x1b[?1003h'); else this._twrite('\x1b[?1003l'); } else { if (opt.allMotion) this.setMode('?1003'); else this.resetMode('?1003'); } } // Ps = 1 0 0 4 -> Send FocusIn/FocusOut events. // Ps = 1 0 0 4 -> Don't send FocusIn/FocusOut events. if (opt.sendFocus != null) { if (opt.sendFocus) this.setMode('?1004'); else this.resetMode('?1004'); } // Ps = 1 0 0 5 -> Enable Extended Mouse Mode. // Ps = 1 0 0 5 -> Disable Extended Mouse Mode. if (opt.utfMouse != null) { if (opt.utfMouse) this.setMode('?1005'); else this.resetMode('?1005'); } // sgr mouse if (opt.sgrMouse != null) { if (opt.sgrMouse) this.setMode('?1006'); else this.resetMode('?1006'); } // urxvt mouse if (opt.urxvtMouse != null) { if (opt.urxvtMouse) this.setMode('?1015'); else this.resetMode('?1015'); } // dec mouse if (opt.decMouse != null) { if (opt.decMouse) this._write('\x1b[1;2\'z\x1b[1;3\'{'); else this._write('\x1b[\'z'); } // pterm mouse if (opt.ptermMouse != null) { if (opt.ptermMouse) this._write('\x1b[>1h\x1b[>6h\x1b[>7h\x1b[>1h\x1b[>9l'); else this._write('\x1b[>1l\x1b[>6l\x1b[>7l\x1b[>1l\x1b[>9h'); } // jsbterm mouse if (opt.jsbtermMouse != null) { // + = advanced mode if (opt.jsbtermMouse) this._write('\x1b[0~ZwLMRK+1Q\x1b\\'); else this._write('\x1b[0~ZwQ\x1b\\'); } // gpm mouse if (opt.gpmMouse != null) { if (opt.gpmMouse) this.enableGpm(); else this.disableGpm(); } }; // CSI Ps ; Ps r // Set Scrolling Region [top;bottom] (default = full size of win- // dow) (DECSTBM). // CSI ? Pm r Program.prototype.decstbm = Program.prototype.csr = Program.prototype.setScrollRegion = function(top, bottom) { if (!this.zero) { top = (top || 1) - 1; bottom = (bottom || this.rows) - 1; } else { top = top || 0; bottom = bottom || (this.rows - 1); } this.scrollTop = top; this.scrollBottom = bottom; this.x = 0; this.y = 0; this._ncoords(); if (this.tput) return this.put.csr(top, bottom); return this._write('\x1b[' + (top + 1) + ';' + (bottom + 1) + 'r'); }; // CSI s // Save cursor (ANSI.SYS). Program.prototype.scA = Program.prototype.saveCursorA = function() { this.savedX = this.x; this.savedY = this.y; if (this.tput) return this.put.sc(); return this._write('\x1b[s'); }; // CSI u // Restore cursor (ANSI.SYS). Program.prototype.rcA = Program.prototype.restoreCursorA = function() { this.x = this.savedX || 0; this.y = this.savedY || 0; if (this.tput) return this.put.rc(); return this._write('\x1b[u'); }; /** * Lesser Used */ // CSI Ps I // Cursor Forward Tabulation Ps tab stops (default = 1) (CHT). Program.prototype.cht = Program.prototype.cursorForwardTab = function(param) { this.x += 8; this._ncoords(); if (this.tput) return this.put.tab(param); return this._write('\x1b[' + (param || 1) + 'I'); }; // CSI Ps S Scroll up Ps lines (default = 1) (SU). Program.prototype.su = Program.prototype.scrollUp = function(param) { this.y -= param || 1; this._ncoords(); if (this.tput) return this.put.parm_index(param); return this._write('\x1b[' + (param || 1) + 'S'); }; // CSI Ps T Scroll down Ps lines (default = 1) (SD). Program.prototype.sd = Program.prototype.scrollDown = function(param) { this.y += param || 1; this._ncoords(); if (this.tput) return this.put.parm_rindex(param); return this._write('\x1b[' + (param || 1) + 'T'); }; // CSI Ps ; Ps ; Ps ; Ps ; Ps T // Initiate highlight mouse tracking. Parameters are // [func;startx;starty;firstrow;lastrow]. See the section Mouse // Tracking. Program.prototype.initMouseTracking = function() { return this._write('\x1b[' + slice.call(arguments).join(';') + 'T'); }; // CSI > Ps; Ps T // Reset one or more features of the title modes to the default // value. Normally, "reset" disables the feature. It is possi- // ble to disable the ability to reset features by compiling a // different default for the title modes into xterm. // Ps = 0 -> Do not set window/icon labels using hexadecimal. // Ps = 1 -> Do not query window/icon labels using hexadeci- // mal. // Ps = 2 -> Do not set window/icon labels using UTF-8. // Ps = 3 -> Do not query window/icon labels using UTF-8. // (See discussion of "Title Modes"). Program.prototype.resetTitleModes = function() { return this._write('\x1b[>' + slice.call(arguments).join(';') + 'T'); }; // CSI Ps Z Cursor Backward Tabulation Ps tab stops (default = 1) (CBT). Program.prototype.cbt = Program.prototype.cursorBackwardTab = function(param) { this.x -= 8; this._ncoords(); if (this.tput) return this.put.cbt(param); return this._write('\x1b[' + (param || 1) + 'Z'); }; // CSI Ps b Repeat the preceding graphic character Ps times (REP). Program.prototype.rep = Program.prototype.repeatPrecedingCharacter = function(param) { this.x += param || 1; this._ncoords(); if (this.tput) return this.put.rep(param); return this._write('\x1b[' + (param || 1) + 'b'); }; // CSI Ps g Tab Clear (TBC). // Ps = 0 -> Clear Current Column (default). // Ps = 3 -> Clear All. // Potentially: // Ps = 2 -> Clear Stops on Line. // http://vt100.net/annarbor/aaa-ug/section6.html Program.prototype.tbc = Program.prototype.tabClear = function(param) { if (this.tput) return this.put.tbc(param); return this._write('\x1b[' + (param || 0) + 'g'); }; // CSI Pm i Media Copy (MC). // Ps = 0 -> Print screen (default). // Ps = 4 -> Turn off printer controller mode. // Ps = 5 -> Turn on printer controller mode. // CSI ? Pm i // Media Copy (MC, DEC-specific). // Ps = 1 -> Print line containing cursor. // Ps = 4 -> Turn off autoprint mode. // Ps = 5 -> Turn on autoprint mode. // Ps = 1 0 -> Print composed display, ignores DECPEX. // Ps = 1 1 -> Print all pages. Program.prototype.mc = Program.prototype.mediaCopy = function() { return this._write('\x1b[' + slice.call(arguments).join(';') + 'i'); }; Program.prototype.print_screen = Program.prototype.ps = Program.prototype.mc0 = function() { if (this.tput) return this.put.mc0(); return this.mc('0'); }; Program.prototype.prtr_on = Program.prototype.po = Program.prototype.mc5 = function() { if (this.tput) return this.put.mc5(); return this.mc('5'); }; Program.prototype.prtr_off = Program.prototype.pf = Program.prototype.mc4 = function() { if (this.tput) return this.put.mc4(); return this.mc('4'); }; Program.prototype.prtr_non = Program.prototype.pO = Program.prototype.mc5p = function() { if (this.tput) return this.put.mc5p(); return this.mc('?5'); }; // CSI > Ps; Ps m // Set or reset resource-values used by xterm to decide whether // to construct escape sequences holding information about the // modifiers pressed with a given key. The first parameter iden- // tifies the resource to set/reset. The second parameter is the // value to assign to the resource. If the second parameter is // omitted, the resource is reset to its initial value. // Ps = 1 -> modifyCursorKeys. // Ps = 2 -> modifyFunctionKeys. // Ps = 4 -> modifyOtherKeys. // If no parameters are given, all resources are reset to their // initial values. Program.prototype.setResources = function() { return this._write('\x1b[>' + slice.call(arguments).join(';') + 'm'); }; // CSI > Ps n // Disable modifiers which may be enabled via the CSI > Ps; Ps m // sequence. This corresponds to a resource value of "-1", which // cannot be set with the other sequence. The parameter identi- // fies the resource to be disabled: // Ps = 1 -> modifyCursorKeys. // Ps = 2 -> modifyFunctionKeys. // Ps = 4 -> modifyOtherKeys. // If the parameter is omitted, modifyFunctionKeys is disabled. // When modifyFunctionKeys is disabled, xterm uses the modifier // keys to make an extended sequence of functions rather than // adding a parameter to each function key to denote the modi- // fiers. Program.prototype.disableModifiers = function(param) { return this._write('\x1b[>' + (param || '') + 'n'); }; // CSI > Ps p // Set resource value pointerMode. This is used by xterm to // decide whether to hide the pointer cursor as the user types. // Valid values for the parameter: // Ps = 0 -> never hide the pointer. // Ps = 1 -> hide if the mouse tracking mode is not enabled. // Ps = 2 -> always hide the pointer. If no parameter is // given, xterm uses the default, which is 1 . Program.prototype.setPointerMode = function(param) { return this._write('\x1b[>' + (param || '') + 'p'); }; // CSI ! p Soft terminal reset (DECSTR). // http://vt100.net/docs/vt220-rm/table4-10.html Program.prototype.decstr = Program.prototype.rs2 = Program.prototype.softReset = function() { //if (this.tput) return this.put.init_2string(); //if (this.tput) return this.put.reset_2string(); if (this.tput) return this.put.rs2(); //return this._write('\x1b[!p'); //return this._write('\x1b[!p\x1b[?3;4l\x1b[4l\x1b>'); // init return this._write('\x1b[!p\x1b[?3;4l\x1b[4l\x1b>'); // reset }; // CSI Ps$ p // Request ANSI mode (DECRQM). For VT300 and up, reply is // CSI Ps; Pm$ y // where Ps is the mode number as in RM, and Pm is the mode // value: // 0 - not recognized // 1 - set // 2 - reset // 3 - permanently set // 4 - permanently reset Program.prototype.decrqm = Program.prototype.requestAnsiMode = function(param) { return this._write('\x1b[' + (param || '') + '$p'); }; // CSI ? Ps$ p // Request DEC private mode (DECRQM). For VT300 and up, reply is // CSI ? Ps; Pm$ p // where Ps is the mode number as in DECSET, Pm is the mode value // as in the ANSI DECRQM. Program.prototype.decrqmp = Program.prototype.requestPrivateMode = function(param) { return this._write('\x1b[?' + (param || '') + '$p'); }; // CSI Ps ; Ps " p // Set conformance level (DECSCL). Valid values for the first // parameter: // Ps = 6 1 -> VT100. // Ps = 6 2 -> VT200. // Ps = 6 3 -> VT300. // Valid values for the second parameter: // Ps = 0 -> 8-bit controls. // Ps = 1 -> 7-bit controls (always set for VT100). // Ps = 2 -> 8-bit controls. Program.prototype.decscl = Program.prototype.setConformanceLevel = function() { return this._write('\x1b[' + slice.call(arguments).join(';') + '"p'); }; // CSI Ps q Load LEDs (DECLL). // Ps = 0 -> Clear all LEDS (default). // Ps = 1 -> Light Num Lock. // Ps = 2 -> Light Caps Lock. // Ps = 3 -> Light Scroll Lock. // Ps = 2 1 -> Extinguish Num Lock. // Ps = 2 2 -> Extinguish Caps Lock. // Ps = 2 3 -> Extinguish Scroll Lock. Program.prototype.decll = Program.prototype.loadLEDs = function(param) { return this._write('\x1b[' + (param || '') + 'q'); }; // CSI Ps SP q // Set cursor style (DECSCUSR, VT520). // Ps = 0 -> blinking block. // Ps = 1 -> blinking block (default). // Ps = 2 -> steady block. // Ps = 3 -> blinking underline. // Ps = 4 -> steady underline. Program.prototype.decscusr = Program.prototype.setCursorStyle = function(param) { switch (param) { case 'blinking block': param = 1; break; case 'block': case 'steady block': param = 2; break; case 'blinking underline': param = 3; break; case 'underline': case 'steady underline': param = 4; break; case 'blinking bar': param = 5; break; case 'bar': case 'steady bar': param = 6; break; } if (param === 2 && this.has('Se')) { return this.put.Se(); } if (this.has('Ss')) { return this.put.Ss(param); } return this._write('\x1b[' + (param || 1) + ' q'); }; // CSI Ps " q // Select character protection attribute (DECSCA). Valid values // for the parameter: // Ps = 0 -> DECSED and DECSEL can erase (default). // Ps = 1 -> DECSED and DECSEL cannot erase. // Ps = 2 -> DECSED and DECSEL can erase. Program.prototype.decsca = Program.prototype.setCharProtectionAttr = function(param) { return this._write('\x1b[' + (param || 0) + '"q'); }; // CSI ? Pm r // Restore DEC Private Mode Values. The value of Ps previously // saved is restored. Ps values are the same as for DECSET. Program.prototype.restorePrivateValues = function() { return this._write('\x1b[?' + slice.call(arguments).join(';') + 'r'); }; // CSI Pt; Pl; Pb; Pr; Ps$ r // Change Attributes in Rectangular Area (DECCARA), VT400 and up. // Pt; Pl; Pb; Pr denotes the rectangle. // Ps denotes the SGR attributes to change: 0, 1, 4, 5, 7. // NOTE: xterm doesn't enable this code by default. Program.prototype.deccara = Program.prototype.setAttrInRectangle = function() { return this._write('\x1b[' + slice.call(arguments).join(';') + '$r'); }; // CSI ? Pm s // Save DEC Private Mode Values. Ps values are the same as for // DECSET. Program.prototype.savePrivateValues = function() { return this._write('\x1b[?' + slice.call(arguments).join(';') + 's'); }; // CSI Ps ; Ps ; Ps t // Window manipulation (from dtterm, as well as extensions). // These controls may be disabled using the allowWindowOps // resource. Valid values for the first (and any additional // parameters) are: // Ps = 1 -> De-iconify window. // Ps = 2 -> Iconify window. // Ps = 3 ; x ; y -> Move window to [x, y]. // Ps = 4 ; height ; width -> Resize the xterm window to // height and width in pixels. // Ps = 5 -> Raise the xterm window to the front of the stack- // ing order. // Ps = 6 -> Lower the xterm window to the bottom of the // stacking order. // Ps = 7 -> Refresh the xterm window. // Ps = 8 ; height ; width -> Resize the text area to // [height;width] in characters. // Ps = 9 ; 0 -> Restore maximized window. // Ps = 9 ; 1 -> Maximize window (i.e., resize to screen // size). // Ps = 1 0 ; 0 -> Undo full-screen mode. // Ps = 1 0 ; 1 -> Change to full-screen. // Ps = 1 1 -> Report xterm window state. If the xterm window // is open (non-iconified), it returns CSI 1 t . If the xterm // window is iconified, it returns CSI 2 t . // Ps = 1 3 -> Report xterm window position. Result is CSI 3 // ; x ; y t // Ps = 1 4 -> Report xterm window in pixels. Result is CSI // 4 ; height ; width t // Ps = 1 8 -> Report the size of the text area in characters. // Result is CSI 8 ; height ; width t // Ps = 1 9 -> Report the size of the screen in characters. // Result is CSI 9 ; height ; width t // Ps = 2 0 -> Report xterm window's icon label. Result is // OSC L label ST // Ps = 2 1 -> Report xterm window's title. Result is OSC l // label ST // Ps = 2 2 ; 0 -> Save xterm icon and window title on // stack. // Ps = 2 2 ; 1 -> Save xterm icon title on stack. // Ps = 2 2 ; 2 -> Save xterm window title on stack. // Ps = 2 3 ; 0 -> Restore xterm icon and window title from // stack. // Ps = 2 3 ; 1 -> Restore xterm icon title from stack. // Ps = 2 3 ; 2 -> Restore xterm window title from stack. // Ps >= 2 4 -> Resize to Ps lines (DECSLPP). Program.prototype.manipulateWindow = function() { var args = slice.call(arguments); var callback = typeof args[args.length - 1] === 'function' ? args.pop() : function() {}; return this.response('window-manipulation', '\x1b[' + args.join(';') + 't', callback); }; Program.prototype.getWindowSize = function(callback) { return this.manipulateWindow(18, callback); }; // CSI Pt; Pl; Pb; Pr; Ps$ t // Reverse Attributes in Rectangular Area (DECRARA), VT400 and // up. // Pt; Pl; Pb; Pr denotes the rectangle. // Ps denotes the attributes to reverse, i.e., 1, 4, 5, 7. // NOTE: xterm doesn't enable this code by default. Program.prototype.decrara = Program.prototype.reverseAttrInRectangle = function() { return this._write('\x1b[' + slice.call(arguments).join(';') + '$t'); }; // CSI > Ps; Ps t // Set one or more features of the title modes. Each parameter // enables a single feature. // Ps = 0 -> Set window/icon labels using hexadecimal. // Ps = 1 -> Query window/icon labels using hexadecimal. // Ps = 2 -> Set window/icon labels using UTF-8. // Ps = 3 -> Query window/icon labels using UTF-8. (See dis- // cussion of "Title Modes") // XXX VTE bizarelly echos this: Program.prototype.setTitleModeFeature = function() { return this._twrite('\x1b[>' + slice.call(arguments).join(';') + 't'); }; // CSI Ps SP t // Set warning-bell volume (DECSWBV, VT520). // Ps = 0 or 1 -> off. // Ps = 2 , 3 or 4 -> low. // Ps = 5 , 6 , 7 , or 8 -> high. Program.prototype.decswbv = Program.prototype.setWarningBellVolume = function(param) { return this._write('\x1b[' + (param || '') + ' t'); }; // CSI Ps SP u // Set margin-bell volume (DECSMBV, VT520). // Ps = 1 -> off. // Ps = 2 , 3 or 4 -> low. // Ps = 0 , 5 , 6 , 7 , or 8 -> high. Program.prototype.decsmbv = Program.prototype.setMarginBellVolume = function(param) { return this._write('\x1b[' + (param || '') + ' u'); }; // CSI Pt; Pl; Pb; Pr; Pp; Pt; Pl; Pp$ v // Copy Rectangular Area (DECCRA, VT400 and up). // Pt; Pl; Pb; Pr denotes the rectangle. // Pp denotes the source page. // Pt; Pl denotes the target location. // Pp denotes the target page. // NOTE: xterm doesn't enable this code by default. Program.prototype.deccra = Program.prototype.copyRectangle = function() { return this._write('\x1b[' + slice.call(arguments).join(';') + '$v'); }; // CSI Pt ; Pl ; Pb ; Pr ' w // Enable Filter Rectangle (DECEFR), VT420 and up. // Parameters are [top;left;bottom;right]. // Defines the coordinates of a filter rectangle and activates // it. Anytime the locator is detected outside of the filter // rectangle, an outside rectangle event is generated and the // rectangle is disabled. Filter rectangles are always treated // as "one-shot" events. Any parameters that are omitted default // to the current locator position. If all parameters are omit- // ted, any locator motion will be reported. DECELR always can- // cels any prevous rectangle definition. Program.prototype.decefr = Program.prototype.enableFilterRectangle = function() { return this._write('\x1b[' + slice.call(arguments).join(';') + '\'w'); }; // CSI Ps x Request Terminal Parameters (DECREQTPARM). // if Ps is a "0" (default) or "1", and xterm is emulating VT100, // the control sequence elicits a response of the same form whose // parameters describe the terminal: // Ps -> the given Ps incremented by 2. // Pn = 1 <- no parity. // Pn = 1 <- eight bits. // Pn = 1 <- 2 8 transmit 38.4k baud. // Pn = 1 <- 2 8 receive 38.4k baud. // Pn = 1 <- clock multiplier. // Pn = 0 <- STP flags. Program.prototype.decreqtparm = Program.prototype.requestParameters = function(param) { return this._write('\x1b[' + (param || 0) + 'x'); }; // CSI Ps x Select Attribute Change Extent (DECSACE). // Ps = 0 -> from start to end position, wrapped. // Ps = 1 -> from start to end position, wrapped. // Ps = 2 -> rectangle (exact). Program.prototype.decsace = Program.prototype.selectChangeExtent = function(param) { return this._write('\x1b[' + (param || 0) + 'x'); }; // CSI Pc; Pt; Pl; Pb; Pr$ x // Fill Rectangular Area (DECFRA), VT420 and up. // Pc is the character to use. // Pt; Pl; Pb; Pr denotes the rectangle. // NOTE: xterm doesn't enable this code by default. Program.prototype.decfra = Program.prototype.fillRectangle = function() { return this._write('\x1b[' + slice.call(arguments).join(';') + '$x'); }; // CSI Ps ; Pu ' z // Enable Locator Reporting (DECELR). // Valid values for the first parameter: // Ps = 0 -> Locator disabled (default). // Ps = 1 -> Locator enabled. // Ps = 2 -> Locator enabled for one report, then disabled. // The second parameter specifies the coordinate unit for locator // reports. // Valid values for the second parameter: // Pu = 0 <- or omitted -> default to character cells. // Pu = 1 <- device physical pixels. // Pu = 2 <- character cells. Program.prototype.decelr = Program.prototype.enableLocatorReporting = function() { return this._write('\x1b[' + slice.call(arguments).join(';') + '\'z'); }; // CSI Pt; Pl; Pb; Pr$ z // Erase Rectangular Area (DECERA), VT400 and up. // Pt; Pl; Pb; Pr denotes the rectangle. // NOTE: xterm doesn't enable this code by default. Program.prototype.decera = Program.prototype.eraseRectangle = function() { return this._write('\x1b[' + slice.call(arguments).join(';') + '$z'); }; // CSI Pm ' { // Select Locator Events (DECSLE). // Valid values for the first (and any additional parameters) // are: // Ps = 0 -> only respond to explicit host requests (DECRQLP). // (This is default). It also cancels any filter // rectangle. // Ps = 1 -> report button down transitions. // Ps = 2 -> do not report button down transitions. // Ps = 3 -> report button up transitions. // Ps = 4 -> do not report button up transitions. Program.prototype.decsle = Program.prototype.setLocatorEvents = function() { return this._write('\x1b[' + slice.call(arguments).join(';') + '\'{'); }; // CSI Pt; Pl; Pb; Pr$ { // Selective Erase Rectangular Area (DECSERA), VT400 and up. // Pt; Pl; Pb; Pr denotes the rectangle. Program.prototype.decsera = Program.prototype.selectiveEraseRectangle = function() { return this._write('\x1b[' + slice.call(arguments).join(';') + '${'); }; // CSI Ps ' | // Request Locator Position (DECRQLP). // Valid values for the parameter are: // Ps = 0 , 1 or omitted -> transmit a single DECLRP locator // report. // If Locator Reporting has been enabled by a DECELR, xterm will // respond with a DECLRP Locator Report. This report is also // generated on button up and down events if they have been // enabled with a DECSLE, or when the locator is detected outside // of a filter rectangle, if filter rectangles have been enabled // with a DECEFR. // -> CSI Pe ; Pb ; Pr ; Pc ; Pp & w // Parameters are [event;button;row;column;page]. // Valid values for the event: // Pe = 0 -> locator unavailable - no other parameters sent. // Pe = 1 -> request - xterm received a DECRQLP. // Pe = 2 -> left button down. // Pe = 3 -> left button up. // Pe = 4 -> middle button down. // Pe = 5 -> middle button up. // Pe = 6 -> right button down. // Pe = 7 -> right button up. // Pe = 8 -> M4 button down. // Pe = 9 -> M4 button up. // Pe = 1 0 -> locator outside filter rectangle. // ``button'' parameter is a bitmask indicating which buttons are // pressed: // Pb = 0 <- no buttons down. // Pb & 1 <- right button down. // Pb & 2 <- middle button down. // Pb & 4 <- left button down. // Pb & 8 <- M4 button down. // ``row'' and ``column'' parameters are the coordinates of the // locator position in the xterm window, encoded as ASCII deci- // mal. // The ``page'' parameter is not used by xterm, and will be omit- // ted. Program.prototype.decrqlp = Program.prototype.req_mouse_pos = Program.prototype.reqmp = Program.prototype.requestLocatorPosition = function(param, callback) { // See also: // get_mouse / getm / Gm // mouse_info / minfo / Mi // Correct for tput? if (this.has('req_mouse_pos')) { var code = this.tput.req_mouse_pos(param); return this.response('locator-position', code, callback); } return this.response('locator-position', '\x1b[' + (param || '') + '\'|', callback); }; // CSI P m SP } // Insert P s Column(s) (default = 1) (DECIC), VT420 and up. // NOTE: xterm doesn't enable this code by default. Program.prototype.decic = Program.prototype.insertColumns = function() { return this._write('\x1b[' + slice.call(arguments).join(';') + ' }'); }; // CSI P m SP ~ // Delete P s Column(s) (default = 1) (DECDC), VT420 and up // NOTE: xterm doesn't enable this code by default. Program.prototype.decdc = Program.prototype.deleteColumns = function() { return this._write('\x1b[' + slice.call(arguments).join(';') + ' ~'); }; Program.prototype.out = function(name) { var args = Array.prototype.slice.call(arguments, 1); this.ret = true; var out = this[name].apply(this, args); this.ret = false; return out; }; Program.prototype.sigtstp = function(callback) { var resume = this.pause(); process.once('SIGCONT', function() { resume(); if (callback) callback(); }); process.kill(process.pid, 'SIGTSTP'); }; Program.prototype.pause = function(callback) { var self = this , isAlt = this.isAlt , mouseEnabled = this.mouseEnabled; this.lsaveCursor('pause'); //this.csr(0, screen.height - 1); if (isAlt) this.normalBuffer(); this.showCursor(); if (mouseEnabled) this.disableMouse(); var write = this.output.write; this.output.write = function() {}; if (this.input.setRawMode) { this.input.setRawMode(false); } this.input.pause(); return this._resume = function() { delete self._resume; if (self.input.setRawMode) { self.input.setRawMode(true); } self.input.resume(); self.output.write = write; if (isAlt) self.alternateBuffer(); //self.csr(0, screen.height - 1); if (mouseEnabled) self.enableMouse(); self.lrestoreCursor('pause', true); if (callback) callback(); }; }; Program.prototype.resume = function() { if (this._resume) return this._resume(); }; /** * Helpers */ // We could do this easier by just manipulating the _events object, or for // older versions of node, manipulating the array returned by listeners(), but // neither of these methods are guaranteed to work in future versions of node. function unshiftEvent(obj, event, listener) { var listeners = obj.listeners(event); obj.removeAllListeners(event); obj.on(event, listener); listeners.forEach(function(listener) { obj.on(event, listener); }); } function merge(out) { slice.call(arguments, 1).forEach(function(obj) { Object.keys(obj).forEach(function(key) { out[key] = obj[key]; }); }); return out; } /** * Expose */ module.exports = Program;
/* 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', 'fi', { auto: 'Automaattinen', bgColorTitle: 'Taustaväri', colors: { '000': 'Musta', '800000': 'Kastanjanruskea', '8B4513': 'Satulanruskea', '2F4F4F': 'Tumma liuskekivenharmaa', '008080': 'Sinivihreä', '000080': 'Laivastonsininen', '4B0082': 'Indigonsininen', '696969': 'Tummanharmaa', B22222: 'Tiili', A52A2A: 'Ruskea', DAA520: 'Kultapiisku', '006400': 'Tummanvihreä', '40E0D0': 'Turkoosi', '0000CD': 'Keskisininen', '800080': 'Purppura', '808080': 'Harmaa', F00: 'Punainen', FF8C00: 'Tumma oranssi', FFD700: 'Kulta', '008000': 'Vihreä', '0FF': 'Syaani', '00F': 'Sininen', EE82EE: 'Violetti', A9A9A9: 'Tummanharmaa', FFA07A: 'Vaaleanlohenpunainen', FFA500: 'Oranssi', FFFF00: 'Keltainen', '00FF00': 'Limetin vihreä', AFEEEE: 'Haalea turkoosi', ADD8E6: 'Vaaleansininen', DDA0DD: 'Luumu', D3D3D3: 'Vaaleanharmaa', FFF0F5: 'Laventelinpunainen', FAEBD7: 'Antiikinvalkoinen', FFFFE0: 'Vaaleankeltainen', F0FFF0: 'Hunajameloni', F0FFFF: 'Asurinsininen', F0F8FF: 'Alice Blue -sininen', E6E6FA: 'Lavanteli', FFF: 'Valkoinen', '1ABC9C': 'Strong Cyan', // MISSING '2ECC71': 'Emerald', // MISSING '3498DB': 'Bright Blue', // MISSING '9B59B6': 'Amethyst', // MISSING '4E5F70': 'Grayish Blue', // MISSING 'F1C40F': 'Vivid Yellow', // MISSING '16A085': 'Dark Cyan', // MISSING '27AE60': 'Dark Emerald', // MISSING '2980B9': 'Strong Blue', // MISSING '8E44AD': 'Dark Violet', // MISSING '2C3E50': 'Desaturated Blue', // MISSING 'F39C12': 'Orange', // MISSING 'E67E22': 'Carrot', // MISSING 'E74C3C': 'Pale Red', // MISSING 'ECF0F1': 'Bright Silver', // MISSING '95A5A6': 'Light Grayish Cyan', // MISSING 'DDD': 'Light Gray', // MISSING 'D35400': 'Pumpkin', // MISSING 'C0392B': 'Strong Red', // MISSING 'BDC3C7': 'Silver', // MISSING '7F8C8D': 'Grayish Cyan', // MISSING '999': 'Dark Gray' // MISSING }, more: 'Lisää värejä...', panelTitle: 'Värit', textColorTitle: 'Tekstiväri' } );
/** * Copyright 2014 Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["ar-AE"] = { name: "ar-AE", numberFormat: { pattern: ["n-"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["$n-","$ n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "د.إ.‏" } }, calendars: { standard: { days: { names: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"], namesAbbr: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"], namesShort: ["ح","ن","ث","ر","خ","ج","س"] }, months: { names: ["يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليو","أغسطس","سبتمبر","أكتوبر","نوفمبر","ديسمبر",""], namesAbbr: ["يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليو","أغسطس","سبتمبر","أكتوبر","نوفمبر","ديسمبر",""] }, AM: ["ص","ص","ص"], PM: ["م","م","م"], patterns: { d: "dd/MM/yyyy", D: "dd MMMM, yyyy", F: "dd MMMM, yyyy hh:mm:ss tt", g: "dd/MM/yyyy hh:mm tt", G: "dd/MM/yyyy hh:mm:ss tt", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "hh:mm tt", T: "hh:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM, yyyy", Y: "MMMM, yyyy" }, "/": "/", ":": ":", firstDay: 6 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
const assertJump = require('./helpers/assertJump'); var BasicTokenMock = artifacts.require("./helpers/BasicTokenMock.sol"); contract('BasicToken', function(accounts) { it("should return the correct totalSupply after construction", async function() { let token = await BasicTokenMock.new(accounts[0], 100); let totalSupply = await token.totalSupply(); assert.equal(totalSupply, 100); }) it("should return correct balances after transfer", async function(){ let token = await BasicTokenMock.new(accounts[0], 100); let transfer = await token.transfer(accounts[1], 100); let firstAccountBalance = await token.balanceOf(accounts[0]); assert.equal(firstAccountBalance, 0); let secondAccountBalance = await token.balanceOf(accounts[1]); assert.equal(secondAccountBalance, 100); }); it('should throw an error when trying to transfer more than balance', async function() { let token = await BasicTokenMock.new(accounts[0], 100); try { let transfer = await token.transfer(accounts[1], 101); assert.fail('should have thrown before'); } catch(error) { assertJump(error); } }); it('should throw an error when trying to transfer to 0x0', async function() { let token = await BasicTokenMock.new(accounts[0], 100); try { let transfer = await token.transfer(0x0, 100); assert.fail('should have thrown before'); } catch(error) { assertJump(error); } }); });
/*! WebUploader 0.1.5 */ /** * @fileOverview 让内部各个部件的代码可以用[amd](https://github.com/amdjs/amdjs-api/wiki/AMD)模块定义方式组织起来。 * * AMD API 内部的简单不完全实现,请忽略。只有当WebUploader被合并成一个文件的时候才会引入。 */ (function( root, factory ) { var modules = {}, // 内部require, 简单不完全实现。 // https://github.com/amdjs/amdjs-api/wiki/require _require = function( deps, callback ) { var args, len, i; // 如果deps不是数组,则直接返回指定module if ( typeof deps === 'string' ) { return getModule( deps ); } else { args = []; for( len = deps.length, i = 0; i < len; i++ ) { args.push( getModule( deps[ i ] ) ); } return callback.apply( null, args ); } }, // 内部define,暂时不支持不指定id. _define = function( id, deps, factory ) { if ( arguments.length === 2 ) { factory = deps; deps = null; } _require( deps || [], function() { setModule( id, factory, arguments ); }); }, // 设置module, 兼容CommonJs写法。 setModule = function( id, factory, args ) { var module = { exports: factory }, returned; if ( typeof factory === 'function' ) { args.length || (args = [ _require, module.exports, module ]); returned = factory.apply( null, args ); returned !== undefined && (module.exports = returned); } modules[ id ] = module.exports; }, // 根据id获取module getModule = function( id ) { var module = modules[ id ] || root[ id ]; if ( !module ) { throw new Error( '`' + id + '` is undefined' ); } return module; }, // 将所有modules,将路径ids装换成对象。 exportsTo = function( obj ) { var key, host, parts, part, last, ucFirst; // make the first character upper case. ucFirst = function( str ) { return str && (str.charAt( 0 ).toUpperCase() + str.substr( 1 )); }; for ( key in modules ) { host = obj; if ( !modules.hasOwnProperty( key ) ) { continue; } parts = key.split('/'); last = ucFirst( parts.pop() ); while( (part = ucFirst( parts.shift() )) ) { host[ part ] = host[ part ] || {}; host = host[ part ]; } host[ last ] = modules[ key ]; } return obj; }, makeExport = function( dollar ) { root.__dollar = dollar; // exports every module. return exportsTo( factory( root, _define, _require ) ); }, origin; if ( typeof module === 'object' && typeof module.exports === 'object' ) { // For CommonJS and CommonJS-like environments where a proper window is present, module.exports = makeExport(); } else if ( typeof define === 'function' && define.amd ) { // Allow using this built library as an AMD module // in another project. That other project will only // see this AMD call, not the internal modules in // the closure below. define([ 'jquery' ], makeExport ); } else { // Browser globals case. Just assign the // result to a property on the global. origin = root.WebUploader; root.WebUploader = makeExport(); root.WebUploader.noConflict = function() { root.WebUploader = origin; }; } })( window, function( window, define, require ) { /** * @fileOverview jQuery or Zepto */ define('dollar-third',[],function() { var $ = window.__dollar || window.jQuery || window.Zepto; if ( !$ ) { throw new Error('jQuery or Zepto not found!'); } return $; }); /** * @fileOverview Dom 操作相关 */ define('dollar',[ 'dollar-third' ], function( _ ) { return _; }); /** * @fileOverview 使用jQuery的Promise */ define('promise-third',[ 'dollar' ], function( $ ) { return { Deferred: $.Deferred, when: $.when, isPromise: function( anything ) { return anything && typeof anything.then === 'function'; } }; }); /** * @fileOverview Promise/A+ */ define('promise',[ 'promise-third' ], function( _ ) { return _; }); /** * @fileOverview 基础类方法。 */ /** * Web Uploader内部类的详细说明,以下提及的功能类,都可以在`WebUploader`这个变量中访问到。 * * As you know, Web Uploader的每个文件都是用过[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD)规范中的`define`组织起来的, 每个Module都会有个module id. * 默认module id为该文件的路径,而此路径将会转化成名字空间存放在WebUploader中。如: * * * module `base`:WebUploader.Base * * module `file`: WebUploader.File * * module `lib/dnd`: WebUploader.Lib.Dnd * * module `runtime/html5/dnd`: WebUploader.Runtime.Html5.Dnd * * * 以下文档中对类的使用可能省略掉了`WebUploader`前缀。 * @module WebUploader * @title WebUploader API文档 */ define('base',[ 'dollar', 'promise' ], function( $, promise ) { var noop = function() {}, call = Function.call; // http://jsperf.com/uncurrythis // 反科里化 function uncurryThis( fn ) { return function() { return call.apply( fn, arguments ); }; } function bindFn( fn, context ) { return function() { return fn.apply( context, arguments ); }; } function createObject( proto ) { var f; if ( Object.create ) { return Object.create( proto ); } else { f = function() {}; f.prototype = proto; return new f(); } } /** * 基础类,提供一些简单常用的方法。 * @class Base */ return { /** * @property {String} version 当前版本号。 */ version: '0.1.5', /** * @property {jQuery|Zepto} $ 引用依赖的jQuery或者Zepto对象。 */ $: $, Deferred: promise.Deferred, isPromise: promise.isPromise, when: promise.when, /** * @description 简单的浏览器检查结果。 * * * `webkit` webkit版本号,如果浏览器为非webkit内核,此属性为`undefined`。 * * `chrome` chrome浏览器版本号,如果浏览器为chrome,此属性为`undefined`。 * * `ie` ie浏览器版本号,如果浏览器为非ie,此属性为`undefined`。**暂不支持ie10+** * * `firefox` firefox浏览器版本号,如果浏览器为非firefox,此属性为`undefined`。 * * `safari` safari浏览器版本号,如果浏览器为非safari,此属性为`undefined`。 * * `opera` opera浏览器版本号,如果浏览器为非opera,此属性为`undefined`。 * * @property {Object} [browser] */ browser: (function( ua ) { var ret = {}, webkit = ua.match( /WebKit\/([\d.]+)/ ), chrome = ua.match( /Chrome\/([\d.]+)/ ) || ua.match( /CriOS\/([\d.]+)/ ), ie = ua.match( /MSIE\s([\d\.]+)/ ) || ua.match( /(?:trident)(?:.*rv:([\w.]+))?/i ), firefox = ua.match( /Firefox\/([\d.]+)/ ), safari = ua.match( /Safari\/([\d.]+)/ ), opera = ua.match( /OPR\/([\d.]+)/ ); webkit && (ret.webkit = parseFloat( webkit[ 1 ] )); chrome && (ret.chrome = parseFloat( chrome[ 1 ] )); ie && (ret.ie = parseFloat( ie[ 1 ] )); firefox && (ret.firefox = parseFloat( firefox[ 1 ] )); safari && (ret.safari = parseFloat( safari[ 1 ] )); opera && (ret.opera = parseFloat( opera[ 1 ] )); return ret; })( navigator.userAgent ), /** * @description 操作系统检查结果。 * * * `android` 如果在android浏览器环境下,此值为对应的android版本号,否则为`undefined`。 * * `ios` 如果在ios浏览器环境下,此值为对应的ios版本号,否则为`undefined`。 * @property {Object} [os] */ os: (function( ua ) { var ret = {}, // osx = !!ua.match( /\(Macintosh\; Intel / ), android = ua.match( /(?:Android);?[\s\/]+([\d.]+)?/ ), ios = ua.match( /(?:iPad|iPod|iPhone).*OS\s([\d_]+)/ ); // osx && (ret.osx = true); android && (ret.android = parseFloat( android[ 1 ] )); ios && (ret.ios = parseFloat( ios[ 1 ].replace( /_/g, '.' ) )); return ret; })( navigator.userAgent ), /** * 实现类与类之间的继承。 * @method inherits * @grammar Base.inherits( super ) => child * @grammar Base.inherits( super, protos ) => child * @grammar Base.inherits( super, protos, statics ) => child * @param {Class} super 父类 * @param {Object | Function} [protos] 子类或者对象。如果对象中包含constructor,子类将是用此属性值。 * @param {Function} [protos.constructor] 子类构造器,不指定的话将创建个临时的直接执行父类构造器的方法。 * @param {Object} [statics] 静态属性或方法。 * @return {Class} 返回子类。 * @example * function Person() { * console.log( 'Super' ); * } * Person.prototype.hello = function() { * console.log( 'hello' ); * }; * * var Manager = Base.inherits( Person, { * world: function() { * console.log( 'World' ); * } * }); * * // 因为没有指定构造器,父类的构造器将会执行。 * var instance = new Manager(); // => Super * * // 继承子父类的方法 * instance.hello(); // => hello * instance.world(); // => World * * // 子类的__super__属性指向父类 * console.log( Manager.__super__ === Person ); // => true */ inherits: function( Super, protos, staticProtos ) { var child; if ( typeof protos === 'function' ) { child = protos; protos = null; } else if ( protos && protos.hasOwnProperty('constructor') ) { child = protos.constructor; } else { child = function() { return Super.apply( this, arguments ); }; } // 复制静态方法 $.extend( true, child, Super, staticProtos || {} ); /* jshint camelcase: false */ // 让子类的__super__属性指向父类。 child.__super__ = Super.prototype; // 构建原型,添加原型方法或属性。 // 暂时用Object.create实现。 child.prototype = createObject( Super.prototype ); protos && $.extend( true, child.prototype, protos ); return child; }, /** * 一个不做任何事情的方法。可以用来赋值给默认的callback. * @method noop */ noop: noop, /** * 返回一个新的方法,此方法将已指定的`context`来执行。 * @grammar Base.bindFn( fn, context ) => Function * @method bindFn * @example * var doSomething = function() { * console.log( this.name ); * }, * obj = { * name: 'Object Name' * }, * aliasFn = Base.bind( doSomething, obj ); * * aliasFn(); // => Object Name * */ bindFn: bindFn, /** * 引用Console.log如果存在的话,否则引用一个[空函数noop](#WebUploader:Base.noop)。 * @grammar Base.log( args... ) => undefined * @method log */ log: (function() { if ( window.console ) { return bindFn( console.log, console ); } return noop; })(), nextTick: (function() { return function( cb ) { setTimeout( cb, 1 ); }; // @bug 当浏览器不在当前窗口时就停了。 // var next = window.requestAnimationFrame || // window.webkitRequestAnimationFrame || // window.mozRequestAnimationFrame || // function( cb ) { // window.setTimeout( cb, 1000 / 60 ); // }; // // fix: Uncaught TypeError: Illegal invocation // return bindFn( next, window ); })(), /** * 被[uncurrythis](http://www.2ality.com/2011/11/uncurrying-this.html)的数组slice方法。 * 将用来将非数组对象转化成数组对象。 * @grammar Base.slice( target, start[, end] ) => Array * @method slice * @example * function doSomthing() { * var args = Base.slice( arguments, 1 ); * console.log( args ); * } * * doSomthing( 'ignored', 'arg2', 'arg3' ); // => Array ["arg2", "arg3"] */ slice: uncurryThis( [].slice ), /** * 生成唯一的ID * @method guid * @grammar Base.guid() => String * @grammar Base.guid( prefx ) => String */ guid: (function() { var counter = 0; return function( prefix ) { var guid = (+new Date()).toString( 32 ), i = 0; for ( ; i < 5; i++ ) { guid += Math.floor( Math.random() * 65535 ).toString( 32 ); } return (prefix || 'wu_') + guid + (counter++).toString( 32 ); }; })(), /** * 格式化文件大小, 输出成带单位的字符串 * @method formatSize * @grammar Base.formatSize( size ) => String * @grammar Base.formatSize( size, pointLength ) => String * @grammar Base.formatSize( size, pointLength, units ) => String * @param {Number} size 文件大小 * @param {Number} [pointLength=2] 精确到的小数点数。 * @param {Array} [units=[ 'B', 'K', 'M', 'G', 'TB' ]] 单位数组。从字节,到千字节,一直往上指定。如果单位数组里面只指定了到了K(千字节),同时文件大小大于M, 此方法的输出将还是显示成多少K. * @example * console.log( Base.formatSize( 100 ) ); // => 100B * console.log( Base.formatSize( 1024 ) ); // => 1.00K * console.log( Base.formatSize( 1024, 0 ) ); // => 1K * console.log( Base.formatSize( 1024 * 1024 ) ); // => 1.00M * console.log( Base.formatSize( 1024 * 1024 * 1024 ) ); // => 1.00G * console.log( Base.formatSize( 1024 * 1024 * 1024, 0, ['B', 'KB', 'MB'] ) ); // => 1024MB */ formatSize: function( size, pointLength, units ) { var unit; units = units || [ 'B', 'K', 'M', 'G', 'TB' ]; while ( (unit = units.shift()) && size > 1024 ) { size = size / 1024; } return (unit === 'B' ? size : size.toFixed( pointLength || 2 )) + unit; } }; }); /** * 事件处理类,可以独立使用,也可以扩展给对象使用。 * @fileOverview Mediator */ define('mediator',[ 'base' ], function( Base ) { var $ = Base.$, slice = [].slice, separator = /\s+/, protos; // 根据条件过滤出事件handlers. function findHandlers( arr, name, callback, context ) { return $.grep( arr, function( handler ) { return handler && (!name || handler.e === name) && (!callback || handler.cb === callback || handler.cb._cb === callback) && (!context || handler.ctx === context); }); } function eachEvent( events, callback, iterator ) { // 不支持对象,只支持多个event用空格隔开 $.each( (events || '').split( separator ), function( _, key ) { iterator( key, callback ); }); } function triggerHanders( events, args ) { var stoped = false, i = -1, len = events.length, handler; while ( ++i < len ) { handler = events[ i ]; if ( handler.cb.apply( handler.ctx2, args ) === false ) { stoped = true; break; } } return !stoped; } protos = { /** * 绑定事件。 * * `callback`方法在执行时,arguments将会来源于trigger的时候携带的参数。如 * ```javascript * var obj = {}; * * // 使得obj有事件行为 * Mediator.installTo( obj ); * * obj.on( 'testa', function( arg1, arg2 ) { * console.log( arg1, arg2 ); // => 'arg1', 'arg2' * }); * * obj.trigger( 'testa', 'arg1', 'arg2' ); * ``` * * 如果`callback`中,某一个方法`return false`了,则后续的其他`callback`都不会被执行到。 * 切会影响到`trigger`方法的返回值,为`false`。 * * `on`还可以用来添加一个特殊事件`all`, 这样所有的事件触发都会响应到。同时此类`callback`中的arguments有一个不同处, * 就是第一个参数为`type`,记录当前是什么事件在触发。此类`callback`的优先级比脚低,会再正常`callback`执行完后触发。 * ```javascript * obj.on( 'all', function( type, arg1, arg2 ) { * console.log( type, arg1, arg2 ); // => 'testa', 'arg1', 'arg2' * }); * ``` * * @method on * @grammar on( name, callback[, context] ) => self * @param {String} name 事件名,支持多个事件用空格隔开 * @param {Function} callback 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable * @class Mediator */ on: function( name, callback, context ) { var me = this, set; if ( !callback ) { return this; } set = this._events || (this._events = []); eachEvent( name, callback, function( name, callback ) { var handler = { e: name }; handler.cb = callback; handler.ctx = context; handler.ctx2 = context || me; handler.id = set.length; set.push( handler ); }); return this; }, /** * 绑定事件,且当handler执行完后,自动解除绑定。 * @method once * @grammar once( name, callback[, context] ) => self * @param {String} name 事件名 * @param {Function} callback 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable */ once: function( name, callback, context ) { var me = this; if ( !callback ) { return me; } eachEvent( name, callback, function( name, callback ) { var once = function() { me.off( name, once ); return callback.apply( context || me, arguments ); }; once._cb = callback; me.on( name, once, context ); }); return me; }, /** * 解除事件绑定 * @method off * @grammar off( [name[, callback[, context] ] ] ) => self * @param {String} [name] 事件名 * @param {Function} [callback] 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable */ off: function( name, cb, ctx ) { var events = this._events; if ( !events ) { return this; } if ( !name && !cb && !ctx ) { this._events = []; return this; } eachEvent( name, cb, function( name, cb ) { $.each( findHandlers( events, name, cb, ctx ), function() { delete events[ this.id ]; }); }); return this; }, /** * 触发事件 * @method trigger * @grammar trigger( name[, args...] ) => self * @param {String} type 事件名 * @param {*} [...] 任意参数 * @return {Boolean} 如果handler中return false了,则返回false, 否则返回true */ trigger: function( type ) { var args, events, allEvents; if ( !this._events || !type ) { return this; } args = slice.call( arguments, 1 ); events = findHandlers( this._events, type ); allEvents = findHandlers( this._events, 'all' ); return triggerHanders( events, args ) && triggerHanders( allEvents, arguments ); } }; /** * 中介者,它本身是个单例,但可以通过[installTo](#WebUploader:Mediator:installTo)方法,使任何对象具备事件行为。 * 主要目的是负责模块与模块之间的合作,降低耦合度。 * * @class Mediator */ return $.extend({ /** * 可以通过这个接口,使任何对象具备事件功能。 * @method installTo * @param {Object} obj 需要具备事件行为的对象。 * @return {Object} 返回obj. */ installTo: function( obj ) { return $.extend( obj, protos ); } }, protos ); }); /** * @fileOverview Uploader上传类 */ define('uploader',[ 'base', 'mediator' ], function( Base, Mediator ) { var $ = Base.$; /** * 上传入口类。 * @class Uploader * @constructor * @grammar new Uploader( opts ) => Uploader * @example * var uploader = WebUploader.Uploader({ * swf: 'path_of_swf/Uploader.swf', * * // 开起分片上传。 * chunked: true * }); */ function Uploader( opts ) { this.options = $.extend( true, {}, Uploader.options, opts ); this._init( this.options ); } // default Options // widgets中有相应扩展 Uploader.options = {}; Mediator.installTo( Uploader.prototype ); // 批量添加纯命令式方法。 $.each({ upload: 'start-upload', stop: 'stop-upload', getFile: 'get-file', getFiles: 'get-files', addFile: 'add-file', addFiles: 'add-file', sort: 'sort-files', removeFile: 'remove-file', cancelFile: 'cancel-file', skipFile: 'skip-file', retry: 'retry', isInProgress: 'is-in-progress', makeThumb: 'make-thumb', md5File: 'md5-file', getDimension: 'get-dimension', addButton: 'add-btn', predictRuntimeType: 'predict-runtime-type', refresh: 'refresh', disable: 'disable', enable: 'enable', reset: 'reset' }, function( fn, command ) { Uploader.prototype[ fn ] = function() { return this.request( command, arguments ); }; }); $.extend( Uploader.prototype, { state: 'pending', _init: function( opts ) { var me = this; me.request( 'init', opts, function() { me.state = 'ready'; me.trigger('ready'); }); }, /** * 获取或者设置Uploader配置项。 * @method option * @grammar option( key ) => * * @grammar option( key, val ) => self * @example * * // 初始状态图片上传前不会压缩 * var uploader = new WebUploader.Uploader({ * compress: null; * }); * * // 修改后图片上传前,尝试将图片压缩到1600 * 1600 * uploader.option( 'compress', { * width: 1600, * height: 1600 * }); */ option: function( key, val ) { var opts = this.options; // setter if ( arguments.length > 1 ) { if ( $.isPlainObject( val ) && $.isPlainObject( opts[ key ] ) ) { $.extend( opts[ key ], val ); } else { opts[ key ] = val; } } else { // getter return key ? opts[ key ] : opts; } }, /** * 获取文件统计信息。返回一个包含一下信息的对象。 * * `successNum` 上传成功的文件数 * * `progressNum` 上传中的文件数 * * `cancelNum` 被删除的文件数 * * `invalidNum` 无效的文件数 * * `uploadFailNum` 上传失败的文件数 * * `queueNum` 还在队列中的文件数 * * `interruptNum` 被暂停的文件数 * @method getStats * @grammar getStats() => Object */ getStats: function() { // return this._mgr.getStats.apply( this._mgr, arguments ); var stats = this.request('get-stats'); return stats ? { successNum: stats.numOfSuccess, progressNum: stats.numOfProgress, // who care? // queueFailNum: 0, cancelNum: stats.numOfCancel, invalidNum: stats.numOfInvalid, uploadFailNum: stats.numOfUploadFailed, queueNum: stats.numOfQueue, interruptNum: stats.numofInterrupt } : {}; }, // 需要重写此方法来来支持opts.onEvent和instance.onEvent的处理器 trigger: function( type/*, args...*/ ) { var args = [].slice.call( arguments, 1 ), opts = this.options, name = 'on' + type.substring( 0, 1 ).toUpperCase() + type.substring( 1 ); if ( // 调用通过on方法注册的handler. Mediator.trigger.apply( this, arguments ) === false || // 调用opts.onEvent $.isFunction( opts[ name ] ) && opts[ name ].apply( this, args ) === false || // 调用this.onEvent $.isFunction( this[ name ] ) && this[ name ].apply( this, args ) === false || // 广播所有uploader的事件。 Mediator.trigger.apply( Mediator, [ this, type ].concat( args ) ) === false ) { return false; } return true; }, /** * 销毁 webuploader 实例 * @method destroy * @grammar destroy() => undefined */ destroy: function() { this.request( 'destroy', arguments ); this.off(); }, // widgets/widget.js将补充此方法的详细文档。 request: Base.noop }); /** * 创建Uploader实例,等同于new Uploader( opts ); * @method create * @class Base * @static * @grammar Base.create( opts ) => Uploader */ Base.create = Uploader.create = function( opts ) { return new Uploader( opts ); }; // 暴露Uploader,可以通过它来扩展业务逻辑。 Base.Uploader = Uploader; return Uploader; }); /** * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/runtime',[ 'base', 'mediator' ], function( Base, Mediator ) { var $ = Base.$, factories = {}, // 获取对象的第一个key getFirstKey = function( obj ) { for ( var key in obj ) { if ( obj.hasOwnProperty( key ) ) { return key; } } return null; }; // 接口类。 function Runtime( options ) { this.options = $.extend({ container: document.body }, options ); this.uid = Base.guid('rt_'); } $.extend( Runtime.prototype, { getContainer: function() { var opts = this.options, parent, container; if ( this._container ) { return this._container; } parent = $( opts.container || document.body ); container = $( document.createElement('div') ); container.attr( 'id', 'rt_' + this.uid ); container.css({ position: 'absolute', top: '0px', left: '0px', width: '1px', height: '1px', overflow: 'hidden' }); parent.append( container ); parent.addClass('webuploader-container'); this._container = container; this._parent = parent; return container; }, init: Base.noop, exec: Base.noop, destroy: function() { this._container && this._container.remove(); this._parent && this._parent.removeClass('webuploader-container'); this.off(); } }); Runtime.orders = 'html5,flash'; /** * 添加Runtime实现。 * @param {String} type 类型 * @param {Runtime} factory 具体Runtime实现。 */ Runtime.addRuntime = function( type, factory ) { factories[ type ] = factory; }; Runtime.hasRuntime = function( type ) { return !!(type ? factories[ type ] : getFirstKey( factories )); }; Runtime.create = function( opts, orders ) { var type, runtime; orders = orders || Runtime.orders; $.each( orders.split( /\s*,\s*/g ), function() { if ( factories[ this ] ) { type = this; return false; } }); type = type || getFirstKey( factories ); if ( !type ) { throw new Error('Runtime Error'); } runtime = new factories[ type ]( opts ); return runtime; }; Mediator.installTo( Runtime.prototype ); return Runtime; }); /** * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/client',[ 'base', 'mediator', 'runtime/runtime' ], function( Base, Mediator, Runtime ) { var cache; cache = (function() { var obj = {}; return { add: function( runtime ) { obj[ runtime.uid ] = runtime; }, get: function( ruid, standalone ) { var i; if ( ruid ) { return obj[ ruid ]; } for ( i in obj ) { // 有些类型不能重用,比如filepicker. if ( standalone && obj[ i ].__standalone ) { continue; } return obj[ i ]; } return null; }, remove: function( runtime ) { delete obj[ runtime.uid ]; } }; })(); function RuntimeClient( component, standalone ) { var deferred = Base.Deferred(), runtime; this.uid = Base.guid('client_'); // 允许runtime没有初始化之前,注册一些方法在初始化后执行。 this.runtimeReady = function( cb ) { return deferred.done( cb ); }; this.connectRuntime = function( opts, cb ) { // already connected. if ( runtime ) { throw new Error('already connected!'); } deferred.done( cb ); if ( typeof opts === 'string' && cache.get( opts ) ) { runtime = cache.get( opts ); } // 像filePicker只能独立存在,不能公用。 runtime = runtime || cache.get( null, standalone ); // 需要创建 if ( !runtime ) { runtime = Runtime.create( opts, opts.runtimeOrder ); runtime.__promise = deferred.promise(); runtime.once( 'ready', deferred.resolve ); runtime.init(); cache.add( runtime ); runtime.__client = 1; } else { // 来自cache Base.$.extend( runtime.options, opts ); runtime.__promise.then( deferred.resolve ); runtime.__client++; } standalone && (runtime.__standalone = standalone); return runtime; }; this.getRuntime = function() { return runtime; }; this.disconnectRuntime = function() { if ( !runtime ) { return; } runtime.__client--; if ( runtime.__client <= 0 ) { cache.remove( runtime ); delete runtime.__promise; runtime.destroy(); } runtime = null; }; this.exec = function() { if ( !runtime ) { return; } var args = Base.slice( arguments ); component && args.unshift( component ); return runtime.exec.apply( this, args ); }; this.getRuid = function() { return runtime && runtime.uid; }; this.destroy = (function( destroy ) { return function() { destroy && destroy.apply( this, arguments ); this.trigger('destroy'); this.off(); this.exec('destroy'); this.disconnectRuntime(); }; })( this.destroy ); } Mediator.installTo( RuntimeClient.prototype ); return RuntimeClient; }); /** * @fileOverview 错误信息 */ define('lib/dnd',[ 'base', 'mediator', 'runtime/client' ], function( Base, Mediator, RuntimeClent ) { var $ = Base.$; function DragAndDrop( opts ) { opts = this.options = $.extend({}, DragAndDrop.options, opts ); opts.container = $( opts.container ); if ( !opts.container.length ) { return; } RuntimeClent.call( this, 'DragAndDrop' ); } DragAndDrop.options = { accept: null, disableGlobalDnd: false }; Base.inherits( RuntimeClent, { constructor: DragAndDrop, init: function() { var me = this; me.connectRuntime( me.options, function() { me.exec('init'); me.trigger('ready'); }); } }); Mediator.installTo( DragAndDrop.prototype ); return DragAndDrop; }); /** * @fileOverview 组件基类。 */ define('widgets/widget',[ 'base', 'uploader' ], function( Base, Uploader ) { var $ = Base.$, _init = Uploader.prototype._init, _destroy = Uploader.prototype.destroy, IGNORE = {}, widgetClass = []; function isArrayLike( obj ) { if ( !obj ) { return false; } var length = obj.length, type = $.type( obj ); if ( obj.nodeType === 1 && length ) { return true; } return type === 'array' || type !== 'function' && type !== 'string' && (length === 0 || typeof length === 'number' && length > 0 && (length - 1) in obj); } function Widget( uploader ) { this.owner = uploader; this.options = uploader.options; } $.extend( Widget.prototype, { init: Base.noop, // 类Backbone的事件监听声明,监听uploader实例上的事件 // widget直接无法监听事件,事件只能通过uploader来传递 invoke: function( apiName, args ) { /* { 'make-thumb': 'makeThumb' } */ var map = this.responseMap; // 如果无API响应声明则忽略 if ( !map || !(apiName in map) || !(map[ apiName ] in this) || !$.isFunction( this[ map[ apiName ] ] ) ) { return IGNORE; } return this[ map[ apiName ] ].apply( this, args ); }, /** * 发送命令。当传入`callback`或者`handler`中返回`promise`时。返回一个当所有`handler`中的promise都完成后完成的新`promise`。 * @method request * @grammar request( command, args ) => * | Promise * @grammar request( command, args, callback ) => Promise * @for Uploader */ request: function() { return this.owner.request.apply( this.owner, arguments ); } }); // 扩展Uploader. $.extend( Uploader.prototype, { /** * @property {String | Array} [disableWidgets=undefined] * @namespace options * @for Uploader * @description 默认所有 Uploader.register 了的 widget 都会被加载,如果禁用某一部分,请通过此 option 指定黑名单。 */ // 覆写_init用来初始化widgets _init: function() { var me = this, widgets = me._widgets = [], deactives = me.options.disableWidgets || ''; $.each( widgetClass, function( _, klass ) { (!deactives || !~deactives.indexOf( klass._name )) && widgets.push( new klass( me ) ); }); return _init.apply( me, arguments ); }, request: function( apiName, args, callback ) { var i = 0, widgets = this._widgets, len = widgets && widgets.length, rlts = [], dfds = [], widget, rlt, promise, key; args = isArrayLike( args ) ? args : [ args ]; for ( ; i < len; i++ ) { widget = widgets[ i ]; rlt = widget.invoke( apiName, args ); if ( rlt !== IGNORE ) { // Deferred对象 if ( Base.isPromise( rlt ) ) { dfds.push( rlt ); } else { rlts.push( rlt ); } } } // 如果有callback,则用异步方式。 if ( callback || dfds.length ) { promise = Base.when.apply( Base, dfds ); key = promise.pipe ? 'pipe' : 'then'; // 很重要不能删除。删除了会死循环。 // 保证执行顺序。让callback总是在下一个 tick 中执行。 return promise[ key ](function() { var deferred = Base.Deferred(), args = arguments; if ( args.length === 1 ) { args = args[ 0 ]; } setTimeout(function() { deferred.resolve( args ); }, 1 ); return deferred.promise(); })[ callback ? key : 'done' ]( callback || Base.noop ); } else { return rlts[ 0 ]; } }, destroy: function() { _destroy.apply( this, arguments ); this._widgets = null; } }); /** * 添加组件 * @grammar Uploader.register(proto); * @grammar Uploader.register(map, proto); * @param {object} responseMap API 名称与函数实现的映射 * @param {object} proto 组件原型,构造函数通过 constructor 属性定义 * @method Uploader.register * @for Uploader * @example * Uploader.register({ * 'make-thumb': 'makeThumb' * }, { * init: function( options ) {}, * makeThumb: function() {} * }); * * Uploader.register({ * 'make-thumb': function() { * * } * }); */ Uploader.register = Widget.register = function( responseMap, widgetProto ) { var map = { init: 'init', destroy: 'destroy', name: 'anonymous' }, klass; if ( arguments.length === 1 ) { widgetProto = responseMap; // 自动生成 map 表。 $.each(widgetProto, function(key) { if ( key[0] === '_' || key === 'name' ) { key === 'name' && (map.name = widgetProto.name); return; } map[key.replace(/[A-Z]/g, '-$&').toLowerCase()] = key; }); } else { map = $.extend( map, responseMap ); } widgetProto.responseMap = map; klass = Base.inherits( Widget, widgetProto ); klass._name = map.name; widgetClass.push( klass ); return klass; }; /** * 删除插件,只有在注册时指定了名字的才能被删除。 * @grammar Uploader.unRegister(name); * @param {string} name 组件名字 * @method Uploader.unRegister * @for Uploader * @example * * Uploader.register({ * name: 'custom', * * 'make-thumb': function() { * * } * }); * * Uploader.unRegister('custom'); */ Uploader.unRegister = Widget.unRegister = function( name ) { if ( !name || name === 'anonymous' ) { return; } // 删除指定的插件。 for ( var i = widgetClass.length; i--; ) { if ( widgetClass[i]._name === name ) { widgetClass.splice(i, 1) } } }; return Widget; }); /** * @fileOverview DragAndDrop Widget。 */ define('widgets/filednd',[ 'base', 'uploader', 'lib/dnd', 'widgets/widget' ], function( Base, Uploader, Dnd ) { var $ = Base.$; Uploader.options.dnd = ''; /** * @property {Selector} [dnd=undefined] 指定Drag And Drop拖拽的容器,如果不指定,则不启动。 * @namespace options * @for Uploader */ /** * @property {Selector} [disableGlobalDnd=false] 是否禁掉整个页面的拖拽功能,如果不禁用,图片拖进来的时候会默认被浏览器打开。 * @namespace options * @for Uploader */ /** * @event dndAccept * @param {DataTransferItemList} items DataTransferItem * @description 阻止此事件可以拒绝某些类型的文件拖入进来。目前只有 chrome 提供这样的 API,且只能通过 mime-type 验证。 * @for Uploader */ return Uploader.register({ name: 'dnd', init: function( opts ) { if ( !opts.dnd || this.request('predict-runtime-type') !== 'html5' ) { return; } var me = this, deferred = Base.Deferred(), options = $.extend({}, { disableGlobalDnd: opts.disableGlobalDnd, container: opts.dnd, accept: opts.accept }), dnd; this.dnd = dnd = new Dnd( options ); dnd.once( 'ready', deferred.resolve ); dnd.on( 'drop', function( files ) { me.request( 'add-file', [ files ]); }); // 检测文件是否全部允许添加。 dnd.on( 'accept', function( items ) { return me.owner.trigger( 'dndAccept', items ); }); dnd.init(); return deferred.promise(); }, destroy: function() { this.dnd && this.dnd.destroy(); } }); }); /** * @fileOverview 错误信息 */ define('lib/filepaste',[ 'base', 'mediator', 'runtime/client' ], function( Base, Mediator, RuntimeClent ) { var $ = Base.$; function FilePaste( opts ) { opts = this.options = $.extend({}, opts ); opts.container = $( opts.container || document.body ); RuntimeClent.call( this, 'FilePaste' ); } Base.inherits( RuntimeClent, { constructor: FilePaste, init: function() { var me = this; me.connectRuntime( me.options, function() { me.exec('init'); me.trigger('ready'); }); } }); Mediator.installTo( FilePaste.prototype ); return FilePaste; }); /** * @fileOverview 组件基类。 */ define('widgets/filepaste',[ 'base', 'uploader', 'lib/filepaste', 'widgets/widget' ], function( Base, Uploader, FilePaste ) { var $ = Base.$; /** * @property {Selector} [paste=undefined] 指定监听paste事件的容器,如果不指定,不启用此功能。此功能为通过粘贴来添加截屏的图片。建议设置为`document.body`. * @namespace options * @for Uploader */ return Uploader.register({ name: 'paste', init: function( opts ) { if ( !opts.paste || this.request('predict-runtime-type') !== 'html5' ) { return; } var me = this, deferred = Base.Deferred(), options = $.extend({}, { container: opts.paste, accept: opts.accept }), paste; this.paste = paste = new FilePaste( options ); paste.once( 'ready', deferred.resolve ); paste.on( 'paste', function( files ) { me.owner.request( 'add-file', [ files ]); }); paste.init(); return deferred.promise(); }, destroy: function() { this.paste && this.paste.destroy(); } }); }); /** * @fileOverview Blob */ define('lib/blob',[ 'base', 'runtime/client' ], function( Base, RuntimeClient ) { function Blob( ruid, source ) { var me = this; me.source = source; me.ruid = ruid; this.size = source.size || 0; // 如果没有指定 mimetype, 但是知道文件后缀。 if ( !source.type && this.ext && ~'jpg,jpeg,png,gif,bmp'.indexOf( this.ext ) ) { this.type = 'image/' + (this.ext === 'jpg' ? 'jpeg' : this.ext); } else { this.type = source.type || 'application/octet-stream'; } RuntimeClient.call( me, 'Blob' ); this.uid = source.uid || this.uid; if ( ruid ) { me.connectRuntime( ruid ); } } Base.inherits( RuntimeClient, { constructor: Blob, slice: function( start, end ) { return this.exec( 'slice', start, end ); }, getSource: function() { return this.source; } }); return Blob; }); /** * 为了统一化Flash的File和HTML5的File而存在。 * 以至于要调用Flash里面的File,也可以像调用HTML5版本的File一下。 * @fileOverview File */ define('lib/file',[ 'base', 'lib/blob' ], function( Base, Blob ) { var uid = 1, rExt = /\.([^.]+)$/; function File( ruid, file ) { var ext; this.name = file.name || ('untitled' + uid++); ext = rExt.exec( file.name ) ? RegExp.$1.toLowerCase() : ''; // todo 支持其他类型文件的转换。 // 如果有 mimetype, 但是文件名里面没有找出后缀规律 if ( !ext && file.type ) { ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec( file.type ) ? RegExp.$1.toLowerCase() : ''; this.name += '.' + ext; } this.ext = ext; this.lastModifiedDate = file.lastModifiedDate || (new Date()).toLocaleString(); Blob.apply( this, arguments ); } return Base.inherits( Blob, File ); }); /** * @fileOverview 错误信息 */ define('lib/filepicker',[ 'base', 'runtime/client', 'lib/file' ], function( Base, RuntimeClent, File ) { var $ = Base.$; function FilePicker( opts ) { opts = this.options = $.extend({}, FilePicker.options, opts ); opts.container = $( opts.id ); if ( !opts.container.length ) { throw new Error('按钮指定错误'); } opts.innerHTML = opts.innerHTML || opts.label || opts.container.html() || ''; opts.button = $( opts.button || document.createElement('div') ); opts.button.html( opts.innerHTML ); opts.container.html( opts.button ); RuntimeClent.call( this, 'FilePicker', true ); } FilePicker.options = { button: null, container: null, label: null, innerHTML: null, multiple: true, accept: null, name: 'file' }; Base.inherits( RuntimeClent, { constructor: FilePicker, init: function() { var me = this, opts = me.options, button = opts.button; button.addClass('webuploader-pick'); me.on( 'all', function( type ) { var files; switch ( type ) { case 'mouseenter': button.addClass('webuploader-pick-hover'); break; case 'mouseleave': button.removeClass('webuploader-pick-hover'); break; case 'change': files = me.exec('getFiles'); me.trigger( 'select', $.map( files, function( file ) { file = new File( me.getRuid(), file ); // 记录来源。 file._refer = opts.container; return file; }), opts.container ); break; } }); me.connectRuntime( opts, function() { me.refresh(); me.exec( 'init', opts ); me.trigger('ready'); }); this._resizeHandler = Base.bindFn( this.refresh, this ); $( window ).on( 'resize', this._resizeHandler ); }, refresh: function() { var shimContainer = this.getRuntime().getContainer(), button = this.options.button, width = button.outerWidth ? button.outerWidth() : button.width(), height = button.outerHeight ? button.outerHeight() : button.height(), pos = button.offset(); width && height && shimContainer.css({ bottom: 'auto', right: 'auto', width: width + 'px', height: height + 'px' }).offset( pos ); }, enable: function() { var btn = this.options.button; btn.removeClass('webuploader-pick-disable'); this.refresh(); }, disable: function() { var btn = this.options.button; this.getRuntime().getContainer().css({ top: '-99999px' }); btn.addClass('webuploader-pick-disable'); }, destroy: function() { var btn = this.options.button; $( window ).off( 'resize', this._resizeHandler ); btn.removeClass('webuploader-pick-disable webuploader-pick-hover ' + 'webuploader-pick'); } }); return FilePicker; }); /** * @fileOverview 文件选择相关 */ define('widgets/filepicker',[ 'base', 'uploader', 'lib/filepicker', 'widgets/widget' ], function( Base, Uploader, FilePicker ) { var $ = Base.$; $.extend( Uploader.options, { /** * @property {Selector | Object} [pick=undefined] * @namespace options * @for Uploader * @description 指定选择文件的按钮容器,不指定则不创建按钮。 * * * `id` {Seletor|dom} 指定选择文件的按钮容器,不指定则不创建按钮。**注意** 这里虽然写的是 id, 但是不是只支持 id, 还支持 class, 或者 dom 节点。 * * `label` {String} 请采用 `innerHTML` 代替 * * `innerHTML` {String} 指定按钮文字。不指定时优先从指定的容器中看是否自带文字。 * * `multiple` {Boolean} 是否开起同时选择多个文件能力。 */ pick: null, /** * @property {Arroy} [accept=null] * @namespace options * @for Uploader * @description 指定接受哪些类型的文件。 由于目前还有ext转mimeType表,所以这里需要分开指定。 * * * `title` {String} 文字描述 * * `extensions` {String} 允许的文件后缀,不带点,多个用逗号分割。 * * `mimeTypes` {String} 多个用逗号分割。 * * 如: * * ``` * { * title: 'Images', * extensions: 'gif,jpg,jpeg,bmp,png', * mimeTypes: 'image/*' * } * ``` */ accept: null/*{ title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' }*/ }); return Uploader.register({ name: 'picker', init: function( opts ) { this.pickers = []; return opts.pick && this.addBtn( opts.pick ); }, refresh: function() { $.each( this.pickers, function() { this.refresh(); }); }, /** * @method addButton * @for Uploader * @grammar addButton( pick ) => Promise * @description * 添加文件选择按钮,如果一个按钮不够,需要调用此方法来添加。参数跟[options.pick](#WebUploader:Uploader:options)一致。 * @example * uploader.addButton({ * id: '#btnContainer', * innerHTML: '选择文件' * }); */ addBtn: function( pick ) { var me = this, opts = me.options, accept = opts.accept, promises = []; if ( !pick ) { return; } $.isPlainObject( pick ) || (pick = { id: pick }); $( pick.id ).each(function() { var options, picker, deferred; deferred = Base.Deferred(); options = $.extend({}, pick, { accept: $.isPlainObject( accept ) ? [ accept ] : accept, swf: opts.swf, runtimeOrder: opts.runtimeOrder, id: this }); picker = new FilePicker( options ); picker.once( 'ready', deferred.resolve ); picker.on( 'select', function( files ) { me.owner.request( 'add-file', [ files ]); }); picker.init(); me.pickers.push( picker ); promises.push( deferred.promise() ); }); return Base.when.apply( Base, promises ); }, disable: function() { $.each( this.pickers, function() { this.disable(); }); }, enable: function() { $.each( this.pickers, function() { this.enable(); }); }, destroy: function() { $.each( this.pickers, function() { this.destroy(); }); this.pickers = null; } }); }); /** * @fileOverview Image */ define('lib/image',[ 'base', 'runtime/client', 'lib/blob' ], function( Base, RuntimeClient, Blob ) { var $ = Base.$; // 构造器。 function Image( opts ) { this.options = $.extend({}, Image.options, opts ); RuntimeClient.call( this, 'Image' ); this.on( 'load', function() { this._info = this.exec('info'); this._meta = this.exec('meta'); }); } // 默认选项。 Image.options = { // 默认的图片处理质量 quality: 90, // 是否裁剪 crop: false, // 是否保留头部信息 preserveHeaders: false, // 是否允许放大。 allowMagnify: false }; // 继承RuntimeClient. Base.inherits( RuntimeClient, { constructor: Image, info: function( val ) { // setter if ( val ) { this._info = val; return this; } // getter return this._info; }, meta: function( val ) { // setter if ( val ) { this._meta = val; return this; } // getter return this._meta; }, loadFromBlob: function( blob ) { var me = this, ruid = blob.getRuid(); this.connectRuntime( ruid, function() { me.exec( 'init', me.options ); me.exec( 'loadFromBlob', blob ); }); }, resize: function() { var args = Base.slice( arguments ); return this.exec.apply( this, [ 'resize' ].concat( args ) ); }, crop: function() { var args = Base.slice( arguments ); return this.exec.apply( this, [ 'crop' ].concat( args ) ); }, getAsDataUrl: function( type ) { return this.exec( 'getAsDataUrl', type ); }, getAsBlob: function( type ) { var blob = this.exec( 'getAsBlob', type ); return new Blob( this.getRuid(), blob ); } }); return Image; }); /** * @fileOverview 图片操作, 负责预览图片和上传前压缩图片 */ define('widgets/image',[ 'base', 'uploader', 'lib/image', 'widgets/widget' ], function( Base, Uploader, Image ) { var $ = Base.$, throttle; // 根据要处理的文件大小来节流,一次不能处理太多,会卡。 throttle = (function( max ) { var occupied = 0, waiting = [], tick = function() { var item; while ( waiting.length && occupied < max ) { item = waiting.shift(); occupied += item[ 0 ]; item[ 1 ](); } }; return function( emiter, size, cb ) { waiting.push([ size, cb ]); emiter.once( 'destroy', function() { occupied -= size; setTimeout( tick, 1 ); }); setTimeout( tick, 1 ); }; })( 5 * 1024 * 1024 ); $.extend( Uploader.options, { /** * @property {Object} [thumb] * @namespace options * @for Uploader * @description 配置生成缩略图的选项。 * * 默认为: * * ```javascript * { * width: 110, * height: 110, * * // 图片质量,只有type为`image/jpeg`的时候才有效。 * quality: 70, * * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false. * allowMagnify: true, * * // 是否允许裁剪。 * crop: true, * * // 为空的话则保留原有图片格式。 * // 否则强制转换成指定的类型。 * type: 'image/jpeg' * } * ``` */ thumb: { width: 110, height: 110, quality: 70, allowMagnify: true, crop: true, preserveHeaders: false, // 为空的话则保留原有图片格式。 // 否则强制转换成指定的类型。 // IE 8下面 base64 大小不能超过 32K 否则预览失败,而非 jpeg 编码的图片很可 // 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg type: 'image/jpeg' }, /** * @property {Object} [compress] * @namespace options * @for Uploader * @description 配置压缩的图片的选项。如果此选项为`false`, 则图片在上传前不进行压缩。 * * 默认为: * * ```javascript * { * width: 1600, * height: 1600, * * // 图片质量,只有type为`image/jpeg`的时候才有效。 * quality: 90, * * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false. * allowMagnify: false, * * // 是否允许裁剪。 * crop: false, * * // 是否保留头部meta信息。 * preserveHeaders: true, * * // 如果发现压缩后文件大小比原来还大,则使用原来图片 * // 此属性可能会影响图片自动纠正功能 * noCompressIfLarger: false, * * // 单位字节,如果图片大小小于此值,不会采用压缩。 * compressSize: 0 * } * ``` */ compress: { width: 1600, height: 1600, quality: 90, allowMagnify: false, crop: false, preserveHeaders: true } }); return Uploader.register({ name: 'image', /** * 生成缩略图,此过程为异步,所以需要传入`callback`。 * 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果。 * * 当 width 或者 height 的值介于 0 - 1 时,被当成百分比使用。 * * `callback`中可以接收到两个参数。 * * 第一个为error,如果生成缩略图有错误,此error将为真。 * * 第二个为ret, 缩略图的Data URL值。 * * **注意** * Date URL在IE6/7中不支持,所以不用调用此方法了,直接显示一张暂不支持预览图片好了。 * 也可以借助服务端,将 base64 数据传给服务端,生成一个临时文件供预览。 * * @method makeThumb * @grammar makeThumb( file, callback ) => undefined * @grammar makeThumb( file, callback, width, height ) => undefined * @for Uploader * @example * * uploader.on( 'fileQueued', function( file ) { * var $li = ...; * * uploader.makeThumb( file, function( error, ret ) { * if ( error ) { * $li.text('预览错误'); * } else { * $li.append('<img alt="" src="' + ret + '" />'); * } * }); * * }); */ makeThumb: function( file, cb, width, height ) { var opts, image; file = this.request( 'get-file', file ); // 只预览图片格式。 if ( !file.type.match( /^image/ ) ) { cb( true ); return; } opts = $.extend({}, this.options.thumb ); // 如果传入的是object. if ( $.isPlainObject( width ) ) { opts = $.extend( opts, width ); width = null; } width = width || opts.width; height = height || opts.height; image = new Image( opts ); image.once( 'load', function() { file._info = file._info || image.info(); file._meta = file._meta || image.meta(); // 如果 width 的值介于 0 - 1 // 说明设置的是百分比。 if ( width <= 1 && width > 0 ) { width = file._info.width * width; } // 同样的规则应用于 height if ( height <= 1 && height > 0 ) { height = file._info.height * height; } image.resize( width, height ); }); // 当 resize 完后 image.once( 'complete', function() { cb( false, image.getAsDataUrl( opts.type ) ); image.destroy(); }); image.once( 'error', function( reason ) { cb( reason || true ); image.destroy(); }); throttle( image, file.source.size, function() { file._info && image.info( file._info ); file._meta && image.meta( file._meta ); image.loadFromBlob( file.source ); }); }, beforeSendFile: function( file ) { var opts = this.options.compress || this.options.resize, compressSize = opts && opts.compressSize || 0, noCompressIfLarger = opts && opts.noCompressIfLarger || false, image, deferred; file = this.request( 'get-file', file ); // 只压缩 jpeg 图片格式。 // gif 可能会丢失针 // bmp png 基本上尺寸都不大,且压缩比比较小。 if ( !opts || !~'image/jpeg,image/jpg'.indexOf( file.type ) || file.size < compressSize || file._compressed ) { return; } opts = $.extend({}, opts ); deferred = Base.Deferred(); image = new Image( opts ); deferred.always(function() { image.destroy(); image = null; }); image.once( 'error', deferred.reject ); image.once( 'load', function() { var width = opts.width, height = opts.height; file._info = file._info || image.info(); file._meta = file._meta || image.meta(); // 如果 width 的值介于 0 - 1 // 说明设置的是百分比。 if ( width <= 1 && width > 0 ) { width = file._info.width * width; } // 同样的规则应用于 height if ( height <= 1 && height > 0 ) { height = file._info.height * height; } image.resize( width, height ); }); image.once( 'complete', function() { var blob, size; // 移动端 UC / qq 浏览器的无图模式下 // ctx.getImageData 处理大图的时候会报 Exception // INDEX_SIZE_ERR: DOM Exception 1 try { blob = image.getAsBlob( opts.type ); size = file.size; // 如果压缩后,比原来还大则不用压缩后的。 if ( !noCompressIfLarger || blob.size < size ) { // file.source.destroy && file.source.destroy(); file.source = blob; file.size = blob.size; file.trigger( 'resize', blob.size, size ); } // 标记,避免重复压缩。 file._compressed = true; deferred.resolve(); } catch ( e ) { // 出错了直接继续,让其上传原始图片 deferred.resolve(); } }); file._info && image.info( file._info ); file._meta && image.meta( file._meta ); image.loadFromBlob( file.source ); return deferred.promise(); } }); }); /** * @fileOverview 文件属性封装 */ define('file',[ 'base', 'mediator' ], function( Base, Mediator ) { var $ = Base.$, idPrefix = 'WU_FILE_', idSuffix = 0, rExt = /\.([^.]+)$/, statusMap = {}; function gid() { return idPrefix + idSuffix++; } /** * 文件类 * @class File * @constructor 构造函数 * @grammar new File( source ) => File * @param {Lib.File} source [lib.File](#Lib.File)实例, 此source对象是带有Runtime信息的。 */ function WUFile( source ) { /** * 文件名,包括扩展名(后缀) * @property name * @type {string} */ this.name = source.name || 'Untitled'; /** * 文件体积(字节) * @property size * @type {uint} * @default 0 */ this.size = source.size || 0; /** * 文件MIMETYPE类型,与文件类型的对应关系请参考[http://t.cn/z8ZnFny](http://t.cn/z8ZnFny) * @property type * @type {string} * @default 'application/octet-stream' */ this.type = source.type || 'application/octet-stream'; /** * 文件最后修改日期 * @property lastModifiedDate * @type {int} * @default 当前时间戳 */ this.lastModifiedDate = source.lastModifiedDate || (new Date() * 1); /** * 文件ID,每个对象具有唯一ID,与文件名无关 * @property id * @type {string} */ this.id = gid(); /** * 文件扩展名,通过文件名获取,例如test.png的扩展名为png * @property ext * @type {string} */ this.ext = rExt.exec( this.name ) ? RegExp.$1 : ''; /** * 状态文字说明。在不同的status语境下有不同的用途。 * @property statusText * @type {string} */ this.statusText = ''; // 存储文件状态,防止通过属性直接修改 statusMap[ this.id ] = WUFile.Status.INITED; this.source = source; this.loaded = 0; this.on( 'error', function( msg ) { this.setStatus( WUFile.Status.ERROR, msg ); }); } $.extend( WUFile.prototype, { /** * 设置状态,状态变化时会触发`change`事件。 * @method setStatus * @grammar setStatus( status[, statusText] ); * @param {File.Status|String} status [文件状态值](#WebUploader:File:File.Status) * @param {String} [statusText=''] 状态说明,常在error时使用,用http, abort,server等来标记是由于什么原因导致文件错误。 */ setStatus: function( status, text ) { var prevStatus = statusMap[ this.id ]; typeof text !== 'undefined' && (this.statusText = text); if ( status !== prevStatus ) { statusMap[ this.id ] = status; /** * 文件状态变化 * @event statuschange */ this.trigger( 'statuschange', status, prevStatus ); } }, /** * 获取文件状态 * @return {File.Status} * @example 文件状态具体包括以下几种类型: { // 初始化 INITED: 0, // 已入队列 QUEUED: 1, // 正在上传 PROGRESS: 2, // 上传出错 ERROR: 3, // 上传成功 COMPLETE: 4, // 上传取消 CANCELLED: 5 } */ getStatus: function() { return statusMap[ this.id ]; }, /** * 获取文件原始信息。 * @return {*} */ getSource: function() { return this.source; }, destroy: function() { this.off(); delete statusMap[ this.id ]; } }); Mediator.installTo( WUFile.prototype ); /** * 文件状态值,具体包括以下几种类型: * * `inited` 初始状态 * * `queued` 已经进入队列, 等待上传 * * `progress` 上传中 * * `complete` 上传完成。 * * `error` 上传出错,可重试 * * `interrupt` 上传中断,可续传。 * * `invalid` 文件不合格,不能重试上传。会自动从队列中移除。 * * `cancelled` 文件被移除。 * @property {Object} Status * @namespace File * @class File * @static */ WUFile.Status = { INITED: 'inited', // 初始状态 QUEUED: 'queued', // 已经进入队列, 等待上传 PROGRESS: 'progress', // 上传中 ERROR: 'error', // 上传出错,可重试 COMPLETE: 'complete', // 上传完成。 CANCELLED: 'cancelled', // 上传取消。 INTERRUPT: 'interrupt', // 上传中断,可续传。 INVALID: 'invalid' // 文件不合格,不能重试上传。 }; return WUFile; }); /** * @fileOverview 文件队列 */ define('queue',[ 'base', 'mediator', 'file' ], function( Base, Mediator, WUFile ) { var $ = Base.$, STATUS = WUFile.Status; /** * 文件队列, 用来存储各个状态中的文件。 * @class Queue * @extends Mediator */ function Queue() { /** * 统计文件数。 * * `numOfQueue` 队列中的文件数。 * * `numOfSuccess` 上传成功的文件数 * * `numOfCancel` 被取消的文件数 * * `numOfProgress` 正在上传中的文件数 * * `numOfUploadFailed` 上传错误的文件数。 * * `numOfInvalid` 无效的文件数。 * * `numofDeleted` 被移除的文件数。 * @property {Object} stats */ this.stats = { numOfQueue: 0, numOfSuccess: 0, numOfCancel: 0, numOfProgress: 0, numOfUploadFailed: 0, numOfInvalid: 0, numofDeleted: 0, numofInterrupt: 0 }; // 上传队列,仅包括等待上传的文件 this._queue = []; // 存储所有文件 this._map = {}; } $.extend( Queue.prototype, { /** * 将新文件加入对队列尾部 * * @method append * @param {File} file 文件对象 */ append: function( file ) { this._queue.push( file ); this._fileAdded( file ); return this; }, /** * 将新文件加入对队列头部 * * @method prepend * @param {File} file 文件对象 */ prepend: function( file ) { this._queue.unshift( file ); this._fileAdded( file ); return this; }, /** * 获取文件对象 * * @method getFile * @param {String} fileId 文件ID * @return {File} */ getFile: function( fileId ) { if ( typeof fileId !== 'string' ) { return fileId; } return this._map[ fileId ]; }, /** * 从队列中取出一个指定状态的文件。 * @grammar fetch( status ) => File * @method fetch * @param {String} status [文件状态值](#WebUploader:File:File.Status) * @return {File} [File](#WebUploader:File) */ fetch: function( status ) { var len = this._queue.length, i, file; status = status || STATUS.QUEUED; for ( i = 0; i < len; i++ ) { file = this._queue[ i ]; if ( status === file.getStatus() ) { return file; } } return null; }, /** * 对队列进行排序,能够控制文件上传顺序。 * @grammar sort( fn ) => undefined * @method sort * @param {Function} fn 排序方法 */ sort: function( fn ) { if ( typeof fn === 'function' ) { this._queue.sort( fn ); } }, /** * 获取指定类型的文件列表, 列表中每一个成员为[File](#WebUploader:File)对象。 * @grammar getFiles( [status1[, status2 ...]] ) => Array * @method getFiles * @param {String} [status] [文件状态值](#WebUploader:File:File.Status) */ getFiles: function() { var sts = [].slice.call( arguments, 0 ), ret = [], i = 0, len = this._queue.length, file; for ( ; i < len; i++ ) { file = this._queue[ i ]; if ( sts.length && !~$.inArray( file.getStatus(), sts ) ) { continue; } ret.push( file ); } return ret; }, /** * 在队列中删除文件。 * @grammar removeFile( file ) => Array * @method removeFile * @param {File} 文件对象。 */ removeFile: function( file ) { var me = this, existing = this._map[ file.id ]; if ( existing ) { delete this._map[ file.id ]; file.destroy(); this.stats.numofDeleted++; } }, _fileAdded: function( file ) { var me = this, existing = this._map[ file.id ]; if ( !existing ) { this._map[ file.id ] = file; file.on( 'statuschange', function( cur, pre ) { me._onFileStatusChange( cur, pre ); }); } }, _onFileStatusChange: function( curStatus, preStatus ) { var stats = this.stats; switch ( preStatus ) { case STATUS.PROGRESS: stats.numOfProgress--; break; case STATUS.QUEUED: stats.numOfQueue --; break; case STATUS.ERROR: stats.numOfUploadFailed--; break; case STATUS.INVALID: stats.numOfInvalid--; break; case STATUS.INTERRUPT: stats.numofInterrupt--; break; } switch ( curStatus ) { case STATUS.QUEUED: stats.numOfQueue++; break; case STATUS.PROGRESS: stats.numOfProgress++; break; case STATUS.ERROR: stats.numOfUploadFailed++; break; case STATUS.COMPLETE: stats.numOfSuccess++; break; case STATUS.CANCELLED: stats.numOfCancel++; break; case STATUS.INVALID: stats.numOfInvalid++; break; case STATUS.INTERRUPT: stats.numofInterrupt++; break; } } }); Mediator.installTo( Queue.prototype ); return Queue; }); /** * @fileOverview 队列 */ define('widgets/queue',[ 'base', 'uploader', 'queue', 'file', 'lib/file', 'runtime/client', 'widgets/widget' ], function( Base, Uploader, Queue, WUFile, File, RuntimeClient ) { var $ = Base.$, rExt = /\.\w+$/, Status = WUFile.Status; return Uploader.register({ name: 'queue', init: function( opts ) { var me = this, deferred, len, i, item, arr, accept, runtime; if ( $.isPlainObject( opts.accept ) ) { opts.accept = [ opts.accept ]; } // accept中的中生成匹配正则。 if ( opts.accept ) { arr = []; for ( i = 0, len = opts.accept.length; i < len; i++ ) { item = opts.accept[ i ].extensions; item && arr.push( item ); } if ( arr.length ) { accept = '\\.' + arr.join(',') .replace( /,/g, '$|\\.' ) .replace( /\*/g, '.*' ) + '$'; } me.accept = new RegExp( accept, 'i' ); } me.queue = new Queue(); me.stats = me.queue.stats; // 如果当前不是html5运行时,那就算了。 // 不执行后续操作 if ( this.request('predict-runtime-type') !== 'html5' ) { return; } // 创建一个 html5 运行时的 placeholder // 以至于外部添加原生 File 对象的时候能正确包裹一下供 webuploader 使用。 deferred = Base.Deferred(); this.placeholder = runtime = new RuntimeClient('Placeholder'); runtime.connectRuntime({ runtimeOrder: 'html5' }, function() { me._ruid = runtime.getRuid(); deferred.resolve(); }); return deferred.promise(); }, // 为了支持外部直接添加一个原生File对象。 _wrapFile: function( file ) { if ( !(file instanceof WUFile) ) { if ( !(file instanceof File) ) { if ( !this._ruid ) { throw new Error('Can\'t add external files.'); } file = new File( this._ruid, file ); } file = new WUFile( file ); } return file; }, // 判断文件是否可以被加入队列 acceptFile: function( file ) { var invalid = !file || !file.size || this.accept && // 如果名字中有后缀,才做后缀白名单处理。 rExt.exec( file.name ) && !this.accept.test( file.name ); return !invalid; }, /** * @event beforeFileQueued * @param {File} file File对象 * @description 当文件被加入队列之前触发,此事件的handler返回值为`false`,则此文件不会被添加进入队列。 * @for Uploader */ /** * @event fileQueued * @param {File} file File对象 * @description 当文件被加入队列以后触发。 * @for Uploader */ _addFile: function( file ) { var me = this; file = me._wrapFile( file ); // 不过类型判断允许不允许,先派送 `beforeFileQueued` if ( !me.owner.trigger( 'beforeFileQueued', file ) ) { return; } // 类型不匹配,则派送错误事件,并返回。 if ( !me.acceptFile( file ) ) { me.owner.trigger( 'error', 'Q_TYPE_DENIED', file ); return; } me.queue.append( file ); me.owner.trigger( 'fileQueued', file ); return file; }, getFile: function( fileId ) { return this.queue.getFile( fileId ); }, /** * @event filesQueued * @param {File} files 数组,内容为原始File(lib/File)对象。 * @description 当一批文件添加进队列以后触发。 * @for Uploader */ /** * @property {Boolean} [auto=false] * @namespace options * @for Uploader * @description 设置为 true 后,不需要手动调用上传,有文件选择即开始上传。 * */ /** * @method addFiles * @grammar addFiles( file ) => undefined * @grammar addFiles( [file1, file2 ...] ) => undefined * @param {Array of File or File} [files] Files 对象 数组 * @description 添加文件到队列 * @for Uploader */ addFile: function( files ) { var me = this; if ( !files.length ) { files = [ files ]; } files = $.map( files, function( file ) { return me._addFile( file ); }); me.owner.trigger( 'filesQueued', files ); if ( me.options.auto ) { setTimeout(function() { me.request('start-upload'); }, 20 ); } }, getStats: function() { return this.stats; }, /** * @event fileDequeued * @param {File} file File对象 * @description 当文件被移除队列后触发。 * @for Uploader */ /** * @method removeFile * @grammar removeFile( file ) => undefined * @grammar removeFile( id ) => undefined * @grammar removeFile( file, true ) => undefined * @grammar removeFile( id, true ) => undefined * @param {File|id} file File对象或这File对象的id * @description 移除某一文件, 默认只会标记文件状态为已取消,如果第二个参数为 `true` 则会从 queue 中移除。 * @for Uploader * @example * * $li.on('click', '.remove-this', function() { * uploader.removeFile( file ); * }) */ removeFile: function( file, remove ) { var me = this; file = file.id ? file : me.queue.getFile( file ); this.request( 'cancel-file', file ); if ( remove ) { this.queue.removeFile( file ); } }, /** * @method getFiles * @grammar getFiles() => Array * @grammar getFiles( status1, status2, status... ) => Array * @description 返回指定状态的文件集合,不传参数将返回所有状态的文件。 * @for Uploader * @example * console.log( uploader.getFiles() ); // => all files * console.log( uploader.getFiles('error') ) // => all error files. */ getFiles: function() { return this.queue.getFiles.apply( this.queue, arguments ); }, fetchFile: function() { return this.queue.fetch.apply( this.queue, arguments ); }, /** * @method retry * @grammar retry() => undefined * @grammar retry( file ) => undefined * @description 重试上传,重试指定文件,或者从出错的文件开始重新上传。 * @for Uploader * @example * function retry() { * uploader.retry(); * } */ retry: function( file, noForceStart ) { var me = this, files, i, len; if ( file ) { file = file.id ? file : me.queue.getFile( file ); file.setStatus( Status.QUEUED ); noForceStart || me.request('start-upload'); return; } files = me.queue.getFiles( Status.ERROR ); i = 0; len = files.length; for ( ; i < len; i++ ) { file = files[ i ]; file.setStatus( Status.QUEUED ); } me.request('start-upload'); }, /** * @method sort * @grammar sort( fn ) => undefined * @description 排序队列中的文件,在上传之前调整可以控制上传顺序。 * @for Uploader */ sortFiles: function() { return this.queue.sort.apply( this.queue, arguments ); }, /** * @event reset * @description 当 uploader 被重置的时候触发。 * @for Uploader */ /** * @method reset * @grammar reset() => undefined * @description 重置uploader。目前只重置了队列。 * @for Uploader * @example * uploader.reset(); */ reset: function() { this.owner.trigger('reset'); this.queue = new Queue(); this.stats = this.queue.stats; }, destroy: function() { this.reset(); this.placeholder && this.placeholder.destroy(); } }); }); /** * @fileOverview 添加获取Runtime相关信息的方法。 */ define('widgets/runtime',[ 'uploader', 'runtime/runtime', 'widgets/widget' ], function( Uploader, Runtime ) { Uploader.support = function() { return Runtime.hasRuntime.apply( Runtime, arguments ); }; /** * @property {Object} [runtimeOrder=html5,flash] * @namespace options * @for Uploader * @description 指定运行时启动顺序。默认会想尝试 html5 是否支持,如果支持则使用 html5, 否则则使用 flash. * * 可以将此值设置成 `flash`,来强制使用 flash 运行时。 */ return Uploader.register({ name: 'runtime', init: function() { if ( !this.predictRuntimeType() ) { throw Error('Runtime Error'); } }, /** * 预测Uploader将采用哪个`Runtime` * @grammar predictRuntimeType() => String * @method predictRuntimeType * @for Uploader */ predictRuntimeType: function() { var orders = this.options.runtimeOrder || Runtime.orders, type = this.type, i, len; if ( !type ) { orders = orders.split( /\s*,\s*/g ); for ( i = 0, len = orders.length; i < len; i++ ) { if ( Runtime.hasRuntime( orders[ i ] ) ) { this.type = type = orders[ i ]; break; } } } return type; } }); }); /** * @fileOverview Transport */ define('lib/transport',[ 'base', 'runtime/client', 'mediator' ], function( Base, RuntimeClient, Mediator ) { var $ = Base.$; function Transport( opts ) { var me = this; opts = me.options = $.extend( true, {}, Transport.options, opts || {} ); RuntimeClient.call( this, 'Transport' ); this._blob = null; this._formData = opts.formData || {}; this._headers = opts.headers || {}; this.on( 'progress', this._timeout ); this.on( 'load error', function() { me.trigger( 'progress', 1 ); clearTimeout( me._timer ); }); } Transport.options = { server: '', method: 'POST', // 跨域时,是否允许携带cookie, 只有html5 runtime才有效 withCredentials: false, fileVal: 'file', timeout: 2 * 60 * 1000, // 2分钟 formData: {}, headers: {}, sendAsBinary: false }; $.extend( Transport.prototype, { // 添加Blob, 只能添加一次,最后一次有效。 appendBlob: function( key, blob, filename ) { var me = this, opts = me.options; if ( me.getRuid() ) { me.disconnectRuntime(); } // 连接到blob归属的同一个runtime. me.connectRuntime( blob.ruid, function() { me.exec('init'); }); me._blob = blob; opts.fileVal = key || opts.fileVal; opts.filename = filename || opts.filename; }, // 添加其他字段 append: function( key, value ) { if ( typeof key === 'object' ) { $.extend( this._formData, key ); } else { this._formData[ key ] = value; } }, setRequestHeader: function( key, value ) { if ( typeof key === 'object' ) { $.extend( this._headers, key ); } else { this._headers[ key ] = value; } }, send: function( method ) { this.exec( 'send', method ); this._timeout(); }, abort: function() { clearTimeout( this._timer ); return this.exec('abort'); }, destroy: function() { this.trigger('destroy'); this.off(); this.exec('destroy'); this.disconnectRuntime(); }, getResponse: function() { return this.exec('getResponse'); }, getResponseAsJson: function() { return this.exec('getResponseAsJson'); }, getStatus: function() { return this.exec('getStatus'); }, _timeout: function() { var me = this, duration = me.options.timeout; if ( !duration ) { return; } clearTimeout( me._timer ); me._timer = setTimeout(function() { me.abort(); me.trigger( 'error', 'timeout' ); }, duration ); } }); // 让Transport具备事件功能。 Mediator.installTo( Transport.prototype ); return Transport; }); /** * @fileOverview 负责文件上传相关。 */ define('widgets/upload',[ 'base', 'uploader', 'file', 'lib/transport', 'widgets/widget' ], function( Base, Uploader, WUFile, Transport ) { var $ = Base.$, isPromise = Base.isPromise, Status = WUFile.Status; // 添加默认配置项 $.extend( Uploader.options, { /** * @property {Boolean} [prepareNextFile=false] * @namespace options * @for Uploader * @description 是否允许在文件传输时提前把下一个文件准备好。 * 对于一个文件的准备工作比较耗时,比如图片压缩,md5序列化。 * 如果能提前在当前文件传输期处理,可以节省总体耗时。 */ prepareNextFile: false, /** * @property {Boolean} [chunked=false] * @namespace options * @for Uploader * @description 是否要分片处理大文件上传。 */ chunked: false, /** * @property {Boolean} [chunkSize=5242880] * @namespace options * @for Uploader * @description 如果要分片,分多大一片? 默认大小为5M. */ chunkSize: 5 * 1024 * 1024, /** * @property {Boolean} [chunkRetry=2] * @namespace options * @for Uploader * @description 如果某个分片由于网络问题出错,允许自动重传多少次? */ chunkRetry: 2, /** * @property {Boolean} [threads=3] * @namespace options * @for Uploader * @description 上传并发数。允许同时最大上传进程数。 */ threads: 3, /** * @property {Object} [formData={}] * @namespace options * @for Uploader * @description 文件上传请求的参数表,每次发送都会发送此对象中的参数。 */ formData: {} /** * @property {Object} [fileVal='file'] * @namespace options * @for Uploader * @description 设置文件上传域的name。 */ /** * @property {Object} [method='POST'] * @namespace options * @for Uploader * @description 文件上传方式,`POST`或者`GET`。 */ /** * @property {Object} [sendAsBinary=false] * @namespace options * @for Uploader * @description 是否已二进制的流的方式发送文件,这样整个上传内容`php://input`都为文件内容, * 其他参数在$_GET数组中。 */ }); // 负责将文件切片。 function CuteFile( file, chunkSize ) { var pending = [], blob = file.source, total = blob.size, chunks = chunkSize ? Math.ceil( total / chunkSize ) : 1, start = 0, index = 0, len, api; api = { file: file, has: function() { return !!pending.length; }, shift: function() { return pending.shift(); }, unshift: function( block ) { pending.unshift( block ); } }; while ( index < chunks ) { len = Math.min( chunkSize, total - start ); pending.push({ file: file, start: start, end: chunkSize ? (start + len) : total, total: total, chunks: chunks, chunk: index++, cuted: api }); start += len; } file.blocks = pending.concat(); file.remaning = pending.length; return api; } Uploader.register({ name: 'upload', init: function() { var owner = this.owner, me = this; this.runing = false; this.progress = false; owner .on( 'startUpload', function() { me.progress = true; }) .on( 'uploadFinished', function() { me.progress = false; }); // 记录当前正在传的数据,跟threads相关 this.pool = []; // 缓存分好片的文件。 this.stack = []; // 缓存即将上传的文件。 this.pending = []; // 跟踪还有多少分片在上传中但是没有完成上传。 this.remaning = 0; this.__tick = Base.bindFn( this._tick, this ); owner.on( 'uploadComplete', function( file ) { // 把其他块取消了。 file.blocks && $.each( file.blocks, function( _, v ) { v.transport && (v.transport.abort(), v.transport.destroy()); delete v.transport; }); delete file.blocks; delete file.remaning; }); }, reset: function() { this.request( 'stop-upload', true ); this.runing = false; this.pool = []; this.stack = []; this.pending = []; this.remaning = 0; this._trigged = false; this._promise = null; }, /** * @event startUpload * @description 当开始上传流程时触发。 * @for Uploader */ /** * 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。 * * 可以指定开始某一个文件。 * @grammar upload() => undefined * @grammar upload( file | fileId) => undefined * @method upload * @for Uploader */ startUpload: function(file) { var me = this; // 移出invalid的文件 $.each( me.request( 'get-files', Status.INVALID ), function() { me.request( 'remove-file', this ); }); // 如果指定了开始某个文件,则只开始指定文件。 if ( file ) { file = file.id ? file : me.request( 'get-file', file ); if (file.getStatus() === Status.INTERRUPT) { $.each( me.pool, function( _, v ) { // 之前暂停过。 if (v.file !== file) { return; } v.transport && v.transport.send(); }); file.setStatus( Status.QUEUED ); } else if (file.getStatus() === Status.PROGRESS) { return; } else { file.setStatus( Status.QUEUED ); } } else { $.each( me.request( 'get-files', [ Status.INITED ] ), function() { this.setStatus( Status.QUEUED ); }); } if ( me.runing ) { return; } me.runing = true; var files = []; // 如果有暂停的,则续传 $.each( me.pool, function( _, v ) { var file = v.file; if ( file.getStatus() === Status.INTERRUPT ) { files.push(file); me._trigged = false; v.transport && v.transport.send(); } }); var file; while ( (file = files.shift()) ) { file.setStatus( Status.PROGRESS ); } file || $.each( me.request( 'get-files', Status.INTERRUPT ), function() { this.setStatus( Status.PROGRESS ); }); me._trigged = false; Base.nextTick( me.__tick ); me.owner.trigger('startUpload'); }, /** * @event stopUpload * @description 当开始上传流程暂停时触发。 * @for Uploader */ /** * 暂停上传。第一个参数为是否中断上传当前正在上传的文件。 * * 如果第一个参数是文件,则只暂停指定文件。 * @grammar stop() => undefined * @grammar stop( true ) => undefined * @grammar stop( file ) => undefined * @method stop * @for Uploader */ stopUpload: function( file, interrupt ) { var me = this; if (file === true) { interrupt = file; file = null; } if ( me.runing === false ) { return; } // 如果只是暂停某个文件。 if ( file ) { file = file.id ? file : me.request( 'get-file', file ); if ( file.getStatus() !== Status.PROGRESS && file.getStatus() !== Status.QUEUED ) { return; } file.setStatus( Status.INTERRUPT ); $.each( me.pool, function( _, v ) { // 只 abort 指定的文件。 if (v.file !== file) { return; } v.transport && v.transport.abort(); me._putback(v); me._popBlock(v); }); return Base.nextTick( me.__tick ); } me.runing = false; if (this._promise && this._promise.file) { this._promise.file.setStatus( Status.INTERRUPT ); } interrupt && $.each( me.pool, function( _, v ) { v.transport && v.transport.abort(); v.file.setStatus( Status.INTERRUPT ); }); me.owner.trigger('stopUpload'); }, /** * @method cancelFile * @grammar cancelFile( file ) => undefined * @grammar cancelFile( id ) => undefined * @param {File|id} file File对象或这File对象的id * @description 标记文件状态为已取消, 同时将中断文件传输。 * @for Uploader * @example * * $li.on('click', '.remove-this', function() { * uploader.cancelFile( file ); * }) */ cancelFile: function( file ) { file = file.id ? file : this.request( 'get-file', file ); // 如果正在上传。 file.blocks && $.each( file.blocks, function( _, v ) { var _tr = v.transport; if ( _tr ) { _tr.abort(); _tr.destroy(); delete v.transport; } }); file.setStatus( Status.CANCELLED ); this.owner.trigger( 'fileDequeued', file ); $('#'+file.id).remove(); }, /** * 判断`Uplaode`r是否正在上传中。 * @grammar isInProgress() => Boolean * @method isInProgress * @for Uploader */ isInProgress: function() { return !!this.progress; }, _getStats: function() { return this.request('get-stats'); }, /** * 掉过一个文件上传,直接标记指定文件为已上传状态。 * @grammar skipFile( file ) => undefined * @method skipFile * @for Uploader */ skipFile: function( file, status ) { file = file.id ? file : this.request( 'get-file', file ); file.setStatus( status || Status.COMPLETE ); file.skipped = true; // 如果正在上传。 file.blocks && $.each( file.blocks, function( _, v ) { var _tr = v.transport; if ( _tr ) { _tr.abort(); _tr.destroy(); delete v.transport; } }); this.owner.trigger( 'uploadSkip', file ); }, /** * @event uploadFinished * @description 当所有文件上传结束时触发。 * @for Uploader */ _tick: function() { var me = this, opts = me.options, fn, val; // 上一个promise还没有结束,则等待完成后再执行。 if ( me._promise ) { return me._promise.always( me.__tick ); } // 还有位置,且还有文件要处理的话。 if ( me.pool.length < opts.threads && (val = me._nextBlock()) ) { me._trigged = false; fn = function( val ) { me._promise = null; // 有可能是reject过来的,所以要检测val的类型。 val && val.file && me._startSend( val ); Base.nextTick( me.__tick ); }; me._promise = isPromise( val ) ? val.always( fn ) : fn( val ); // 没有要上传的了,且没有正在传输的了。 } else if ( !me.remaning && !me._getStats().numOfQueue && !me._getStats().numofInterrupt ) { me.runing = false; me._trigged || Base.nextTick(function() { me.owner.trigger('uploadFinished'); }); me._trigged = true; } }, _putback: function(block) { var idx; block.cuted.unshift(block); idx = this.stack.indexOf(block.cuted); if (!~idx) { this.stack.unshift(block.cuted); } }, _getStack: function() { var i = 0, act; while ( (act = this.stack[ i++ ]) ) { if ( act.has() && act.file.getStatus() === Status.PROGRESS ) { return act; } else if (!act.has() || act.file.getStatus() !== Status.PROGRESS && act.file.getStatus() !== Status.INTERRUPT ) { // 把已经处理完了的,或者,状态为非 progress(上传中)、 // interupt(暂停中) 的移除。 this.stack.splice( --i, 1 ); } } return null; }, _nextBlock: function() { var me = this, opts = me.options, act, next, done, preparing; // 如果当前文件还有没有需要传输的,则直接返回剩下的。 if ( (act = this._getStack()) ) { // 是否提前准备下一个文件 if ( opts.prepareNextFile && !me.pending.length ) { me._prepareNextFile(); } return act.shift(); // 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。 } else if ( me.runing ) { // 如果缓存中有,则直接在缓存中取,没有则去queue中取。 if ( !me.pending.length && me._getStats().numOfQueue ) { me._prepareNextFile(); } next = me.pending.shift(); done = function( file ) { if ( !file ) { return null; } act = CuteFile( file, opts.chunked ? opts.chunkSize : 0 ); me.stack.push(act); return act.shift(); }; // 文件可能还在prepare中,也有可能已经完全准备好了。 if ( isPromise( next) ) { preparing = next.file; next = next[ next.pipe ? 'pipe' : 'then' ]( done ); next.file = preparing; return next; } return done( next ); } }, /** * @event uploadStart * @param {File} file File对象 * @description 某个文件开始上传前触发,一个文件只会触发一次。 * @for Uploader */ _prepareNextFile: function() { var me = this, file = me.request('fetch-file'), pending = me.pending, promise; if ( file ) { promise = me.request( 'before-send-file', file, function() { // 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued. if ( file.getStatus() === Status.PROGRESS || file.getStatus() === Status.INTERRUPT ) { return file; } return me._finishFile( file ); }); me.owner.trigger( 'uploadStart', file ); file.setStatus( Status.PROGRESS ); promise.file = file; // 如果还在pending中,则替换成文件本身。 promise.done(function() { var idx = $.inArray( promise, pending ); ~idx && pending.splice( idx, 1, file ); }); // befeore-send-file的钩子就有错误发生。 promise.fail(function( reason ) { file.setStatus( Status.ERROR, reason ); me.owner.trigger( 'uploadError', file, reason ); me.owner.trigger( 'uploadComplete', file ); }); pending.push( promise ); } }, // 让出位置了,可以让其他分片开始上传 _popBlock: function( block ) { var idx = $.inArray( block, this.pool ); this.pool.splice( idx, 1 ); block.file.remaning--; this.remaning--; }, // 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。 _startSend: function( block ) { var me = this, file = block.file, promise; // 有可能在 before-send-file 的 promise 期间改变了文件状态。 // 如:暂停,取消 // 我们不能中断 promise, 但是可以在 promise 完后,不做上传操作。 if ( file.getStatus() !== Status.PROGRESS ) { // 如果是中断,则还需要放回去。 if (file.getStatus() === Status.INTERRUPT) { me._putback(block); } return; } me.pool.push( block ); me.remaning++; // 如果没有分片,则直接使用原始的。 // 不会丢失content-type信息。 block.blob = block.chunks === 1 ? file.source : file.source.slice( block.start, block.end ); // hook, 每个分片发送之前可能要做些异步的事情。 promise = me.request( 'before-send', block, function() { // 有可能文件已经上传出错了,所以不需要再传输了。 if ( file.getStatus() === Status.PROGRESS ) { me._doSend( block ); } else { me._popBlock( block ); Base.nextTick( me.__tick ); } }); // 如果为fail了,则跳过此分片。 promise.fail(function() { if ( file.remaning === 1 ) { me._finishFile( file ).always(function() { block.percentage = 1; me._popBlock( block ); me.owner.trigger( 'uploadComplete', file ); Base.nextTick( me.__tick ); }); } else { block.percentage = 1; me.updateFileProgress( file ); me._popBlock( block ); Base.nextTick( me.__tick ); } }); }, /** * @event uploadBeforeSend * @param {Object} object * @param {Object} data 默认的上传参数,可以扩展此对象来控制上传参数。 * @param {Object} headers 可以扩展此对象来控制上传头部。 * @description 当某个文件的分块在发送前触发,主要用来询问是否要添加附带参数,大文件在开起分片上传的前提下此事件可能会触发多次。 * @for Uploader */ /** * @event uploadAccept * @param {Object} object * @param {Object} ret 服务端的返回数据,json格式,如果服务端不是json格式,从ret._raw中取数据,自行解析。 * @description 当某个文件上传到服务端响应后,会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件。 * @for Uploader */ /** * @event uploadProgress * @param {File} file File对象 * @param {Number} percentage 上传进度 * @description 上传过程中触发,携带上传进度。 * @for Uploader */ /** * @event uploadError * @param {File} file File对象 * @param {String} reason 出错的code * @description 当文件上传出错时触发。 * @for Uploader */ /** * @event uploadSuccess * @param {File} file File对象 * @param {Object} response 服务端返回的数据 * @description 当文件上传成功时触发。 * @for Uploader */ /** * @event uploadComplete * @param {File} [file] File对象 * @description 不管成功或者失败,文件上传完成时触发。 * @for Uploader */ // 做上传操作。 _doSend: function( block ) { var me = this, owner = me.owner, opts = me.options, file = block.file, tr = new Transport( opts ), data = $.extend({}, opts.formData ), headers = $.extend({}, opts.headers ), requestAccept, ret; block.transport = tr; tr.on( 'destroy', function() { delete block.transport; me._popBlock( block ); Base.nextTick( me.__tick ); }); // 广播上传进度。以文件为单位。 tr.on( 'progress', function( percentage ) { block.percentage = percentage; me.updateFileProgress( file ); }); // 用来询问,是否返回的结果是有错误的。 requestAccept = function( reject ) { var fn; ret = tr.getResponseAsJson() || {}; ret._raw = tr.getResponse(); fn = function( value ) { reject = value; }; // 服务端响应了,不代表成功了,询问是否响应正确。 if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) { reject = reject || 'server'; } return reject; }; // 尝试重试,然后广播文件上传出错。 tr.on( 'error', function( type, flag ) { block.retried = block.retried || 0; // 自动重试 if ( block.chunks > 1 && ~'http,abort'.indexOf( type ) && block.retried < opts.chunkRetry ) { block.retried++; tr.send(); } else { // http status 500 ~ 600 if ( !flag && type === 'server' ) { type = requestAccept( type ); } file.setStatus( Status.ERROR, type ); owner.trigger( 'uploadError', file, type ); owner.trigger( 'uploadComplete', file ); } }); // 上传成功 tr.on( 'load', function() { var reason; // 如果非预期,转向上传出错。 if ( (reason = requestAccept()) ) { tr.trigger( 'error', reason, true ); return; } // 全部上传完成。 if ( file.remaning === 1 ) { me._finishFile( file, ret ); } else { tr.destroy(); } }); // 配置默认的上传字段。 data = $.extend( data, { id: file.id, name: file.name, type: file.type, lastModifiedDate: file.lastModifiedDate, size: file.size }); block.chunks > 1 && $.extend( data, { chunks: block.chunks, chunk: block.chunk }); // 在发送之间可以添加字段什么的。。。 // 如果默认的字段不够使用,可以通过监听此事件来扩展 owner.trigger( 'uploadBeforeSend', block, data, headers ); // 开始发送。 tr.appendBlob( opts.fileVal, block.blob, file.name ); tr.append( data ); tr.setRequestHeader( headers ); tr.send(); }, // 完成上传。 _finishFile: function( file, ret, hds ) { var owner = this.owner; return owner .request( 'after-send-file', arguments, function() { file.setStatus( Status.COMPLETE ); owner.trigger( 'uploadSuccess', file, ret, hds ); }) .fail(function( reason ) { // 如果外部已经标记为invalid什么的,不再改状态。 if ( file.getStatus() === Status.PROGRESS ) { file.setStatus( Status.ERROR, reason ); } owner.trigger( 'uploadError', file, reason ); }) .always(function() { owner.trigger( 'uploadComplete', file ); }); }, updateFileProgress: function(file) { var totalPercent = 0, uploaded = 0; if (!file.blocks) { return; } $.each( file.blocks, function( _, v ) { uploaded += (v.percentage || 0) * (v.end - v.start); }); totalPercent = uploaded / file.size; this.owner.trigger( 'uploadProgress', file, totalPercent || 0 ); } }); }); /** * @fileOverview 各种验证,包括文件总大小是否超出、单文件是否超出和文件是否重复。 */ define('widgets/validator',[ 'base', 'uploader', 'file', 'widgets/widget' ], function( Base, Uploader, WUFile ) { var $ = Base.$, validators = {}, api; /** * @event error * @param {String} type 错误类型。 * @description 当validate不通过时,会以派送错误事件的形式通知调用者。通过`upload.on('error', handler)`可以捕获到此类错误,目前有以下错误会在特定的情况下派送错来。 * * * `Q_EXCEED_NUM_LIMIT` 在设置了`fileNumLimit`且尝试给`uploader`添加的文件数量超出这个值时派送。 * * `Q_EXCEED_SIZE_LIMIT` 在设置了`Q_EXCEED_SIZE_LIMIT`且尝试给`uploader`添加的文件总大小超出这个值时派送。 * * `Q_TYPE_DENIED` 当文件类型不满足时触发。。 * @for Uploader */ // 暴露给外面的api api = { // 添加验证器 addValidator: function( type, cb ) { validators[ type ] = cb; }, // 移除验证器 removeValidator: function( type ) { delete validators[ type ]; } }; // 在Uploader初始化的时候启动Validators的初始化 Uploader.register({ name: 'validator', init: function() { var me = this; Base.nextTick(function() { $.each( validators, function() { this.call( me.owner ); }); }); } }); /** * @property {int} [fileNumLimit=undefined] * @namespace options * @for Uploader * @description 验证文件总数量, 超出则不允许加入队列。 */ api.addValidator( 'fileNumLimit', function() { var uploader = this, opts = uploader.options, count = 0, max = parseInt( opts.fileNumLimit, 10 ), flag = true; if ( !max ) { return; } uploader.on( 'beforeFileQueued', function( file ) { if ( count >= max && flag ) { flag = false; this.trigger( 'error', 'Q_EXCEED_NUM_LIMIT', max, file ); setTimeout(function() { flag = true; }, 1 ); } return count >= max ? false : true; }); uploader.on( 'fileQueued', function() { count++; }); uploader.on( 'fileDequeued', function() { count--; }); uploader.on( 'reset', function() { count = 0; }); }); /** * @property {int} [fileSizeLimit=undefined] * @namespace options * @for Uploader * @description 验证文件总大小是否超出限制, 超出则不允许加入队列。 */ api.addValidator( 'fileSizeLimit', function() { var uploader = this, opts = uploader.options, count = 0, max = parseInt( opts.fileSizeLimit, 10 ), flag = true; if ( !max ) { return; } uploader.on( 'beforeFileQueued', function( file ) { var invalid = count + file.size > max; if ( invalid && flag ) { flag = false; this.trigger( 'error', 'Q_EXCEED_SIZE_LIMIT', max, file ); setTimeout(function() { flag = true; }, 1 ); } return invalid ? false : true; }); uploader.on( 'fileQueued', function( file ) { count += file.size; }); uploader.on( 'fileDequeued', function( file ) { count -= file.size; }); uploader.on( 'reset', function() { count = 0; }); }); /** * @property {int} [fileSingleSizeLimit=undefined] * @namespace options * @for Uploader * @description 验证单个文件大小是否超出限制, 超出则不允许加入队列。 */ api.addValidator( 'fileSingleSizeLimit', function() { var uploader = this, opts = uploader.options, max = opts.fileSingleSizeLimit; if ( !max ) { return; } uploader.on( 'beforeFileQueued', function( file ) { if ( file.size > max ) { file.setStatus( WUFile.Status.INVALID, 'exceed_size' ); this.trigger( 'error', 'F_EXCEED_SIZE', max, file ); return false; } }); }); /** * @property {Boolean} [duplicate=undefined] * @namespace options * @for Uploader * @description 去重, 根据文件名字、文件大小和最后修改时间来生成hash Key. */ api.addValidator( 'duplicate', function() { var uploader = this, opts = uploader.options, mapping = {}; if ( opts.duplicate ) { return; } function hashString( str ) { var hash = 0, i = 0, len = str.length, _char; for ( ; i < len; i++ ) { _char = str.charCodeAt( i ); hash = _char + (hash << 6) + (hash << 16) - hash; } return hash; } uploader.on( 'beforeFileQueued', function( file ) { var hash = file.__hash || (file.__hash = hashString( file.name + file.size + file.lastModifiedDate )); // 已经重复了 if ( mapping[ hash ] ) { this.trigger( 'error', 'F_DUPLICATE', file ); return false; } }); uploader.on( 'fileQueued', function( file ) { var hash = file.__hash; hash && (mapping[ hash ] = true); }); uploader.on( 'fileDequeued', function( file ) { var hash = file.__hash; hash && (delete mapping[ hash ]); }); uploader.on( 'reset', function() { mapping = {}; }); }); return api; }); /** * @fileOverview Md5 */ define('lib/md5',[ 'runtime/client', 'mediator' ], function( RuntimeClient, Mediator ) { function Md5() { RuntimeClient.call( this, 'Md5' ); } // 让 Md5 具备事件功能。 Mediator.installTo( Md5.prototype ); Md5.prototype.loadFromBlob = function( blob ) { var me = this; if ( me.getRuid() ) { me.disconnectRuntime(); } // 连接到blob归属的同一个runtime. me.connectRuntime( blob.ruid, function() { me.exec('init'); me.exec( 'loadFromBlob', blob ); }); }; Md5.prototype.getResult = function() { return this.exec('getResult'); }; return Md5; }); /** * @fileOverview 图片操作, 负责预览图片和上传前压缩图片 */ define('widgets/md5',[ 'base', 'uploader', 'lib/md5', 'lib/blob', 'widgets/widget' ], function( Base, Uploader, Md5, Blob ) { return Uploader.register({ name: 'md5', /** * 计算文件 md5 值,返回一个 promise 对象,可以监听 progress 进度。 * * * @method md5File * @grammar md5File( file[, start[, end]] ) => promise * @for Uploader * @example * * uploader.on( 'fileQueued', function( file ) { * var $li = ...; * * uploader.md5File( file ) * * // 及时显示进度 * .progress(function(percentage) { * console.log('Percentage:', percentage); * }) * * // 完成 * .then(function(val) { * console.log('md5 result:', val); * }); * * }); */ md5File: function( file, start, end ) { var md5 = new Md5(), deferred = Base.Deferred(), blob = (file instanceof Blob) ? file : this.request( 'get-file', file ).source; md5.on( 'progress load', function( e ) { e = e || {}; deferred.notify( e.total ? e.loaded / e.total : 1 ); }); md5.on( 'complete', function() { deferred.resolve( md5.getResult() ); }); md5.on( 'error', function( reason ) { deferred.reject( reason ); }); if ( arguments.length > 1 ) { start = start || 0; end = end || 0; start < 0 && (start = blob.size + start); end < 0 && (end = blob.size + end); end = Math.min( end, blob.size ); blob = blob.slice( start, end ); } md5.loadFromBlob( blob ); return deferred.promise(); } }); }); /** * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/compbase',[],function() { function CompBase( owner, runtime ) { this.owner = owner; this.options = owner.options; this.getRuntime = function() { return runtime; }; this.getRuid = function() { return runtime.uid; }; this.trigger = function() { return owner.trigger.apply( owner, arguments ); }; } return CompBase; }); /** * @fileOverview Html5Runtime */ define('runtime/html5/runtime',[ 'base', 'runtime/runtime', 'runtime/compbase' ], function( Base, Runtime, CompBase ) { var type = 'html5', components = {}; function Html5Runtime() { var pool = {}, me = this, destroy = this.destroy; Runtime.apply( me, arguments ); me.type = type; // 这个方法的调用者,实际上是RuntimeClient me.exec = function( comp, fn/*, args...*/) { var client = this, uid = client.uid, args = Base.slice( arguments, 2 ), instance; if ( components[ comp ] ) { instance = pool[ uid ] = pool[ uid ] || new components[ comp ]( client, me ); if ( instance[ fn ] ) { return instance[ fn ].apply( instance, args ); } } }; me.destroy = function() { // @todo 删除池子中的所有实例 return destroy && destroy.apply( this, arguments ); }; } Base.inherits( Runtime, { constructor: Html5Runtime, // 不需要连接其他程序,直接执行callback init: function() { var me = this; setTimeout(function() { me.trigger('ready'); }, 1 ); } }); // 注册Components Html5Runtime.register = function( name, component ) { var klass = components[ name ] = Base.inherits( CompBase, component ); return klass; }; // 注册html5运行时。 // 只有在支持的前提下注册。 if ( window.Blob && window.FileReader && window.DataView ) { Runtime.addRuntime( type, Html5Runtime ); } return Html5Runtime; }); /** * @fileOverview Blob Html实现 */ define('runtime/html5/blob',[ 'runtime/html5/runtime', 'lib/blob' ], function( Html5Runtime, Blob ) { return Html5Runtime.register( 'Blob', { slice: function( start, end ) { var blob = this.owner.source, slice = blob.slice || blob.webkitSlice || blob.mozSlice; blob = slice.call( blob, start, end ); return new Blob( this.getRuid(), blob ); } }); }); /** * @fileOverview FilePaste */ define('runtime/html5/dnd',[ 'base', 'runtime/html5/runtime', 'lib/file' ], function( Base, Html5Runtime, File ) { var $ = Base.$, prefix = 'webuploader-dnd-'; return Html5Runtime.register( 'DragAndDrop', { init: function() { var elem = this.elem = this.options.container; this.dragEnterHandler = Base.bindFn( this._dragEnterHandler, this ); this.dragOverHandler = Base.bindFn( this._dragOverHandler, this ); this.dragLeaveHandler = Base.bindFn( this._dragLeaveHandler, this ); this.dropHandler = Base.bindFn( this._dropHandler, this ); this.dndOver = false; elem.on( 'dragenter', this.dragEnterHandler ); elem.on( 'dragover', this.dragOverHandler ); elem.on( 'dragleave', this.dragLeaveHandler ); elem.on( 'drop', this.dropHandler ); if ( this.options.disableGlobalDnd ) { $( document ).on( 'dragover', this.dragOverHandler ); $( document ).on( 'drop', this.dropHandler ); } }, _dragEnterHandler: function( e ) { var me = this, denied = me._denied || false, items; e = e.originalEvent || e; if ( !me.dndOver ) { me.dndOver = true; // 注意只有 chrome 支持。 items = e.dataTransfer.items; if ( items && items.length ) { me._denied = denied = !me.trigger( 'accept', items ); } me.elem.addClass( prefix + 'over' ); me.elem[ denied ? 'addClass' : 'removeClass' ]( prefix + 'denied' ); } e.dataTransfer.dropEffect = denied ? 'none' : 'copy'; return false; }, _dragOverHandler: function( e ) { // 只处理框内的。 var parentElem = this.elem.parent().get( 0 ); if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) { return false; } clearTimeout( this._leaveTimer ); this._dragEnterHandler.call( this, e ); return false; }, _dragLeaveHandler: function() { var me = this, handler; handler = function() { me.dndOver = false; me.elem.removeClass( prefix + 'over ' + prefix + 'denied' ); }; clearTimeout( me._leaveTimer ); me._leaveTimer = setTimeout( handler, 100 ); return false; }, _dropHandler: function( e ) { var me = this, ruid = me.getRuid(), parentElem = me.elem.parent().get( 0 ), dataTransfer, data; // 只处理框内的。 if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) { return false; } e = e.originalEvent || e; dataTransfer = e.dataTransfer; // 如果是页面内拖拽,还不能处理,不阻止事件。 // 此处 ie11 下会报参数错误, try { data = dataTransfer.getData('text/html'); } catch( err ) { } if ( data ) { return; } me._getTansferFiles( dataTransfer, function( results ) { me.trigger( 'drop', $.map( results, function( file ) { return new File( ruid, file ); }) ); }); me.dndOver = false; me.elem.removeClass( prefix + 'over' ); return false; }, // 如果传入 callback 则去查看文件夹,否则只管当前文件夹。 _getTansferFiles: function( dataTransfer, callback ) { var results = [], promises = [], items, files, file, item, i, len, canAccessFolder; items = dataTransfer.items; files = dataTransfer.files; canAccessFolder = !!(items && items[ 0 ].webkitGetAsEntry); for ( i = 0, len = files.length; i < len; i++ ) { file = files[ i ]; item = items && items[ i ]; if ( canAccessFolder && item.webkitGetAsEntry().isDirectory ) { promises.push( this._traverseDirectoryTree( item.webkitGetAsEntry(), results ) ); } else { results.push( file ); } } Base.when.apply( Base, promises ).done(function() { if ( !results.length ) { return; } callback( results ); }); }, _traverseDirectoryTree: function( entry, results ) { var deferred = Base.Deferred(), me = this; if ( entry.isFile ) { entry.file(function( file ) { results.push( file ); deferred.resolve(); }); } else if ( entry.isDirectory ) { entry.createReader().readEntries(function( entries ) { var len = entries.length, promises = [], arr = [], // 为了保证顺序。 i; for ( i = 0; i < len; i++ ) { promises.push( me._traverseDirectoryTree( entries[ i ], arr ) ); } Base.when.apply( Base, promises ).then(function() { results.push.apply( results, arr ); deferred.resolve(); }, deferred.reject ); }); } return deferred.promise(); }, destroy: function() { var elem = this.elem; // 还没 init 就调用 destroy if (!elem) { return; } elem.off( 'dragenter', this.dragEnterHandler ); elem.off( 'dragover', this.dragOverHandler ); elem.off( 'dragleave', this.dragLeaveHandler ); elem.off( 'drop', this.dropHandler ); if ( this.options.disableGlobalDnd ) { $( document ).off( 'dragover', this.dragOverHandler ); $( document ).off( 'drop', this.dropHandler ); } } }); }); /** * @fileOverview FilePaste */ define('runtime/html5/filepaste',[ 'base', 'runtime/html5/runtime', 'lib/file' ], function( Base, Html5Runtime, File ) { return Html5Runtime.register( 'FilePaste', { init: function() { var opts = this.options, elem = this.elem = opts.container, accept = '.*', arr, i, len, item; // accetp的mimeTypes中生成匹配正则。 if ( opts.accept ) { arr = []; for ( i = 0, len = opts.accept.length; i < len; i++ ) { item = opts.accept[ i ].mimeTypes; item && arr.push( item ); } if ( arr.length ) { accept = arr.join(','); accept = accept.replace( /,/g, '|' ).replace( /\*/g, '.*' ); } } this.accept = accept = new RegExp( accept, 'i' ); this.hander = Base.bindFn( this._pasteHander, this ); elem.on( 'paste', this.hander ); }, _pasteHander: function( e ) { var allowed = [], ruid = this.getRuid(), items, item, blob, i, len; e = e.originalEvent || e; items = e.clipboardData.items; for ( i = 0, len = items.length; i < len; i++ ) { item = items[ i ]; if ( item.kind !== 'file' || !(blob = item.getAsFile()) ) { continue; } allowed.push( new File( ruid, blob ) ); } if ( allowed.length ) { // 不阻止非文件粘贴(文字粘贴)的事件冒泡 e.preventDefault(); e.stopPropagation(); this.trigger( 'paste', allowed ); } }, destroy: function() { this.elem.off( 'paste', this.hander ); } }); }); /** * @fileOverview FilePicker */ define('runtime/html5/filepicker',[ 'base', 'runtime/html5/runtime' ], function( Base, Html5Runtime ) { var $ = Base.$; return Html5Runtime.register( 'FilePicker', { init: function() { var container = this.getRuntime().getContainer(), me = this, owner = me.owner, opts = me.options, label = this.label = $( document.createElement('label') ), input = this.input = $( document.createElement('input') ), arr, i, len, mouseHandler; input.attr( 'type', 'file' ); input.attr( 'name', opts.name ); input.addClass('webuploader-element-invisible'); label.on( 'click', function() { input.trigger('click'); }); label.css({ opacity: 0, width: '100%', height: '100%', display: 'block', cursor: 'pointer', background: '#ffffff' }); if ( opts.multiple ) { input.attr( 'multiple', 'multiple' ); } // @todo Firefox不支持单独指定后缀 if ( opts.accept && opts.accept.length > 0 ) { arr = []; for ( i = 0, len = opts.accept.length; i < len; i++ ) { arr.push( opts.accept[ i ].mimeTypes ); } input.attr( 'accept', arr.join(',') ); } container.append( input ); container.append( label ); mouseHandler = function( e ) { owner.trigger( e.type ); }; input.on( 'change', function( e ) { var fn = arguments.callee, clone; me.files = e.target.files; // reset input clone = this.cloneNode( true ); clone.value = null; this.parentNode.replaceChild( clone, this ); input.off(); input = $( clone ).on( 'change', fn ) .on( 'mouseenter mouseleave', mouseHandler ); owner.trigger('change'); }); label.on( 'mouseenter mouseleave', mouseHandler ); }, getFiles: function() { return this.files; }, destroy: function() { this.input.off(); this.label.off(); } }); }); /** * Terms: * * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer * @fileOverview Image控件 */ define('runtime/html5/util',[ 'base' ], function( Base ) { var urlAPI = window.createObjectURL && window || window.URL && URL.revokeObjectURL && URL || window.webkitURL, createObjectURL = Base.noop, revokeObjectURL = createObjectURL; if ( urlAPI ) { // 更安全的方式调用,比如android里面就能把context改成其他的对象。 createObjectURL = function() { return urlAPI.createObjectURL.apply( urlAPI, arguments ); }; revokeObjectURL = function() { return urlAPI.revokeObjectURL.apply( urlAPI, arguments ); }; } return { createObjectURL: createObjectURL, revokeObjectURL: revokeObjectURL, dataURL2Blob: function( dataURI ) { var byteStr, intArray, ab, i, mimetype, parts; parts = dataURI.split(','); if ( ~parts[ 0 ].indexOf('base64') ) { byteStr = atob( parts[ 1 ] ); } else { byteStr = decodeURIComponent( parts[ 1 ] ); } ab = new ArrayBuffer( byteStr.length ); intArray = new Uint8Array( ab ); for ( i = 0; i < byteStr.length; i++ ) { intArray[ i ] = byteStr.charCodeAt( i ); } mimetype = parts[ 0 ].split(':')[ 1 ].split(';')[ 0 ]; return this.arrayBufferToBlob( ab, mimetype ); }, dataURL2ArrayBuffer: function( dataURI ) { var byteStr, intArray, i, parts; parts = dataURI.split(','); if ( ~parts[ 0 ].indexOf('base64') ) { byteStr = atob( parts[ 1 ] ); } else { byteStr = decodeURIComponent( parts[ 1 ] ); } intArray = new Uint8Array( byteStr.length ); for ( i = 0; i < byteStr.length; i++ ) { intArray[ i ] = byteStr.charCodeAt( i ); } return intArray.buffer; }, arrayBufferToBlob: function( buffer, type ) { var builder = window.BlobBuilder || window.WebKitBlobBuilder, bb; // android不支持直接new Blob, 只能借助blobbuilder. if ( builder ) { bb = new builder(); bb.append( buffer ); return bb.getBlob( type ); } return new Blob([ buffer ], type ? { type: type } : {} ); }, // 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg. // 你得到的结果是png. canvasToDataUrl: function( canvas, type, quality ) { return canvas.toDataURL( type, quality / 100 ); }, // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。 parseMeta: function( blob, callback ) { callback( false, {}); }, // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。 updateImageHead: function( data ) { return data; } }; }); /** * Terms: * * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer * @fileOverview Image控件 */ define('runtime/html5/imagemeta',[ 'runtime/html5/util' ], function( Util ) { var api; api = { parsers: { 0xffe1: [] }, maxMetaDataSize: 262144, parse: function( blob, cb ) { var me = this, fr = new FileReader(); fr.onload = function() { cb( false, me._parse( this.result ) ); fr = fr.onload = fr.onerror = null; }; fr.onerror = function( e ) { cb( e.message ); fr = fr.onload = fr.onerror = null; }; blob = blob.slice( 0, me.maxMetaDataSize ); fr.readAsArrayBuffer( blob.getSource() ); }, _parse: function( buffer, noParse ) { if ( buffer.byteLength < 6 ) { return; } var dataview = new DataView( buffer ), offset = 2, maxOffset = dataview.byteLength - 4, headLength = offset, ret = {}, markerBytes, markerLength, parsers, i; if ( dataview.getUint16( 0 ) === 0xffd8 ) { while ( offset < maxOffset ) { markerBytes = dataview.getUint16( offset ); if ( markerBytes >= 0xffe0 && markerBytes <= 0xffef || markerBytes === 0xfffe ) { markerLength = dataview.getUint16( offset + 2 ) + 2; if ( offset + markerLength > dataview.byteLength ) { break; } parsers = api.parsers[ markerBytes ]; if ( !noParse && parsers ) { for ( i = 0; i < parsers.length; i += 1 ) { parsers[ i ].call( api, dataview, offset, markerLength, ret ); } } offset += markerLength; headLength = offset; } else { break; } } if ( headLength > 6 ) { if ( buffer.slice ) { ret.imageHead = buffer.slice( 2, headLength ); } else { // Workaround for IE10, which does not yet // support ArrayBuffer.slice: ret.imageHead = new Uint8Array( buffer ) .subarray( 2, headLength ); } } } return ret; }, updateImageHead: function( buffer, head ) { var data = this._parse( buffer, true ), buf1, buf2, bodyoffset; bodyoffset = 2; if ( data.imageHead ) { bodyoffset = 2 + data.imageHead.byteLength; } if ( buffer.slice ) { buf2 = buffer.slice( bodyoffset ); } else { buf2 = new Uint8Array( buffer ).subarray( bodyoffset ); } buf1 = new Uint8Array( head.byteLength + 2 + buf2.byteLength ); buf1[ 0 ] = 0xFF; buf1[ 1 ] = 0xD8; buf1.set( new Uint8Array( head ), 2 ); buf1.set( new Uint8Array( buf2 ), head.byteLength + 2 ); return buf1.buffer; } }; Util.parseMeta = function() { return api.parse.apply( api, arguments ); }; Util.updateImageHead = function() { return api.updateImageHead.apply( api, arguments ); }; return api; }); /** * 代码来自于:https://github.com/blueimp/JavaScript-Load-Image * 暂时项目中只用了orientation. * * 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail. * @fileOverview EXIF解析 */ // Sample // ==================================== // Make : Apple // Model : iPhone 4S // Orientation : 1 // XResolution : 72 [72/1] // YResolution : 72 [72/1] // ResolutionUnit : 2 // Software : QuickTime 7.7.1 // DateTime : 2013:09:01 22:53:55 // ExifIFDPointer : 190 // ExposureTime : 0.058823529411764705 [1/17] // FNumber : 2.4 [12/5] // ExposureProgram : Normal program // ISOSpeedRatings : 800 // ExifVersion : 0220 // DateTimeOriginal : 2013:09:01 22:52:51 // DateTimeDigitized : 2013:09:01 22:52:51 // ComponentsConfiguration : YCbCr // ShutterSpeedValue : 4.058893515764426 // ApertureValue : 2.5260688216892597 [4845/1918] // BrightnessValue : -0.3126686601998395 // MeteringMode : Pattern // Flash : Flash did not fire, compulsory flash mode // FocalLength : 4.28 [107/25] // SubjectArea : [4 values] // FlashpixVersion : 0100 // ColorSpace : 1 // PixelXDimension : 2448 // PixelYDimension : 3264 // SensingMethod : One-chip color area sensor // ExposureMode : 0 // WhiteBalance : Auto white balance // FocalLengthIn35mmFilm : 35 // SceneCaptureType : Standard define('runtime/html5/imagemeta/exif',[ 'base', 'runtime/html5/imagemeta' ], function( Base, ImageMeta ) { var EXIF = {}; EXIF.ExifMap = function() { return this; }; EXIF.ExifMap.prototype.map = { 'Orientation': 0x0112 }; EXIF.ExifMap.prototype.get = function( id ) { return this[ id ] || this[ this.map[ id ] ]; }; EXIF.exifTagTypes = { // byte, 8-bit unsigned int: 1: { getValue: function( dataView, dataOffset ) { return dataView.getUint8( dataOffset ); }, size: 1 }, // ascii, 8-bit byte: 2: { getValue: function( dataView, dataOffset ) { return String.fromCharCode( dataView.getUint8( dataOffset ) ); }, size: 1, ascii: true }, // short, 16 bit int: 3: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getUint16( dataOffset, littleEndian ); }, size: 2 }, // long, 32 bit int: 4: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getUint32( dataOffset, littleEndian ); }, size: 4 }, // rational = two long values, // first is numerator, second is denominator: 5: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getUint32( dataOffset, littleEndian ) / dataView.getUint32( dataOffset + 4, littleEndian ); }, size: 8 }, // slong, 32 bit signed int: 9: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getInt32( dataOffset, littleEndian ); }, size: 4 }, // srational, two slongs, first is numerator, second is denominator: 10: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getInt32( dataOffset, littleEndian ) / dataView.getInt32( dataOffset + 4, littleEndian ); }, size: 8 } }; // undefined, 8-bit byte, value depending on field: EXIF.exifTagTypes[ 7 ] = EXIF.exifTagTypes[ 1 ]; EXIF.getExifValue = function( dataView, tiffOffset, offset, type, length, littleEndian ) { var tagType = EXIF.exifTagTypes[ type ], tagSize, dataOffset, values, i, str, c; if ( !tagType ) { Base.log('Invalid Exif data: Invalid tag type.'); return; } tagSize = tagType.size * length; // Determine if the value is contained in the dataOffset bytes, // or if the value at the dataOffset is a pointer to the actual data: dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32( offset + 8, littleEndian ) : (offset + 8); if ( dataOffset + tagSize > dataView.byteLength ) { Base.log('Invalid Exif data: Invalid data offset.'); return; } if ( length === 1 ) { return tagType.getValue( dataView, dataOffset, littleEndian ); } values = []; for ( i = 0; i < length; i += 1 ) { values[ i ] = tagType.getValue( dataView, dataOffset + i * tagType.size, littleEndian ); } if ( tagType.ascii ) { str = ''; // Concatenate the chars: for ( i = 0; i < values.length; i += 1 ) { c = values[ i ]; // Ignore the terminating NULL byte(s): if ( c === '\u0000' ) { break; } str += c; } return str; } return values; }; EXIF.parseExifTag = function( dataView, tiffOffset, offset, littleEndian, data ) { var tag = dataView.getUint16( offset, littleEndian ); data.exif[ tag ] = EXIF.getExifValue( dataView, tiffOffset, offset, dataView.getUint16( offset + 2, littleEndian ), // tag type dataView.getUint32( offset + 4, littleEndian ), // tag length littleEndian ); }; EXIF.parseExifTags = function( dataView, tiffOffset, dirOffset, littleEndian, data ) { var tagsNumber, dirEndOffset, i; if ( dirOffset + 6 > dataView.byteLength ) { Base.log('Invalid Exif data: Invalid directory offset.'); return; } tagsNumber = dataView.getUint16( dirOffset, littleEndian ); dirEndOffset = dirOffset + 2 + 12 * tagsNumber; if ( dirEndOffset + 4 > dataView.byteLength ) { Base.log('Invalid Exif data: Invalid directory size.'); return; } for ( i = 0; i < tagsNumber; i += 1 ) { this.parseExifTag( dataView, tiffOffset, dirOffset + 2 + 12 * i, // tag offset littleEndian, data ); } // Return the offset to the next directory: return dataView.getUint32( dirEndOffset, littleEndian ); }; // EXIF.getExifThumbnail = function(dataView, offset, length) { // var hexData, // i, // b; // if (!length || offset + length > dataView.byteLength) { // Base.log('Invalid Exif data: Invalid thumbnail data.'); // return; // } // hexData = []; // for (i = 0; i < length; i += 1) { // b = dataView.getUint8(offset + i); // hexData.push((b < 16 ? '0' : '') + b.toString(16)); // } // return 'data:image/jpeg,%' + hexData.join('%'); // }; EXIF.parseExifData = function( dataView, offset, length, data ) { var tiffOffset = offset + 10, littleEndian, dirOffset; // Check for the ASCII code for "Exif" (0x45786966): if ( dataView.getUint32( offset + 4 ) !== 0x45786966 ) { // No Exif data, might be XMP data instead return; } if ( tiffOffset + 8 > dataView.byteLength ) { Base.log('Invalid Exif data: Invalid segment size.'); return; } // Check for the two null bytes: if ( dataView.getUint16( offset + 8 ) !== 0x0000 ) { Base.log('Invalid Exif data: Missing byte alignment offset.'); return; } // Check the byte alignment: switch ( dataView.getUint16( tiffOffset ) ) { case 0x4949: littleEndian = true; break; case 0x4D4D: littleEndian = false; break; default: Base.log('Invalid Exif data: Invalid byte alignment marker.'); return; } // Check for the TIFF tag marker (0x002A): if ( dataView.getUint16( tiffOffset + 2, littleEndian ) !== 0x002A ) { Base.log('Invalid Exif data: Missing TIFF marker.'); return; } // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal: dirOffset = dataView.getUint32( tiffOffset + 4, littleEndian ); // Create the exif object to store the tags: data.exif = new EXIF.ExifMap(); // Parse the tags of the main image directory and retrieve the // offset to the next directory, usually the thumbnail directory: dirOffset = EXIF.parseExifTags( dataView, tiffOffset, tiffOffset + dirOffset, littleEndian, data ); // 尝试读取缩略图 // if ( dirOffset ) { // thumbnailData = {exif: {}}; // dirOffset = EXIF.parseExifTags( // dataView, // tiffOffset, // tiffOffset + dirOffset, // littleEndian, // thumbnailData // ); // // Check for JPEG Thumbnail offset: // if (thumbnailData.exif[0x0201]) { // data.exif.Thumbnail = EXIF.getExifThumbnail( // dataView, // tiffOffset + thumbnailData.exif[0x0201], // thumbnailData.exif[0x0202] // Thumbnail data length // ); // } // } }; ImageMeta.parsers[ 0xffe1 ].push( EXIF.parseExifData ); return EXIF; }); /** * 这个方式性能不行,但是可以解决android里面的toDataUrl的bug * android里面toDataUrl('image/jpege')得到的结果却是png. * * 所以这里没辙,只能借助这个工具 * @fileOverview jpeg encoder */ define('runtime/html5/jpegencoder',[], function( require, exports, module ) { /* Copyright (c) 2008, Adobe Systems Incorporated 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 Adobe Systems Incorporated 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. */ /* JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009 Basic GUI blocking jpeg encoder */ function JPEGEncoder(quality) { var self = this; var fround = Math.round; var ffloor = Math.floor; var YTable = new Array(64); var UVTable = new Array(64); var fdtbl_Y = new Array(64); var fdtbl_UV = new Array(64); var YDC_HT; var UVDC_HT; var YAC_HT; var UVAC_HT; var bitcode = new Array(65535); var category = new Array(65535); var outputfDCTQuant = new Array(64); var DU = new Array(64); var byteout = []; var bytenew = 0; var bytepos = 7; var YDU = new Array(64); var UDU = new Array(64); var VDU = new Array(64); var clt = new Array(256); var RGB_YUV_TABLE = new Array(2048); var currentQuality; var ZigZag = [ 0, 1, 5, 6,14,15,27,28, 2, 4, 7,13,16,26,29,42, 3, 8,12,17,25,30,41,43, 9,11,18,24,31,40,44,53, 10,19,23,32,39,45,52,54, 20,22,33,38,46,51,55,60, 21,34,37,47,50,56,59,61, 35,36,48,49,57,58,62,63 ]; var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0]; var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11]; var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d]; var std_ac_luminance_values = [ 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12, 0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07, 0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08, 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0, 0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16, 0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28, 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39, 0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49, 0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59, 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69, 0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79, 0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89, 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98, 0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7, 0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6, 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5, 0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4, 0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2, 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea, 0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8, 0xf9,0xfa ]; var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0]; var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11]; var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77]; var std_ac_chrominance_values = [ 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21, 0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71, 0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91, 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0, 0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34, 0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26, 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38, 0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48, 0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58, 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68, 0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78, 0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87, 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96, 0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5, 0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4, 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3, 0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2, 0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda, 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9, 0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8, 0xf9,0xfa ]; function initQuantTables(sf){ var YQT = [ 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68,109,103, 77, 24, 35, 55, 64, 81,104,113, 92, 49, 64, 78, 87,103,121,120,101, 72, 92, 95, 98,112,100,103, 99 ]; for (var i = 0; i < 64; i++) { var t = ffloor((YQT[i]*sf+50)/100); if (t < 1) { t = 1; } else if (t > 255) { t = 255; } YTable[ZigZag[i]] = t; } var UVQT = [ 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99 ]; for (var j = 0; j < 64; j++) { var u = ffloor((UVQT[j]*sf+50)/100); if (u < 1) { u = 1; } else if (u > 255) { u = 255; } UVTable[ZigZag[j]] = u; } var aasf = [ 1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379 ]; var k = 0; for (var row = 0; row < 8; row++) { for (var col = 0; col < 8; col++) { fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0)); fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0)); k++; } } } function computeHuffmanTbl(nrcodes, std_table){ var codevalue = 0; var pos_in_table = 0; var HT = new Array(); for (var k = 1; k <= 16; k++) { for (var j = 1; j <= nrcodes[k]; j++) { HT[std_table[pos_in_table]] = []; HT[std_table[pos_in_table]][0] = codevalue; HT[std_table[pos_in_table]][1] = k; pos_in_table++; codevalue++; } codevalue*=2; } return HT; } function initHuffmanTbl() { YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values); UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values); YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values); UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values); } function initCategoryNumber() { var nrlower = 1; var nrupper = 2; for (var cat = 1; cat <= 15; cat++) { //Positive numbers for (var nr = nrlower; nr<nrupper; nr++) { category[32767+nr] = cat; bitcode[32767+nr] = []; bitcode[32767+nr][1] = cat; bitcode[32767+nr][0] = nr; } //Negative numbers for (var nrneg =-(nrupper-1); nrneg<=-nrlower; nrneg++) { category[32767+nrneg] = cat; bitcode[32767+nrneg] = []; bitcode[32767+nrneg][1] = cat; bitcode[32767+nrneg][0] = nrupper-1+nrneg; } nrlower <<= 1; nrupper <<= 1; } } function initRGBYUVTable() { for(var i = 0; i < 256;i++) { RGB_YUV_TABLE[i] = 19595 * i; RGB_YUV_TABLE[(i+ 256)>>0] = 38470 * i; RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000; RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i; RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i; RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF; RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i; RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i; } } // IO functions function writeBits(bs) { var value = bs[0]; var posval = bs[1]-1; while ( posval >= 0 ) { if (value & (1 << posval) ) { bytenew |= (1 << bytepos); } posval--; bytepos--; if (bytepos < 0) { if (bytenew == 0xFF) { writeByte(0xFF); writeByte(0); } else { writeByte(bytenew); } bytepos=7; bytenew=0; } } } function writeByte(value) { byteout.push(clt[value]); // write char directly instead of converting later } function writeWord(value) { writeByte((value>>8)&0xFF); writeByte((value )&0xFF); } // DCT & quantization core function fDCTQuant(data, fdtbl) { var d0, d1, d2, d3, d4, d5, d6, d7; /* Pass 1: process rows. */ var dataOff=0; var i; var I8 = 8; var I64 = 64; for (i=0; i<I8; ++i) { d0 = data[dataOff]; d1 = data[dataOff+1]; d2 = data[dataOff+2]; d3 = data[dataOff+3]; d4 = data[dataOff+4]; d5 = data[dataOff+5]; d6 = data[dataOff+6]; d7 = data[dataOff+7]; var tmp0 = d0 + d7; var tmp7 = d0 - d7; var tmp1 = d1 + d6; var tmp6 = d1 - d6; var tmp2 = d2 + d5; var tmp5 = d2 - d5; var tmp3 = d3 + d4; var tmp4 = d3 - d4; /* Even part */ var tmp10 = tmp0 + tmp3; /* phase 2 */ var tmp13 = tmp0 - tmp3; var tmp11 = tmp1 + tmp2; var tmp12 = tmp1 - tmp2; data[dataOff] = tmp10 + tmp11; /* phase 3 */ data[dataOff+4] = tmp10 - tmp11; var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */ data[dataOff+2] = tmp13 + z1; /* phase 5 */ data[dataOff+6] = tmp13 - z1; /* Odd part */ tmp10 = tmp4 + tmp5; /* phase 2 */ tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; /* The rotator is modified from fig 4-8 to avoid extra negations. */ var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */ var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */ var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */ var z3 = tmp11 * 0.707106781; /* c4 */ var z11 = tmp7 + z3; /* phase 5 */ var z13 = tmp7 - z3; data[dataOff+5] = z13 + z2; /* phase 6 */ data[dataOff+3] = z13 - z2; data[dataOff+1] = z11 + z4; data[dataOff+7] = z11 - z4; dataOff += 8; /* advance pointer to next row */ } /* Pass 2: process columns. */ dataOff = 0; for (i=0; i<I8; ++i) { d0 = data[dataOff]; d1 = data[dataOff + 8]; d2 = data[dataOff + 16]; d3 = data[dataOff + 24]; d4 = data[dataOff + 32]; d5 = data[dataOff + 40]; d6 = data[dataOff + 48]; d7 = data[dataOff + 56]; var tmp0p2 = d0 + d7; var tmp7p2 = d0 - d7; var tmp1p2 = d1 + d6; var tmp6p2 = d1 - d6; var tmp2p2 = d2 + d5; var tmp5p2 = d2 - d5; var tmp3p2 = d3 + d4; var tmp4p2 = d3 - d4; /* Even part */ var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */ var tmp13p2 = tmp0p2 - tmp3p2; var tmp11p2 = tmp1p2 + tmp2p2; var tmp12p2 = tmp1p2 - tmp2p2; data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */ data[dataOff+32] = tmp10p2 - tmp11p2; var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */ data[dataOff+16] = tmp13p2 + z1p2; /* phase 5 */ data[dataOff+48] = tmp13p2 - z1p2; /* Odd part */ tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */ tmp11p2 = tmp5p2 + tmp6p2; tmp12p2 = tmp6p2 + tmp7p2; /* The rotator is modified from fig 4-8 to avoid extra negations. */ var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */ var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */ var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */ var z3p2 = tmp11p2 * 0.707106781; /* c4 */ var z11p2 = tmp7p2 + z3p2; /* phase 5 */ var z13p2 = tmp7p2 - z3p2; data[dataOff+40] = z13p2 + z2p2; /* phase 6 */ data[dataOff+24] = z13p2 - z2p2; data[dataOff+ 8] = z11p2 + z4p2; data[dataOff+56] = z11p2 - z4p2; dataOff++; /* advance pointer to next column */ } // Quantize/descale the coefficients var fDCTQuant; for (i=0; i<I64; ++i) { // Apply the quantization and scaling factor & Round to nearest integer fDCTQuant = data[i]*fdtbl[i]; outputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0); //outputfDCTQuant[i] = fround(fDCTQuant); } return outputfDCTQuant; } function writeAPP0() { writeWord(0xFFE0); // marker writeWord(16); // length writeByte(0x4A); // J writeByte(0x46); // F writeByte(0x49); // I writeByte(0x46); // F writeByte(0); // = "JFIF",'\0' writeByte(1); // versionhi writeByte(1); // versionlo writeByte(0); // xyunits writeWord(1); // xdensity writeWord(1); // ydensity writeByte(0); // thumbnwidth writeByte(0); // thumbnheight } function writeSOF0(width, height) { writeWord(0xFFC0); // marker writeWord(17); // length, truecolor YUV JPG writeByte(8); // precision writeWord(height); writeWord(width); writeByte(3); // nrofcomponents writeByte(1); // IdY writeByte(0x11); // HVY writeByte(0); // QTY writeByte(2); // IdU writeByte(0x11); // HVU writeByte(1); // QTU writeByte(3); // IdV writeByte(0x11); // HVV writeByte(1); // QTV } function writeDQT() { writeWord(0xFFDB); // marker writeWord(132); // length writeByte(0); for (var i=0; i<64; i++) { writeByte(YTable[i]); } writeByte(1); for (var j=0; j<64; j++) { writeByte(UVTable[j]); } } function writeDHT() { writeWord(0xFFC4); // marker writeWord(0x01A2); // length writeByte(0); // HTYDCinfo for (var i=0; i<16; i++) { writeByte(std_dc_luminance_nrcodes[i+1]); } for (var j=0; j<=11; j++) { writeByte(std_dc_luminance_values[j]); } writeByte(0x10); // HTYACinfo for (var k=0; k<16; k++) { writeByte(std_ac_luminance_nrcodes[k+1]); } for (var l=0; l<=161; l++) { writeByte(std_ac_luminance_values[l]); } writeByte(1); // HTUDCinfo for (var m=0; m<16; m++) { writeByte(std_dc_chrominance_nrcodes[m+1]); } for (var n=0; n<=11; n++) { writeByte(std_dc_chrominance_values[n]); } writeByte(0x11); // HTUACinfo for (var o=0; o<16; o++) { writeByte(std_ac_chrominance_nrcodes[o+1]); } for (var p=0; p<=161; p++) { writeByte(std_ac_chrominance_values[p]); } } function writeSOS() { writeWord(0xFFDA); // marker writeWord(12); // length writeByte(3); // nrofcomponents writeByte(1); // IdY writeByte(0); // HTY writeByte(2); // IdU writeByte(0x11); // HTU writeByte(3); // IdV writeByte(0x11); // HTV writeByte(0); // Ss writeByte(0x3f); // Se writeByte(0); // Bf } function processDU(CDU, fdtbl, DC, HTDC, HTAC){ var EOB = HTAC[0x00]; var M16zeroes = HTAC[0xF0]; var pos; var I16 = 16; var I63 = 63; var I64 = 64; var DU_DCT = fDCTQuant(CDU, fdtbl); //ZigZag reorder for (var j=0;j<I64;++j) { DU[ZigZag[j]]=DU_DCT[j]; } var Diff = DU[0] - DC; DC = DU[0]; //Encode DC if (Diff==0) { writeBits(HTDC[0]); // Diff might be 0 } else { pos = 32767+Diff; writeBits(HTDC[category[pos]]); writeBits(bitcode[pos]); } //Encode ACs var end0pos = 63; // was const... which is crazy for (; (end0pos>0)&&(DU[end0pos]==0); end0pos--) {}; //end0pos = first element in reverse order !=0 if ( end0pos == 0) { writeBits(EOB); return DC; } var i = 1; var lng; while ( i <= end0pos ) { var startpos = i; for (; (DU[i]==0) && (i<=end0pos); ++i) {} var nrzeroes = i-startpos; if ( nrzeroes >= I16 ) { lng = nrzeroes>>4; for (var nrmarker=1; nrmarker <= lng; ++nrmarker) writeBits(M16zeroes); nrzeroes = nrzeroes&0xF; } pos = 32767+DU[i]; writeBits(HTAC[(nrzeroes<<4)+category[pos]]); writeBits(bitcode[pos]); i++; } if ( end0pos != I63 ) { writeBits(EOB); } return DC; } function initCharLookupTable(){ var sfcc = String.fromCharCode; for(var i=0; i < 256; i++){ ///// ACHTUNG // 255 clt[i] = sfcc(i); } } this.encode = function(image,quality) // image data object { // var time_start = new Date().getTime(); if(quality) setQuality(quality); // Initialize bit writer byteout = new Array(); bytenew=0; bytepos=7; // Add JPEG headers writeWord(0xFFD8); // SOI writeAPP0(); writeDQT(); writeSOF0(image.width,image.height); writeDHT(); writeSOS(); // Encode 8x8 macroblocks var DCY=0; var DCU=0; var DCV=0; bytenew=0; bytepos=7; this.encode.displayName = "_encode_"; var imageData = image.data; var width = image.width; var height = image.height; var quadWidth = width*4; var tripleWidth = width*3; var x, y = 0; var r, g, b; var start,p, col,row,pos; while(y < height){ x = 0; while(x < quadWidth){ start = quadWidth * y + x; p = start; col = -1; row = 0; for(pos=0; pos < 64; pos++){ row = pos >> 3;// /8 col = ( pos & 7 ) * 4; // %8 p = start + ( row * quadWidth ) + col; if(y+row >= height){ // padding bottom p-= (quadWidth*(y+1+row-height)); } if(x+col >= quadWidth){ // padding right p-= ((x+col) - quadWidth +4) } r = imageData[ p++ ]; g = imageData[ p++ ]; b = imageData[ p++ ]; /* // calculate YUV values dynamically YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80 UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b)); VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b)); */ // use lookup table (slightly faster) YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128; UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128; VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128; } DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); x+=32; } y+=8; } //////////////////////////////////////////////////////////////// // Do the bit alignment of the EOI marker if ( bytepos >= 0 ) { var fillbits = []; fillbits[1] = bytepos+1; fillbits[0] = (1<<(bytepos+1))-1; writeBits(fillbits); } writeWord(0xFFD9); //EOI var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join('')); byteout = []; // benchmarking // var duration = new Date().getTime() - time_start; // console.log('Encoding time: '+ currentQuality + 'ms'); // return jpegDataUri } function setQuality(quality){ if (quality <= 0) { quality = 1; } if (quality > 100) { quality = 100; } if(currentQuality == quality) return // don't recalc if unchanged var sf = 0; if (quality < 50) { sf = Math.floor(5000 / quality); } else { sf = Math.floor(200 - quality*2); } initQuantTables(sf); currentQuality = quality; // console.log('Quality set to: '+quality +'%'); } function init(){ // var time_start = new Date().getTime(); if(!quality) quality = 50; // Create tables initCharLookupTable() initHuffmanTbl(); initCategoryNumber(); initRGBYUVTable(); setQuality(quality); // var duration = new Date().getTime() - time_start; // console.log('Initialization '+ duration + 'ms'); } init(); }; JPEGEncoder.encode = function( data, quality ) { var encoder = new JPEGEncoder( quality ); return encoder.encode( data ); } return JPEGEncoder; }); /** * @fileOverview Fix android canvas.toDataUrl bug. */ define('runtime/html5/androidpatch',[ 'runtime/html5/util', 'runtime/html5/jpegencoder', 'base' ], function( Util, encoder, Base ) { var origin = Util.canvasToDataUrl, supportJpeg; Util.canvasToDataUrl = function( canvas, type, quality ) { var ctx, w, h, fragement, parts; // 非android手机直接跳过。 if ( !Base.os.android ) { return origin.apply( null, arguments ); } // 检测是否canvas支持jpeg导出,根据数据格式来判断。 // JPEG 前两位分别是:255, 216 if ( type === 'image/jpeg' && typeof supportJpeg === 'undefined' ) { fragement = origin.apply( null, arguments ); parts = fragement.split(','); if ( ~parts[ 0 ].indexOf('base64') ) { fragement = atob( parts[ 1 ] ); } else { fragement = decodeURIComponent( parts[ 1 ] ); } fragement = fragement.substring( 0, 2 ); supportJpeg = fragement.charCodeAt( 0 ) === 255 && fragement.charCodeAt( 1 ) === 216; } // 只有在android环境下才修复 if ( type === 'image/jpeg' && !supportJpeg ) { w = canvas.width; h = canvas.height; ctx = canvas.getContext('2d'); return encoder.encode( ctx.getImageData( 0, 0, w, h ), quality ); } return origin.apply( null, arguments ); }; }); /** * @fileOverview Image */ define('runtime/html5/image',[ 'base', 'runtime/html5/runtime', 'runtime/html5/util' ], function( Base, Html5Runtime, Util ) { var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D'; return Html5Runtime.register( 'Image', { // flag: 标记是否被修改过。 modified: false, init: function() { var me = this, img = new Image(); img.onload = function() { me._info = { type: me.type, width: this.width, height: this.height }; // 读取meta信息。 if ( !me._metas && 'image/jpeg' === me.type ) { Util.parseMeta( me._blob, function( error, ret ) { me._metas = ret; me.owner.trigger('load'); }); } else { me.owner.trigger('load'); } }; img.onerror = function() { me.owner.trigger('error'); }; me._img = img; }, loadFromBlob: function( blob ) { var me = this, img = me._img; me._blob = blob; me.type = blob.type; img.src = Util.createObjectURL( blob.getSource() ); me.owner.once( 'load', function() { Util.revokeObjectURL( img.src ); }); }, resize: function( width, height ) { var canvas = this._canvas || (this._canvas = document.createElement('canvas')); this._resize( this._img, canvas, width, height ); this._blob = null; // 没用了,可以删掉了。 this.modified = true; this.owner.trigger( 'complete', 'resize' ); }, crop: function( x, y, w, h, s ) { var cvs = this._canvas || (this._canvas = document.createElement('canvas')), opts = this.options, img = this._img, iw = img.naturalWidth, ih = img.naturalHeight, orientation = this.getOrientation(); s = s || 1; // todo 解决 orientation 的问题。 // values that require 90 degree rotation // if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) { // switch ( orientation ) { // case 6: // tmp = x; // x = y; // y = iw * s - tmp - w; // console.log(ih * s, tmp, w) // break; // } // (w ^= h, h ^= w, w ^= h); // } cvs.width = w; cvs.height = h; opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation ); this._renderImageToCanvas( cvs, img, -x, -y, iw * s, ih * s ); this._blob = null; // 没用了,可以删掉了。 this.modified = true; this.owner.trigger( 'complete', 'crop' ); }, getAsBlob: function( type ) { var blob = this._blob, opts = this.options, canvas; type = type || this.type; // blob需要重新生成。 if ( this.modified || this.type !== type ) { canvas = this._canvas; if ( type === 'image/jpeg' ) { blob = Util.canvasToDataUrl( canvas, type, opts.quality ); if ( opts.preserveHeaders && this._metas && this._metas.imageHead ) { blob = Util.dataURL2ArrayBuffer( blob ); blob = Util.updateImageHead( blob, this._metas.imageHead ); blob = Util.arrayBufferToBlob( blob, type ); return blob; } } else { blob = Util.canvasToDataUrl( canvas, type ); } blob = Util.dataURL2Blob( blob ); } return blob; }, getAsDataUrl: function( type ) { var opts = this.options; type = type || this.type; if ( type === 'image/jpeg' ) { return Util.canvasToDataUrl( this._canvas, type, opts.quality ); } else { return this._canvas.toDataURL( type ); } }, getOrientation: function() { return this._metas && this._metas.exif && this._metas.exif.get('Orientation') || 1; }, info: function( val ) { // setter if ( val ) { this._info = val; return this; } // getter return this._info; }, meta: function( val ) { // setter if ( val ) { this._meta = val; return this; } // getter return this._meta; }, destroy: function() { var canvas = this._canvas; this._img.onload = null; if ( canvas ) { canvas.getContext('2d') .clearRect( 0, 0, canvas.width, canvas.height ); canvas.width = canvas.height = 0; this._canvas = null; } // 释放内存。非常重要,否则释放不了image的内存。 this._img.src = BLANK; this._img = this._blob = null; }, _resize: function( img, cvs, width, height ) { var opts = this.options, naturalWidth = img.width, naturalHeight = img.height, orientation = this.getOrientation(), scale, w, h, x, y; // values that require 90 degree rotation if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) { // 交换width, height的值。 width ^= height; height ^= width; width ^= height; } scale = Math[ opts.crop ? 'max' : 'min' ]( width / naturalWidth, height / naturalHeight ); // 不允许放大。 opts.allowMagnify || (scale = Math.min( 1, scale )); w = naturalWidth * scale; h = naturalHeight * scale; if ( opts.crop ) { cvs.width = width; cvs.height = height; } else { cvs.width = w; cvs.height = h; } x = (cvs.width - w) / 2; y = (cvs.height - h) / 2; opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation ); this._renderImageToCanvas( cvs, img, x, y, w, h ); }, _rotate2Orientaion: function( canvas, orientation ) { var width = canvas.width, height = canvas.height, ctx = canvas.getContext('2d'); switch ( orientation ) { case 5: case 6: case 7: case 8: canvas.width = height; canvas.height = width; break; } switch ( orientation ) { case 2: // horizontal flip ctx.translate( width, 0 ); ctx.scale( -1, 1 ); break; case 3: // 180 rotate left ctx.translate( width, height ); ctx.rotate( Math.PI ); break; case 4: // vertical flip ctx.translate( 0, height ); ctx.scale( 1, -1 ); break; case 5: // vertical flip + 90 rotate right ctx.rotate( 0.5 * Math.PI ); ctx.scale( 1, -1 ); break; case 6: // 90 rotate right ctx.rotate( 0.5 * Math.PI ); ctx.translate( 0, -height ); break; case 7: // horizontal flip + 90 rotate right ctx.rotate( 0.5 * Math.PI ); ctx.translate( width, -height ); ctx.scale( -1, 1 ); break; case 8: // 90 rotate left ctx.rotate( -0.5 * Math.PI ); ctx.translate( -width, 0 ); break; } }, // https://github.com/stomita/ios-imagefile-megapixel/ // blob/master/src/megapix-image.js _renderImageToCanvas: (function() { // 如果不是ios, 不需要这么复杂! if ( !Base.os.ios ) { return function( canvas ) { var args = Base.slice( arguments, 1 ), ctx = canvas.getContext('2d'); ctx.drawImage.apply( ctx, args ); }; } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into * canvas for some images. */ function detectVerticalSquash( img, iw, ih ) { var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), sy = 0, ey = ih, py = ih, data, alpha, ratio; canvas.width = 1; canvas.height = ih; ctx.drawImage( img, 0, 0 ); data = ctx.getImageData( 0, 0, 1, ih ).data; // search image edge pixel position in case // it is squashed vertically. while ( py > sy ) { alpha = data[ (py - 1) * 4 + 3 ]; if ( alpha === 0 ) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } ratio = (py / ih); return (ratio === 0) ? 1 : ratio; } // fix ie7 bug // http://stackoverflow.com/questions/11929099/ // html5-canvas-drawimage-ratio-bug-ios if ( Base.os.ios >= 7 ) { return function( canvas, img, x, y, w, h ) { var iw = img.naturalWidth, ih = img.naturalHeight, vertSquashRatio = detectVerticalSquash( img, iw, ih ); return canvas.getContext('2d').drawImage( img, 0, 0, iw * vertSquashRatio, ih * vertSquashRatio, x, y, w, h ); }; } /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be * subsampled in rendering. */ function detectSubsampling( img ) { var iw = img.naturalWidth, ih = img.naturalHeight, canvas, ctx; // subsampling may happen overmegapixel image if ( iw * ih > 1024 * 1024 ) { canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; ctx = canvas.getContext('2d'); ctx.drawImage( img, -iw + 1, 0 ); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering // edge pixel or not. if alpha value is 0 // image is not covering, hence subsampled. return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0; } else { return false; } } return function( canvas, img, x, y, width, height ) { var iw = img.naturalWidth, ih = img.naturalHeight, ctx = canvas.getContext('2d'), subsampled = detectSubsampling( img ), doSquash = this.type === 'image/jpeg', d = 1024, sy = 0, dy = 0, tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx; if ( subsampled ) { iw /= 2; ih /= 2; } ctx.save(); tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; tmpCtx = tmpCanvas.getContext('2d'); vertSquashRatio = doSquash ? detectVerticalSquash( img, iw, ih ) : 1; dw = Math.ceil( d * width / iw ); dh = Math.ceil( d * height / ih / vertSquashRatio ); while ( sy < ih ) { sx = 0; dx = 0; while ( sx < iw ) { tmpCtx.clearRect( 0, 0, d, d ); tmpCtx.drawImage( img, -sx, -sy ); ctx.drawImage( tmpCanvas, 0, 0, d, d, x + dx, y + dy, dw, dh ); sx += d; dx += dw; } sy += d; dy += dh; } ctx.restore(); tmpCanvas = tmpCtx = null; }; })() }); }); /** * @fileOverview Transport * @todo 支持chunked传输,优势: * 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分, * 而不需要重头再传一次。另外断点续传也需要用chunked方式。 */ define('runtime/html5/transport',[ 'base', 'runtime/html5/runtime' ], function( Base, Html5Runtime ) { var noop = Base.noop, $ = Base.$; return Html5Runtime.register( 'Transport', { init: function() { this._status = 0; this._response = null; }, send: function() { var owner = this.owner, opts = this.options, xhr = this._initAjax(), blob = owner._blob, server = opts.server, formData, binary, fr; if ( opts.sendAsBinary ) { server += (/\?/.test( server ) ? '&' : '?') + $.param( owner._formData ); binary = blob.getSource(); } else { formData = new FormData(); $.each( owner._formData, function( k, v ) { formData.append( k, v ); }); formData.append( opts.fileVal, blob.getSource(), opts.filename || owner._formData.name || '' ); } if ( opts.withCredentials && 'withCredentials' in xhr ) { xhr.open( opts.method, server, true ); xhr.withCredentials = true; } else { xhr.open( opts.method, server ); } this._setRequestHeader( xhr, opts.headers ); if ( binary ) { // 强制设置成 content-type 为文件流。 xhr.overrideMimeType && xhr.overrideMimeType('application/octet-stream'); // android直接发送blob会导致服务端接收到的是空文件。 // bug详情。 // https://code.google.com/p/android/issues/detail?id=39882 // 所以先用fileReader读取出来再通过arraybuffer的方式发送。 if ( Base.os.android ) { fr = new FileReader(); fr.onload = function() { xhr.send( this.result ); fr = fr.onload = null; }; fr.readAsArrayBuffer( binary ); } else { xhr.send( binary ); } } else { xhr.send( formData ); } }, getResponse: function() { return this._response; }, getResponseAsJson: function() { return this._parseJson( this._response ); }, getStatus: function() { return this._status; }, abort: function() { var xhr = this._xhr; if ( xhr ) { xhr.upload.onprogress = noop; xhr.onreadystatechange = noop; xhr.abort(); this._xhr = xhr = null; } }, destroy: function() { this.abort(); }, _initAjax: function() { var me = this, xhr = new XMLHttpRequest(), opts = this.options; if ( opts.withCredentials && !('withCredentials' in xhr) && typeof XDomainRequest !== 'undefined' ) { xhr = new XDomainRequest(); } xhr.upload.onprogress = function( e ) { var percentage = 0; if ( e.lengthComputable ) { percentage = e.loaded / e.total; } return me.trigger( 'progress', percentage ); }; xhr.onreadystatechange = function() { if ( xhr.readyState !== 4 ) { return; } xhr.upload.onprogress = noop; xhr.onreadystatechange = noop; me._xhr = null; me._status = xhr.status; if ( xhr.status >= 200 && xhr.status < 300 ) { me._response = xhr.responseText; return me.trigger('load'); } else if ( xhr.status >= 500 && xhr.status < 600 ) { me._response = xhr.responseText; return me.trigger( 'error', 'server' ); } return me.trigger( 'error', me._status ? 'http' : 'abort' ); }; me._xhr = xhr; return xhr; }, _setRequestHeader: function( xhr, headers ) { $.each( headers, function( key, val ) { xhr.setRequestHeader( key, val ); }); }, _parseJson: function( str ) { var json; try { json = JSON.parse( str ); } catch ( ex ) { json = {}; } return json; } }); }); /** * @fileOverview Transport flash实现 */ define('runtime/html5/md5',[ 'runtime/html5/runtime' ], function( FlashRuntime ) { /* * Fastest md5 implementation around (JKM md5) * Credits: Joseph Myers * * @see http://www.myersdaily.org/joseph/javascript/md5-text.html * @see http://jsperf.com/md5-shootout/7 */ /* this function is much faster, so if possible we use it. Some IEs are the only ones I know of that need the idiotic second function, generated by an if clause. */ var add32 = function (a, b) { return (a + b) & 0xFFFFFFFF; }, cmn = function (q, a, b, x, s, t) { a = add32(add32(a, q), add32(x, t)); return add32((a << s) | (a >>> (32 - s)), b); }, ff = function (a, b, c, d, x, s, t) { return cmn((b & c) | ((~b) & d), a, b, x, s, t); }, gg = function (a, b, c, d, x, s, t) { return cmn((b & d) | (c & (~d)), a, b, x, s, t); }, hh = function (a, b, c, d, x, s, t) { return cmn(b ^ c ^ d, a, b, x, s, t); }, ii = function (a, b, c, d, x, s, t) { return cmn(c ^ (b | (~d)), a, b, x, s, t); }, md5cycle = function (x, k) { var a = x[0], b = x[1], c = x[2], d = x[3]; a = ff(a, b, c, d, k[0], 7, -680876936); d = ff(d, a, b, c, k[1], 12, -389564586); c = ff(c, d, a, b, k[2], 17, 606105819); b = ff(b, c, d, a, k[3], 22, -1044525330); a = ff(a, b, c, d, k[4], 7, -176418897); d = ff(d, a, b, c, k[5], 12, 1200080426); c = ff(c, d, a, b, k[6], 17, -1473231341); b = ff(b, c, d, a, k[7], 22, -45705983); a = ff(a, b, c, d, k[8], 7, 1770035416); d = ff(d, a, b, c, k[9], 12, -1958414417); c = ff(c, d, a, b, k[10], 17, -42063); b = ff(b, c, d, a, k[11], 22, -1990404162); a = ff(a, b, c, d, k[12], 7, 1804603682); d = ff(d, a, b, c, k[13], 12, -40341101); c = ff(c, d, a, b, k[14], 17, -1502002290); b = ff(b, c, d, a, k[15], 22, 1236535329); a = gg(a, b, c, d, k[1], 5, -165796510); d = gg(d, a, b, c, k[6], 9, -1069501632); c = gg(c, d, a, b, k[11], 14, 643717713); b = gg(b, c, d, a, k[0], 20, -373897302); a = gg(a, b, c, d, k[5], 5, -701558691); d = gg(d, a, b, c, k[10], 9, 38016083); c = gg(c, d, a, b, k[15], 14, -660478335); b = gg(b, c, d, a, k[4], 20, -405537848); a = gg(a, b, c, d, k[9], 5, 568446438); d = gg(d, a, b, c, k[14], 9, -1019803690); c = gg(c, d, a, b, k[3], 14, -187363961); b = gg(b, c, d, a, k[8], 20, 1163531501); a = gg(a, b, c, d, k[13], 5, -1444681467); d = gg(d, a, b, c, k[2], 9, -51403784); c = gg(c, d, a, b, k[7], 14, 1735328473); b = gg(b, c, d, a, k[12], 20, -1926607734); a = hh(a, b, c, d, k[5], 4, -378558); d = hh(d, a, b, c, k[8], 11, -2022574463); c = hh(c, d, a, b, k[11], 16, 1839030562); b = hh(b, c, d, a, k[14], 23, -35309556); a = hh(a, b, c, d, k[1], 4, -1530992060); d = hh(d, a, b, c, k[4], 11, 1272893353); c = hh(c, d, a, b, k[7], 16, -155497632); b = hh(b, c, d, a, k[10], 23, -1094730640); a = hh(a, b, c, d, k[13], 4, 681279174); d = hh(d, a, b, c, k[0], 11, -358537222); c = hh(c, d, a, b, k[3], 16, -722521979); b = hh(b, c, d, a, k[6], 23, 76029189); a = hh(a, b, c, d, k[9], 4, -640364487); d = hh(d, a, b, c, k[12], 11, -421815835); c = hh(c, d, a, b, k[15], 16, 530742520); b = hh(b, c, d, a, k[2], 23, -995338651); a = ii(a, b, c, d, k[0], 6, -198630844); d = ii(d, a, b, c, k[7], 10, 1126891415); c = ii(c, d, a, b, k[14], 15, -1416354905); b = ii(b, c, d, a, k[5], 21, -57434055); a = ii(a, b, c, d, k[12], 6, 1700485571); d = ii(d, a, b, c, k[3], 10, -1894986606); c = ii(c, d, a, b, k[10], 15, -1051523); b = ii(b, c, d, a, k[1], 21, -2054922799); a = ii(a, b, c, d, k[8], 6, 1873313359); d = ii(d, a, b, c, k[15], 10, -30611744); c = ii(c, d, a, b, k[6], 15, -1560198380); b = ii(b, c, d, a, k[13], 21, 1309151649); a = ii(a, b, c, d, k[4], 6, -145523070); d = ii(d, a, b, c, k[11], 10, -1120210379); c = ii(c, d, a, b, k[2], 15, 718787259); b = ii(b, c, d, a, k[9], 21, -343485551); x[0] = add32(a, x[0]); x[1] = add32(b, x[1]); x[2] = add32(c, x[2]); x[3] = add32(d, x[3]); }, /* there needs to be support for Unicode here, * unless we pretend that we can redefine the MD-5 * algorithm for multi-byte characters (perhaps * by adding every four 16-bit characters and * shortening the sum to 32 bits). Otherwise * I suggest performing MD-5 as if every character * was two bytes--e.g., 0040 0025 = @%--but then * how will an ordinary MD-5 sum be matched? * There is no way to standardize text to something * like UTF-8 before transformation; speed cost is * utterly prohibitive. The JavaScript standard * itself needs to look at this: it should start * providing access to strings as preformed UTF-8 * 8-bit unsigned value arrays. */ md5blk = function (s) { var md5blks = [], i; /* Andy King said do it this way. */ for (i = 0; i < 64; i += 4) { md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24); } return md5blks; }, md5blk_array = function (a) { var md5blks = [], i; /* Andy King said do it this way. */ for (i = 0; i < 64; i += 4) { md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24); } return md5blks; }, md51 = function (s) { var n = s.length, state = [1732584193, -271733879, -1732584194, 271733878], i, length, tail, tmp, lo, hi; for (i = 64; i <= n; i += 64) { md5cycle(state, md5blk(s.substring(i - 64, i))); } s = s.substring(i - 64); length = s.length; tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; for (i = 0; i < length; i += 1) { tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3); } tail[i >> 2] |= 0x80 << ((i % 4) << 3); if (i > 55) { md5cycle(state, tail); for (i = 0; i < 16; i += 1) { tail[i] = 0; } } // Beware that the final length might not fit in 32 bits so we take care of that tmp = n * 8; tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/); lo = parseInt(tmp[2], 16); hi = parseInt(tmp[1], 16) || 0; tail[14] = lo; tail[15] = hi; md5cycle(state, tail); return state; }, md51_array = function (a) { var n = a.length, state = [1732584193, -271733879, -1732584194, 271733878], i, length, tail, tmp, lo, hi; for (i = 64; i <= n; i += 64) { md5cycle(state, md5blk_array(a.subarray(i - 64, i))); } // Not sure if it is a bug, however IE10 will always produce a sub array of length 1 // containing the last element of the parent array if the sub array specified starts // beyond the length of the parent array - weird. // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0); length = a.length; tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; for (i = 0; i < length; i += 1) { tail[i >> 2] |= a[i] << ((i % 4) << 3); } tail[i >> 2] |= 0x80 << ((i % 4) << 3); if (i > 55) { md5cycle(state, tail); for (i = 0; i < 16; i += 1) { tail[i] = 0; } } // Beware that the final length might not fit in 32 bits so we take care of that tmp = n * 8; tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/); lo = parseInt(tmp[2], 16); hi = parseInt(tmp[1], 16) || 0; tail[14] = lo; tail[15] = hi; md5cycle(state, tail); return state; }, hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'], rhex = function (n) { var s = '', j; for (j = 0; j < 4; j += 1) { s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; } return s; }, hex = function (x) { var i; for (i = 0; i < x.length; i += 1) { x[i] = rhex(x[i]); } return x.join(''); }, md5 = function (s) { return hex(md51(s)); }, //////////////////////////////////////////////////////////////////////////// /** * SparkMD5 OOP implementation. * * Use this class to perform an incremental md5, otherwise use the * static methods instead. */ SparkMD5 = function () { // call reset to init the instance this.reset(); }; // In some cases the fast add32 function cannot be used.. if (md5('hello') !== '5d41402abc4b2a76b9719d911017c592') { add32 = function (x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); }; } /** * Appends a string. * A conversion will be applied if an utf8 string is detected. * * @param {String} str The string to be appended * * @return {SparkMD5} The instance itself */ SparkMD5.prototype.append = function (str) { // converts the string to utf8 bytes if necessary if (/[\u0080-\uFFFF]/.test(str)) { str = unescape(encodeURIComponent(str)); } // then append as binary this.appendBinary(str); return this; }; /** * Appends a binary string. * * @param {String} contents The binary string to be appended * * @return {SparkMD5} The instance itself */ SparkMD5.prototype.appendBinary = function (contents) { this._buff += contents; this._length += contents.length; var length = this._buff.length, i; for (i = 64; i <= length; i += 64) { md5cycle(this._state, md5blk(this._buff.substring(i - 64, i))); } this._buff = this._buff.substr(i - 64); return this; }; /** * Finishes the incremental computation, reseting the internal state and * returning the result. * Use the raw parameter to obtain the raw result instead of the hex one. * * @param {Boolean} raw True to get the raw result, false to get the hex result * * @return {String|Array} The result */ SparkMD5.prototype.end = function (raw) { var buff = this._buff, length = buff.length, i, tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ret; for (i = 0; i < length; i += 1) { tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3); } this._finish(tail, length); ret = !!raw ? this._state : hex(this._state); this.reset(); return ret; }; /** * Finish the final calculation based on the tail. * * @param {Array} tail The tail (will be modified) * @param {Number} length The length of the remaining buffer */ SparkMD5.prototype._finish = function (tail, length) { var i = length, tmp, lo, hi; tail[i >> 2] |= 0x80 << ((i % 4) << 3); if (i > 55) { md5cycle(this._state, tail); for (i = 0; i < 16; i += 1) { tail[i] = 0; } } // Do the final computation based on the tail and length // Beware that the final length may not fit in 32 bits so we take care of that tmp = this._length * 8; tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/); lo = parseInt(tmp[2], 16); hi = parseInt(tmp[1], 16) || 0; tail[14] = lo; tail[15] = hi; md5cycle(this._state, tail); }; /** * Resets the internal state of the computation. * * @return {SparkMD5} The instance itself */ SparkMD5.prototype.reset = function () { this._buff = ""; this._length = 0; this._state = [1732584193, -271733879, -1732584194, 271733878]; return this; }; /** * Releases memory used by the incremental buffer and other aditional * resources. If you plan to use the instance again, use reset instead. */ SparkMD5.prototype.destroy = function () { delete this._state; delete this._buff; delete this._length; }; /** * Performs the md5 hash on a string. * A conversion will be applied if utf8 string is detected. * * @param {String} str The string * @param {Boolean} raw True to get the raw result, false to get the hex result * * @return {String|Array} The result */ SparkMD5.hash = function (str, raw) { // converts the string to utf8 bytes if necessary if (/[\u0080-\uFFFF]/.test(str)) { str = unescape(encodeURIComponent(str)); } var hash = md51(str); return !!raw ? hash : hex(hash); }; /** * Performs the md5 hash on a binary string. * * @param {String} content The binary string * @param {Boolean} raw True to get the raw result, false to get the hex result * * @return {String|Array} The result */ SparkMD5.hashBinary = function (content, raw) { var hash = md51(content); return !!raw ? hash : hex(hash); }; /** * SparkMD5 OOP implementation for array buffers. * * Use this class to perform an incremental md5 ONLY for array buffers. */ SparkMD5.ArrayBuffer = function () { // call reset to init the instance this.reset(); }; //////////////////////////////////////////////////////////////////////////// /** * Appends an array buffer. * * @param {ArrayBuffer} arr The array to be appended * * @return {SparkMD5.ArrayBuffer} The instance itself */ SparkMD5.ArrayBuffer.prototype.append = function (arr) { // TODO: we could avoid the concatenation here but the algorithm would be more complex // if you find yourself needing extra performance, please make a PR. var buff = this._concatArrayBuffer(this._buff, arr), length = buff.length, i; this._length += arr.byteLength; for (i = 64; i <= length; i += 64) { md5cycle(this._state, md5blk_array(buff.subarray(i - 64, i))); } // Avoids IE10 weirdness (documented above) this._buff = (i - 64) < length ? buff.subarray(i - 64) : new Uint8Array(0); return this; }; /** * Finishes the incremental computation, reseting the internal state and * returning the result. * Use the raw parameter to obtain the raw result instead of the hex one. * * @param {Boolean} raw True to get the raw result, false to get the hex result * * @return {String|Array} The result */ SparkMD5.ArrayBuffer.prototype.end = function (raw) { var buff = this._buff, length = buff.length, tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], i, ret; for (i = 0; i < length; i += 1) { tail[i >> 2] |= buff[i] << ((i % 4) << 3); } this._finish(tail, length); ret = !!raw ? this._state : hex(this._state); this.reset(); return ret; }; SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish; /** * Resets the internal state of the computation. * * @return {SparkMD5.ArrayBuffer} The instance itself */ SparkMD5.ArrayBuffer.prototype.reset = function () { this._buff = new Uint8Array(0); this._length = 0; this._state = [1732584193, -271733879, -1732584194, 271733878]; return this; }; /** * Releases memory used by the incremental buffer and other aditional * resources. If you plan to use the instance again, use reset instead. */ SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy; /** * Concats two array buffers, returning a new one. * * @param {ArrayBuffer} first The first array buffer * @param {ArrayBuffer} second The second array buffer * * @return {ArrayBuffer} The new array buffer */ SparkMD5.ArrayBuffer.prototype._concatArrayBuffer = function (first, second) { var firstLength = first.length, result = new Uint8Array(firstLength + second.byteLength); result.set(first); result.set(new Uint8Array(second), firstLength); return result; }; /** * Performs the md5 hash on an array buffer. * * @param {ArrayBuffer} arr The array buffer * @param {Boolean} raw True to get the raw result, false to get the hex result * * @return {String|Array} The result */ SparkMD5.ArrayBuffer.hash = function (arr, raw) { var hash = md51_array(new Uint8Array(arr)); return !!raw ? hash : hex(hash); }; return FlashRuntime.register( 'Md5', { init: function() { // do nothing. }, loadFromBlob: function( file ) { var blob = file.getSource(), chunkSize = 2 * 1024 * 1024, chunks = Math.ceil( blob.size / chunkSize ), chunk = 0, owner = this.owner, spark = new SparkMD5.ArrayBuffer(), me = this, blobSlice = blob.mozSlice || blob.webkitSlice || blob.slice, loadNext, fr; fr = new FileReader(); loadNext = function() { var start, end; start = chunk * chunkSize; end = Math.min( start + chunkSize, blob.size ); fr.onload = function( e ) { spark.append( e.target.result ); owner.trigger( 'progress', { total: file.size, loaded: end }); }; fr.onloadend = function() { fr.onloadend = fr.onload = null; if ( ++chunk < chunks ) { setTimeout( loadNext, 1 ); } else { setTimeout(function(){ owner.trigger('load'); me.result = spark.end(); loadNext = file = blob = spark = null; owner.trigger('complete'); }, 50 ); } }; fr.readAsArrayBuffer( blobSlice.call( blob, start, end ) ); }; loadNext(); }, getResult: function() { return this.result; } }); }); /** * @fileOverview FlashRuntime */ define('runtime/flash/runtime',[ 'base', 'runtime/runtime', 'runtime/compbase' ], function( Base, Runtime, CompBase ) { var $ = Base.$, type = 'flash', components = {}; function getFlashVersion() { var version; try { version = navigator.plugins[ 'Shockwave Flash' ]; version = version.description; } catch ( ex ) { try { version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash') .GetVariable('$version'); } catch ( ex2 ) { version = '0.0'; } } version = version.match( /\d+/g ); return parseFloat( version[ 0 ] + '.' + version[ 1 ], 10 ); } function FlashRuntime() { var pool = {}, clients = {}, destroy = this.destroy, me = this, jsreciver = Base.guid('webuploader_'); Runtime.apply( me, arguments ); me.type = type; // 这个方法的调用者,实际上是RuntimeClient me.exec = function( comp, fn/*, args...*/ ) { var client = this, uid = client.uid, args = Base.slice( arguments, 2 ), instance; clients[ uid ] = client; if ( components[ comp ] ) { if ( !pool[ uid ] ) { pool[ uid ] = new components[ comp ]( client, me ); } instance = pool[ uid ]; if ( instance[ fn ] ) { return instance[ fn ].apply( instance, args ); } } return me.flashExec.apply( client, arguments ); }; function handler( evt, obj ) { var type = evt.type || evt, parts, uid; parts = type.split('::'); uid = parts[ 0 ]; type = parts[ 1 ]; // console.log.apply( console, arguments ); if ( type === 'Ready' && uid === me.uid ) { me.trigger('ready'); } else if ( clients[ uid ] ) { clients[ uid ].trigger( type.toLowerCase(), evt, obj ); } // Base.log( evt, obj ); } // flash的接受器。 window[ jsreciver ] = function() { var args = arguments; // 为了能捕获得到。 setTimeout(function() { handler.apply( null, args ); }, 1 ); }; this.jsreciver = jsreciver; this.destroy = function() { // @todo 删除池子中的所有实例 return destroy && destroy.apply( this, arguments ); }; this.flashExec = function( comp, fn ) { var flash = me.getFlash(), args = Base.slice( arguments, 2 ); return flash.exec( this.uid, comp, fn, args ); }; // @todo } Base.inherits( Runtime, { constructor: FlashRuntime, init: function() { var container = this.getContainer(), opts = this.options, html; // if not the minimal height, shims are not initialized // in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc) container.css({ position: 'absolute', top: '-8px', left: '-8px', width: '9px', height: '9px', overflow: 'hidden' }); // insert flash object html = '<object id="' + this.uid + '" type="application/' + 'x-shockwave-flash" data="' + opts.swf + '" '; if ( Base.browser.ie ) { html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '; } html += 'width="100%" height="100%" style="outline:0">' + '<param name="movie" value="' + opts.swf + '" />' + '<param name="flashvars" value="uid=' + this.uid + '&jsreciver=' + this.jsreciver + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowscriptaccess" value="always" />' + '</object>'; container.html( html ); }, getFlash: function() { if ( this._flash ) { return this._flash; } this._flash = $( '#' + this.uid ).get( 0 ); return this._flash; } }); FlashRuntime.register = function( name, component ) { component = components[ name ] = Base.inherits( CompBase, $.extend({ // @todo fix this later flashExec: function() { var owner = this.owner, runtime = this.getRuntime(); return runtime.flashExec.apply( owner, arguments ); } }, component ) ); return component; }; if ( getFlashVersion() >= 11.4 ) { Runtime.addRuntime( type, FlashRuntime ); } return FlashRuntime; }); /** * @fileOverview FilePicker */ define('runtime/flash/filepicker',[ 'base', 'runtime/flash/runtime' ], function( Base, FlashRuntime ) { var $ = Base.$; return FlashRuntime.register( 'FilePicker', { init: function( opts ) { var copy = $.extend({}, opts ), len, i; // 修复Flash再没有设置title的情况下无法弹出flash文件选择框的bug. len = copy.accept && copy.accept.length; for ( i = 0; i < len; i++ ) { if ( !copy.accept[ i ].title ) { copy.accept[ i ].title = 'Files'; } } delete copy.button; delete copy.id; delete copy.container; this.flashExec( 'FilePicker', 'init', copy ); }, destroy: function() { this.flashExec( 'FilePicker', 'destroy' ); } }); }); /** * @fileOverview 图片压缩 */ define('runtime/flash/image',[ 'runtime/flash/runtime' ], function( FlashRuntime ) { return FlashRuntime.register( 'Image', { // init: function( options ) { // var owner = this.owner; // this.flashExec( 'Image', 'init', options ); // owner.on( 'load', function() { // debugger; // }); // }, loadFromBlob: function( blob ) { var owner = this.owner; owner.info() && this.flashExec( 'Image', 'info', owner.info() ); owner.meta() && this.flashExec( 'Image', 'meta', owner.meta() ); this.flashExec( 'Image', 'loadFromBlob', blob.uid ); } }); }); /** * @fileOverview Transport flash实现 */ define('runtime/flash/transport',[ 'base', 'runtime/flash/runtime', 'runtime/client' ], function( Base, FlashRuntime, RuntimeClient ) { var $ = Base.$; return FlashRuntime.register( 'Transport', { init: function() { this._status = 0; this._response = null; this._responseJson = null; }, send: function() { var owner = this.owner, opts = this.options, xhr = this._initAjax(), blob = owner._blob, server = opts.server, binary; xhr.connectRuntime( blob.ruid ); if ( opts.sendAsBinary ) { server += (/\?/.test( server ) ? '&' : '?') + $.param( owner._formData ); binary = blob.uid; } else { $.each( owner._formData, function( k, v ) { xhr.exec( 'append', k, v ); }); xhr.exec( 'appendBlob', opts.fileVal, blob.uid, opts.filename || owner._formData.name || '' ); } this._setRequestHeader( xhr, opts.headers ); xhr.exec( 'send', { method: opts.method, url: server, forceURLStream: opts.forceURLStream, mimeType: 'application/octet-stream' }, binary ); }, getStatus: function() { return this._status; }, getResponse: function() { return this._response || ''; }, getResponseAsJson: function() { return this._responseJson; }, abort: function() { var xhr = this._xhr; if ( xhr ) { xhr.exec('abort'); xhr.destroy(); this._xhr = xhr = null; } }, destroy: function() { this.abort(); }, _initAjax: function() { var me = this, xhr = new RuntimeClient('XMLHttpRequest'); xhr.on( 'uploadprogress progress', function( e ) { var percent = e.loaded / e.total; percent = Math.min( 1, Math.max( 0, percent ) ); return me.trigger( 'progress', percent ); }); xhr.on( 'load', function() { var status = xhr.exec('getStatus'), readBody = false, err = '', p; xhr.off(); me._xhr = null; if ( status >= 200 && status < 300 ) { readBody = true; } else if ( status >= 500 && status < 600 ) { readBody = true; err = 'server'; } else { err = 'http'; } if ( readBody ) { me._response = xhr.exec('getResponse'); me._response = decodeURIComponent( me._response ); // flash 处理可能存在 bug, 没辙只能靠 js 了 // try { // me._responseJson = xhr.exec('getResponseAsJson'); // } catch ( error ) { p = window.JSON && window.JSON.parse || function( s ) { try { return new Function('return ' + s).call(); } catch ( err ) { return {}; } }; me._responseJson = me._response ? p(me._response) : {}; // } } xhr.destroy(); xhr = null; return err ? me.trigger( 'error', err ) : me.trigger('load'); }); xhr.on( 'error', function() { xhr.off(); me._xhr = null; me.trigger( 'error', 'http' ); }); me._xhr = xhr; return xhr; }, _setRequestHeader: function( xhr, headers ) { $.each( headers, function( key, val ) { xhr.exec( 'setRequestHeader', key, val ); }); } }); }); /** * @fileOverview Blob Html实现 */ define('runtime/flash/blob',[ 'runtime/flash/runtime', 'lib/blob' ], function( FlashRuntime, Blob ) { return FlashRuntime.register( 'Blob', { slice: function( start, end ) { var blob = this.flashExec( 'Blob', 'slice', start, end ); return new Blob( blob.uid, blob ); } }); }); /** * @fileOverview Md5 flash实现 */ define('runtime/flash/md5',[ 'runtime/flash/runtime' ], function( FlashRuntime ) { return FlashRuntime.register( 'Md5', { init: function() { // do nothing. }, loadFromBlob: function( blob ) { return this.flashExec( 'Md5', 'loadFromBlob', blob.uid ); } }); }); /** * @fileOverview 完全版本。 */ define('preset/all',[ 'base', // widgets 'widgets/filednd', 'widgets/filepaste', 'widgets/filepicker', 'widgets/image', 'widgets/queue', 'widgets/runtime', 'widgets/upload', 'widgets/validator', 'widgets/md5', // runtimes // html5 'runtime/html5/blob', 'runtime/html5/dnd', 'runtime/html5/filepaste', 'runtime/html5/filepicker', 'runtime/html5/imagemeta/exif', 'runtime/html5/androidpatch', 'runtime/html5/image', 'runtime/html5/transport', 'runtime/html5/md5', // flash 'runtime/flash/filepicker', 'runtime/flash/image', 'runtime/flash/transport', 'runtime/flash/blob', 'runtime/flash/md5' ], function( Base ) { return Base; }); /** * @fileOverview 日志组件,主要用来收集错误信息,可以帮助 webuploader 更好的定位问题和发展。 * * 如果您不想要启用此功能,请在打包的时候去掉 log 模块。 * * 或者可以在初始化的时候通过 options.disableWidgets 属性禁用。 * * 如: * WebUploader.create({ * ... * * disableWidgets: 'log', * * ... * }) */ define('widgets/log',[ 'base', 'uploader', 'widgets/widget' ], function( Base, Uploader ) { var $ = Base.$, logUrl = ' http://static.tieba.baidu.com/tb/pms/img/st.gif??', product = (location.hostname || location.host || 'protected').toLowerCase(), // 只针对 baidu 内部产品用户做统计功能。 enable = product && /baidu/i.exec(product), base; if (!enable) { return; } base = { dv: 3, master: 'webuploader', online: /test/.exec(product) ? 0 : 1, module: '', product: product, type: 0 }; function send(data) { var obj = $.extend({}, base, data), url = logUrl.replace(/^(.*)\?/, '$1' + $.param( obj )), image = new Image(); image.src = url; } return Uploader.register({ name: 'log', init: function() { var owner = this.owner, count = 0, size = 0; owner .on('error', function(code) { send({ type: 2, c_error_code: code }); }) .on('uploadError', function(file, reason) { send({ type: 2, c_error_code: 'UPLOAD_ERROR', c_reason: '' + reason }); }) .on('uploadComplete', function(file) { count++; size += file.size; }). on('uploadFinished', function() { send({ c_count: count, c_size: size }); count = size = 0; }); send({ c_usage: 1 }); } }); }); /** * @fileOverview Uploader上传类 */ define('webuploader',[ 'preset/all', 'widgets/log' ], function( preset ) { return preset; }); return require('webuploader'); });
var Stream = require('stream').Stream; /** * "fakeDuplexStream" is meant to be used in testing StreamStack subclasses. * It simulates both ends (client and server) of a full-duplex `net.Stream` * connection, without acutally using any real TCP connections. Everything is * done in V8's memory. Usage: * * var streams = require('stream-stack/util').fakeDuplexStream(); * var client = new HttpRequestStack(streams[0]); * var server = new HttpResponseStack(streams[1]); * */ function fakeDuplexStream() { var conn1 = new Stream(); var conn2 = new Stream(); setupFakeStream(conn1, conn2); setupFakeStream(conn2, conn1); return [conn1, conn2]; } exports.fakeDuplexStream = fakeDuplexStream; function setupFakeStream(readable, writable) { var encoding; var paused = false; var backlog = []; readable.readable = true; readable.setEncoding = function(enc) { encoding = enc; } readable.pause = function() { paused = true; } readable.resume = function() { paused = false; backlog.forEach(function(chunk) { readable.emit('data', encoding ? chunk.toString(encoding) : chunk); }); backlog = []; } writable.writable = true; writable.write = function(chunk, enc) { if (!Buffer.isBuffer(chunk)) { chunk = new Buffer(chunk, enc); } if (paused) { backlog.push(chunk); return false; } else { readable.emit('data', encoding ? chunk.toString(encoding) : chunk); return true; } } writable.end = function(chunk, enc) { if (chunk) this.write(chunk, enc); writable.writable = readable.readable = false; readable.emit('end'); } }
import run from "ember-metal/run_loop"; import EmberView from "ember-views/views/view"; import EmberHandlebars from "ember-htmlbars/compat"; import { runAppend, runDestroy } from "ember-runtime/tests/utils"; var view; var compile = EmberHandlebars.compile; QUnit.module("ember-htmlbars: tagless views should be able to add/remove child views", { teardown: function() { runDestroy(view); } }); QUnit.test("can insert new child views after initial tagless view rendering", function() { view = EmberView.create({ shouldShow: false, array: Ember.A([1]), template: compile('{{#if view.shouldShow}}{{#each item in view.array}}{{item}}{{/each}}{{/if}}') }); runAppend(view); equal(view.$().text(), ''); run(function() { view.set('shouldShow', true); }); equal(view.$().text(), '1'); run(function() { view.get('array').pushObject(2); }); equal(view.$().text(), '12'); }); QUnit.test("can remove child views after initial tagless view rendering", function() { view = EmberView.create({ shouldShow: false, array: Ember.A([]), template: compile('{{#if view.shouldShow}}{{#each item in view.array}}{{item}}{{/each}}{{/if}}') }); runAppend(view); equal(view.$().text(), ''); run(function() { view.set('shouldShow', true); view.get('array').pushObject(1); }); equal(view.$().text(), '1'); run(function() { view.get('array').removeObject(1); }); equal(view.$().text(), ''); });
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Animated zippy widget implementation. * * @author eae@google.com (Emil A Eklund) * @see ../demos/zippy.html */ goog.provide('goog.ui.AnimatedZippy'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.fx.Animation'); goog.require('goog.fx.Transition'); goog.require('goog.fx.easing'); goog.require('goog.ui.Zippy'); goog.require('goog.ui.ZippyEvent'); /** * Zippy widget. Expandable/collapsible container, clicking the header toggles * the visibility of the content. * * @param {Element|string|null} header Header element, either element * reference, string id or null if no header exists. * @param {Element|string} content Content element, either element reference or * string id. * @param {boolean=} opt_expanded Initial expanded/visibility state. Defaults to * false. * @param {goog.dom.DomHelper=} opt_domHelper An optional DOM helper. * @constructor * @extends {goog.ui.Zippy} */ goog.ui.AnimatedZippy = function(header, content, opt_expanded, opt_domHelper) { var domHelper = opt_domHelper || goog.dom.getDomHelper(); // Create wrapper element and move content into it. var elWrapper = domHelper.createDom('div', {'style': 'overflow:hidden'}); var elContent = domHelper.getElement(content); elContent.parentNode.replaceChild(elWrapper, elContent); elWrapper.appendChild(elContent); /** * Content wrapper, used for animation. * @type {Element} * @private */ this.elWrapper_ = elWrapper; /** * Reference to animation or null if animation is not active. * @type {goog.fx.Animation} * @private */ this.anim_ = null; // Call constructor of super class. goog.ui.Zippy.call(this, header, elContent, opt_expanded, undefined, domHelper); // Set initial state. // NOTE: Set the class names as well otherwise animated zippys // start with empty class names. var expanded = this.isExpanded(); this.elWrapper_.style.display = expanded ? '' : 'none'; this.updateHeaderClassName(expanded); }; goog.inherits(goog.ui.AnimatedZippy, goog.ui.Zippy); /** * Duration of expand/collapse animation, in milliseconds. * @type {number} */ goog.ui.AnimatedZippy.prototype.animationDuration = 500; /** * Acceleration function for expand/collapse animation. * @type {!Function} */ goog.ui.AnimatedZippy.prototype.animationAcceleration = goog.fx.easing.easeOut; /** * @return {boolean} Whether the zippy is in the process of being expanded or * collapsed. */ goog.ui.AnimatedZippy.prototype.isBusy = function() { return this.anim_ != null; }; /** * Sets expanded state. * * @param {boolean} expanded Expanded/visibility state. * @override */ goog.ui.AnimatedZippy.prototype.setExpanded = function(expanded) { if (this.isExpanded() == expanded && !this.anim_) { return; } // Reset display property of wrapper to allow content element to be // measured. if (this.elWrapper_.style.display == 'none') { this.elWrapper_.style.display = ''; } // Measure content element. var h = this.getContentElement().offsetHeight; // Stop active animation (if any) and determine starting height. var startH = 0; if (this.anim_) { expanded = this.isExpanded(); goog.events.removeAll(this.anim_); this.anim_.stop(false); var marginTop = parseInt(this.getContentElement().style.marginTop, 10); startH = h - Math.abs(marginTop); } else { startH = expanded ? 0 : h; } // Updates header class name after the animation has been stopped. this.updateHeaderClassName(expanded); // Set up expand/collapse animation. this.anim_ = new goog.fx.Animation([0, startH], [0, expanded ? h : 0], this.animationDuration, this.animationAcceleration); var events = [goog.fx.Transition.EventType.BEGIN, goog.fx.Animation.EventType.ANIMATE, goog.fx.Transition.EventType.END]; goog.events.listen(this.anim_, events, this.onAnimate_, false, this); goog.events.listen(this.anim_, goog.fx.Transition.EventType.END, goog.bind(this.onAnimationCompleted_, this, expanded)); // Start animation. this.anim_.play(false); }; /** * Called during animation * * @param {goog.events.Event} e The event. * @private */ goog.ui.AnimatedZippy.prototype.onAnimate_ = function(e) { var contentElement = this.getContentElement(); var h = contentElement.offsetHeight; contentElement.style.marginTop = (e.y - h) + 'px'; }; /** * Called once the expand/collapse animation has completed. * * @param {boolean} expanded Expanded/visibility state. * @private */ goog.ui.AnimatedZippy.prototype.onAnimationCompleted_ = function(expanded) { // Fix wrong end position if the content has changed during the animation. if (expanded) { this.getContentElement().style.marginTop = '0'; } goog.events.removeAll(this.anim_); this.setExpandedInternal(expanded); this.anim_ = null; if (!expanded) { this.elWrapper_.style.display = 'none'; } // Fire toggle event. this.dispatchEvent(new goog.ui.ZippyEvent(goog.ui.Zippy.Events.TOGGLE, this, expanded)); };
version https://git-lfs.github.com/spec/v1 oid sha256:09048ebb343298062c8f1f9370b783b0b98ec4dd7b72b6339502d6f8a0b7355c size 7062
function attachEventHandler(element, eventType, eventHandler) { if (!element) { return; } if (document.addEventListener) { element.addEventListener(eventType, eventHandler, true); } else if (document.attachEvent) { element.attachEvent("on" + eventType, eventHandler); } else { element['on' + eventType] = eventHandler; } }
define({ "_widgetLabel": "이미지 측정" });
'use strict'; const common = require('../common'); const fixtures = require('../common/fixtures'); if (!common.hasCrypto) common.skip('missing crypto'); const tls = require('tls'); // This test expects `tls.connect()` to emit a warning when // `servername` of options is an IP address. common.expectWarning( 'DeprecationWarning', 'Setting the TLS ServerName to an IP address is not permitted by ' + 'RFC 6066. This will be ignored in a future version.', 'DEP0123' ); { const options = { key: fixtures.readKey('agent1-key.pem'), cert: fixtures.readKey('agent1-cert.pem') }; const server = tls.createServer(options, function(s) { s.end('hello'); }).listen(0, function() { const client = tls.connect({ port: this.address().port, rejectUnauthorized: false, servername: '127.0.0.1', }, function() { client.end(); }); }); server.on('connection', common.mustCall(function(socket) { server.close(); })); }
/** * @fileoverview Config initialization wizard. * @author Ilya Volodin * @copyright 2015 Ilya Volodin. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var util = require("util"), debug = require("debug"), lodash = require("lodash"), inquirer = require("inquirer"), ProgressBar = require("progress"), autoconfig = require("./autoconfig.js"), ConfigFile = require("./config-file"), ConfigOps = require("./config-ops"), getSourceCodeOfFiles = require("../util/source-code-util").getSourceCodeOfFiles, npmUtil = require("../util/npm-util"), recConfig = require("../../conf/eslint.json"), log = require("../logging"); debug = debug("eslint:config-initializer"); //------------------------------------------------------------------------------ // Private //------------------------------------------------------------------------------ /* istanbul ignore next: hard to test fs function */ /** * Create .eslintrc file in the current working directory * @param {Object} config object that contains user's answers * @param {string} format The file format to write to. * @returns {void} */ function writeFile(config, format) { // default is .js var extname = ".js"; if (format === "YAML") { extname = ".yml"; } else if (format === "JSON") { extname = ".json"; } ConfigFile.write(config, "./.eslintrc" + extname); log.info("Successfully created .eslintrc" + extname + " file in " + process.cwd()); } /** * Synchronously install necessary plugins, configs, parsers, etc. based on the config * @param {Object} config config object * @returns {void} */ function installModules(config) { var modules = [], installStatus, modulesToInstall; // Create a list of modules which should be installed based on config if (config.plugins) { modules = modules.concat(config.plugins.map(function(name) { return "eslint-plugin-" + name; })); } if (config.extends && config.extends.indexOf("eslint:") === -1) { modules.push("eslint-config-" + config.extends); } // Determine which modules are already installed if (modules.length === 0) { return; } installStatus = npmUtil.checkDevDeps(modules); // Install packages which aren't already installed modulesToInstall = Object.keys(installStatus).filter(function(module) { return installStatus[module] === false; }); if (modulesToInstall.length > 0) { log.info("Installing " + modulesToInstall.join(", ")); npmUtil.installSyncSaveDev(modulesToInstall); } } /** * Set the `rules` of a config by examining a user's source code * * Note: This clones the config object and returns a new config to avoid mutating * the original config parameter. * * @param {Object} answers answers received from inquirer * @param {Object} config config object * @returns {Object} config object with configured rules */ function configureRules(answers, config) { var BAR_TOTAL = 20, BAR_SOURCE_CODE_TOTAL = 4; var newConfig = lodash.assign({}, config), bar, patterns, sourceCodes, fileQty, registry, failingRegistry, disabledConfigs = {}, singleConfigs, specTwoConfigs, specThreeConfigs, defaultConfigs; // Set up a progress bar, as this process can take a long time bar = new ProgressBar("Determining Config: :percent [:bar] :elapseds elapsed, eta :etas ", { width: 30, total: BAR_TOTAL }); bar.tick(0); // Shows the progress bar // Get the SourceCode of all chosen files patterns = answers.patterns.split(/[\s]+/); try { sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, function(total) { bar.tick((BAR_SOURCE_CODE_TOTAL / total)); }); } catch (e) { log.info("\n"); throw e; } fileQty = Object.keys(sourceCodes).length; if (fileQty === 0) { log.info("\n"); throw new Error("Automatic Configuration failed. No files were able to be parsed."); } // Create a registry of rule configs registry = new autoconfig.Registry(); registry.populateFromCoreRules(); // Lint all files with each rule config in the registry registry = registry.lintSourceCode(sourceCodes, newConfig, function(total) { bar.tick((BAR_TOTAL - BAR_SOURCE_CODE_TOTAL) / total); // Subtract out ticks used at beginning }); debug("\nRegistry: " + util.inspect(registry.rules, {depth: null})); // Create a list of recommended rules, because we don't want to disable them var recRules = Object.keys(recConfig.rules).filter(function(ruleId) { return ConfigOps.isErrorSeverity(recConfig.rules[ruleId]); }); // Find and disable rules which had no error-free configuration failingRegistry = registry.getFailingRulesRegistry(); Object.keys(failingRegistry.rules).forEach(function(ruleId) { // If the rule is recommended, set it to error, otherwise disable it disabledConfigs[ruleId] = (recRules.indexOf(ruleId) !== -1) ? 2 : 0; }); // Now that we know which rules to disable, strip out configs with errors registry = registry.stripFailingConfigs(); // If there is only one config that results in no errors for a rule, we should use it. // createConfig will only add rules that have one configuration in the registry. singleConfigs = registry.createConfig().rules; // The "sweet spot" for number of options in a config seems to be two (severity plus one option). // Very often, a third option (usually an object) is available to address // edge cases, exceptions, or unique situations. We will prefer to use a config with // specificity of two. specTwoConfigs = registry.filterBySpecificity(2).createConfig().rules; // Maybe a specific combination using all three options works specThreeConfigs = registry.filterBySpecificity(3).createConfig().rules; // If all else fails, try to use the default (severity only) defaultConfigs = registry.filterBySpecificity(1).createConfig().rules; // Combine configs in reverse priority order (later take precedence) newConfig.rules = lodash.assign({}, disabledConfigs, defaultConfigs, specThreeConfigs, specTwoConfigs, singleConfigs); // Make sure progress bar has finished (floating point rounding) bar.update(BAR_TOTAL); // Log out some stats to let the user know what happened var finalRuleIds = Object.keys(newConfig.rules), totalRules = finalRuleIds.length; var enabledRules = finalRuleIds.filter(function(ruleId) { return (newConfig.rules[ruleId] !== 0); }).length; var resultMessage = [ "\nEnabled " + enabledRules + " out of " + totalRules, "rules based on " + fileQty, "file" + ((fileQty === 1) ? "." : "s.") ].join(" "); log.info(resultMessage); ConfigOps.normalizeToStrings(newConfig); return newConfig; } /** * process user's answers and create config object * @param {Object} answers answers received from inquirer * @returns {Object} config object */ function processAnswers(answers) { var config = {rules: {}, env: {}}; if (answers.es6) { config.env.es6 = true; if (answers.modules) { config.parserOptions = config.parserOptions || {}; config.parserOptions.sourceType = "module"; } } if (answers.commonjs) { config.env.commonjs = true; } answers.env.forEach(function(env) { config.env[env] = true; }); if (answers.jsx) { config.parserOptions = config.parserOptions || {}; config.parserOptions.ecmaFeatures = config.parserOptions.ecmaFeatures || {}; config.parserOptions.ecmaFeatures.jsx = true; if (answers.react) { config.plugins = ["react"]; config.parserOptions.ecmaFeatures.experimentalObjectRestSpread = true; } } if (answers.source === "prompt") { config.extends = "eslint:recommended"; config.rules.indent = ["error", answers.indent]; config.rules.quotes = ["error", answers.quotes]; config.rules["linebreak-style"] = ["error", answers.linebreak]; config.rules.semi = ["error", answers.semi ? "always" : "never"]; } installModules(config); if (answers.source === "auto") { config = configureRules(answers, config); config = autoconfig.extendFromRecommended(config); } ConfigOps.normalizeToStrings(config); return config; } /** * process user's style guide of choice and return an appropriate config object. * @param {string} guide name of the chosen style guide * @returns {Object} config object */ function getConfigForStyleGuide(guide) { var guides = { google: {extends: "google"}, airbnb: {extends: "airbnb", plugins: ["react"]}, standard: {extends: "standard", plugins: ["standard"]} }; if (!guides[guide]) { throw new Error("You referenced an unsupported guide."); } installModules(guides[guide]); return guides[guide]; } /* istanbul ignore next: no need to test inquirer*/ /** * Ask use a few questions on command prompt * @param {function} callback callback function when file has been written * @returns {void} */ function promptUser(callback) { var config; inquirer.prompt([ { type: "list", name: "source", message: "How would you like to configure ESLint?", default: "prompt", choices: [ {name: "Answer questions about your style", value: "prompt"}, {name: "Use a popular style guide", value: "guide"}, {name: "Inspect your JavaScript file(s)", value: "auto"} ] }, { type: "list", name: "styleguide", message: "Which style guide do you want to follow?", choices: [{name: "Google", value: "google"}, {name: "AirBnB", value: "airbnb"}, {name: "Standard", value: "standard"}], when: function(answers) { return answers.source === "guide"; } }, { type: "input", name: "patterns", message: "Which file(s), path(s), or glob(s) should be examined?", when: function(answers) { return (answers.source === "auto"); }, validate: function(input) { if (input.trim().length === 0 && input.trim() !== ",") { return "You must tell us what code to examine. Try again."; } return true; } }, { type: "list", name: "format", message: "What format do you want your config file to be in?", default: "JavaScript", choices: ["JavaScript", "YAML", "JSON"], when: function(answers) { return (answers.source === "guide" || answers.source === "auto"); } } ], function(earlyAnswers) { // early exit if you are using a style guide if (earlyAnswers.source === "guide") { try { config = getConfigForStyleGuide(earlyAnswers.styleguide); writeFile(config, earlyAnswers.format); } catch (err) { callback(err); return; } return; } // continue with the questions otherwise... inquirer.prompt([ { type: "confirm", name: "es6", message: "Are you using ECMAScript 6 features?", default: false }, { type: "confirm", name: "modules", message: "Are you using ES6 modules?", default: false, when: function(answers) { return answers.es6 === true; } }, { type: "checkbox", name: "env", message: "Where will your code run?", default: ["browser"], choices: [{name: "Node", value: "node"}, {name: "Browser", value: "browser"}] }, { type: "confirm", name: "commonjs", message: "Do you use CommonJS?", default: false, when: function(answers) { return answers.env.some(function(env) { return env === "browser"; }); } }, { type: "confirm", name: "jsx", message: "Do you use JSX?", default: false }, { type: "confirm", name: "react", message: "Do you use React", default: false, when: function(answers) { return answers.jsx; } } ], function(secondAnswers) { // early exit if you are using automatic style generation if (earlyAnswers.source === "auto") { try { var combinedAnswers = lodash.assign({}, earlyAnswers, secondAnswers); config = processAnswers(combinedAnswers); installModules(config); writeFile(config, earlyAnswers.format); } catch (err) { callback(err); return; } return; } // continue with the style questions otherwise... inquirer.prompt([ { type: "list", name: "indent", message: "What style of indentation do you use?", default: "tab", choices: [{name: "Tabs", value: "tab"}, {name: "Spaces", value: 4}] }, { type: "list", name: "quotes", message: "What quotes do you use for strings?", default: "double", choices: [{name: "Double", value: "double"}, {name: "Single", value: "single"}] }, { type: "list", name: "linebreak", message: "What line endings do you use?", default: "unix", choices: [{name: "Unix", value: "unix"}, {name: "Windows", value: "windows"}] }, { type: "confirm", name: "semi", message: "Do you require semicolons?", default: true }, { type: "list", name: "format", message: "What format do you want your config file to be in?", default: "JavaScript", choices: ["JavaScript", "YAML", "JSON"] } ], function(answers) { try { var totalAnswers = lodash.assign({}, earlyAnswers, secondAnswers, answers); config = processAnswers(totalAnswers); installModules(config); writeFile(config, answers.format); } catch (err) { callback(err); return; } return; }); }); }); } //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ var init = { getConfigForStyleGuide: getConfigForStyleGuide, processAnswers: processAnswers, initializeConfig: /* istanbul ignore next */ function(callback) { promptUser(callback); } }; module.exports = init;
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- var a=true; // eval declared as a formal in strict mode (function(){if(a){function foo() {"use strict"; var x = function(eval) { print(eval); };};foo();}})();
/** * Copyright 2015 Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["it"] = { name: "it", numberFormat: { pattern: ["-n"], decimals: 2, ",": ".", ".": ",", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": ".", ".": ",", groupSize: [3], symbol: "%" }, currency: { pattern: ["-$ n","$ n"], decimals: 2, ",": ".", ".": ",", groupSize: [3], symbol: "€" } }, calendars: { standard: { days: { names: ["domenica","lunedì","martedì","mercoledì","giovedì","venerdì","sabato"], namesAbbr: ["dom","lun","mar","mer","gio","ven","sab"], namesShort: ["do","lu","ma","me","gi","ve","sa"] }, months: { names: ["gennaio","febbraio","marzo","aprile","maggio","giugno","luglio","agosto","settembre","ottobre","novembre","dicembre"], namesAbbr: ["gen","feb","mar","apr","mag","giu","lug","ago","set","ott","nov","dic"] }, AM: [""], 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: "d MMMM", M: "d MMMM", 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); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
import { Component, ChangeDetectionStrategy, ViewEncapsulation, ElementRef, Input, ContentChildren, NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { PrimeTemplate } from 'primeng/api'; class Toolbar { constructor(el) { this.el = el; } getBlockableElement() { return this.el.nativeElement.children[0]; } ngAfterContentInit() { this.templates.forEach((item) => { switch (item.getType()) { case 'left': this.leftTemplate = item.template; break; case 'right': this.rightTemplate = item.template; break; } }); } } Toolbar.decorators = [ { type: Component, args: [{ selector: 'p-toolbar', template: ` <div [ngClass]="'p-toolbar p-component'" [ngStyle]="style" [class]="styleClass" role="toolbar"> <ng-content></ng-content> <div class="p-toolbar-group-left" *ngIf="leftTemplate"> <ng-container *ngTemplateOutlet="leftTemplate"></ng-container> </div> <div class="p-toolbar-group-right" *ngIf="rightTemplate"> <ng-container *ngTemplateOutlet="rightTemplate"></ng-container> </div> </div> `, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, styles: [".p-toolbar{-ms-flex-pack:justify;-ms-flex-wrap:wrap;flex-wrap:wrap;justify-content:space-between}.p-toolbar,.p-toolbar-group-left,.p-toolbar-group-right{-ms-flex-align:center;align-items:center;display:-ms-flexbox;display:flex}"] },] } ]; Toolbar.ctorParameters = () => [ { type: ElementRef } ]; Toolbar.propDecorators = { style: [{ type: Input }], styleClass: [{ type: Input }], templates: [{ type: ContentChildren, args: [PrimeTemplate,] }] }; class ToolbarModule { } ToolbarModule.decorators = [ { type: NgModule, args: [{ imports: [CommonModule], exports: [Toolbar], declarations: [Toolbar] },] } ]; /** * Generated bundle index. Do not edit. */ export { Toolbar, ToolbarModule }; //# sourceMappingURL=primeng-toolbar.js.map
/*! * Common test dependencies. */ // expose the globals that are obtained through `<script>` on the browser expect = require('expect.js'); MessageFormat = require('../');
var convertTemplateType = require("./convertTemplateType"); var toToken = require("./toToken"); module.exports = function (tokens, tt, code) { // transform tokens to type "Template" convertTemplateType(tokens, tt); var transformedTokens = tokens.filter((token) => { return token.type !== "CommentLine" && token.type !== "CommentBlock"; }); for (var i = 0, l = transformedTokens.length; i < l; i++) { transformedTokens[i] = toToken(transformedTokens[i], tt, code); } return transformedTokens; };
'use strict'; angular.module('copayApp.controllers').controller('amazonCardDetailsController', function($scope, $log, $timeout, bwcError, amazonService, lodash, ongoingProcess) { $scope.cancelGiftCard = function() { ongoingProcess.set('Canceling gift card...', true); amazonService.cancelGiftCard($scope.card, function(err, data) { ongoingProcess.set('Canceling gift card...', false); if (err) { $scope.error = bwcError.msg(err); return; } $scope.card.cardStatus = data.cardStatus; amazonService.savePendingGiftCard($scope.card, null, function(err) { $scope.$emit('UpdateAmazonList'); }); }); }; $scope.remove = function() { amazonService.savePendingGiftCard($scope.card, { remove: true }, function(err) { $scope.$emit('UpdateAmazonList'); $scope.cancel(); }); }; $scope.refreshGiftCard = function() { amazonService.getPendingGiftCards(function(err, gcds) { if (err) { self.error = err; return; } lodash.forEach(gcds, function(dataFromStorage) { if (dataFromStorage.status == 'PENDING' && dataFromStorage.invoiceId == $scope.card.invoiceId) { $log.debug("creating gift card"); amazonService.createGiftCard(dataFromStorage, function(err, giftCard) { if (err) { self.error = bwcError.msg(err); $log.debug(bwcError.msg(err)); return; } if (!lodash.isEmpty(giftCard)) { var newData = {}; lodash.merge(newData, dataFromStorage, giftCard); amazonService.savePendingGiftCard(newData, null, function(err) { $log.debug("Saving new gift card"); $scope.card = newData; $scope.$emit('UpdateAmazonList'); $timeout(function() { $scope.$digest(); }); }); } else $log.debug("pending gift card not available yet"); }); } }); }); }; $scope.cancel = function() { $scope.amazonCardDetailsModal.hide(); }; });
define("p3/widget/InteractionGridContainer", [ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/on', 'dojo/topic', 'dojo/dom-construct', 'dijit/popup', 'dijit/TooltipDialog', 'dijit/Dialog', 'FileSaver', './GridContainer', './FacetFilterPanel', './InteractionGrid', './PerspectiveToolTip', './SelectionToGroup' ], function ( declare, lang, on, Topic, domConstruct, popup, TooltipDialog, Dialog, saveAs, GridContainer, FacetFilterPanel, Grid, PerspectiveToolTipDialog, SelectionToGroup ) { var dfc = '<div>Download Table As...</div><div class="wsActionTooltip" rel="text/tsv">Text</div><div class="wsActionTooltip" rel="text/csv">CSV</div>'; var downloadTT = new TooltipDialog({ content: dfc, onMouseLeave: function () { popup.close(downloadTT); } }); var vfc = '<div class="wsActionTooltip" rel="dna">View FASTA DNA</div><div class="wsActionTooltip" rel="protein">View FASTA Proteins</div>'; var viewFASTATT = new TooltipDialog({ content: vfc, onMouseLeave: function () { popup.close(viewFASTATT); } }); on(viewFASTATT.domNode, 'click', function (evt) { var rel = evt.target.attributes.rel.value; var sel = viewFASTATT.selection; delete viewFASTATT.selection; var ids = sel.map(function (x) { return [x.feature_id_a, x.feature_id_b]; }).reduce(function (a, b) { return a.concat(b); }); Topic.publish('/navigate', { href: '/view/FASTA/' + rel + '/?in(feature_id,(' + ids.join(',') + '))', target: 'blank' }); }); return declare([GridContainer], { gridCtor: Grid, containerType: 'interaction_data', tutorialLink: 'user_guides/organisms_taxon/interactions.html', facetFields: ['category', 'evidence', 'detection_method', 'interaction_type', 'source_db', 'genome_name_a', 'genome_name_b'], dataModel: 'ppi', defaultFilter: 'eq(evidence,experimental)', constructor: function (options) { this.topicId = options.topicId; // Topic.subscribe }, buildQuery: function () { return ''; }, _setQueryAttr: function () { // }, _setStateAttr: function (state) { this.inherited(arguments); if (!state) { return; } // console.log("InteractionGridContainer _setStateAttr", state.taxon_id); if (this.grid) { this.grid.set('state', state); } this._set('state', state); }, containerActions: GridContainer.prototype.containerActions.concat([ [ 'DownloadTable', 'fa icon-download fa-2x', { label: 'DOWNLOAD', multiple: false, validTypes: ['*'], tooltip: 'Download Table', tooltipDialog: downloadTT }, function () { downloadTT.set('content', dfc); on(downloadTT.domNode, 'div:click', lang.hitch(this, function (evt) { var rel = evt.target.attributes.rel.value; var DELIMITER, ext; if (rel === 'text/csv') { DELIMITER = ','; ext = 'csv'; } else { DELIMITER = '\t'; ext = 'txt'; } var data = this.grid.store.query('', { sort: this.grid.store.sort }); var headers = ['Interactor A ID', 'Interactor A Type', 'Interactor A Desc', 'Domain A', 'Taxon ID A', 'Genome ID A', 'Genome Name A', 'RefSeq Locus Tag A', 'gene A', 'Interactor B ID', 'Interactor B Type', 'Interactor B Desc', 'Domain B', 'Taxon ID B', 'Genome ID B', 'Genome Name B', 'RefSeq Locus Tag B', 'gene B', 'Category', 'Interaction Type', 'Detection Method', 'Evidence', 'PMID', 'Source DB', 'Source ID', 'Score']; var content = []; data.forEach(function (row) { content.push([row.interactor_a, row.interactor_type_a, '"' + row.interactor_desc_a + '"', row.domain_a, row.taxon_id_a, row.genome_id_a, row.genome_name_a, row.refseq_locus_tag_a, row.gene_a, row.interactor_b, row.interactor_type_b, '"' + row.interactor_desc_b + '"', row.domain_b, row.taxon_id_b, row.genome_id_b, row.genome_name_b, row.refseq_locus_tag_b, row.gene_b, row.category, '"' + row.interaction_type + '"', '"' + row.detection_method + '"', '"' + row.evidence + '"', '"' + (row.pmid || []).join(',') + '"', '"' + row.source_db + '"', '"' + (row.source_id || '') + '"', row.score].join(DELIMITER)); }); saveAs(new Blob([headers.join(DELIMITER) + '\n' + content.join('\n')], { type: rel }), 'PATRIC_interactions.' + ext); popup.close(downloadTT); })); popup.open({ popup: this.containerActionBar._actions.DownloadTable.options.tooltipDialog, around: this.containerActionBar._actions.DownloadTable.button, orient: ['below'] }); }, true ] ]), selectionActions: GridContainer.prototype.selectionActions.concat([ [ 'ViewFeatureItems', 'MultiButton fa icon-selection-FeatureList fa-2x', { label: 'FEATURES', validTypes: ['*'], multiple: true, min: 1, max: 5000, tooltip: 'Switch to Feature List View. Press and Hold for more options.', validContainerTypes: ['interaction_data'], pressAndHold: function (selection, button, opts, evt) { var sel = selection.map(function (x) { return [x.feature_id_a, x.feature_id_b]; }).reduce(function (a, b) { return a.concat(b); }).filter(function (x, i, orig) { return orig.indexOf(x) == i; }); popup.open({ popup: new PerspectiveToolTipDialog({ perspective: 'FeatureList', perspectiveUrl: '/view/FeatureList/?in(feature_id,(' + sel.join(',') + '))' }), around: button, orient: ['below'] }); } }, function (selection) { var sel = selection.map(function (x) { return [x.feature_id_a, x.feature_id_b]; }).reduce(function (a, b) { return a.concat(b); }).filter(function (x, i, orig) { return orig.indexOf(x) == i; }); // console.log(sel); Topic.publish('/navigate', { href: '/view/FeatureList/?in(feature_id,(' + sel.join(',') + '))' }); }, false ], [ 'ViewFASTA', 'fa icon-fasta fa-2x', { label: 'FASTA', ignoreDataType: true, multiple: true, validTypes: ['*'], max: 5000, tooltip: 'View FASTA Data', tooltipDialog: viewFASTATT, validContainerTypes: ['interaction_data'] }, function (selection) { viewFASTATT.selection = selection; popup.open({ popup: this.selectionActionBar._actions.ViewFASTA.options.tooltipDialog, around: this.selectionActionBar._actions.ViewFASTA.button, orient: ['below'] }); }, false ], [ 'AddGroup', 'fa icon-object-group fa-2x', { label: 'GROUP', ignoreDataType: true, multiple: true, validTypes: ['*'], requireAuth: true, max: 10000, tooltip: 'Add selection to a new or existing group', validContainerTypes: ['interaction_data'] }, function (selection) { var sel_feature = selection.map(function (x) { return [x.feature_id_a, x.feature_id_b]; }).reduce(function (a, b) { return a.concat(b); }).filter(function (x, i, orig) { return orig.indexOf(x) == i; }); var sel_genome = selection.map(function (x) { return [x.genome_id_a, x.genome_id_b]; }).reduce(function (a, b) { return a.concat(b); }).filter(function (x, i, orig) { return orig.indexOf(x) == i; }); var feature_ids = sel_feature.map(function (x) { return { feature_id: x }; }); var genome_ids = sel_genome.map(function (x) { return { genome_id: x }; }); var dlg = new Dialog({ title: 'Add selected items to group' }); var type = 'feature_group'; if (!type) { console.error('Missing type for AddGroup'); return; } var stg = new SelectionToGroup({ selection: feature_ids.concat(genome_ids), type: type, inputType: 'feature_data', path: '' }); on(dlg.domNode, 'dialogAction', function (evt) { dlg.hide(); setTimeout(function () { dlg.destroy(); }, 2000); }); domConstruct.place(stg.domNode, dlg.containerNode, 'first'); stg.startup(); dlg.startup(); dlg.show(); }, false ] ]) }); });
const Bar = () => { const Foo = () => { const Component = ({thing, ..._react}) => { if (!thing) { var _react2 = "something useless"; var b = _react3(); var c = _react5(); var jsx = 1; var _jsx = 2; return <div />; }; return <span />; }; } }
'use strict'; var StrictModeError = require('../../error/strict'); var utils = require('../../utils'); /*! * Casts an update op based on the given schema * * @param {Schema} schema * @param {Object} obj * @param {Object} options * @param {Boolean} [options.overwrite] defaults to false * @param {Boolean|String} [options.strict] defaults to true * @return {Boolean} true iff the update is non-empty */ module.exports = function castUpdate(schema, obj, options) { if (!obj) { return undefined; } var ops = Object.keys(obj); var i = ops.length; var ret = {}; var hasKeys; var val; var hasDollarKey = false; var overwrite = options.overwrite; while (i--) { var op = ops[i]; // if overwrite is set, don't do any of the special $set stuff if (op[0] !== '$' && !overwrite) { // fix up $set sugar if (!ret.$set) { if (obj.$set) { ret.$set = obj.$set; } else { ret.$set = {}; } } ret.$set[op] = obj[op]; ops.splice(i, 1); if (!~ops.indexOf('$set')) ops.push('$set'); } else if (op === '$set') { if (!ret.$set) { ret[op] = obj[op]; } } else { ret[op] = obj[op]; } } // cast each value i = ops.length; // if we get passed {} for the update, we still need to respect that when it // is an overwrite scenario if (overwrite) { hasKeys = true; } while (i--) { op = ops[i]; val = ret[op]; hasDollarKey = hasDollarKey || op.charAt(0) === '$'; if (val && typeof val === 'object' && (!overwrite || hasDollarKey)) { hasKeys |= walkUpdatePath(schema, val, op, options.strict); } else if (overwrite && ret && typeof ret === 'object') { // if we are just using overwrite, cast the query and then we will // *always* return the value, even if it is an empty object. We need to // set hasKeys above because we need to account for the case where the // user passes {} and wants to clobber the whole document // Also, _walkUpdatePath expects an operation, so give it $set since that // is basically what we're doing walkUpdatePath(schema, ret, '$set', options.strict); } else { var msg = 'Invalid atomic update value for ' + op + '. ' + 'Expected an object, received ' + typeof val; throw new Error(msg); } } return hasKeys && ret; }; /*! * Walk each path of obj and cast its values * according to its schema. * * @param {Schema} schema * @param {Object} obj - part of a query * @param {String} op - the atomic operator ($pull, $set, etc) * @param {Boolean|String} strict * @param {String} pref - path prefix (internal only) * @return {Bool} true if this path has keys to update * @api private */ function walkUpdatePath(schema, obj, op, strict, pref) { var prefix = pref ? pref + '.' : '', keys = Object.keys(obj), i = keys.length, hasKeys = false, schematype, key, val; var useNestedStrict = schema.options.useNestedStrict; while (i--) { key = keys[i]; val = obj[key]; if (val && val.constructor.name === 'Object') { // watch for embedded doc schemas schematype = schema._getSchema(prefix + key); if (schematype && schematype.caster && op in castOps) { // embedded doc schema hasKeys = true; if ('$each' in val) { obj[key] = { $each: castUpdateVal(schematype, val.$each, op) }; if (val.$slice != null) { obj[key].$slice = val.$slice | 0; } if (val.$sort) { obj[key].$sort = val.$sort; } if (!!val.$position || val.$position === 0) { obj[key].$position = val.$position; } } else { obj[key] = castUpdateVal(schematype, val, op); } } else if (op === '$currentDate') { // $currentDate can take an object obj[key] = castUpdateVal(schematype, val, op); hasKeys = true; } else if (op in castOps && schematype) { obj[key] = castUpdateVal(schematype, val, op); hasKeys = true; } else { var pathToCheck = (prefix + key); var v = schema._getPathType(pathToCheck); var _strict = strict; if (useNestedStrict && v && v.schema && 'strict' in v.schema.options) { _strict = v.schema.options.strict; } if (v.pathType === 'undefined') { if (_strict === 'throw') { throw new StrictModeError(pathToCheck); } else if (_strict) { delete obj[key]; continue; } } // gh-2314 // we should be able to set a schema-less field // to an empty object literal hasKeys |= walkUpdatePath(schema, val, op, strict, prefix + key) || (utils.isObject(val) && Object.keys(val).length === 0); } } else { var checkPath = (key === '$each' || key === '$or' || key === '$and') ? pref : prefix + key; schematype = schema._getSchema(checkPath); var pathDetails = schema._getPathType(checkPath); var isStrict = strict; if (useNestedStrict && pathDetails && pathDetails.schema && 'strict' in pathDetails.schema.options) { isStrict = pathDetails.schema.options.strict; } var skip = isStrict && !schematype && !/real|nested/.test(pathDetails.pathType); if (skip) { if (isStrict === 'throw') { throw new StrictModeError(prefix + key); } else { delete obj[key]; } } else { // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking // improving this. if (op === '$rename') { hasKeys = true; continue; } hasKeys = true; obj[key] = castUpdateVal(schematype, val, op, key); } } } return hasKeys; } /*! * These operators should be cast to numbers instead * of their path schema type. */ var numberOps = { $pop: 1, $unset: 1, $inc: 1 }; /*! * These operators require casting docs * to real Documents for Update operations. */ var castOps = { $push: 1, $pushAll: 1, $addToSet: 1, $set: 1, $setOnInsert: 1 }; /*! * Casts `val` according to `schema` and atomic `op`. * * @param {SchemaType} schema * @param {Object} val * @param {String} op - the atomic operator ($pull, $set, etc) * @param {String} [$conditional] * @api private */ function castUpdateVal(schema, val, op, $conditional) { if (!schema) { // non-existing schema path return op in numberOps ? Number(val) : val; } var cond = schema.caster && op in castOps && (utils.isObject(val) || Array.isArray(val)); if (cond) { // Cast values for ops that add data to MongoDB. // Ensures embedded documents get ObjectIds etc. var tmp = schema.cast(val); if (Array.isArray(val)) { val = tmp; } else if (Array.isArray(tmp)) { val = tmp[0]; } else { val = tmp; } return val; } if (op in numberOps) { if (op === '$inc') { return schema.castForQuery(val); } return Number(val); } if (op === '$currentDate') { if (typeof val === 'object') { return {$type: val.$type}; } return Boolean(val); } if (/^\$/.test($conditional)) { return schema.castForQuery($conditional, val); } return schema.castForQuery(val); }
/** * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> * Build: `lodash modularize modern exports="amd" -o ./modern/` * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ define(['../functions/createCallback', '../objects/forOwn'], function(createCallback, forOwn) { /** * Iterates over elements of a collection, returning an array of all elements * the callback returns truey for. The callback is bound to `thisArg` and * invoked with three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias select * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of elements that passed the callback check. * @example * * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); * // => [2, 4, 6] * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true } * ]; * * // using "_.pluck" callback shorthand * _.filter(characters, 'blocked'); * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] * * // using "_.where" callback shorthand * _.filter(characters, { 'age': 36 }); * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] */ function filter(collection, callback, thisArg) { var result = []; callback = createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { var value = collection[index]; if (callback(value, index, collection)) { result.push(value); } } } else { forOwn(collection, function(value, index, collection) { if (callback(value, index, collection)) { result.push(value); } }); } return result; } return filter; });
describe('accordion', function () { var $scope; beforeEach(module('ui.bootstrap.accordion')); beforeEach(module('template/accordion/accordion.html')); beforeEach(module('template/accordion/accordion-group.html')); beforeEach(inject(function ($rootScope) { $scope = $rootScope; })); describe('controller', function () { var ctrl, $element, $attrs; beforeEach(inject(function($controller) { $attrs = {}; $element = {}; ctrl = $controller('AccordionController', { $scope: $scope, $element: $element, $attrs: $attrs }); })); describe('addGroup', function() { it('adds a the specified group to the collection', function() { var group1, group2; ctrl.addGroup(group1 = $scope.$new()); ctrl.addGroup(group2 = $scope.$new()); expect(ctrl.groups.length).toBe(2); expect(ctrl.groups[0]).toBe(group1); expect(ctrl.groups[1]).toBe(group2); }); }); describe('closeOthers', function() { var group1, group2, group3; beforeEach(function() { ctrl.addGroup(group1 = { isOpen: true, $on : angular.noop }); ctrl.addGroup(group2 = { isOpen: true, $on : angular.noop }); ctrl.addGroup(group3 = { isOpen: true, $on : angular.noop }); }); it('should close other groups if close-others attribute is not defined', function() { delete $attrs.closeOthers; ctrl.closeOthers(group2); expect(group1.isOpen).toBe(false); expect(group2.isOpen).toBe(true); expect(group3.isOpen).toBe(false); }); it('should close other groups if close-others attribute is true', function() { $attrs.closeOthers = 'true'; ctrl.closeOthers(group3); expect(group1.isOpen).toBe(false); expect(group2.isOpen).toBe(false); expect(group3.isOpen).toBe(true); }); it('should not close other groups if close-others attribute is false', function() { $attrs.closeOthers = 'false'; ctrl.closeOthers(group2); expect(group1.isOpen).toBe(true); expect(group2.isOpen).toBe(true); expect(group3.isOpen).toBe(true); }); describe('setting accordionConfig', function() { var originalCloseOthers; beforeEach(inject(function(accordionConfig) { originalCloseOthers = accordionConfig.closeOthers; accordionConfig.closeOthers = false; })); afterEach(inject(function(accordionConfig) { // return it to the original value accordionConfig.closeOthers = originalCloseOthers; })); it('should not close other groups if accordionConfig.closeOthers is false', function() { ctrl.closeOthers(group2); expect(group1.isOpen).toBe(true); expect(group2.isOpen).toBe(true); expect(group3.isOpen).toBe(true); }); }); }); describe('removeGroup', function() { it('should remove the specified group', function () { var group1, group2, group3; ctrl.addGroup(group1 = $scope.$new()); ctrl.addGroup(group2 = $scope.$new()); ctrl.addGroup(group3 = $scope.$new()); ctrl.removeGroup(group2); expect(ctrl.groups.length).toBe(2); expect(ctrl.groups[0]).toBe(group1); expect(ctrl.groups[1]).toBe(group3); }); it('should ignore remove of non-existing group', function () { var group1, group2; ctrl.addGroup(group1 = $scope.$new()); ctrl.addGroup(group2 = $scope.$new()); expect(ctrl.groups.length).toBe(2); ctrl.removeGroup({}); expect(ctrl.groups.length).toBe(2); }); }); }); describe('accordion-group', function () { var scope, $compile; var element, groups; var findGroupLink = function (index) { return groups.eq(index).find('a').eq(0); }; var findGroupBody = function (index) { return groups.eq(index).find('.accordion-body').eq(0); }; beforeEach(inject(function(_$rootScope_, _$compile_) { scope = _$rootScope_; $compile = _$compile_; })); afterEach(function () { element = groups = scope = $compile = undefined; }); describe('with static groups', function () { beforeEach(function () { var tpl = "<accordion>" + "<accordion-group heading=\"title 1\">Content 1</accordion-group>" + "<accordion-group heading=\"title 2\">Content 2</accordion-group>" + "</accordion>"; element = angular.element(tpl); angular.element(document.body).append(element); $compile(element)(scope); scope.$digest(); groups = element.find('.accordion-group'); }); afterEach(function() { element.remove(); }); it('should create accordion groups with content', function () { expect(groups.length).toEqual(2); expect(findGroupLink(0).text()).toEqual('title 1'); expect(findGroupBody(0).text().trim()).toEqual('Content 1'); expect(findGroupLink(1).text()).toEqual('title 2'); expect(findGroupBody(1).text().trim()).toEqual('Content 2'); }); it('should change selected element on click', function () { findGroupLink(0).click(); scope.$digest(); expect(findGroupBody(0).scope().isOpen).toBe(true); findGroupLink(1).click(); scope.$digest(); expect(findGroupBody(0).scope().isOpen).toBe(false); expect(findGroupBody(1).scope().isOpen).toBe(true); }); it('should toggle element on click', function() { findGroupLink(0).click(); scope.$digest(); expect(findGroupBody(0).scope().isOpen).toBe(true); findGroupLink(0).click(); scope.$digest(); expect(findGroupBody(0).scope().isOpen).toBe(false); }); }); describe('with dynamic groups', function () { var model; beforeEach(function () { var tpl = "<accordion>" + "<accordion-group ng-repeat='group in groups' heading='{{group.name}}'>{{group.content}}</accordion-group>" + "</accordion>"; element = angular.element(tpl); model = [ {name: 'title 1', content: 'Content 1'}, {name: 'title 2', content: 'Content 2'} ]; $compile(element)(scope); scope.$digest(); }); it('should have no groups initially', function () { groups = element.find('.accordion-group'); expect(groups.length).toEqual(0); }); it('should have a group for each model item', function() { scope.groups = model; scope.$digest(); groups = element.find('.accordion-group'); expect(groups.length).toEqual(2); expect(findGroupLink(0).text()).toEqual('title 1'); expect(findGroupBody(0).text().trim()).toEqual('Content 1'); expect(findGroupLink(1).text()).toEqual('title 2'); expect(findGroupBody(1).text().trim()).toEqual('Content 2'); }); it('should react properly on removing items from the model', function () { scope.groups = model; scope.$digest(); groups = element.find('.accordion-group'); expect(groups.length).toEqual(2); scope.groups.splice(0,1); scope.$digest(); groups = element.find('.accordion-group'); expect(groups.length).toEqual(1); }); }); describe('is-open attribute', function() { beforeEach(function () { var tpl = '<accordion>' + '<accordion-group heading="title 1" is-open="open.first">Content 1</accordion-group>' + '<accordion-group heading="title 2" is-open="open.second">Content 2</accordion-group>' + '</accordion>'; element = angular.element(tpl); scope.open = { first: false, second: true }; $compile(element)(scope); scope.$digest(); groups = element.find('.accordion-group'); }); it('should open the group with isOpen set to true', function () { expect(findGroupBody(0).scope().isOpen).toBe(false); expect(findGroupBody(1).scope().isOpen).toBe(true); }); it('should toggle variable on element click', function() { findGroupLink(0).click(); scope.$digest(); expect(scope.open.first).toBe(true); findGroupLink(0).click(); scope.$digest(); expect(scope.open.second).toBe(false); }); }); describe('is-open attribute with dynamic content', function() { beforeEach(function () { var tpl = "<accordion>" + "<accordion-group heading=\"title 1\" is-open=\"open1\"><div ng-repeat='item in items'>{{item}}</div></accordion-group>" + "<accordion-group heading=\"title 2\" is-open=\"open2\">Static content</accordion-group>" + "</accordion>"; element = angular.element(tpl); scope.items = ['Item 1', 'Item 2', 'Item 3']; scope.open1 = true; scope.open2 = false; angular.element(document.body).append(element); $compile(element)(scope); scope.$digest(); groups = element.find('.accordion-group'); }); afterEach(function() { element.remove(); }); it('should have visible group body when the group with isOpen set to true', function () { expect(findGroupBody(0)[0].clientHeight).not.toBe(0); expect(findGroupBody(1)[0].clientHeight).toBe(0); }); }); describe('is-open attribute with dynamic groups', function () { var model; beforeEach(function () { var tpl = '<accordion>' + '<accordion-group ng-repeat="group in groups" heading="{{group.name}}" is-open="group.open">{{group.content}}</accordion-group>' + '</accordion>'; element = angular.element(tpl); scope.groups = [ {name: 'title 1', content: 'Content 1', open: false}, {name: 'title 2', content: 'Content 2', open: true} ]; $compile(element)(scope); scope.$digest(); groups = element.find('.accordion-group'); }); it('should have visible group body when the group with isOpen set to true', function () { expect(findGroupBody(0).scope().isOpen).toBe(false); expect(findGroupBody(1).scope().isOpen).toBe(true); }); it('should toggle element on click', function() { findGroupLink(0).click(); scope.$digest(); expect(findGroupBody(0).scope().isOpen).toBe(true); expect(scope.groups[0].open).toBe(true); findGroupLink(0).click(); scope.$digest(); expect(findGroupBody(0).scope().isOpen).toBe(false); expect(scope.groups[0].open).toBe(false); }); }); describe('accordion-heading element', function() { beforeEach(function() { var tpl = '<accordion ng-init="a = [1,2,3]">' + '<accordion-group heading="I get overridden">' + '<accordion-heading>Heading Element <span ng-repeat="x in a">{{x}}</span> </accordion-heading>' + 'Body' + '</accordion-group>' + '</accordion>'; element = $compile(tpl)(scope); scope.$digest(); groups = element.find('.accordion-group'); }); it('transcludes the <accordion-heading> content into the heading link', function() { expect(findGroupLink(0).text()).toBe('Heading Element 123 '); }); it('attaches the same scope to the transcluded heading and body', function() { expect(findGroupLink(0).find('span').scope().$id).toBe(findGroupBody(0).find('span').scope().$id); }); }); describe('accordion-heading attribute', function() { beforeEach(function() { var tpl = '<accordion ng-init="a = [1,2,3]">' + '<accordion-group heading="I get overridden">' + '<div accordion-heading>Heading Element <span ng-repeat="x in a">{{x}}</span> </div>' + 'Body' + '</accordion-group>' + '</accordion>'; element = $compile(tpl)(scope); scope.$digest(); groups = element.find('.accordion-group'); }); it('transcludes the <accordion-heading> content into the heading link', function() { expect(findGroupLink(0).text()).toBe('Heading Element 123 '); }); it('attaches the same scope to the transcluded heading and body', function() { expect(findGroupLink(0).find('span').scope().$id).toBe(findGroupBody(0).find('span').scope().$id); }); }); describe('accordion-heading, with repeating accordion-groups', function() { it('should clone the accordion-heading for each group', function() { element = $compile('<accordion><accordion-group ng-repeat="x in [1,2,3]"><accordion-heading>{{x}}</accordion-heading></accordion-group></accordion>')(scope); scope.$digest(); groups = element.find('.accordion-group'); expect(groups.length).toBe(3); expect(findGroupLink(0).text()).toBe('1'); expect(findGroupLink(1).text()).toBe('2'); expect(findGroupLink(2).text()).toBe('3'); }); }); describe('accordion-heading attribute, with repeating accordion-groups', function() { it('should clone the accordion-heading for each group', function() { element = $compile('<accordion><accordion-group ng-repeat="x in [1,2,3]"><div accordion-heading>{{x}}</div></accordion-group></accordion>')(scope); scope.$digest(); groups = element.find('.accordion-group'); expect(groups.length).toBe(3); expect(findGroupLink(0).text()).toBe('1'); expect(findGroupLink(1).text()).toBe('2'); expect(findGroupLink(2).text()).toBe('3'); }); }); }); });
/** * 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. */ /* jshint maxlen: false */ 'use strict'; var createAPIRequest = require('../../lib/apirequest'); /** * DoubleClick Search API * * @classdesc Report and modify your advertising data in DoubleClick Search (for example, campaigns, ad groups, keywords, and conversions). * @namespace doubleclicksearch * @version v2 * @variation v2 * @this Doubleclicksearch * @param {object=} options Options for Doubleclicksearch */ function Doubleclicksearch(options) { var self = this; this._options = options || {}; this.conversion = { /** * doubleclicksearch.conversion.get * * @desc Retrieves a list of conversions from a DoubleClick Search engine account. * * @alias doubleclicksearch.conversion.get * @memberOf! doubleclicksearch(v2) * * @param {object} params - Parameters for request * @param {string=} params.adGroupId - Numeric ID of the ad group. * @param {string=} params.adId - Numeric ID of the ad. * @param {string} params.advertiserId - Numeric ID of the advertiser. * @param {string} params.agencyId - Numeric ID of the agency. * @param {string=} params.campaignId - Numeric ID of the campaign. * @param {string=} params.criterionId - Numeric ID of the criterion. * @param {integer} params.endDate - Last date (inclusive) on which to retrieve conversions. Format is yyyymmdd. * @param {string} params.engineAccountId - Numeric ID of the engine account. * @param {integer} params.rowCount - The number of conversions to return per call. * @param {integer} params.startDate - First date (inclusive) on which to retrieve conversions. Format is yyyymmdd. * @param {integer} params.startRow - The 0-based starting index for retrieving conversions results. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/doubleclicksearch/v2/agency/{agencyId}/advertiser/{advertiserId}/engine/{engineAccountId}/conversion', method: 'GET' }, params: params, requiredParams: ['agencyId', 'advertiserId', 'engineAccountId', 'endDate', 'rowCount', 'startDate', 'startRow'], pathParams: ['advertiserId', 'agencyId', 'engineAccountId'], context: self }; return createAPIRequest(parameters, callback); }, /** * doubleclicksearch.conversion.insert * * @desc Inserts a batch of new conversions into DoubleClick Search. * * @alias doubleclicksearch.conversion.insert * @memberOf! doubleclicksearch(v2) * * @param {object} params - Parameters for request * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/doubleclicksearch/v2/conversion', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * doubleclicksearch.conversion.patch * * @desc Updates a batch of conversions in DoubleClick Search. This method supports patch semantics. * * @alias doubleclicksearch.conversion.patch * @memberOf! doubleclicksearch(v2) * * @param {object} params - Parameters for request * @param {string} params.advertiserId - Numeric ID of the advertiser. * @param {string} params.agencyId - Numeric ID of the agency. * @param {integer} params.endDate - Last date (inclusive) on which to retrieve conversions. Format is yyyymmdd. * @param {string} params.engineAccountId - Numeric ID of the engine account. * @param {integer} params.rowCount - The number of conversions to return per call. * @param {integer} params.startDate - First date (inclusive) on which to retrieve conversions. Format is yyyymmdd. * @param {integer} params.startRow - The 0-based starting index for retrieving conversions results. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/doubleclicksearch/v2/conversion', method: 'PATCH' }, params: params, requiredParams: ['advertiserId', 'agencyId', 'endDate', 'engineAccountId', 'rowCount', 'startDate', 'startRow'], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * doubleclicksearch.conversion.update * * @desc Updates a batch of conversions in DoubleClick Search. * * @alias doubleclicksearch.conversion.update * @memberOf! doubleclicksearch(v2) * * @param {object} params - Parameters for request * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/doubleclicksearch/v2/conversion', method: 'PUT' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * doubleclicksearch.conversion.updateAvailability * * @desc Updates the availabilities of a batch of floodlight activities in DoubleClick Search. * * @alias doubleclicksearch.conversion.updateAvailability * @memberOf! doubleclicksearch(v2) * * @param {object} params - Parameters for request * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ updateAvailability: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/doubleclicksearch/v2/conversion/updateAvailability', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); } }; this.reports = { /** * doubleclicksearch.reports.generate * * @desc Generates and returns a report immediately. * * @alias doubleclicksearch.reports.generate * @memberOf! doubleclicksearch(v2) * * @param {object} params - Parameters for request * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ generate: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/doubleclicksearch/v2/reports/generate', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * doubleclicksearch.reports.get * * @desc Polls for the status of a report request. * * @alias doubleclicksearch.reports.get * @memberOf! doubleclicksearch(v2) * * @param {object} params - Parameters for request * @param {string} params.reportId - ID of the report request being polled. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/doubleclicksearch/v2/reports/{reportId}', method: 'GET' }, params: params, requiredParams: ['reportId'], pathParams: ['reportId'], context: self }; return createAPIRequest(parameters, callback); }, /** * doubleclicksearch.reports.getFile * * @desc Downloads a report file encoded in UTF-8. * * @alias doubleclicksearch.reports.getFile * @memberOf! doubleclicksearch(v2) * * @param {object} params - Parameters for request * @param {integer} params.reportFragment - The index of the report fragment to download. * @param {string} params.reportId - ID of the report. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ getFile: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/doubleclicksearch/v2/reports/{reportId}/files/{reportFragment}', method: 'GET' }, params: params, requiredParams: ['reportId', 'reportFragment'], pathParams: ['reportFragment', 'reportId'], context: self }; return createAPIRequest(parameters, callback); }, /** * doubleclicksearch.reports.request * * @desc Inserts a report request into the reporting system. * * @alias doubleclicksearch.reports.request * @memberOf! doubleclicksearch(v2) * * @param {object} params - Parameters for request * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ request: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/doubleclicksearch/v2/reports', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); } }; this.savedColumns = { /** * doubleclicksearch.savedColumns.list * * @desc Retrieve the list of saved columns for a specified advertiser. * * @alias doubleclicksearch.savedColumns.list * @memberOf! doubleclicksearch(v2) * * @param {object} params - Parameters for request * @param {string} params.advertiserId - DS ID of the advertiser. * @param {string} params.agencyId - DS ID of the agency. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/doubleclicksearch/v2/agency/{agencyId}/advertiser/{advertiserId}/savedcolumns', method: 'GET' }, params: params, requiredParams: ['agencyId', 'advertiserId'], pathParams: ['advertiserId', 'agencyId'], context: self }; return createAPIRequest(parameters, callback); } }; } /** * Exports Doubleclicksearch object * @type Doubleclicksearch */ module.exports = Doubleclicksearch;
import Cache from '../cache' import { inBrowser, trimNode, isTemplate, isFragment } from '../util/index' const templateCache = new Cache(1000) const idSelectorCache = new Cache(1000) const map = { efault: [0, '', ''], legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [ 2, '<table><tbody></tbody><colgroup>', '</colgroup></table>' ] } map.td = map.th = [ 3, '<table><tbody><tr>', '</tr></tbody></table>' ] map.option = map.optgroup = [ 1, '<select multiple="multiple">', '</select>' ] map.thead = map.tbody = map.colgroup = map.caption = map.tfoot = [1, '<table>', '</table>'] map.g = map.defs = map.symbol = map.use = map.image = map.text = map.circle = map.ellipse = map.line = map.path = map.polygon = map.polyline = map.rect = [ 1, '<svg ' + 'xmlns="http://www.w3.org/2000/svg" ' + 'xmlns:xlink="http://www.w3.org/1999/xlink" ' + 'xmlns:ev="http://www.w3.org/2001/xml-events"' + 'version="1.1">', '</svg>' ] /** * Check if a node is a supported template node with a * DocumentFragment content. * * @param {Node} node * @return {Boolean} */ function isRealTemplate (node) { return isTemplate(node) && isFragment(node.content) } const tagRE = /<([\w:]+)/ const entityRE = /&#?\w+?;/ /** * Convert a string template to a DocumentFragment. * Determines correct wrapping by tag types. Wrapping * strategy found in jQuery & component/domify. * * @param {String} templateString * @param {Boolean} raw * @return {DocumentFragment} */ function stringToFragment (templateString, raw) { // try a cache hit first var cacheKey = raw ? templateString : templateString.trim() var hit = templateCache.get(cacheKey) if (hit) { return hit } var frag = document.createDocumentFragment() var tagMatch = templateString.match(tagRE) var entityMatch = entityRE.test(templateString) if (!tagMatch && !entityMatch) { // text only, return a single text node. frag.appendChild( document.createTextNode(templateString) ) } else { var tag = tagMatch && tagMatch[1] var wrap = map[tag] || map.efault var depth = wrap[0] var prefix = wrap[1] var suffix = wrap[2] var node = document.createElement('div') node.innerHTML = prefix + templateString + suffix while (depth--) { node = node.lastChild } var child /* eslint-disable no-cond-assign */ while (child = node.firstChild) { /* eslint-enable no-cond-assign */ frag.appendChild(child) } } if (!raw) { trimNode(frag) } templateCache.put(cacheKey, frag) return frag } /** * Convert a template node to a DocumentFragment. * * @param {Node} node * @return {DocumentFragment} */ function nodeToFragment (node) { // if its a template tag and the browser supports it, // its content is already a document fragment. if (isRealTemplate(node)) { trimNode(node.content) return node.content } // script template if (node.tagName === 'SCRIPT') { return stringToFragment(node.textContent) } // normal node, clone it to avoid mutating the original var clonedNode = cloneNode(node) var frag = document.createDocumentFragment() var child /* eslint-disable no-cond-assign */ while (child = clonedNode.firstChild) { /* eslint-enable no-cond-assign */ frag.appendChild(child) } trimNode(frag) return frag } // Test for the presence of the Safari template cloning bug // https://bugs.webkit.org/showug.cgi?id=137755 var hasBrokenTemplate = (function () { /* istanbul ignore else */ if (inBrowser) { var a = document.createElement('div') a.innerHTML = '<template>1</template>' return !a.cloneNode(true).firstChild.innerHTML } else { return false } })() // Test for IE10/11 textarea placeholder clone bug var hasTextareaCloneBug = (function () { /* istanbul ignore else */ if (inBrowser) { var t = document.createElement('textarea') t.placeholder = 't' return t.cloneNode(true).value === 't' } else { return false } })() /** * 1. Deal with Safari cloning nested <template> bug by * manually cloning all template instances. * 2. Deal with IE10/11 textarea placeholder bug by setting * the correct value after cloning. * * @param {Element|DocumentFragment} node * @return {Element|DocumentFragment} */ export function cloneNode (node) { if (!node.querySelectorAll) { return node.cloneNode() } var res = node.cloneNode(true) var i, original, cloned /* istanbul ignore if */ if (hasBrokenTemplate) { var tempClone = res if (isRealTemplate(node)) { node = node.content tempClone = res.content } original = node.querySelectorAll('template') if (original.length) { cloned = tempClone.querySelectorAll('template') i = cloned.length while (i--) { cloned[i].parentNode.replaceChild( cloneNode(original[i]), cloned[i] ) } } } /* istanbul ignore if */ if (hasTextareaCloneBug) { if (node.tagName === 'TEXTAREA') { res.value = node.value } else { original = node.querySelectorAll('textarea') if (original.length) { cloned = res.querySelectorAll('textarea') i = cloned.length while (i--) { cloned[i].value = original[i].value } } } } return res } /** * Process the template option and normalizes it into a * a DocumentFragment that can be used as a partial or a * instance template. * * @param {*} template * Possible values include: * - DocumentFragment object * - Node object of type Template * - id selector: '#some-template-id' * - template string: '<div><span>{{msg}}</span></div>' * @param {Boolean} shouldClone * @param {Boolean} raw * inline HTML interpolation. Do not check for id * selector and keep whitespace in the string. * @return {DocumentFragment|undefined} */ export function parseTemplate (template, shouldClone, raw) { var node, frag // if the template is already a document fragment, // do nothing if (isFragment(template)) { trimNode(template) return shouldClone ? cloneNode(template) : template } if (typeof template === 'string') { // id selector if (!raw && template.charAt(0) === '#') { // id selector can be cached too frag = idSelectorCache.get(template) if (!frag) { node = document.getElementById(template.slice(1)) if (node) { frag = nodeToFragment(node) // save selector to cache idSelectorCache.put(template, frag) } } } else { // normal string template frag = stringToFragment(template, raw) } } else if (template.nodeType) { // a direct node frag = nodeToFragment(template) } return frag && shouldClone ? cloneNode(frag) : frag }
// Note: this spec can be run using jasmine-node var createRjsConfig = require('../../../../deployment/scripts/createrjsconfig'); describe('createRjsConfig', function() { var PACKAGE_NAME_STUB = 'PACKAGE_NAME_STUB'; var OUT_DIR_STUB = 'OUT_DIR_STUB'; var PACKAGES_STUB = ['PKG_STUB_A', 'PKG_STUB_B', 'PKG_STUB_C']; it('should return an extend a base config', function() { var STUB_BASE_CONFIG = { foo: 'bar' }; expect(createRjsConfig(PACKAGE_NAME_STUB, { baseConfig: STUB_BASE_CONFIG }).foo).toEqual('bar'); }); it('should not override original deep nested path properties because of strategy option', function() { var STRATEGY_ORIG = 'STRATEGY_ORIG'; var STUB_BASE_CONFIG = { path: { 'aeris/maps/strategy': STRATEGY_ORIG } }; createRjsConfig(PACKAGE_NAME_STUB, { baseConfig: STUB_BASE_CONFIG, strategy: 'new_strategy' }); expect(STUB_BASE_CONFIG.path['aeris/maps/strategy']).toEqual(STRATEGY_ORIG); }); it('should not overwrite the original base config', function() { var STUB_BASE_CONFIG = { out: 'foo' }; createRjsConfig(PACKAGE_NAME_STUB, { baseConfig: STUB_BASE_CONFIG }); expect(STUB_BASE_CONFIG.out).toEqual('foo'); }); it('should set the out path, using the packageName and outDir', function() { var config = createRjsConfig(PACKAGE_NAME_STUB, { outDir: OUT_DIR_STUB }); expect(config.out).toEqual(OUT_DIR_STUB + '/' + PACKAGE_NAME_STUB + '.js'); }); it('should set the minified out path, using the packageName and outDir', function() { var config = createRjsConfig(PACKAGE_NAME_STUB, { outDir: OUT_DIR_STUB, minify: true }); expect(config.out).toEqual(OUT_DIR_STUB + '/' + PACKAGE_NAME_STUB + '.min.js'); }); it('should set \'optimize:uglify2\' if minify option is true', function() { var config = createRjsConfig(PACKAGE_NAME_STUB, { minify: true }); expect(config.optimize).toEqual('uglify2'); }); it('should set \'optimize:none\' if minify option is false', function() { var config = createRjsConfig(PACKAGE_NAME_STUB, { minify: false }); expect(config.optimize).toEqual('none'); }); it('should set a start wrapper using the startWrapperTemplate option', function() { var START_TEMPLATE_STUB = 'START_TEMPLATE_STUB'; var config = createRjsConfig(PACKAGE_NAME_STUB, { startWrapperTemplate: START_TEMPLATE_STUB }); expect(config.wrap.start).toEqual(START_TEMPLATE_STUB); }); it('should set an end wrapper using the endWrapperTemplate option', function() { var END_TEMPLATE_STUB = 'END_TEMPLATE_STUB'; var config = createRjsConfig(PACKAGE_NAME_STUB, { endWrapperTemplate: END_TEMPLATE_STUB }); expect(config.wrap.end).toEqual(END_TEMPLATE_STUB); }); it('should set a start wrapper using the endWrapperTemplate option, with packages data', function() { var END_TEMPLATE_STUB = '{{#each packages}}{{this}}{{/each}}'; var config = createRjsConfig(PACKAGE_NAME_STUB, { endWrapperTemplate: END_TEMPLATE_STUB, packages: PACKAGES_STUB }); expect(config.wrap.end).toEqual(PACKAGES_STUB.join('')); }); it('should set includes using \'packages\' options', function() { var config = createRjsConfig(PACKAGE_NAME_STUB, { packages: PACKAGE_NAME_STUB }); expect(config.include).toEqual(PACKAGE_NAME_STUB); }); it('should set a strategy', function() { var STRATEGY_STUB = 'STRATEGY_STUB'; var config = createRjsConfig(PACKAGE_NAME_STUB, { strategy: STRATEGY_STUB }); expect(config.paths['aeris/maps/strategy']).toEqual('src/maps/' + STRATEGY_STUB); }); it('should not remove existing baseConfig paths', function() { var STRATEGY_STUB = 'STRATEGY_STUB'; var config = createRjsConfig(PACKAGE_NAME_STUB, { strategy: STRATEGY_STUB, baseConfig: { paths: { foo: 'bar' } } }); expect(config.paths.foo).toEqual('bar'); }); });
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.4.4.11_A7.7; * @section: 15.4.4.11, 11.2.2; * @assertion: The sort property of Array can't be used as constructor; * @description: If property does not implement the internal [[Construct]] method, throw a TypeError exception; */ //CHECK#1 try { new Array.prototype.sort(); $ERROR('#1.1: new Array.prototype.sort() throw TypeError. Actual: ' + (new Array.prototype.sort())); } catch (e) { if ((e instanceof TypeError) !== true) { $ERROR('#1.2: new Array.prototype.sort() throw TypeError. Actual: ' + (e)); } }
'use strict'; var test = require('tape') var Client = require('../../lib/dialects/sqlite3'); var Pool = require('generic-pool').Pool test('#822, pool config, max: 0 should skip pool construction', function(t) { var client = new Client({connection: {filename: ':memory:'}, pool: {max: 0}}) try { t.equal(client.pool, undefined) t.end() } finally { client.destroy() } }) test('#823, should not skip pool construction pool config is not defined', function(t) { var client = new Client({connection: {filename: ':memory:'}}) try { t.ok(client.pool instanceof Pool) t.end() } finally { client.destroy() } })
module.exports={title:"WP Engine",slug:"wpengine",svg:'<svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>WP Engine icon</title><path d="M8.145 0v5.867L9.99 7.71h4.022l1.845-1.844V0zm8.145 0v5.867l1.845 1.844h5.864V.001zM1.845 0L0 1.845v5.866h7.712V0zM0 8.146v7.71h5.866l1.845-1.844V8.145zm18.133 0L16.29 9.989v4.022l1.845 1.845H24V8.145zm-6.147 2.75a1.105 1.105 0 00.014 2.21A1.105 1.105 0 0013.105 12a1.105 1.105 0 00-1.118-1.104zM0 16.29v7.71h5.866l1.845-1.842v-4.023l-1.845-1.845zm9.988 0l-1.843 1.845V24h7.71v-5.866L14.01 16.29zm6.3 0V24H24v-5.865l-1.842-1.845z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://wpengine.com/brand-assets/",hex:"0ECAD4",license:void 0};
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { useThemeVariants } from '@material-ui/styles'; import withStyles from '../styles/withStyles'; import { alpha } from '../styles/colorManipulator'; import ButtonBase from '../ButtonBase'; import capitalize from '../utils/capitalize'; export var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: _extends({}, theme.typography.button, { minWidth: 64, padding: '6px 16px', borderRadius: theme.shape.borderRadius, transition: theme.transitions.create(['background-color', 'box-shadow', 'border-color', 'color'], { duration: theme.transitions.duration.short }), '&:hover': { textDecoration: 'none', backgroundColor: alpha(theme.palette.text.primary, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } }, '&$disabled': { color: theme.palette.action.disabled } }), /* Styles applied to the span element that wraps the children. */ label: { width: '100%', // Ensure the correct width for iOS Safari display: 'inherit', alignItems: 'inherit', justifyContent: 'inherit' }, /* Styles applied to the root element if `variant="text"`. */ text: { padding: '6px 8px' }, /* Styles applied to the root element if `variant="text"` and `color="primary"`. */ textPrimary: { color: theme.palette.primary.main, '&:hover': { backgroundColor: alpha(theme.palette.primary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, /* Styles applied to the root element if `variant="text"` and `color="secondary"`. */ textSecondary: { color: theme.palette.secondary.main, '&:hover': { backgroundColor: alpha(theme.palette.secondary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, /* Styles applied to the root element if `variant="outlined"`. */ outlined: { padding: '5px 15px', border: "1px solid ".concat(theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'), '&$disabled': { border: "1px solid ".concat(theme.palette.action.disabledBackground) } }, /* Styles applied to the root element if `variant="outlined"` and `color="primary"`. */ outlinedPrimary: { color: theme.palette.primary.main, border: "1px solid ".concat(alpha(theme.palette.primary.main, 0.5)), '&:hover': { border: "1px solid ".concat(theme.palette.primary.main), backgroundColor: alpha(theme.palette.primary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, /* Styles applied to the root element if `variant="outlined"` and `color="secondary"`. */ outlinedSecondary: { color: theme.palette.secondary.main, border: "1px solid ".concat(alpha(theme.palette.secondary.main, 0.5)), '&:hover': { border: "1px solid ".concat(theme.palette.secondary.main), backgroundColor: alpha(theme.palette.secondary.main, theme.palette.action.hoverOpacity), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } }, '&$disabled': { border: "1px solid ".concat(theme.palette.action.disabled) } }, /* Styles applied to the root element if `variant="contained"`. */ contained: { color: theme.palette.getContrastText(theme.palette.grey[300]), backgroundColor: theme.palette.grey[300], boxShadow: theme.shadows[2], '&:hover': { backgroundColor: theme.palette.grey.A100, boxShadow: theme.shadows[4], // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { boxShadow: theme.shadows[2], backgroundColor: theme.palette.grey[300] } }, '&$focusVisible': { boxShadow: theme.shadows[6] }, '&:active': { boxShadow: theme.shadows[8] }, '&$disabled': { color: theme.palette.action.disabled, boxShadow: theme.shadows[0], backgroundColor: theme.palette.action.disabledBackground } }, /* Styles applied to the root element if `variant="contained"` and `color="primary"`. */ containedPrimary: { color: theme.palette.primary.contrastText, backgroundColor: theme.palette.primary.main, '&:hover': { backgroundColor: theme.palette.primary.dark, // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: theme.palette.primary.main } } }, /* Styles applied to the root element if `variant="contained"` and `color="secondary"`. */ containedSecondary: { color: theme.palette.secondary.contrastText, backgroundColor: theme.palette.secondary.main, '&:hover': { backgroundColor: theme.palette.secondary.dark, // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: theme.palette.secondary.main } } }, /* Styles applied to the root element if `disableElevation={true}`. */ disableElevation: { boxShadow: 'none', '&:hover': { boxShadow: 'none' }, '&$focusVisible': { boxShadow: 'none' }, '&:active': { boxShadow: 'none' }, '&$disabled': { boxShadow: 'none' } }, /* Pseudo-class applied to the ButtonBase root element if the button is keyboard focused. */ focusVisible: {}, /* Pseudo-class applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the root element if `color="inherit"`. */ colorInherit: { color: 'inherit', borderColor: 'currentColor' }, /* Styles applied to the root element if `size="small"` and `variant="text"`. */ textSizeSmall: { padding: '4px 5px', fontSize: theme.typography.pxToRem(13) }, /* Styles applied to the root element if `size="large"` and `variant="text"`. */ textSizeLarge: { padding: '8px 11px', fontSize: theme.typography.pxToRem(15) }, /* Styles applied to the root element if `size="small"` and `variant="outlined"`. */ outlinedSizeSmall: { padding: '3px 9px', fontSize: theme.typography.pxToRem(13) }, /* Styles applied to the root element if `size="large"` and `variant="outlined"`. */ outlinedSizeLarge: { padding: '7px 21px', fontSize: theme.typography.pxToRem(15) }, /* Styles applied to the root element if `size="small"` and `variant="contained"`. */ containedSizeSmall: { padding: '4px 10px', fontSize: theme.typography.pxToRem(13) }, /* Styles applied to the root element if `size="large"` and `variant="contained"`. */ containedSizeLarge: { padding: '8px 22px', fontSize: theme.typography.pxToRem(15) }, /* Styles applied to the root element if `size="small"`. */ sizeSmall: {}, /* Styles applied to the root element if `size="large"`. */ sizeLarge: {}, /* Styles applied to the root element if `fullWidth={true}`. */ fullWidth: { width: '100%' }, /* Styles applied to the startIcon element if supplied. */ startIcon: { display: 'inherit', marginRight: 8, marginLeft: -4, '&$iconSizeSmall': { marginLeft: -2 } }, /* Styles applied to the endIcon element if supplied. */ endIcon: { display: 'inherit', marginRight: -4, marginLeft: 8, '&$iconSizeSmall': { marginRight: -2 } }, /* Styles applied to the icon element if supplied and `size="small"`. */ iconSizeSmall: { '& > *:first-child': { fontSize: 18 } }, /* Styles applied to the icon element if supplied and `size="medium"`. */ iconSizeMedium: { '& > *:first-child': { fontSize: 20 } }, /* Styles applied to the icon element if supplied and `size="large"`. */ iconSizeLarge: { '& > *:first-child': { fontSize: 22 } } }; }; var Button = /*#__PURE__*/React.forwardRef(function Button(props, ref) { var children = props.children, classes = props.classes, className = props.className, _props$color = props.color, color = _props$color === void 0 ? 'primary' : _props$color, _props$component = props.component, component = _props$component === void 0 ? 'button' : _props$component, _props$disabled = props.disabled, disabled = _props$disabled === void 0 ? false : _props$disabled, _props$disableElevati = props.disableElevation, disableElevation = _props$disableElevati === void 0 ? false : _props$disableElevati, _props$disableFocusRi = props.disableFocusRipple, disableFocusRipple = _props$disableFocusRi === void 0 ? false : _props$disableFocusRi, endIconProp = props.endIcon, focusVisibleClassName = props.focusVisibleClassName, _props$fullWidth = props.fullWidth, fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth, _props$size = props.size, size = _props$size === void 0 ? 'medium' : _props$size, startIconProp = props.startIcon, type = props.type, _props$variant = props.variant, variant = _props$variant === void 0 ? 'text' : _props$variant, other = _objectWithoutProperties(props, ["children", "classes", "className", "color", "component", "disabled", "disableElevation", "disableFocusRipple", "endIcon", "focusVisibleClassName", "fullWidth", "size", "startIcon", "type", "variant"]); var themeVariantsClasses = useThemeVariants(_extends({}, props, { color: color, component: component, disabled: disabled, disableElevation: disableElevation, disableFocusRipple: disableFocusRipple, fullWidth: fullWidth, size: size, type: type, variant: variant }), 'MuiButton'); var startIcon = startIconProp && /*#__PURE__*/React.createElement("span", { className: clsx(classes.startIcon, classes["iconSize".concat(capitalize(size))]) }, startIconProp); var endIcon = endIconProp && /*#__PURE__*/React.createElement("span", { className: clsx(classes.endIcon, classes["iconSize".concat(capitalize(size))]) }, endIconProp); return /*#__PURE__*/React.createElement(ButtonBase, _extends({ className: clsx(classes.root, classes[variant], themeVariantsClasses, className, color === 'inherit' ? classes.colorInherit : classes["".concat(variant).concat(capitalize(color))], size !== 'medium' && [classes["".concat(variant, "Size").concat(capitalize(size))], classes["size".concat(capitalize(size))]], disableElevation && classes.disableElevation, disabled && classes.disabled, fullWidth && classes.fullWidth), component: component, disabled: disabled, focusRipple: !disableFocusRipple, focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName), ref: ref, type: type }, other), /*#__PURE__*/React.createElement("span", { className: classes.label }, startIcon, children, endIcon)); }); process.env.NODE_ENV !== "production" ? Button.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The content of the button. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. * @default 'primary' */ color: PropTypes.oneOf(['inherit', 'primary', 'secondary']), /** * The component used for the root node. * Either a string to use a HTML element or a component. */ component: PropTypes.elementType, /** * If `true`, the button is disabled. * @default false */ disabled: PropTypes.bool, /** * If `true`, no elevation is used. * @default false */ disableElevation: PropTypes.bool, /** * If `true`, the keyboard focus ripple is disabled. * @default false */ disableFocusRipple: PropTypes.bool, /** * If `true`, the ripple effect is disabled. * * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure * to highlight the element by applying separate styles with the `focusVisibleClassName`. * @default false */ disableRipple: PropTypes.bool, /** * Element placed after the children. */ endIcon: PropTypes.node, /** * @ignore */ focusVisibleClassName: PropTypes.string, /** * If `true`, the button will take up the full width of its container. * @default false */ fullWidth: PropTypes.bool, /** * The URL to link to when the button is clicked. * If defined, an `a` element will be used as the root node. */ href: PropTypes.string, /** * The size of the button. * `small` is equivalent to the dense button styling. * @default 'medium' */ size: PropTypes.oneOf(['large', 'medium', 'small']), /** * Element placed before the children. */ startIcon: PropTypes.node, /** * @ignore */ type: PropTypes.oneOfType([PropTypes.oneOf(['button', 'reset', 'submit']), PropTypes.string]), /** * The variant to use. * @default 'text' */ variant: PropTypes /* @typescript-to-proptypes-ignore */ .oneOfType([PropTypes.oneOf(['contained', 'outlined', 'text']), PropTypes.string]) } : void 0; export default withStyles(styles, { name: 'MuiButton' })(Button);
/* version: 0.2.73 */ var Organic = (function(w){ var o = { helpers: {}, lib: { atoms: {}, molecules: {} } } var require = function(v) { if(v == "./helpers/extend") { return o.helpers.extend; } else if(v == "/helpers/snippets" || v == "../../helpers/snippets") { return o.helpers.snippets; } else if(v == "/lib/atoms/atoms" || v == "../../lib/atoms/atoms" || v == "../atoms/atoms.js") { return o.lib.atoms.atoms; } else if(v == "../../helpers/units") { return o.helpers.units; } else if(v == "../../helpers/args") { return o.helpers.args; } else if(v == "path") { return { basename: function(f) { return f.split("/").pop(); } } } else { var moduleParts = v.split("/"); return (function getModule(currentModule) { var part = moduleParts.shift().replace(".js", ""); if(currentModule[part]) { if(moduleParts.length == 0) { return currentModule[part]; } else { return getModule(currentModule[part]) } } })(o); } } var __dirname = ''; var walkClientSide = function(res, obj, path) { if(typeof res == 'undefined') res = []; if(typeof obj == 'undefined') obj = o.lib; if(typeof path == 'undefined') path = "lib/"; for(var part in obj) { if(typeof obj[part] == 'function') { res.push(path + part + ".js"); } else { walkClientSide(res, obj[part], path + part + "/"); } } return res; };o.helpers.args = function(value) { value = value.toString().replace(/\/ /g, '/').split('/'); return value; } o.helpers.extend = function() { var process = function(destination, source) { for (var key in source) { if (hasOwnProperty.call(source, key)) { destination[key] = source[key]; } } return destination; }; var result = arguments[0]; for(var i=1; i<arguments.length; i++) { result = process(result, arguments[i]); } return result; } o.helpers.snippets = function() { // http://peters-playground.com/Emmet-Css-Snippets-for-Sublime-Text-2/ return { // Visual Formatting "pos": "position", "pos:s": "position:static", "pos:a": "position:absolute", "pos:r": "position:relative", "pos:f": "position:fixed", // "top": "top", "t:a": "top:auto", "rig": "right", "r:a": "right:auto", "bot": "bottom", // "b:a": "bottom:auto", // breaks the multiple comma selectors "lef": "left", "l:a": "left:auto", "zin": "z-index", "z:a": "z-index:auto", "fl": "float", "fl:n": "float:none", "fl:l": "float:left", "fl:r": "float:right", "cl": "clear", "cl:n": "clear:none", "cl:l": "clear:left", "cl:r": "clear:right", "cl:b": "clear:both", "dis": "display", "d:n": "display:none", "d:b": "display:block", "d:i": "display:inline", "d:ib": "display:inline-block", "d:li": "display:list-item", "d:ri": "display:run-in", "d:cp": "display:compact", "d:tb": "display:table", "d:itb": "display:inline-table", "d:tbcp": "display:table-caption", "d:tbcl": "display:table-column", "d:tbclg": "display:table-column-group", "d:tbhg": "display:table-header-group", "d:tbfg": "display:table-footer-group", "d:tbr": "display:table-row", "d:tbrg": "display:table-row-group", "d:tbc": "display:table-cell", "d:rb": "display:ruby", "d:rbb": "display:ruby-base", "d:rbbg": "display:ruby-base-group", "d:rbt": "display:ruby-text", "d:rbtg": "display:ruby-text-group", "vis": "visibility", "v:v": "visibility:visible", "v:h": "visibility:hidden", "v:c": "visibility:collapse", "ov": "overflow", "ov:v": "overflow:visible", "ov:h": "overflow:hidden", "ov:s": "overflow:scroll", "ov:a": "overflow:auto", "ovx": "overflow-x", "ovx:v": "overflow-x:visible", "ovx:h": "overflow-x:hidden", "ovx:s": "overflow-x:scroll", "ovx:a": "overflow-x:auto", "ovy": "overflow-y", "ovy:v": "overflow-y:visible", "ovy:h": "overflow-y:hidden", "ovy:s": "overflow-y:scroll", "ovy:a": "overflow-y:auto", "ovs": "overflow-style", "ovs:a": "overflow-style:auto", "ovs:s": "overflow-style:scrollbar", "ovs:p": "overflow-style:panner", "ovs:m": "overflow-style:move", "ovs:mq": "overflow-style:marquee", "zoo": "zoom:1", "cp": "clip", "cp:a": "clip:auto", "cp:r": "clip:rect()", "rz": "resize", "rz:n": "resize:none", "rz:b": "resize:both", "rz:h": "resize:horizontal", "rz:v": "resize:vertical", "cur": "cursor", "cur:a": "cursor:auto", "cur:d": "cursor:default", "cur:c": "cursor:crosshair", "cur:ha": "cursor:hand", "cur:he": "cursor:help", "cur:m": "cursor:move", "cur:p": "cursor:pointer", "cur:t": "cursor:text", // Margin & Padding "mar": "margin", "m:au": "margin:0 auto", "mt": "margin-top", "mt:a": "margin-top:auto", "mr": "margin-right", "mr:a": "margin-right:auto", "mb": "margin-bottom", "mb:a": "margin-bottom:auto", "ml": "margin-left", "ml:a": "margin-left:auto", "pad": "padding", "pt": "padding-top", "pr": "padding-right", "pb": "padding-bottom", "pl": "padding-left", // Box Sizing "bxz": "box-sizing", "bxz:cb": "box-sizing:content-box", "bxz:bb": "box-sizing:border-box", "bxsh": "box-shadow", "bxsh:n": "box-shadow:none", "bxsh+": "box-shadow:0 0 0 #000", "wid": "width", "w:a": "width:auto", "hei": "height", "h:a": "height:auto", "maw": "max-width", "maw:n": "max-width:none", "mah": "max-height", "mah:n": "max-height:none", "miw": "min-width", "mih": "min-height", // Font "fon": "font", "fon+": "font:1em Arial, sans-serif", "fw": "font-weight", "fw:n": "font-weight:normal", "fw:b": "font-weight:bold", "fw:br": "font-weight:bolder", "fw:lr": "font-weight:lighter", "fs": "font-style", "fs:n": "font-style:normal", "fs:i": "font-style:italic", "fs:o": "font-style:oblique", "fv": "font-variant", "fv:n": "font-variant:normal", "fv:sc": "font-variant:small-caps", "fz": "font-size", "fza": "font-size-adjust", "fza:n": "font-size-adjust:none", "ff": "font-family", "ff:s": "font-family:serif", "ff:ss": "font-family:sans-serif", "ff:c": "font-family:cursive", "ff:f": "font-family:fantasy", "ff:m": "font-family:monospace", "fef": "font-effect", "fef:n": "font-effect:none", "fef:eg": "font-effect:engrave", "fef:eb": "font-effect:emboss", "fef:o": "font-effect:outline", "fem": "font-emphasize", "femp": "font-emphasize-position", "femp:b": "font-emphasize-position:before", "femp:a": "font-emphasize-position:after", "fems": "font-emphasize-style", "fems:n": "font-emphasize-style:none", "fems:ac": "font-emphasize-style:accent", "fems:dt": "font-emphasize-style:dot", "fems:c": "font-emphasize-style:circle", "fems:ds": "font-emphasize-style:disc", "fsm": "font-smooth", "fsm:au": "font-smooth:auto", "fsm:n": "font-smooth:never", "fsm:al": "font-smooth:always", "fst": "font-stretch", "fst:n": "font-stretch:normal", "fst:uc": "font-stretch:ultra-condensed", "fst:ec": "font-stretch:extra-condensed", "fst:c": "font-stretch:condensed", "fst:sc": "font-stretch:semi-condensed", "fst:se": "font-stretch:semi-expanded", "fst:e": "font-stretch:expanded", "fst:ee": "font-stretch:extra-expanded", "fst:ue": "font-stretch:ultra-expanded", // Text "va": "vertical-align", "va:sup": "vertical-align:super", "va:t": "vertical-align:top", "va:tt": "vertical-align:text-top", "va:m": "vertical-align:middle", "va:bl": "vertical-align:baseline", "va:b": "vertical-align:bottom", "va:tb": "vertical-align:text-bottom", "va:sub": "vertical-align:sub", "ta": "text-align", "ta:le": "text-align:left", "ta:c": "text-align:center", "ta:r": "text-align:right", "ta:j": "text-align:justify", "tal": "text-align-last", "tal:a": "text-align-last:auto", "tal:l": "text-align-last:left", "tal:c": "text-align-last:center", "tal:r": "text-align-last:right", "td": "text-decoration", "td:n": "text-decoration:none", "td:u": "text-decoration:underline", "td:o": "text-decoration:overline", "td:l": "text-decoration:line-through", "te": "text-emphasis", "te:n": "text-emphasis:none", "te:ac": "text-emphasis:accent", "te:dt": "text-emphasis:dot", "te:c": "text-emphasis:circle", "te:ds": "text-emphasis:disc", "te:b": "text-emphasis:before", "te:a": "text-emphasis:after", "th": "text-height", "th:a": "text-height:auto", "th:f": "text-height:font-size", "th:t": "text-height:text-size", "th:m": "text-height:max-size", "ti": "text-indent", "ti:-": "text-indent:-9999px", "tj": "text-justify", "tj:a": "text-justify:auto", "tj:iw": "text-justify:inter-word", "tj:ii": "text-justify:inter-ideograph", "tj:ic": "text-justify:inter-cluster", "tj:d": "text-justify:distribute", "tj:k": "text-justify:kashida", "tj:t": "text-justify:tibetan", "to": "text-outline", "to+": "text-outline:0 0 #000", "to:n": "text-outline:none", "tr": "text-replace", "tr:n": "text-replace:none", "tt": "text-transform", "tt:n": "text-transform:none", "tt:c": "text-transform:capitalize", "tt:u": "text-transform:uppercase", "tt:l": "text-transform:lowercase", "tw": "text-wrap", "tw:n": "text-wrap:normal", "tw:no": "text-wrap:none", "tw:u": "text-wrap:unrestricted", "tw:s": "text-wrap:suppress", "tsh": "text-shadow", "tsh+": "text-shadow:0 0 0 #000", "tsh:n": "text-shadow:none", "lh": "line-height", "lts": "letter-spacing", "whs": "white-space", "whs:n": "white-space:normal", "whs:p": "white-space:pre", "whs:nw": "white-space:nowrap", "whs:pw": "white-space:pre-wrap", "whs:pl": "white-space:pre-line", "whsc": "white-space-collapse", "whsc:n": "white-space-collapse:normal", "whsc:k": "white-space-collapse:keep-all", "whsc:l": "white-space-collapse:loose", "whsc:bs": "white-space-collapse:break-strict", "whsc:ba": "white-space-collapse:break-all", "wob": "word-break", "wob:n": "word-break:normal", "wob:k": "word-break:keep-all", "wob:l": "word-break:loose", "wob:bs": "word-break:break-strict", "wob:ba": "word-break:break-all", "wos": "word-spacing", "wow": "word-wrap", "wow:nm": "word-wrap:normal", "wow:n": "word-wrap:none", "wow:u": "word-wrap:unrestricted", "wow:s": "word-wrap:suppress", // Background "bg": "background", "bg+": "background:#fff url() 0 0 no-repeat", "bg:n": "background:none", "bgc": "background-color:#fff", "bgc:t": "background-color:transparent", "bgi": "background-image:url()", "bgi:n": "background-image:none", "bgr": "background-repeat", "bgr:r": "background-repeat:repeat", "bgr:n": "background-repeat:no-repeat", "bgr:x": "background-repeat:repeat-x", "bgr:y": "background-repeat:repeat-y", "bga": "background-attachment", "bga:f": "background-attachment:fixed", "bga:s": "background-attachment:scroll", "bgp": "background-position:0 0", "bgpx": "background-position-x", "bgpy": "background-position-y", "bgbk": "background-break", "bgbk:bb": "background-break:bounding-box", "bgbk:eb": "background-break:each-box", "bgbk:c": "background-break:continuous", "bgcp": "background-clip", "bgcp:bb": "background-clip:border-box", "bgcp:pb": "background-clip:padding-box", "bgcp:cb": "background-clip:content-box", "bgcp:nc": "background-clip:no-clip", "bgo": "background-origin", "bgo:pb": "background-origin:padding-box", "bgo:bb": "background-origin:border-box", "bgo:cb": "background-origin:content-box", "bgz": "background-size", "bgz:a": "background-size:auto", "bgz:ct": "background-size:contain", "bgz:cv": "background-size:cover", // Color "col": "color:#000", "op": "opacity", "hsl": "hsl(359,100%,100%)", "hsla": "hsla(359,100%,100%,0.5)", "rgb": "rgb(255,255,255)", "rgba": "rgba(255,255,255,0.5)", // Generated Content "ct": "content", "ct:n": "content:normal", "ct:oq": "content:open-quote", "ct:noq": "content:no-open-quote", "ct:cq": "content:close-quote", "ct:ncq": "content:no-close-quote", "ct:a": "content:attr()", "ct:c": "content:counter()", "ct:cs": "content:counters()", "quo": "quotes", "q:n": "quotes:none", "q:ru": "quotes:'\00AB' '\00BB' '\201E' '\201C'", "q:en": "quotes:'\201C' '\201D' '\2018' '\2019'", "coi": "counter-increment", "cor": "counter-reset", // Outline "out": "outline", "o:n": "outline:none", "oo": "outline-offset", "ow": "outline-width", "os": "outline-style", "oc": "outline-color:#000", "oc:i": "outline-color:invert", // Table "tbl": "table-layout", "tbl:a": "table-layout:auto", "tbl:f": "table-layout:fixed", "cps": "caption-side", "cps:t": "caption-side:top", "cps:b": "caption-side:bottom", "ec": "empty-cells", "ec:s": "empty-cells:show", "ec:h": "empty-cells:hide", // Border "bd": "border", "bd+": "border:1px solid #000", "bd:n": "border:none", "bdbk": "border-break", "bdbk:c": "border-break:close", "bdcl": "border-collapse", "bdcl:c": "border-collapse:collapse", "bdcl:s": "border-collapse:separate", "bdc": "border-color:#000", "bdi": "border-image:url()", "bdi:n": "border-image:none", "bdti": "border-top-image:url()", "bdti:n": "border-top-image:none", "bdri": "border-right-image:url()", "bdri:n": "border-right-image:none", "bdbi": "border-bottom-image:url()", "bdbi:n": "border-bottom-image:none", "bdli": "border-left-image:url()", "bdli:n": "border-left-image:none", "bdci": "border-corner-image:url()", "bdci:n": "border-corner-image:none", "bdci:c": "border-corner-image:continue", "bdtli": "border-top-left-image:url()", "bdtli:n": "border-top-left-image:none", "bdtli:c": "border-top-left-image:continue", "bdtri": "border-top-right-image:url()", "bdtri:n": "border-top-right-image:none", "bdtri:c": "border-top-right-image:continue", "bdbri": "border-bottom-right-image:url()", "bdbri:n": "border-bottom-right-image:none", "bdbri:c": "border-bottom-right-image:continue", "bdbli": "border-bottom-left-image:url()", "bdbli:n": "border-bottom-left-image:none", "bdbli:c": "border-bottom-left-image:continue", "bdf": "border-fit", "bdf:c": "border-fit:clip", "bdf:r": "border-fit:repeat", "bdf:sc": "border-fit:scale", "bdf:st": "border-fit:stretch", "bdf:ow": "border-fit:overwrite", "bdf:of": "border-fit:overflow", "bdf:sp": "border-fit:space", "bdlt": "border-length", "bdlt:a": "border-length:auto", "bdsp": "border-spacing", "bds": "border-style", "bds:n": "border-style:none", "bds:h": "border-style:hidden", "bds:dt": "border-style:dotted", "bds:ds": "border-style:dashed", "bds:s": "border-style:solid", "bds:db": "border-style:double", "bds:dd": "border-style:dot-dash", "bds:ddd": "border-style:dot-dot-dash", "bds:w": "border-style:wave", "bds:g": "border-style:groove", "bds:r": "border-style:ridge", "bds:i": "border-style:inset", "bds:o": "border-style:outset", "bdw": "border-width", "bdt": "border-top", "bdt+": "border-top:1px solid #000", "bdt:n": "border-top:none", "bdtw": "border-top-width", "bdts": "border-top-style", "bdts:n": "border-top-style:none", "bdtc": "border-top-color:#000", "bdr": "border-right", "bdr+": "border-right:1px solid #000", "bdr:n": "border-right:none", "bdrw": "border-right-width", "bdrs": "border-right-style", "bdrs:n": "border-right-style:none", "bdrc": "border-right-color:#000", "bdb": "border-bottom", "bdb+": "border-bottom:1px solid #000", "bdb:n": "border-bottom:none", "bdbw": "border-bottom-width", "bdbs": "border-bottom-style", "bdbs:n": "border-bottom-style:none", "bdbc": "border-bottom-color:#000", "bdl": "border-left", "bdl+": "border-left:1px solid #000", "bdl:n": "border-left:none", "bdlw": "border-left-width", "bdls": "border-left-style", "bdls:n": "border-left-style:none", "bdlc": "border-left-color:#000", "bdrsa": "border-radius", "bdtrrs": "border-top-right-radius", "bdtlrs": "border-top-left-radius", "bdbrrs": "border-bottom-right-radius", "bdblrs": "border-bottom-left-radius", // Lists "lis": "list-style", "lis:n": "list-style:none", "lisp": "list-style-position", "lisp:i": "list-style-position:inside", "lisp:o": "list-style-position:outside", "list": "list-style-type", "list:n": "list-style-type:none", "list:d": "list-style-type:disc", "list:c": "list-style-type:circle", "list:s": "list-style-type:square", "list:dc": "list-style-type:decimal", "list:dclz": "list-style-type:decimal-leading-zero", "list:lr": "list-style-type:lower-roman", "list:ur": "list-style-type:upper-roman", "lisi": "list-style-image", "lisi:n": "list-style-image:none", // Print "pgbb": "page-break-before", "pgbb:au": "page-break-before:auto", "pgbb:al": "page-break-before:always", "pgbb:l": "page-break-before:left", "pgbb:r": "page-break-before:right", "pgbi": "page-break-inside", "pgbi:au": "page-break-inside:auto", "pgbi:av": "page-break-inside:avoid", "pgba": "page-break-after", "pgba:au": "page-break-after:auto", "pgba:al": "page-break-after:always", "pgba:l": "page-break-after:left", "pgba:r": "page-break-after:right", "orp": "orphans", "widows": "widows", // Others "ipt": "!important", "ffa": "@font-family {<br>&nbsp;&nbsp;font-family:;<br>&nbsp;&nbsp;src:url();<br>}", "ffa+": "@font-family {<br>&nbsp;&nbsp;font-family: 'FontName';<br>&nbsp;&nbsp;src: url('FileName.eot');<br>&nbsp;&nbsp;src: url('FileName.eot?#iefix') format('embedded-opentype'),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;url('FileName.woff') format('woff'),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;url('FileName.ttf') format('truetype'),<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;url('FileName.svg#FontName') format('svg');<br>&nbsp;&nbsp;font-style: normal;<br>&nbsp;&nbsp;font-weight: normal;<br>}", "imp": "@import url()", "mp": "@media print {}", "bg:ie": "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='x.png',sizingMethod='crop')", "op:ie": "filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=100)", "op:ms": "-ms-filter:'progid:DXImageTransform.Microsoft.Alpha(Opacity=100)'", "trf": "transform", "trf:r": "transform:rotate(90deg)", "trf:sc": "transform:scale(x,y)", "trf:scx": "transform:scaleX(x)", "trf:scy": "transform:scaleY(y)", "trf:skx": "transform:skewX(90deg)", "trf:sky": "transform:skewY(90deg)", "trf:t": "transform:translate(x,y)", "trf:tx": "transform:translateX(x)", "trf:ty": "transform:translateY(y)", "trs": "transition", "trsde": "transition-delay", "trsdu": "transition-duration", "trsp": "transition-property", "trstf": "transition-timing-function", "ani": "animation", "ann": "animation-name", "adu": "animation-duration", "atf": "animation-timing-function", "ade": "animation-delay", "aic": "animation-iteration-count", "adi": "animation-direction", "aps": "animation-play-state", "key": "@keyframes {}", "ms": "@media screen and () {}", "in": "inherit", "tra": "transparent", "beh": "behavior:url()", "cha": "@charset''", // Pseudo Class "ac": " :active{}", "ac:a": "&:active{}", "af": " :after{}", "af:a": "&:after{}", "be": " :before{}", "be:a": "&:before{}", "ch": " :checked{}", "ch:a": "&:checked{}", "dsa": " :disabled{}<i>[da]</i>", "dsa:a": "&:disabled{}<i>[da:a]</i>", "en": " :enabled{}", "en:a": "&:enabled{}", "fc": " :first-child{}", "fc:a": "&:first-child{}", "fle": " :first-letter{}", "fle:a": "&:first-letter{}", "fli": " :first-line{}", "fli:a": "&:first-line{}", "foc": " :focus{}", "foc:a": "&:focus{}", "ho": " :hover{}", "ho:a": "&:hover{}", "ln": " :lang(){}", "ln:a": "&:lang(){}", "lc": " :last-child{}", "lc:a": "&:last-child{}", "li": " :link{}", "li:a": "&:link{}", "nc": " :nth-child(){}", "nc:a": "&:nth-child(){}", "vit": " :visited{}", "vit:a": "&:visited{}", "tgt": " :target{}", "tgt:a": "&:target{}", "fot": " :first-of-type{}", "fot:a": "&:first-of-type{}", "lot": " :last-of-type{}", "lot:a": "&:last-of-type{}", "not": " :nth-of-type(){}", "not:a": "&:nth-of-type(){}", // Scss & Sass "ext": "@extend", "inc": "@include", "mix": "@mixin", "ieh": "ie-hex-str()" }; } o.helpers.units = function(v, def) { if(!v.toString().match(/[%|in|cm|mm|em|ex|pt|pc|px|deg|ms|s]/)) return v + (def || '%'); else return v; } var extend = require("./helpers/extend"), fs = require('fs'), path = require('path') var walk = function(dir) { return walkClientSide(); var results = []; var list = fs.readdirSync(dir); for(var i=0; i<list.length; i++) { var file = dir + '/' + list[i]; var stat = fs.statSync(file); if (stat && stat.isDirectory()) { results = results.concat(walk(file)); } else { results.push(file); } } return results; }; o.index = { absurd: null, init: function(decoration) { if(typeof decoration != 'undefined') { this.absurd = decoration; } // getting atoms and molecules var files = walk(__dirname + "/lib/"), self = this; for(var i=0; i<files.length; i++) { var file = path.basename(files[i]); (function(m) { var module = require(m); self.absurd.plugin(file.replace(".js", ""), function(absurd, value) { return module(value); }); })(files[i]); } // converting snippets to plugins var snippets = require(__dirname + "/helpers/snippets")(); for(var atom in snippets) { atom = atom.split(":"); (function(pluginName) { self.absurd.plugin(pluginName, function(absurd, value, prefixes) { if(prefixes === false) { prefixes = ''; } var s, r = {}; if(s = snippets[pluginName + ':' + value]) { s = s.split(':'); r[prefixes + s[0]] = s[1] || ''; } else if(s = snippets[pluginName]){ r[prefixes + s] = value; } return r; }); })(atom.shift()); } return this; } } o.lib.atoms.atoms = function(value) { var toObj = function(value, r) { value = value.replace(/( )?:( )?/, ':').split(':'); r = r || {}; r[value[0]] = value[1] || ''; return r; } var processArr = function(value) { var r = {}; for(var i=0; i<value.length; i++) { toObj(value[i], r); } return r; } if(typeof value == 'string') { return processArr(value.replace(/( )?\/( )?/g, '/').split('/')); } else if(typeof value == 'object') { if(!(value instanceof Array)) { return value; } else { return processArr(value); } } } /*! Animate.css - http://daneden.me/animate Licensed under the MIT license Copyright (c) 2013 Daniel Eden 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. */ o.lib.molecules.animate = function(value) { var r = {}; r['-w-animation-duration'] = '1s'; r['-w-animation-fill-mode'] = 'both'; switch(value) { case "bounce": r.keyframes = { name: "bounce", frames: { "0%, 20%, 50%, 80%, 100%": { "-w-transform": "translateY(0)" }, "40%": { "-w-transform": "translateY(-30px)" }, "60%": { "-w-transform": "translateY(-15px)" } } } r["-w-animation-name"] = "bounce"; break; case "flash": r.keyframes = { name: "flash", frames: { "0%, 50%, 100%": { "opacity": "1" }, "25%, 75%": { "opacity": "0" } } } r["-w-animation-name"] = "flash"; break; case "pulse": r.keyframes = { name: "pulse", frames: { "0%": { "-w-transform": "scale(1)" }, "50%": { "-w-transform": "scale(1.1)" }, "100%": { "-w-transform": "scale(1)" } } } r["-w-animation-name"] = "pulse"; break; case "shake": r.keyframes = { name: "shake", frames: { "0%, 100%": { "-w-transform": "translateX(0)" }, "10%, 30%, 50%, 70%, 90%": { "-w-transform": "translateX(-10px)" }, "20%, 40%, 60%, 80%": { "-w-transform": "translateX(10px)" } } } r["-w-animation-name"] = "shake"; break; case "swing": r.keyframes = { name: "swing", frames: { "20%": { "-w-transform": "rotate(15deg)" }, "40%": { "-w-transform": "rotate(-10deg)" }, "60%": { "-w-transform": "rotate(5deg)" }, "80%": { "-w-transform": "rotate(-5deg)" }, "100%": { "-w-transform": "rotate(0deg)" } } } r["-w-animation-name"] = "swing"; break; case "tada": r.keyframes = { name: "tada", frames: { "0%": { "-w-transform": "scale(1)" }, "10%, 20%": { "-w-transform": "scale(0.9) rotate(-3deg)" }, "30%, 50%, 70%, 90%": { "-w-transform": "scale(1.1) rotate(3deg)" }, "40%, 60%, 80%": { "-w-transform": "scale(1.1) rotate(-3deg)" }, "100%": { "-w-transform": "scale(1) rotate(0)" } } } r["-w-animation-name"] = "tada"; break; case "wobble": r.keyframes = { name: "wobble", frames: { "0%": { "-w-transform": "translateX(0%)" }, "15%": { "-w-transform": "translateX(-25%) rotate(-5deg)" }, "30%": { "-w-transform": "translateX(20%) rotate(3deg)" }, "45%": { "-w-transform": "translateX(-15%) rotate(-3deg)" }, "60%": { "-w-transform": "translateX(10%) rotate(2deg)" }, "75%": { "-w-transform": "translateX(-5%) rotate(-1deg)" }, "100%": { "-w-transform": "translateX(0%)" } } } r["-w-animation-name"] = "wobble"; break; case "bounceIn": r.keyframes = { name: "bounceIn", frames: { "0%": { "opacity": "0", "-w-transform": "scale(.3)" }, "50%": { "opacity": "1", "-w-transform": "scale(1.05)" }, "70%": { "-w-transform": "scale(.9)" }, "100%": { "-w-transform": "scale(1)" } } } r["-w-animation-name"] = "bounceIn"; break; case "bounceInDown": r.keyframes = { name: "bounceInDown", frames: { "0%": { "opacity": "0", "-w-transform": "translateY(-2000px)" }, "60%": { "opacity": "1", "-w-transform": "translateY(30px)" }, "80%": { "-w-transform": "translateY(-10px)" }, "100%": { "-w-transform": "translateY(0)" } } } r["-w-animation-name"] = "bounceInDown"; break; case "bounceInLeft": r.keyframes = { name: "bounceInLeft", frames: { "0%": { "opacity": "0", "-w-transform": "translateX(-2000px)" }, "60%": { "opacity": "1", "-w-transform": "translateX(30px)" }, "80%": { "-w-transform": "translateX(-10px)" }, "100%": { "-w-transform": "translateX(0)" } } } r["-w-animation-name"] = "bounceInLeft"; break; case "bounceInRight": r.keyframes = { name: "bounceInRight", frames: { "0%": { "opacity": "0", "-w-transform": "translateX(2000px)" }, "60%": { "opacity": "1", "-w-transform": "translateX(-30px)" }, "80%": { "-w-transform": "translateX(10px)" }, "100%": { "-w-transform": "translateX(0)" } } } r["-w-animation-name"] = "bounceInRight"; break; case "bounceInUp": r.keyframes = { name: "bounceInUp", frames: { "0%": { "opacity": "0", "-w-transform": "translateY(2000px)" }, "60%": { "opacity": "1", "-w-transform": "translateY(-30px)" }, "80%": { "-w-transform": "translateY(10px)" }, "100%": { "-w-transform": "translateY(0)" } } } r["-w-animation-name"] = "bounceInUp"; break; case "bounceOut": r.keyframes = { name: "bounceOut", frames: { "0%": { "-w-transform": "scale(1)" }, "25%": { "-w-transform": "scale(.95)" }, "50%": { "opacity": "1", "-w-transform": "scale(1.1)" }, "100%": { "opacity": "0", "-w-transform": "scale(.3)" } } } r["-w-animation-name"] = "bounceOut"; break; case "bounceOutDown": r.keyframes = { name: "bounceOutDown", frames: { "0%": { "-w-transform": "translateY(0)" }, "20%": { "opacity": "1", "-w-transform": "translateY(-20px)" }, "100%": { "opacity": "0", "-w-transform": "translateY(2000px)" } } } r["-w-animation-name"] = "bounceOutDown"; break; case "bounceOutLeft": r.keyframes = { name: "bounceOutLeft", frames: { "0%": { "-w-transform": "translateX(0)" }, "20%": { "opacity": "1", "-w-transform": "translateX(20px)" }, "100%": { "opacity": "0", "-w-transform": "translateX(-2000px)" } } } r["-w-animation-name"] = "bounceOutLeft"; break; case "bounceOutRight": r.keyframes = { name: "bounceOutRight", frames: { "0%": { "-w-transform": "translateX(0)" }, "20%": { "opacity": "1", "-w-transform": "translateX(-20px)" }, "100%": { "opacity": "0", "-w-transform": "translateX(2000px)" } } } r["-w-animation-name"] = "bounceOutRight"; break; case "bounceOutUp": r.keyframes = { name: "bounceOutUp", frames: { "0%": { "-w-transform": "translateY(0)" }, "20%": { "opacity": "1", "-w-transform": "translateY(20px)" }, "100%": { "opacity": "0", "-w-transform": "translateY(-2000px)" } } } r["-w-animation-name"] = "bounceOutUp"; break; case "fadeIn": r.keyframes = { name: "fadeIn", frames: { "0%": { "opacity": "0" }, "100%": { "opacity": "1" } } } r["-w-animation-name"] = "fadeIn"; break; case "fadeInDown": r.keyframes = { name: "fadeInDown", frames: { "0%": { "opacity": "0", "-w-transform": "translateY(-20px)" }, "100%": { "opacity": "1", "-w-transform": "translateY(0)" } } } r["-w-animation-name"] = "fadeInDown"; break; case "fadeInDownBig": r.keyframes = { name: "fadeInDownBig", frames: { "0%": { "opacity": "0", "-w-transform": "translateY(-2000px)" }, "100%": { "opacity": "1", "-w-transform": "translateY(0)" } } } r["-w-animation-name"] = "fadeInDownBig"; break; case "fadeInLeft": r.keyframes = { name: "fadeInLeft", frames: { "0%": { "opacity": "0", "-w-transform": "translateX(-20px)" }, "100%": { "opacity": "1", "-w-transform": "translateX(0)" } } } r["-w-animation-name"] = "fadeInLeft"; break; case "fadeInLeftBig": r.keyframes = { name: "fadeInLeftBig", frames: { "0%": { "opacity": "0", "-w-transform": "translateX(-2000px)" }, "100%": { "opacity": "1", "-w-transform": "translateX(0)" } } } r["-w-animation-name"] = "fadeInLeftBig"; break; case "fadeInRight": r.keyframes = { name: "fadeInRight", frames: { "0%": { "opacity": "0", "-w-transform": "translateX(20px)" }, "100%": { "opacity": "1", "-w-transform": "translateX(0)" } } } r["-w-animation-name"] = "fadeInRight"; break; case "fadeInRightBig": r.keyframes = { name: "fadeInRightBig", frames: { "0%": { "opacity": "0", "-w-transform": "translateX(2000px)" }, "100%": { "opacity": "1", "-w-transform": "translateX(0)" } } } r["-w-animation-name"] = "fadeInRightBig"; break; case "fadeInUp": r.keyframes = { name: "fadeInUp", frames: { "0%": { "opacity": "0", "-w-transform": "translateY(20px)" }, "100%": { "opacity": "1", "-w-transform": "translateY(0)" } } } r["-w-animation-name"] = "fadeInUp"; break; case "fadeInUpBig": r.keyframes = { name: "fadeInUpBig", frames: { "0%": { "opacity": "0", "-w-transform": "translateY(2000px)" }, "100%": { "opacity": "1", "-w-transform": "translateY(0)" } } } r["-w-animation-name"] = "fadeInUpBig"; break; case "fadeOut": r.keyframes = { name: "fadeOut", frames: { "0%": { "opacity": "1" }, "100%": { "opacity": "0" } } } r["-w-animation-name"] = "fadeOut"; break; case "fadeOutDown": r.keyframes = { name: "fadeOutDown", frames: { "0%": { "opacity": "1", "-w-transform": "translateY(0)" }, "100%": { "opacity": "0", "-w-transform": "translateY(20px)" } } } r["-w-animation-name"] = "fadeOutDown"; break; case "fadeOutDownBig": r.keyframes = { name: "fadeOutDownBig", frames: { "0%": { "opacity": "1", "-w-transform": "translateY(0)" }, "100%": { "opacity": "0", "-w-transform": "translateY(2000px)" } } } r["-w-animation-name"] = "fadeOutDownBig"; break; case "fadeOutLeft": r.keyframes = { name: "fadeOutLeft", frames: { "0%": { "opacity": "1", "-w-transform": "translateX(0)" }, "100%": { "opacity": "0", "-w-transform": "translateX(-20px)" } } } r["-w-animation-name"] = "fadeOutLeft"; break; case "fadeOutLeftBig": r.keyframes = { name: "fadeOutLeftBig", frames: { "0%": { "opacity": "1", "-w-transform": "translateX(0)" }, "100%": { "opacity": "0", "-w-transform": "translateX(-2000px)" } } } r["-w-animation-name"] = "fadeOutLeftBig"; break; case "fadeOutRight": r.keyframes = { name: "fadeOutRight", frames: { "0%": { "opacity": "1", "-w-transform": "translateX(0)" }, "100%": { "opacity": "0", "-w-transform": "translateX(20px)" } } } r["-w-animation-name"] = "fadeOutRight"; break; case "fadeOutRightBig": r.keyframes = { name: "fadeOutRightBig", frames: { "0%": { "opacity": "1", "-w-transform": "translateX(0)" }, "100%": { "opacity": "0", "-w-transform": "translateX(2000px)" } } } r["-w-animation-name"] = "fadeOutRightBig"; break; case "fadeOutUp": r.keyframes = { name: "fadeOutUp", frames: { "0%": { "opacity": "1", "-w-transform": "translateY(0)" }, "100%": { "opacity": "0", "-w-transform": "translateY(-20px)" } } } r["-w-animation-name"] = "fadeOutUp"; break; case "fadeOutUpBig": r.keyframes = { name: "fadeOutUpBig", frames: { "0%": { "opacity": "1", "-w-transform": "translateY(0)" }, "100%": { "opacity": "0", "-w-transform": "translateY(-2000px)" } } } r["-w-animation-name"] = "fadeOutUpBig"; break; case "flip": r.keyframes = { name: "flip", frames: { "0%": { "-w-transform": "perspective(400px) translateZ(0) rotateY(0) scale(1)", "animation-timing-function": "ease-out" }, "40%": { "-w-transform": "perspective(400px) translateZ(150px) rotateY(170deg) scale(1)", "animation-timing-function": "ease-out" }, "50%": { "-w-transform": "perspective(400px) translateZ(150px) rotateY(190deg) scale(1)", "animation-timing-function": "ease-in" }, "80%": { "-w-transform": "perspective(400px) translateZ(0) rotateY(360deg) scale(.95)", "animation-timing-function": "ease-in" }, "100%": { "-w-transform": "perspective(400px) translateZ(0) rotateY(360deg) scale(1)", "animation-timing-function": "ease-in" } } } r["-w-animation-name"] = "flip"; break; case "flipInX": r.keyframes = { name: "flipInX", frames: { "0%": { "-w-transform": "perspective(400px) rotateX(90deg)", "opacity": "0" }, "40%": { "-w-transform": "perspective(400px) rotateX(-10deg)" }, "70%": { "-w-transform": "perspective(400px) rotateX(10deg)" }, "100%": { "-w-transform": "perspective(400px) rotateX(0deg)", "opacity": "1" } } } r["-w-animation-name"] = "flipInX"; break; case "flipInY": r.keyframes = { name: "flipInY", frames: { "0%": { "-w-transform": "perspective(400px) rotateY(90deg)", "opacity": "0" }, "40%": { "-w-transform": "perspective(400px) rotateY(-10deg)" }, "70%": { "-w-transform": "perspective(400px) rotateY(10deg)" }, "100%": { "-w-transform": "perspective(400px) rotateY(0deg)", "opacity": "1" } } } r["-w-animation-name"] = "flipInY"; break; case "flipOutX": r.keyframes = { name: "flipOutX", frames: { "0%": { "-w-transform": "perspective(400px) rotateX(0deg)", "opacity": "1" }, "100%": { "-w-transform": "perspective(400px) rotateX(90deg)", "opacity": "0" } } } r["-w-animation-name"] = "flipOutX"; break; case "flipOutY": r.keyframes = { name: "flipOutY", frames: { "0%": { "-w-transform": "perspective(400px) rotateY(0deg)", "opacity": "1" }, "100%": { "-w-transform": "perspective(400px) rotateY(90deg)", "opacity": "0" } } } r["-w-animation-name"] = "flipOutY"; break; case "lightSpeedIn": r.keyframes = { name: "lightSpeedIn", frames: { "0%": { "-w-transform": "translateX(100%) skewX(-30deg)", "opacity": "0" }, "60%": { "-w-transform": "translateX(-20%) skewX(30deg)", "opacity": "1" }, "80%": { "-w-transform": "translateX(0%) skewX(-15deg)", "opacity": "1" }, "100%": { "-w-transform": "translateX(0%) skewX(0deg)", "opacity": "1" } } } r["-w-animation-name"] = "lightSpeedIn"; break; case "lightSpeedOut": r.keyframes = { name: "lightSpeedOut", frames: { "0%": { "-w-transform": "translateX(0%) skewX(0deg)", "opacity": "1" }, "100%": { "-w-transform": "translateX(100%) skewX(-30deg)", "opacity": "0" } } } r["-w-animation-name"] = "lightSpeedOut"; break; case "rotateIn": r.keyframes = { name: "rotateIn", frames: { "0%": { "transform-origin": "center center", "-w-transform": "rotate(-200deg)", "opacity": "0" }, "100%": { "transform-origin": "center center", "-w-transform": "rotate(0)", "opacity": "1" } } } r["-w-animation-name"] = "rotateIn"; break; case "rotateInDownLeft": r.keyframes = { name: "rotateInDownLeft", frames: { "0%": { "transform-origin": "left bottom", "-w-transform": "rotate(-90deg)", "opacity": "0" }, "100%": { "transform-origin": "left bottom", "-w-transform": "rotate(0)", "opacity": "1" } } } r["-w-animation-name"] = "rotateInDownLeft"; break; case "rotateInDownRight": r.keyframes = { name: "rotateInDownRight", frames: { "0%": { "transform-origin": "right bottom", "-w-transform": "rotate(90deg)", "opacity": "0" }, "100%": { "transform-origin": "right bottom", "-w-transform": "rotate(0)", "opacity": "1" } } } r["-w-animation-name"] = "rotateInDownRight"; break; case "rotateInUpLeft": r.keyframes = { name: "rotateInUpLeft", frames: { "0%": { "transform-origin": "left bottom", "-w-transform": "rotate(90deg)", "opacity": "0" }, "100%": { "transform-origin": "left bottom", "-w-transform": "rotate(0)", "opacity": "1" } } } r["-w-animation-name"] = "rotateInUpLeft"; break; case "rotateInUpRight": r.keyframes = { name: "rotateInUpRight", frames: { "0%": { "transform-origin": "right bottom", "-w-transform": "rotate(-90deg)", "opacity": "0" }, "100%": { "transform-origin": "right bottom", "-w-transform": "rotate(0)", "opacity": "1" } } } r["-w-animation-name"] = "rotateInUpRight"; break; case "rotateOut": r.keyframes = { name: "rotateOut", frames: { "0%": { "transform-origin": "center center", "-w-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "center center", "-w-transform": "rotate(200deg)", "opacity": "0" } } } r["-w-animation-name"] = "rotateOut"; break; case "rotateOutDownLeft": r.keyframes = { name: "rotateOutDownLeft", frames: { "0%": { "transform-origin": "left bottom", "-w-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "left bottom", "-w-transform": "rotate(90deg)", "opacity": "0" } } } r["-w-animation-name"] = "rotateOutDownLeft"; break; case "rotateOutDownRight": r.keyframes = { name: "rotateOutDownRight", frames: { "0%": { "transform-origin": "right bottom", "-w-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "right bottom", "-w-transform": "rotate(-90deg)", "opacity": "0" } } } r["-w-animation-name"] = "rotateOutDownRight"; break; case "rotateOutUpLeft": r.keyframes = { name: "rotateOutUpLeft", frames: { "0%": { "transform-origin": "left bottom", "-w-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "left bottom", "-w-transform": "rotate(-90deg)", "opacity": "0" } } } r["-w-animation-name"] = "rotateOutUpLeft"; break; case "rotateOutUpRight": r.keyframes = { name: "rotateOutUpRight", frames: { "0%": { "transform-origin": "right bottom", "-w-transform": "rotate(0)", "opacity": "1" }, "100%": { "transform-origin": "right bottom", "-w-transform": "rotate(90deg)", "opacity": "0" } } } r["-w-animation-name"] = "rotateOutUpRight"; break; case "slideInDown": r.keyframes = { name: "slideInDown", frames: { "0%": { "opacity": "0", "-w-transform": "translateY(-2000px)" }, "100%": { "-w-transform": "translateY(0)" } } } r["-w-animation-name"] = "slideInDown"; break; case "slideInLeft": r.keyframes = { name: "slideInLeft", frames: { "0%": { "opacity": "0", "-w-transform": "translateX(-2000px)" }, "100%": { "-w-transform": "translateX(0)" } } } r["-w-animation-name"] = "slideInLeft"; break; case "slideInRight": r.keyframes = { name: "slideInRight", frames: { "0%": { "opacity": "0", "-w-transform": "translateX(2000px)" }, "100%": { "-w-transform": "translateX(0)" } } } r["-w-animation-name"] = "slideInRight"; break; case "slideOutLeft": r.keyframes = { name: "slideOutLeft", frames: { "0%": { "-w-transform": "translateX(0)" }, "100%": { "opacity": "0", "-w-transform": "translateX(-2000px)" } } } r["-w-animation-name"] = "slideOutLeft"; break; case "slideOutRight": r.keyframes = { name: "slideOutRight", frames: { "0%": { "-w-transform": "translateX(0)" }, "100%": { "opacity": "0", "-w-transform": "translateX(2000px)" } } } r["-w-animation-name"] = "slideOutRight"; break; case "slideOutUp": r.keyframes = { name: "slideOutUp", frames: { "0%": { "-w-transform": "translateY(0)" }, "100%": { "opacity": "0", "-w-transform": "translateY(-2000px)" } } } r["-w-animation-name"] = "slideOutUp"; break; case "hinge": r.keyframes = { name: "hinge", frames: { "0%": { "-w-transform": "rotate(0)", "transform-origin": "top left", "animation-timing-function": "ease-in-out" }, "20%, 60%": { "-w-transform": "rotate(80deg)", "transform-origin": "top left", "animation-timing-function": "ease-in-out" }, "40%": { "-w-transform": "rotate(60deg)", "transform-origin": "top left", "animation-timing-function": "ease-in-out" }, "80%": { "-w-transform": "rotate(60deg) translateY(0)", "opacity": "1", "transform-origin": "top left", "animation-timing-function": "ease-in-out" }, "100%": { "-w-transform": "translateY(700px)", "opacity": "0" } } } r["-w-animation-name"] = "hinge"; break; case "rollIn": r.keyframes = { name: "rollIn", frames: { "0%": { "opacity": "0", "-w-transform": "translateX(-100%) rotate(-120deg)" }, "100%": { "opacity": "1", "-w-transform": "translateX(0px) rotate(0deg)" } } } r["-w-animation-name"] = "rollIn"; break; case "rollOut": r.keyframes = { name: "rollOut", frames: { "0%": { "opacity": "1", "-w-transform": "translateX(0px) rotate(0deg)" }, "100%": { "opacity": "0", "-w-transform": "translateX(100%) rotate(120deg)" } } } r["-w-animation-name"] = "rollOut"; break; default: r = { "-wmo-animation": value }; break; } return r; } o.lib.molecules.cf = function(value) { var r = {}, clearing = { content: '" "', display: 'table', clear: 'both' }; switch(value) { case 'before': r['&:before'] = clearing; break; case 'after': r['&:after'] = clearing; break; default: r['&:before'] = clearing; r['&:after'] = clearing; break; } return r; } o.lib.molecules.metrics = function(value) { var r = {}, args = require('../../helpers/args')(value); if(args.length == 2) { if(args[0] != '') { r.margin = args[0]; } if(args[1] != '') { r.padding = args[1]; } return r; } else { return { margin: args[0], padding: args[1] || args[0] } } } o.lib.molecules.moveto = function(value) { var units = require('../../helpers/units'), args = require('../../helpers/args')(value), x = units(!args[0] || args[0] == '' ? 0 : args[0], 'px'), y = units(!args[1] || args[1] == '' ? 0 : args[1], 'px'), z = units(!args[2] || args[2] == '' ? 0 : args[2], 'px'); if(args.length == 2) { return {"-ws-trf": ">translate(" + x + "," + y + ")"}; } else if(args.length == 3) { return {"-ws-trf": ">translate3d(" + x + "," + y + "," + z + ")"}; } } o.lib.molecules.rotateto = function(value) { var units = require('../../helpers/units'), args = require('../../helpers/args')(value); if(args.length == 1) { return {"-ws-trf": ">rotate(" + units(args[0], 'deg') + ")"}; } } o.lib.molecules.scaleto = function(value) { var args = require('../../helpers/args')(value), x = !args[0] || args[0] == '' ? 0 : args[0], y = !args[1] || args[1] == '' ? 0 : args[1]; if(args.length == 2) { return {"-ws-trf": ">scale(" + x + "," + y + ")"}; } } o.lib.molecules.size = function(value) { var units = require('../../helpers/units'), args = require('../../helpers/args')(value), r = {}; if(args.length == 2) { if(args[0] != '') { r.width = units(args[0]); } if(args[1] != '') { r.height = units(args[1]); } return r; } else { return { width: units(args[0]), height: units(args[0]) } } }; return o.index; })(window);
'use strict'; var padRight = require('pad-right'); var utils = require('../utils'); var bold = utils.colors.bold; var cyan = utils.colors.cyan; var gray = utils.colors.gray; /** * Show a help menu. * * ```sh * $ app --help * ``` * @name help * @api public */ module.exports = function(app, base, options) { return function(val, key, config, next) { config.run = false; console.log(format(help(app, base, options))); next(); }; }; /** * Create `help` documentation */ function help(app, base, options) { var configname = base.option('help.configname') || app.constructor.name.toLowerCase(); var appname = base.option('help.appname') || base._name; var command = base.option('help.command') || appname; return { heading: `Usage: ${cyan(command + ' <command> [options]')}` + '\n' + `\nCommand: ${configname} or tasks to run` + `\n\nOptions:`, examples: 'Examples:' + '\n' + gray(`\n # run ${configname} "foo"`) + bold(`\n $ ${command} foo`) + '\n' + gray(`\n # run task "bar" from ${configname} "foo"`) + bold(`\n $ ${command} foo:bar`) + '\n' + gray(`\n # run multiple tasks from ${configname} "foo"`) + bold(`\n $ ${command} foo:bar,baz,qux`) + '\n' + gray(`\n # run a sub-generator from ${configname} "foo"`) + bold(`\n $ ${command} foo.abc`) + '\n' + gray(`\n # run task "xyz" from sub-generator "foo.abc"`) + bold(`\n $ ${command} foo.abc:xyz`) + '\n' + gray(`\n ${upper(appname)} attempts to automatically determine if "foo" is a task or ${configname}.` + `\n If there is a conflict, you can force ${appname} to run ${configname} "foo"` + `\n by specifying its default task. Example: \`$ ${command} foo:default\``) + '\n', options: { config: { description: `Save a configuration value to the \`${command}\` object in package.json`, example: '--config=toc:false', short: 'c' }, cwd: { description: 'Set or display the current working directory', example: '', short: null }, data: { description: 'Define data. API equivalent of `app.data()`', example: '', short: 'd' }, diff: { hide: true, description: 'this command is not enabled yet', example: '', short: null }, disable: { description: 'Disable an option. API equivalent of "app.disable(\'foo\')"', example: '', short: null }, enable: { description: 'Enable an option. API equivalent of "app.enable(\'foo\')"', example: '', short: null }, global: { description: 'Save a global configuration value to use as a default', example: '--global=toc:false', short: 'g' }, help: { description: 'Display this help menu', example: '', short: 'h' }, init: { description: 'Prompts for configuration values and stores the answers', example: '', short: 'i' }, option: { description: 'Define options. API equivalent of `app.option()`', example: '', short: 'o' }, run: { description: 'Force tasks to run regardless of command line flags used', example: '', short: null }, silent: { description: 'Silence all tasks and updaters in the terminal', example: '--silent', short: 'S' }, show: { description: 'Display the value of <key>', example: '--show <key>', command: 'key', short: null }, version: { description: 'Display the current version of ' + appname, example: '', short: 'V' }, verbose: { description: 'Display all verbose logging messages', example: '', short: 'v' } }, footer: '' }; } function format(help) { var heading = help.heading || ''; var options = help.options || {}; var footer = help.footer || ''; var optsList = ''; for (var key in options) { if (options.hasOwnProperty(key)) { var val = options[key]; if (val.hide === true) continue; if (val.command) { key += ' <' + val.command + '>'; } optsList += toFlag(key, val.short); optsList += val.description + '\n'; } } var res = '\n' + heading + '\n\n'; res += optsList + '\n'; res += footer; return res + help.examples; } function upper(str) { return str.charAt(0).toUpperCase() + str.slice(1); } function toFlag(key, short, max) { var str = ' --' + key + shortKey(short); return padRight(str, 20, ' '); } function shortKey(sh) { return sh ? (', '+ '-' + sh) : ' '; }
// Simple phantom.js integration script // Adapted from Modernizr function waitFor (testFx, onReady, timeOutMillis) { var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 5001 //< Default Max Timout is 5s , start = new Date ().getTime () , condition = false , interval = setInterval (function () { if ((new Date ().getTime () - start < maxtimeOutMillis) && !condition) { // If not time-out yet and condition not yet fulfilled condition = (typeof(testFx) === "string" ? eval (testFx) : testFx ()) //< defensive code } else { if (!condition) { // If condition still not fulfilled (timeout but condition is 'false') console.log ("'waitFor()' timeout") phantom.exit (1) } else { // Condition fulfilled (timeout and/or condition is 'true') typeof(onReady) === "string" ? eval (onReady) : onReady () //< Do what it's supposed to do once the condition is fulfilled clearInterval (interval) //< Stop this interval } } }, 100) //< repeat check every 100ms } if (phantom.args.length === 0 || phantom.args.length > 2) { console.log ('Usage: phantom.js URL') phantom.exit () } var page = new WebPage () // Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") page.onConsoleMessage = function (msg) { console.log (msg) }; page.open (phantom.args[0], function (status) { if (status !== "success") { console.log ("Unable to access network") phantom.exit () } else { waitFor (function () { return page.evaluate (function () { var el = document.getElementById ('qunit-testresult') if (el && el.innerText.match ('completed')) { return true } return false }) }, function () { var failedNum = page.evaluate (function () { var el = document.getElementById ('qunit-testresult') try { return el.getElementsByClassName ('failed')[0].innerHTML } catch (e) { } return 10000 }); phantom.exit ((parseInt (failedNum, 10) > 0) ? 1 : 0) }) } })
YUI.add('enc-hex-test', function (Y) { var C = CryptoJS; Y.Test.Runner.add(new Y.Test.Case({ name: 'Hex', testStringify: function () { Y.Assert.areEqual('12345678', C.enc.Hex.stringify(C.lib.WordArray.create([0x12345678]))); }, testParse: function () { Y.Assert.areEqual(C.lib.WordArray.create([0x12345678]).toString(), C.enc.Hex.parse('12345678').toString()); } })); }, '$Rev$');
var express = require('../') , request = require('supertest') , utils = require('../lib/utils') , assert = require('assert'); var app1 = express(); app1.use(function(req, res, next){ res.format({ 'text/plain': function(){ res.send('hey'); }, 'text/html': function(){ res.send('<p>hey</p>'); }, 'application/json': function(a, b, c){ assert(req == a); assert(res == b); assert(next == c); res.send({ message: 'hey' }); } }); }); app1.use(function(err, req, res, next){ if (!err.types) throw err; res.send(err.status, 'Supports: ' + err.types.join(', ')); }) var app2 = express(); app2.use(function(req, res, next){ res.format({ text: function(){ res.send('hey') }, html: function(){ res.send('<p>hey</p>') }, json: function(){ res.send({ message: 'hey' }) } }); }); app2.use(function(err, req, res, next){ res.send(err.status, 'Supports: ' + err.types.join(', ')); }) var app3 = express(); app3.use(function(req, res, next){ res.format({ text: function(){ res.send('hey') }, default: function(){ res.send('default') } }) }); var app4 = express(); app4.get('/', function(req, res, next){ res.format({ text: function(){ res.send('hey') }, html: function(){ res.send('<p>hey</p>') }, json: function(){ res.send({ message: 'hey' }) } }); }); app4.use(function(err, req, res, next){ res.send(err.status, 'Supports: ' + err.types.join(', ')); }) describe('res', function(){ describe('.format(obj)', function(){ describe('with canonicalized mime types', function(){ test(app1); }) describe('with extnames', function(){ test(app2); }) describe('given .default', function(){ it('should be invoked instead of auto-responding', function(done){ request(app3) .get('/') .set('Accept: text/html') .expect('default', done); }) }) describe('in router', function(){ test(app4); }) describe('in router', function(){ var app = express(); var router = express.Router(); router.get('/', function(req, res, next){ res.format({ text: function(){ res.send('hey') }, html: function(){ res.send('<p>hey</p>') }, json: function(){ res.send({ message: 'hey' }) } }); }); router.use(function(err, req, res, next){ res.send(err.status, 'Supports: ' + err.types.join(', ')); }) app.use(router) test(app) }) }) }) function test(app) { it('should utilize qvalues in negotiation', function(done){ request(app) .get('/') .set('Accept', 'text/html; q=.5, application/json, */*; q=.1') .expect({"message":"hey"}, done); }) it('should allow wildcard type/subtypes', function(done){ request(app) .get('/') .set('Accept', 'text/html; q=.5, application/*, */*; q=.1') .expect({"message":"hey"}, done); }) it('should default the Content-Type', function(done){ request(app) .get('/') .set('Accept', 'text/html; q=.5, text/plain') .expect('Content-Type', 'text/plain; charset=utf-8') .expect('hey', done); }) it('should set the correct charset for the Content-Type', function() { request(app) .get('/') .set('Accept', 'text/html') .expect('Content-Type', 'text/html; charset=utf-8'); request(app) .get('/') .set('Accept', 'text/plain') .expect('Content-Type', 'text/plain; charset=utf-8'); request(app) .get('/') .set('Accept', 'application/json') .expect('Content-Type', 'application/json'); }) it('should Vary: Accept', function(done){ request(app) .get('/') .set('Accept', 'text/html; q=.5, text/plain') .expect('Vary', 'Accept', done); }) describe('when Accept is not present', function(){ it('should invoke the first callback', function(done){ request(app) .get('/') .expect('hey', done); }) }) describe('when no match is made', function(){ it('should should respond with 406 not acceptable', function(done){ request(app) .get('/') .set('Accept', 'foo/bar') .expect('Supports: text/plain, text/html, application/json') .expect(406, done) }) }) }
"use strict"; module.exports = require("./is-implemented")() ? Array.prototype.splice : require("./shim");
import { Quaternion } from '../math/Quaternion.js'; import { Vector3 } from '../math/Vector3.js'; import { Matrix4 } from '../math/Matrix4.js'; import { EventDispatcher } from './EventDispatcher.js'; import { Euler } from '../math/Euler.js'; import { Layers } from './Layers.js'; import { Matrix3 } from '../math/Matrix3.js'; import { _Math } from '../math/Math.js'; /** * @author mrdoob / http://mrdoob.com/ * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley * @author elephantatwork / www.elephantatwork.ch */ var object3DId = 0; function Object3D() { Object.defineProperty( this, 'id', { value: object3DId ++ } ); this.uuid = _Math.generateUUID(); this.name = ''; this.type = 'Object3D'; this.parent = null; this.children = []; this.up = Object3D.DefaultUp.clone(); var position = new Vector3(); var rotation = new Euler(); var quaternion = new Quaternion(); var scale = new Vector3( 1, 1, 1 ); function onRotationChange() { quaternion.setFromEuler( rotation, false ); } function onQuaternionChange() { rotation.setFromQuaternion( quaternion, undefined, false ); } rotation.onChange( onRotationChange ); quaternion.onChange( onQuaternionChange ); Object.defineProperties( this, { position: { enumerable: true, value: position }, rotation: { enumerable: true, value: rotation }, quaternion: { enumerable: true, value: quaternion }, scale: { enumerable: true, value: scale }, modelViewMatrix: { value: new Matrix4() }, normalMatrix: { value: new Matrix3() } } ); this.matrix = new Matrix4(); this.matrixWorld = new Matrix4(); this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; this.matrixWorldNeedsUpdate = false; this.layers = new Layers(); this.visible = true; this.castShadow = false; this.receiveShadow = false; this.frustumCulled = true; this.renderOrder = 0; this.userData = {}; } Object3D.DefaultUp = new Vector3( 0, 1, 0 ); Object3D.DefaultMatrixAutoUpdate = true; Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { constructor: Object3D, isObject3D: true, onBeforeRender: function () {}, onAfterRender: function () {}, applyMatrix: function ( matrix ) { this.matrix.multiplyMatrices( matrix, this.matrix ); this.matrix.decompose( this.position, this.quaternion, this.scale ); }, applyQuaternion: function ( q ) { this.quaternion.premultiply( q ); return this; }, setRotationFromAxisAngle: function ( axis, angle ) { // assumes axis is normalized this.quaternion.setFromAxisAngle( axis, angle ); }, setRotationFromEuler: function ( euler ) { this.quaternion.setFromEuler( euler, true ); }, setRotationFromMatrix: function ( m ) { // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) this.quaternion.setFromRotationMatrix( m ); }, setRotationFromQuaternion: function ( q ) { // assumes q is normalized this.quaternion.copy( q ); }, rotateOnAxis: function () { // rotate object on axis in object space // axis is assumed to be normalized var q1 = new Quaternion(); return function rotateOnAxis( axis, angle ) { q1.setFromAxisAngle( axis, angle ); this.quaternion.multiply( q1 ); return this; }; }(), rotateOnWorldAxis: function () { // rotate object on axis in world space // axis is assumed to be normalized // method assumes no rotated parent var q1 = new Quaternion(); return function rotateOnWorldAxis( axis, angle ) { q1.setFromAxisAngle( axis, angle ); this.quaternion.premultiply( q1 ); return this; }; }(), rotateX: function () { var v1 = new Vector3( 1, 0, 0 ); return function rotateX( angle ) { return this.rotateOnAxis( v1, angle ); }; }(), rotateY: function () { var v1 = new Vector3( 0, 1, 0 ); return function rotateY( angle ) { return this.rotateOnAxis( v1, angle ); }; }(), rotateZ: function () { var v1 = new Vector3( 0, 0, 1 ); return function rotateZ( angle ) { return this.rotateOnAxis( v1, angle ); }; }(), translateOnAxis: function () { // translate object by distance along axis in object space // axis is assumed to be normalized var v1 = new Vector3(); return function translateOnAxis( axis, distance ) { v1.copy( axis ).applyQuaternion( this.quaternion ); this.position.add( v1.multiplyScalar( distance ) ); return this; }; }(), translateX: function () { var v1 = new Vector3( 1, 0, 0 ); return function translateX( distance ) { return this.translateOnAxis( v1, distance ); }; }(), translateY: function () { var v1 = new Vector3( 0, 1, 0 ); return function translateY( distance ) { return this.translateOnAxis( v1, distance ); }; }(), translateZ: function () { var v1 = new Vector3( 0, 0, 1 ); return function translateZ( distance ) { return this.translateOnAxis( v1, distance ); }; }(), localToWorld: function ( vector ) { return vector.applyMatrix4( this.matrixWorld ); }, worldToLocal: function () { var m1 = new Matrix4(); return function worldToLocal( vector ) { return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); }; }(), lookAt: function () { // This method does not support objects with rotated and/or translated parent(s) var m1 = new Matrix4(); var vector = new Vector3(); return function lookAt( x, y, z ) { if ( x.isVector3 ) { vector.copy( x ); } else { vector.set( x, y, z ); } if ( this.isCamera ) { m1.lookAt( this.position, vector, this.up ); } else { m1.lookAt( vector, this.position, this.up ); } this.quaternion.setFromRotationMatrix( m1 ); }; }(), add: function ( object ) { if ( arguments.length > 1 ) { for ( var i = 0; i < arguments.length; i ++ ) { this.add( arguments[ i ] ); } return this; } if ( object === this ) { console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); return this; } if ( ( object && object.isObject3D ) ) { if ( object.parent !== null ) { object.parent.remove( object ); } object.parent = this; object.dispatchEvent( { type: 'added' } ); this.children.push( object ); } else { console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); } return this; }, remove: function ( object ) { if ( arguments.length > 1 ) { for ( var i = 0; i < arguments.length; i ++ ) { this.remove( arguments[ i ] ); } return this; } var index = this.children.indexOf( object ); if ( index !== - 1 ) { object.parent = null; object.dispatchEvent( { type: 'removed' } ); this.children.splice( index, 1 ); } return this; }, getObjectById: function ( id ) { return this.getObjectByProperty( 'id', id ); }, getObjectByName: function ( name ) { return this.getObjectByProperty( 'name', name ); }, getObjectByProperty: function ( name, value ) { if ( this[ name ] === value ) return this; for ( var i = 0, l = this.children.length; i < l; i ++ ) { var child = this.children[ i ]; var object = child.getObjectByProperty( name, value ); if ( object !== undefined ) { return object; } } return undefined; }, getWorldPosition: function ( optionalTarget ) { var result = optionalTarget || new Vector3(); this.updateMatrixWorld( true ); return result.setFromMatrixPosition( this.matrixWorld ); }, getWorldQuaternion: function () { var position = new Vector3(); var scale = new Vector3(); return function getWorldQuaternion( optionalTarget ) { var result = optionalTarget || new Quaternion(); this.updateMatrixWorld( true ); this.matrixWorld.decompose( position, result, scale ); return result; }; }(), getWorldRotation: function () { var quaternion = new Quaternion(); return function getWorldRotation( optionalTarget ) { var result = optionalTarget || new Euler(); this.getWorldQuaternion( quaternion ); return result.setFromQuaternion( quaternion, this.rotation.order, false ); }; }(), getWorldScale: function () { var position = new Vector3(); var quaternion = new Quaternion(); return function getWorldScale( optionalTarget ) { var result = optionalTarget || new Vector3(); this.updateMatrixWorld( true ); this.matrixWorld.decompose( position, quaternion, result ); return result; }; }(), getWorldDirection: function () { var quaternion = new Quaternion(); return function getWorldDirection( optionalTarget ) { var result = optionalTarget || new Vector3(); this.getWorldQuaternion( quaternion ); return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); }; }(), raycast: function () {}, traverse: function ( callback ) { callback( this ); var children = this.children; for ( var i = 0, l = children.length; i < l; i ++ ) { children[ i ].traverse( callback ); } }, traverseVisible: function ( callback ) { if ( this.visible === false ) return; callback( this ); var children = this.children; for ( var i = 0, l = children.length; i < l; i ++ ) { children[ i ].traverseVisible( callback ); } }, traverseAncestors: function ( callback ) { var parent = this.parent; if ( parent !== null ) { callback( parent ); parent.traverseAncestors( callback ); } }, updateMatrix: function () { this.matrix.compose( this.position, this.quaternion, this.scale ); this.matrixWorldNeedsUpdate = true; }, updateMatrixWorld: function ( force ) { if ( this.matrixAutoUpdate ) this.updateMatrix(); if ( this.matrixWorldNeedsUpdate || force ) { if ( this.parent === null ) { this.matrixWorld.copy( this.matrix ); } else { this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); } this.matrixWorldNeedsUpdate = false; force = true; } // update children var children = this.children; for ( var i = 0, l = children.length; i < l; i ++ ) { children[ i ].updateMatrixWorld( force ); } }, toJSON: function ( meta ) { // meta is a string when called from JSON.stringify var isRootObject = ( meta === undefined || typeof meta === 'string' ); var output = {}; // meta is a hash used to collect geometries, materials. // not providing it implies that this is the root object // being serialized. if ( isRootObject ) { // initialize meta obj meta = { geometries: {}, materials: {}, textures: {}, images: {}, shapes: {} }; output.metadata = { version: 4.5, type: 'Object', generator: 'Object3D.toJSON' }; } // standard Object3D serialization var object = {}; object.uuid = this.uuid; object.type = this.type; if ( this.name !== '' ) object.name = this.name; if ( this.castShadow === true ) object.castShadow = true; if ( this.receiveShadow === true ) object.receiveShadow = true; if ( this.visible === false ) object.visible = false; if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; object.matrix = this.matrix.toArray(); // function serialize( library, element ) { if ( library[ element.uuid ] === undefined ) { library[ element.uuid ] = element.toJSON( meta ); } return element.uuid; } if ( this.geometry !== undefined ) { object.geometry = serialize( meta.geometries, this.geometry ); var parameters = this.geometry.parameters; if ( parameters !== undefined && parameters.shapes !== undefined ) { var shapes = parameters.shapes; if ( Array.isArray( shapes ) ) { for ( var i = 0, l = shapes.length; i < l; i ++ ) { var shape = shapes[ i ]; serialize( meta.shapes, shape ); } } else { serialize( meta.shapes, shapes ); } } } if ( this.material !== undefined ) { if ( Array.isArray( this.material ) ) { var uuids = []; for ( var i = 0, l = this.material.length; i < l; i ++ ) { uuids.push( serialize( meta.materials, this.material[ i ] ) ); } object.material = uuids; } else { object.material = serialize( meta.materials, this.material ); } } // if ( this.children.length > 0 ) { object.children = []; for ( var i = 0; i < this.children.length; i ++ ) { object.children.push( this.children[ i ].toJSON( meta ).object ); } } if ( isRootObject ) { var geometries = extractFromCache( meta.geometries ); var materials = extractFromCache( meta.materials ); var textures = extractFromCache( meta.textures ); var images = extractFromCache( meta.images ); var shapes = extractFromCache( meta.shapes ); if ( geometries.length > 0 ) output.geometries = geometries; if ( materials.length > 0 ) output.materials = materials; if ( textures.length > 0 ) output.textures = textures; if ( images.length > 0 ) output.images = images; if ( shapes.length > 0 ) output.shapes = shapes; } output.object = object; return output; // extract data from the cache hash // remove metadata on each item // and return as array function extractFromCache( cache ) { var values = []; for ( var key in cache ) { var data = cache[ key ]; delete data.metadata; values.push( data ); } return values; } }, clone: function ( recursive ) { return new this.constructor().copy( this, recursive ); }, copy: function ( source, recursive ) { if ( recursive === undefined ) recursive = true; this.name = source.name; this.up.copy( source.up ); this.position.copy( source.position ); this.quaternion.copy( source.quaternion ); this.scale.copy( source.scale ); this.matrix.copy( source.matrix ); this.matrixWorld.copy( source.matrixWorld ); this.matrixAutoUpdate = source.matrixAutoUpdate; this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; this.layers.mask = source.layers.mask; this.visible = source.visible; this.castShadow = source.castShadow; this.receiveShadow = source.receiveShadow; this.frustumCulled = source.frustumCulled; this.renderOrder = source.renderOrder; this.userData = JSON.parse( JSON.stringify( source.userData ) ); if ( recursive === true ) { for ( var i = 0; i < source.children.length; i ++ ) { var child = source.children[ i ]; this.add( child.clone() ); } } return this; } } ); export { Object3D };
/** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ var Pointer = Highcharts.Pointer = function (chart, options) { this.init(chart, options); }; Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var chartOptions = options.chart, chartEvents = chartOptions.events, zoomType = useCanVG ? '' : chartOptions.zoomType, inverted = chart.inverted, zoomX, zoomY; // Store references this.options = options; this.chart = chart; // Zoom status this.zoomX = zoomX = /x/.test(zoomType); this.zoomY = zoomY = /y/.test(zoomType); this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); // Do we need to handle click on a touch device? this.runChartClick = chartEvents && !!chartEvents.click; this.pinchDown = []; this.lastValidTouch = {}; if (options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e, chartPosition) { var chartX, chartY, ePos; // common IE normalizing e = e || win.event; if (!e.target) { e.target = e.srcElement; } // Framework specific normalizing (#1165) e = washMouseEvent(e); // iOS ePos = e.touches ? e.touches.item(0) : e; // Get mouse position if (!chartPosition) { this.chartPosition = chartPosition = offset(this.chart.container); } // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is // for IE10 quirks mode within framesets chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function (axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * Return the index in the tooltipPoints array, corresponding to pixel position in * the plot area. */ getIndex: function (e) { var chart = this.chart; return chart.inverted ? chart.plotHeight + chart.plotTop - e.chartY : e.chartX - chart.plotLeft; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function (e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, point, points, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, j, distance = chart.chartWidth, index = pointer.getIndex(e), anchor; // shared tooltip if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) { points = []; // loop over all series and find the ones with points closest to the mouse i = series.length; for (j = 0; j < i; j++) { if (series[j].visible && series[j].options.enableMouseTracking !== false && !series[j].noSharedTooltip && series[j].tooltipPoints.length) { point = series[j].tooltipPoints[index]; if (point && point.series) { // not a dummy point, #1544 point._dist = mathAbs(index - point.clientX); distance = mathMin(distance, point._dist); points.push(point); } } } // remove furthest points i = points.length; while (i--) { if (points[i]._dist > distance) { points.splice(i, 1); } } // refresh the tooltip if necessary if (points.length && (points[0].clientX !== pointer.hoverX)) { tooltip.refresh(points, e); pointer.hoverX = points[0].clientX; } } // separate tooltip and general mouse events if (hoverSeries && hoverSeries.tracker) { // only use for line-type series with common tracker // get the point point = hoverSeries.tooltipPoints[index]; // a new point is hovered, refresh the tooltip if (point && point !== hoverPoint) { // trigger the events point.onMouseOver(e); } } else if (tooltip && tooltip.followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } // Start the event listener to pick up the tooltip if (tooltip && !pointer._onDocumentMouseMove) { pointer._onDocumentMouseMove = function (e) { pointer.onDocumentMouseMove(e); }; addEvent(doc, 'mousemove', pointer._onDocumentMouseMove); } // Draw independent crosshairs each(chart.axes, function (axis) { axis.drawCrosshair(e, pick(point, hoverPoint)); }); }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function (allowMove) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint; // Narrow in allowMove allowMove = allowMove && tooltip && tooltipPoints; // Check if the points have moved outside the plot area, #1003 if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) { allowMove = false; } // Just move the tooltip, #349 if (allowMove) { tooltip.refresh(tooltipPoints); if (hoverPoint) { // #2500 hoverPoint.setState(hoverPoint.state, true); } // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(); } if (pointer._onDocumentMouseMove) { removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove); pointer._onDocumentMouseMove = null; } // Remove crosshairs each(chart.axes, function (axis) { axis.hideCrosshair(); }); pointer.hoverX = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart, seriesAttribs; // Scale each series each(chart.series, function (series) { seriesAttribs = attribs || series.getPlotBox(); // #1701 if (series.xAxis && series.xAxis.zoomEnabled) { series.group.attr(seriesAttribs); if (series.markerGroup) { series.markerGroup.attr(seriesAttribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(seriesAttribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Run translation operations */ pinchTranslate: function (zoomHor, zoomVert, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { if (zoomHor) { this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (zoomVert) { this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = forcedScale || 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function () { if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { // TODO: implement clipping for inverted charts clip[xy] = clipXY - plotLeftTop; clip[wh] = selectionWH; } scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY; transformScale = inverted ? 1 / scale : scale; selectionMarker[wh] = selectionWH; selectionMarker[xy] = selectionXY; transform[scaleKey] = scale; transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start)); }, /** * Handle touch events with two touches */ pinch: function (e) { var self = this, chart = self.chart, pinchDown = self.pinchDown, followTouchMove = chart.tooltip && chart.tooltip.options.followTouchMove, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, zoomHor = self.zoomHor || self.pinchHor, zoomVert = self.zoomVert || self.pinchVert, hasZoom = zoomHor || zoomVert, selectionMarker = self.selectionMarker, transform = {}, fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') && chart.runTrackerClick) || chart.runChartClick), clip = {}; // On touch devices, only proceed to trigger click if a handler is defined if ((hasZoom || followTouchMove) && !fireClickEvent) { e.preventDefault(); } // Normalize each touch map(touches, function (e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function (e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function (axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(axis.dataMin), max = axis.toPixels(axis.dataMax), absMin = mathMin(min, max), absMax = mathMax(min, max); // Store the bounds for use in the touchmove handler bounds.min = mathMin(axis.pos, absMin - minPixelPadding); bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding); } }); // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop }, chart.plotBox); } self.pinchTranslate(zoomHor, zoomVert, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } } }, /** * Start a drag operation */ dragStart: function (e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; chart.mouseDownY = this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function (e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY; // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside) { if (!this.selectionMarker) { this.selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (this.selectionMarker && zoomHor) { size = chartX - mouseDownX; this.selectionMarker.attr({ width: mathAbs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (this.selectionMarker && zoomVert) { size = chartY - mouseDownY; this.selectionMarker.attr({ height: mathAbs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !this.selectionMarker && chartOptions.panning) { chart.pan(e, chartOptions.panning); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { xAxis: [], yAxis: [], originalEvent: e.originalEvent || e }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.x, selectionTop = selectionBox.y, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled) { var horiz = axis.horiz, selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop)), selectionMax = axis.toValue((horiz ? selectionLeft + selectionBox.width : selectionTop + selectionBox.height)); if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859 selectionData[axis.coll].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes, max: mathMax(selectionMin, selectionMax) }); runZoom = true; } } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups(); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged > 10; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function (e) { e = this.normalize(e); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function (e) { this.drop(e); }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function (e) { var chart = this.chart, chartPosition = this.chartPosition, hoverSeries = chart.hoverSeries; e = this.normalize(e, chartPosition); // If we're outside, hide the tooltip if (chartPosition && hoverSeries && !this.inClass(e.target, 'highcharts-tracker') && !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function () { this.reset(); this.chartPosition = null; // also reset the chart position, used in #149 fix }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function (e) { var chart = this.chart; // normalize e = this.normalize(e); if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if ((this.inClass(e.target, 'highcharts-tracker') || chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function (element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function (e) { var series = this.chart.hoverSeries, relatedTarget = e.relatedTarget || e.toElement, relatedSeries = relatedTarget && relatedTarget.point && relatedTarget.point.series; // #2499 if (series && !series.options.stickyTracking && !this.inClass(relatedTarget, PREFIX + 'tooltip') && relatedSeries !== series) { series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop, inverted = chart.inverted, chartPosition, plotX, plotY; e = this.normalize(e); e.cancelBubble = true; // IE specific if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) { chartPosition = this.chartPosition; plotX = hoverPoint.plotX; plotY = hoverPoint.plotY; // add page position info extend(hoverPoint, { pageX: chartPosition.left + plotLeft + (inverted ? chart.plotWidth - plotY : plotX), pageY: chartPosition.top + plotTop + (inverted ? chart.plotHeight - plotX : plotY) }); // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event if (chart.hoverPoint) { // it may be destroyed (#1844) hoverPoint.firePointEvent('click', e); } // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, onContainerTouchStart: function (e) { var chart = this.chart; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { // Prevent the click pseudo event from firing unless it is set in the options /*if (!chart.runChartClick) { e.preventDefault(); }*/ // Run mouse events and display tooltip etc this.runPointActions(e); this.pinch(e); } else { // Hide the tooltip on touching outside the plot area (#1203) this.reset(); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchMove: function (e) { if (e.touches.length === 1 || e.touches.length === 2) { this.pinch(e); } }, onDocumentTouchEnd: function (e) { this.drop(e); }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function () { var pointer = this, container = pointer.chart.container, events; this._events = events = [ [container, 'onmousedown', 'onContainerMouseDown'], [container, 'onmousemove', 'onContainerMouseMove'], [container, 'onclick', 'onContainerClick'], [container, 'mouseleave', 'onContainerMouseLeave'], [doc, 'mouseup', 'onDocumentMouseUp'] ]; if (hasTouch) { events.push( [container, 'ontouchstart', 'onContainerTouchStart'], [container, 'ontouchmove', 'onContainerTouchMove'], [doc, 'touchend', 'onDocumentTouchEnd'] ); } each(events, function (eventConfig) { // First, create the callback function that in turn calls the method on Pointer pointer['_' + eventConfig[2]] = function (e) { pointer[eventConfig[2]](e); }; // Now attach the function, either as a direct property or through addEvent if (eventConfig[1].indexOf('on') === 0) { eventConfig[0][eventConfig[1]] = pointer['_' + eventConfig[2]]; } else { addEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]); } }); }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var pointer = this; // Release all DOM events each(pointer._events, function (eventConfig) { if (eventConfig[1].indexOf('on') === 0) { eventConfig[0][eventConfig[1]] = null; // delete breaks oldIE } else { removeEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]); } }); delete pointer._events; // memory and CPU leak clearInterval(pointer.tooltipTimeout); } }; /** * PointTrackerMixin */ var TrackerMixin = Highcharts.TrackerMixin = { drawTrackerPoint: function () { var series = this, chart = series.chart, pointer = chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; if (chart.hoverSeries !== series) { series.onMouseOver(); } while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function (point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); series._hasTracking = true; } }, /** * 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. */ 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, cursor = options.cursor, css = cursor && { cursor: cursor }, singlePoints = series.singlePoints, singlePoint, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }; // 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]); } } } // handle single points for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = renderer.path(trackerPath) .attr({ 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .add(series.group); // 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. each([series.tracker, series.markerGroup], function (tracker) { tracker.addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } } };
/** @license * @pnp/common v1.0.1 - pnp - provides shared functionality across all pnp libraries * MIT (https://github.com/pnp/pnp/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: http://officedev.github.io/PnP-JS-Core * source: https://github.com/pnp/pnp * bugs: https://github.com/pnp/pnp/issues */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@pnp/logging'), require('tslib')) : typeof define === 'function' && define.amd ? define(['exports', '@pnp/logging', 'tslib'], factory) : (factory((global.pnp = global.pnp || {}, global.pnp.common = {}),global.pnp.logging,global.tslib_1)); }(this, (function (exports,logging,tslib_1) { 'use strict'; /** * Reads a blob as text * * @param blob The data to read */ function readBlobAsText(blob) { return readBlobAs(blob, "string"); } /** * Reads a blob into an array buffer * * @param blob The data to read */ function readBlobAsArrayBuffer(blob) { return readBlobAs(blob, "buffer"); } /** * Generic method to read blob's content * * @param blob The data to read * @param mode The read mode */ function readBlobAs(blob, mode) { return new Promise(function (resolve, reject) { try { var reader = new FileReader(); reader.onload = function (e) { resolve(e.target.result); }; switch (mode) { case "string": reader.readAsText(blob); break; case "buffer": reader.readAsArrayBuffer(blob); break; } } catch (e) { reject(e); } }); } /** * Generic dictionary */ var Dictionary = /** @class */ (function () { /** * Creates a new instance of the Dictionary<T> class * * @constructor */ function Dictionary(keys, values) { if (keys === void 0) { keys = []; } if (values === void 0) { values = []; } this.keys = keys; this.values = values; } /** * Gets a value from the collection using the specified key * * @param key The key whose value we want to return, returns null if the key does not exist */ Dictionary.prototype.get = function (key) { var index = this.keys.indexOf(key); if (index < 0) { return null; } return this.values[index]; }; /** * Adds the supplied key and value to the dictionary * * @param key The key to add * @param o The value to add */ Dictionary.prototype.add = function (key, o) { var index = this.keys.indexOf(key); if (index > -1) { if (o === null) { this.remove(key); } else { this.values[index] = o; } } else { if (o !== null) { this.keys.push(key); this.values.push(o); } } }; /** * Merges the supplied typed hash into this dictionary instance. Existing values are updated and new ones are created as appropriate. */ Dictionary.prototype.merge = function (source) { var _this = this; if ("getKeys" in source) { var sourceAsDictionary_1 = source; sourceAsDictionary_1.getKeys().map(function (key) { _this.add(key, sourceAsDictionary_1.get(key)); }); } else { var sourceAsHash = source; for (var key in sourceAsHash) { if (sourceAsHash.hasOwnProperty(key)) { this.add(key, sourceAsHash[key]); } } } }; /** * Removes a value from the dictionary * * @param key The key of the key/value pair to remove. Returns null if the key was not found. */ Dictionary.prototype.remove = function (key) { var index = this.keys.indexOf(key); if (index < 0) { return null; } var val = this.values[index]; this.keys.splice(index, 1); this.values.splice(index, 1); return val; }; /** * Returns all the keys currently in the dictionary as an array */ Dictionary.prototype.getKeys = function () { return this.keys; }; /** * Returns all the values currently in the dictionary as an array */ Dictionary.prototype.getValues = function () { return this.values; }; /** * Clears the current dictionary */ Dictionary.prototype.clear = function () { this.keys = []; this.values = []; }; Object.defineProperty(Dictionary.prototype, "count", { /** * Gets a count of the items currently in the dictionary */ get: function () { return this.keys.length; }, enumerable: true, configurable: true }); return Dictionary; }()); function deprecated(deprecationVersion, message) { return function (target, propertyKey, descriptor) { var method = descriptor.value; descriptor.value = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } logging.Logger.log({ data: { descriptor: descriptor, propertyKey: propertyKey, target: target, }, level: 2 /* Warning */, message: "(" + deprecationVersion + ") " + message, }); return method.apply(this, args); }; }; } function beta(message) { if (message === void 0) { message = "This feature is flagged as beta and is subject to change."; } return function (target, propertyKey, descriptor) { var method = descriptor.value; descriptor.value = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } logging.Logger.log({ data: { descriptor: descriptor, propertyKey: propertyKey, target: target, }, level: 2 /* Warning */, message: message, }); return method.apply(this, args); }; }; } var UrlException = /** @class */ (function (_super) { tslib_1.__extends(UrlException, _super); function UrlException(msg) { var _this = _super.call(this, msg) || this; _this.name = "UrlException"; logging.Logger.log({ data: {}, level: 3 /* Error */, message: "[" + _this.name + "]::" + _this.message }); return _this; } return UrlException; }(Error)); function setup(config) { RuntimeConfig.extend(config); } var RuntimeConfigImpl = /** @class */ (function () { function RuntimeConfigImpl() { this._v = new Dictionary(); // setup defaults this._v.add("defaultCachingStore", "session"); this._v.add("defaultCachingTimeoutSeconds", 60); this._v.add("globalCacheDisable", false); this._v.add("enableCacheExpiration", false); this._v.add("cacheExpirationIntervalMilliseconds", 750); this._v.add("spfxContext", null); } /** * * @param config The set of properties to add to the globa configuration instance */ RuntimeConfigImpl.prototype.extend = function (config) { var _this = this; Object.keys(config).forEach(function (key) { _this._v.add(key, config[key]); }); }; RuntimeConfigImpl.prototype.get = function (key) { return this._v.get(key); }; Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingStore", { get: function () { return this.get("defaultCachingStore"); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingTimeoutSeconds", { get: function () { return this.get("defaultCachingTimeoutSeconds"); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "globalCacheDisable", { get: function () { return this.get("globalCacheDisable"); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "enableCacheExpiration", { get: function () { return this.get("enableCacheExpiration"); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "cacheExpirationIntervalMilliseconds", { get: function () { return this.get("cacheExpirationIntervalMilliseconds"); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "spfxContext", { get: function () { return this.get("spfxContext"); }, enumerable: true, configurable: true }); return RuntimeConfigImpl; }()); var _runtimeConfig = new RuntimeConfigImpl(); var RuntimeConfig = _runtimeConfig; /** * Gets a callback function which will maintain context across async calls. * Allows for the calling pattern getCtxCallback(thisobj, method, methodarg1, methodarg2, ...) * * @param context The object that will be the 'this' value in the callback * @param method The method to which we will apply the context and parameters * @param params Optional, additional arguments to supply to the wrapped method when it is invoked */ function getCtxCallback(context, method) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } return function () { method.apply(context, params); }; } /** * Adds a value to a date * * @param date The date to which we will add units, done in local time * @param interval The name of the interval to add, one of: ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'] * @param units The amount to add to date of the given interval * * http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object */ function dateAdd(date, interval, units) { var ret = new Date(date); // don't change original date switch (interval.toLowerCase()) { case "year": ret.setFullYear(ret.getFullYear() + units); break; case "quarter": ret.setMonth(ret.getMonth() + 3 * units); break; case "month": ret.setMonth(ret.getMonth() + units); break; case "week": ret.setDate(ret.getDate() + 7 * units); break; case "day": ret.setDate(ret.getDate() + units); break; case "hour": ret.setTime(ret.getTime() + units * 3600000); break; case "minute": ret.setTime(ret.getTime() + units * 60000); break; case "second": ret.setTime(ret.getTime() + units * 1000); break; default: ret = undefined; break; } return ret; } /** * Combines an arbitrary set of paths ensuring and normalizes the slashes * * @param paths 0 to n path parts to combine */ function combinePaths() { var paths = []; for (var _i = 0; _i < arguments.length; _i++) { paths[_i] = arguments[_i]; } return paths .filter(function (path) { return !Util.stringIsNullOrEmpty(path); }) .map(function (path) { return path.replace(/^[\\|\/]/, "").replace(/[\\|\/]$/, ""); }) .join("/") .replace(/\\/g, "/"); } /** * Gets a random string of chars length * * @param chars The length of the random string to generate */ function getRandomString(chars) { var text = new Array(chars); var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < chars; i++) { text[i] = possible.charAt(Math.floor(Math.random() * possible.length)); } return text.join(""); } /** * Gets a random GUID value * * http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript */ /* tslint:disable no-bitwise */ function getGUID() { var d = new Date().getTime(); var guid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16); }); return guid; } /* tslint:enable */ /** * Determines if a given value is a function * * @param cf The thing to test for functionness */ function isFunc(cf) { return typeof cf === "function"; } /** * Determines if an object is both defined and not null * @param obj Object to test */ function objectDefinedNotNull(obj) { return typeof obj !== "undefined" && obj !== null; } /** * @returns whether the provided parameter is a JavaScript Array or not. */ function isArray(array) { if (Array.isArray) { return Array.isArray(array); } return array && typeof array.length === "number" && array.constructor === Array; } /** * Provides functionality to extend the given object by doing a shallow copy * * @param target The object to which properties will be copied * @param source The source object from which properties will be copied * @param noOverwrite If true existing properties on the target are not overwritten from the source * */ function extend(target, source, noOverwrite) { if (noOverwrite === void 0) { noOverwrite = false; } if (!Util.objectDefinedNotNull(source)) { return target; } // ensure we don't overwrite things we don't want overwritten var check = noOverwrite ? function (o, i) { return !(i in o); } : function () { return true; }; return Object.getOwnPropertyNames(source) .filter(function (v) { return check(target, v); }) .reduce(function (t, v) { t[v] = source[v]; return t; }, target); } /** * Determines if a given url is absolute * * @param url The url to check to see if it is absolute */ function isUrlAbsolute(url) { return /^https?:\/\/|^\/\//i.test(url); } /** * Determines if a string is null or empty or undefined * * @param s The string to test */ function stringIsNullOrEmpty(s) { return typeof s === "undefined" || s === null || s.length < 1; } var Util = /** @class */ (function () { function Util() { } /** * Gets a callback function which will maintain context across async calls. * Allows for the calling pattern getCtxCallback(thisobj, method, methodarg1, methodarg2, ...) * * @param context The object that will be the 'this' value in the callback * @param method The method to which we will apply the context and parameters * @param params Optional, additional arguments to supply to the wrapped method when it is invoked */ Util.getCtxCallback = getCtxCallback; /** * Adds a value to a date * * @param date The date to which we will add units, done in local time * @param interval The name of the interval to add, one of: ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'] * @param units The amount to add to date of the given interval * * http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object */ Util.dateAdd = dateAdd; /** * Combines an arbitrary set of paths ensuring and normalizes the slashes * * @param paths 0 to n path parts to combine */ Util.combinePaths = combinePaths; /** * Gets a random string of chars length * * @param chars The length of the random string to generate */ Util.getRandomString = getRandomString; /** * Gets a random GUID value * * http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript */ Util.getGUID = getGUID; /** * Determines if a given value is a function * * @param cf The thing to test for functionness */ Util.isFunc = isFunc; /** * Determines if an object is both defined and not null * @param obj Object to test */ Util.objectDefinedNotNull = objectDefinedNotNull; /** * @returns whether the provided parameter is a JavaScript Array or not. */ Util.isArray = isArray; /** * Provides functionality to extend the given object by doing a shallow copy * * @param target The object to which properties will be copied * @param source The source object from which properties will be copied * @param noOverwrite If true existing properties on the target are not overwritten from the source * */ Util.extend = extend; /** * Determines if a given url is absolute * * @param url The url to check to see if it is absolute */ Util.isUrlAbsolute = isUrlAbsolute; /** * Determines if a string is null or empty or undefined * * @param s The string to test */ Util.stringIsNullOrEmpty = stringIsNullOrEmpty; return Util; }()); function mergeHeaders(target, source) { if (typeof source !== "undefined" && source !== null) { var temp = new Request("", { headers: source }); temp.headers.forEach(function (value, name) { target.append(name, value); }); } } function mergeOptions(target, source) { if (Util.objectDefinedNotNull(source)) { var headers = Util.extend(target.headers || {}, source.headers); target = Util.extend(target, source); target.headers = headers; } } /** * Makes requests using the global/window fetch API */ var FetchClient = /** @class */ (function () { function FetchClient() { } FetchClient.prototype.fetch = function (url, options) { return global.fetch(url, options); }; return FetchClient; }()); /** * Makes requests using the fetch API adding the supplied token to the Authorization header */ var BearerTokenFetchClient = /** @class */ (function (_super) { tslib_1.__extends(BearerTokenFetchClient, _super); function BearerTokenFetchClient(_token) { var _this = _super.call(this) || this; _this._token = _token; return _this; } BearerTokenFetchClient.prototype.fetch = function (url, options) { if (options === void 0) { options = {}; } var headers = new Headers(); mergeHeaders(headers, options.headers); headers.set("Authorization", "Bearer " + this._token); options.headers = headers; return _super.prototype.fetch.call(this, url, options); }; return BearerTokenFetchClient; }(FetchClient)); /** * A wrapper class to provide a consistent interface to browser based storage * */ var PnPClientStorageWrapper = /** @class */ (function () { /** * Creates a new instance of the PnPClientStorageWrapper class * * @constructor */ function PnPClientStorageWrapper(store, defaultTimeoutMinutes) { if (defaultTimeoutMinutes === void 0) { defaultTimeoutMinutes = -1; } this.store = store; this.defaultTimeoutMinutes = defaultTimeoutMinutes; this.enabled = this.test(); // if the cache timeout is enabled call the handler // this will clear any expired items and set the timeout function if (RuntimeConfig.enableCacheExpiration) { logging.Logger.write("Enabling cache expiration.", 1 /* Info */); this.cacheExpirationHandler(); } } /** * Get a value from storage, or null if that value does not exist * * @param key The key whose value we want to retrieve */ PnPClientStorageWrapper.prototype.get = function (key) { if (!this.enabled) { return null; } var o = this.store.getItem(key); if (o == null) { return null; } var persistable = JSON.parse(o); if (new Date(persistable.expiration) <= new Date()) { logging.Logger.write("Removing item with key '" + key + "' from cache due to expiration.", 1 /* Info */); this.delete(key); return null; } else { return persistable.value; } }; /** * Adds a value to the underlying storage * * @param key The key to use when storing the provided value * @param o The value to store * @param expire Optional, if provided the expiration of the item, otherwise the default is used */ PnPClientStorageWrapper.prototype.put = function (key, o, expire) { if (this.enabled) { this.store.setItem(key, this.createPersistable(o, expire)); } }; /** * Deletes a value from the underlying storage * * @param key The key of the pair we want to remove from storage */ PnPClientStorageWrapper.prototype.delete = function (key) { if (this.enabled) { this.store.removeItem(key); } }; /** * Gets an item from the underlying storage, or adds it if it does not exist using the supplied getter function * * @param key The key to use when storing the provided value * @param getter A function which will upon execution provide the desired value * @param expire Optional, if provided the expiration of the item, otherwise the default is used */ PnPClientStorageWrapper.prototype.getOrPut = function (key, getter, expire) { var _this = this; if (!this.enabled) { return getter(); } return new Promise(function (resolve) { var o = _this.get(key); if (o == null) { getter().then(function (d) { _this.put(key, d, expire); resolve(d); }); } else { resolve(o); } }); }; /** * Deletes any expired items placed in the store by the pnp library, leaves other items untouched */ PnPClientStorageWrapper.prototype.deleteExpired = function () { var _this = this; return new Promise(function (resolve, reject) { if (!_this.enabled) { resolve(); } try { for (var i = 0; i < _this.store.length; i++) { var key = _this.store.key(i); if (key !== null) { // test the stored item to see if we stored it if (/["|']?pnp["|']? ?: ?1/i.test(_this.store.getItem(key))) { // get those items as get will delete from cache if they are expired _this.get(key); } } } resolve(); } catch (e) { reject(e); } }); }; /** * Used to determine if the wrapped storage is available currently */ PnPClientStorageWrapper.prototype.test = function () { var str = "test"; try { this.store.setItem(str, str); this.store.removeItem(str); return true; } catch (e) { return false; } }; /** * Creates the persistable to store */ PnPClientStorageWrapper.prototype.createPersistable = function (o, expire) { if (typeof expire === "undefined") { // ensure we are by default inline with the global library setting var defaultTimeout = RuntimeConfig.defaultCachingTimeoutSeconds; if (this.defaultTimeoutMinutes > 0) { defaultTimeout = this.defaultTimeoutMinutes * 60; } expire = Util.dateAdd(new Date(), "second", defaultTimeout); } return JSON.stringify({ pnp: 1, expiration: expire, value: o }); }; /** * Deletes expired items added by this library in this.store and sets a timeout to call itself */ PnPClientStorageWrapper.prototype.cacheExpirationHandler = function () { var _this = this; logging.Logger.write("Called cache expiration handler.", 0 /* Verbose */); this.deleteExpired().then(function (_) { // call ourself in the future setTimeout(Util.getCtxCallback(_this, _this.cacheExpirationHandler), RuntimeConfig.cacheExpirationIntervalMilliseconds); }).catch(function (e) { // we've got some error - so just stop the loop and report the error logging.Logger.log({ data: e, level: 3 /* Error */, message: "Error deleting expired cache entries, see data for details. Timeout not reset.", }); }); }; return PnPClientStorageWrapper; }()); /** * A thin implementation of in-memory storage for use in nodejs */ var MemoryStorage = /** @class */ (function () { function MemoryStorage(_store) { if (_store === void 0) { _store = new Dictionary(); } this._store = _store; } Object.defineProperty(MemoryStorage.prototype, "length", { get: function () { return this._store.count; }, enumerable: true, configurable: true }); MemoryStorage.prototype.clear = function () { this._store.clear(); }; MemoryStorage.prototype.getItem = function (key) { return this._store.get(key); }; MemoryStorage.prototype.key = function (index) { return this._store.getKeys()[index]; }; MemoryStorage.prototype.removeItem = function (key) { this._store.remove(key); }; MemoryStorage.prototype.setItem = function (key, data) { this._store.add(key, data); }; return MemoryStorage; }()); /** * A class that will establish wrappers for both local and session storage */ var PnPClientStorage = /** @class */ (function () { /** * Creates a new instance of the PnPClientStorage class * * @constructor */ function PnPClientStorage(_local, _session) { if (_local === void 0) { _local = null; } if (_session === void 0) { _session = null; } this._local = _local; this._session = _session; } Object.defineProperty(PnPClientStorage.prototype, "local", { /** * Provides access to the local storage of the browser */ get: function () { if (this._local === null) { this._local = typeof localStorage !== "undefined" ? new PnPClientStorageWrapper(localStorage) : new PnPClientStorageWrapper(new MemoryStorage()); } return this._local; }, enumerable: true, configurable: true }); Object.defineProperty(PnPClientStorage.prototype, "session", { /** * Provides access to the session storage of the browser */ get: function () { if (this._session === null) { this._session = typeof sessionStorage !== "undefined" ? new PnPClientStorageWrapper(sessionStorage) : new PnPClientStorageWrapper(new MemoryStorage()); } return this._session; }, enumerable: true, configurable: true }); return PnPClientStorage; }()); exports.readBlobAsText = readBlobAsText; exports.readBlobAsArrayBuffer = readBlobAsArrayBuffer; exports.Dictionary = Dictionary; exports.deprecated = deprecated; exports.beta = beta; exports.UrlException = UrlException; exports.setup = setup; exports.RuntimeConfigImpl = RuntimeConfigImpl; exports.RuntimeConfig = RuntimeConfig; exports.mergeHeaders = mergeHeaders; exports.mergeOptions = mergeOptions; exports.FetchClient = FetchClient; exports.BearerTokenFetchClient = BearerTokenFetchClient; exports.PnPClientStorageWrapper = PnPClientStorageWrapper; exports.PnPClientStorage = PnPClientStorage; exports.getCtxCallback = getCtxCallback; exports.dateAdd = dateAdd; exports.combinePaths = combinePaths; exports.getRandomString = getRandomString; exports.getGUID = getGUID; exports.isFunc = isFunc; exports.objectDefinedNotNull = objectDefinedNotNull; exports.isArray = isArray; exports.extend = extend; exports.isUrlAbsolute = isUrlAbsolute; exports.stringIsNullOrEmpty = stringIsNullOrEmpty; exports.Util = Util; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=common.es5.umd.js.map
'use strict' /* eslint-disable standard/no-callback-literal */ const BB = require('bluebird') const figgyPudding = require('figgy-pudding') const libaccess = require('libnpm/access') const npmConfig = require('./config/figgy-config.js') const output = require('./utils/output.js') const otplease = require('./utils/otplease.js') const path = require('path') const prefix = require('./npm.js').prefix const readPackageJson = BB.promisify(require('read-package-json')) const usage = require('./utils/usage.js') const whoami = require('./whoami.js') module.exports = access access.usage = usage( 'npm access', 'npm access public [<package>]\n' + 'npm access restricted [<package>]\n' + 'npm access grant <read-only|read-write> <scope:team> [<package>]\n' + 'npm access revoke <scope:team> [<package>]\n' + 'npm access 2fa-required [<package>]\n' + 'npm access 2fa-not-required [<package>]\n' + 'npm access ls-packages [<user>|<scope>|<scope:team>]\n' + 'npm access ls-collaborators [<package> [<user>]]\n' + 'npm access edit [<package>]' ) access.subcommands = [ 'public', 'restricted', 'grant', 'revoke', 'ls-packages', 'ls-collaborators', 'edit', '2fa-required', '2fa-not-required' ] const AccessConfig = figgyPudding({ json: {} }) function UsageError (msg = '') { throw Object.assign(new Error( (msg ? `\nUsage: ${msg}\n\n` : '') + access.usage ), {code: 'EUSAGE'}) } access.completion = function (opts, cb) { var argv = opts.conf.argv.remain if (argv.length === 2) { return cb(null, access.subcommands) } switch (argv[2]) { case 'grant': if (argv.length === 3) { return cb(null, ['read-only', 'read-write']) } else { return cb(null, []) } case 'public': case 'restricted': case 'ls-packages': case 'ls-collaborators': case 'edit': case '2fa-required': case '2fa-not-required': return cb(null, []) case 'revoke': return cb(null, []) default: return cb(new Error(argv[2] + ' not recognized')) } } function access ([cmd, ...args], cb) { return BB.try(() => { const fn = access.subcommands.includes(cmd) && access[cmd] if (!cmd) { UsageError('Subcommand is required.') } if (!fn) { UsageError(`${cmd} is not a recognized subcommand.`) } return fn(args, AccessConfig(npmConfig())) }).then( x => cb(null, x), err => err.code === 'EUSAGE' ? cb(err.message) : cb(err) ) } access.public = ([pkg], opts) => { return modifyPackage(pkg, opts, libaccess.public) } access.restricted = ([pkg], opts) => { return modifyPackage(pkg, opts, libaccess.restricted) } access.grant = ([perms, scopeteam, pkg], opts) => { return BB.try(() => { if (!perms || (perms !== 'read-only' && perms !== 'read-write')) { UsageError('First argument must be either `read-only` or `read-write.`') } if (!scopeteam) { UsageError('`<scope:team>` argument is required.') } const [, scope, team] = scopeteam.match(/^@?([^:]+):(.*)$/) || [] if (!scope && !team) { UsageError( 'Second argument used incorrect format.\n' + 'Example: @example:developers' ) } return modifyPackage(pkg, opts, (pkgName, opts) => { return libaccess.grant(pkgName, scopeteam, perms, opts) }) }) } access.revoke = ([scopeteam, pkg], opts) => { return BB.try(() => { if (!scopeteam) { UsageError('`<scope:team>` argument is required.') } const [, scope, team] = scopeteam.match(/^@?([^:]+):(.*)$/) || [] if (!scope || !team) { UsageError( 'First argument used incorrect format.\n' + 'Example: @example:developers' ) } return modifyPackage(pkg, opts, (pkgName, opts) => { return libaccess.revoke(pkgName, scopeteam, opts) }) }) } access['2fa-required'] = access.tfaRequired = ([pkg], opts) => { return modifyPackage(pkg, opts, libaccess.tfaRequired, false) } access['2fa-not-required'] = access.tfaNotRequired = ([pkg], opts) => { return modifyPackage(pkg, opts, libaccess.tfaNotRequired, false) } access['ls-packages'] = access.lsPackages = ([owner], opts) => { return ( owner ? BB.resolve(owner) : BB.fromNode(cb => whoami([], true, cb)) ).then(owner => { return libaccess.lsPackages(owner, opts) }).then(pkgs => { // TODO - print these out nicely (breaking change) output(JSON.stringify(pkgs, null, 2)) }) } access['ls-collaborators'] = access.lsCollaborators = ([pkg, usr], opts) => { return getPackage(pkg, false).then(pkgName => libaccess.lsCollaborators(pkgName, usr, opts) ).then(collabs => { // TODO - print these out nicely (breaking change) output(JSON.stringify(collabs, null, 2)) }) } access['edit'] = () => BB.reject(new Error('edit subcommand is not implemented yet')) function modifyPackage (pkg, opts, fn, requireScope = true) { return getPackage(pkg, requireScope).then(pkgName => otplease(opts, opts => fn(pkgName, opts)) ) } function getPackage (name, requireScope = true) { return BB.try(() => { if (name && name.trim()) { return name.trim() } else { return readPackageJson( path.resolve(prefix, 'package.json') ).then( data => data.name, err => { if (err.code === 'ENOENT') { throw new Error('no package name passed to command and no package.json found') } else { throw err } } ) } }).then(name => { if (requireScope && !name.match(/^@[^/]+\/.*$/)) { UsageError('This command is only available for scoped packages.') } else { return name } }) }
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency"); const ModuleHotAcceptDependency = require("../dependencies/ModuleHotAcceptDependency"); const ModuleHotDeclineDependency = require("../dependencies/ModuleHotDeclineDependency"); const ConcatenatedModule = require("./ConcatenatedModule"); const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency"); const StackedSetMap = require("../util/StackedSetMap"); const formatBailoutReason = msg => { return "ModuleConcatenation bailout: " + msg; }; class ModuleConcatenationPlugin { constructor(options) { if (typeof options !== "object") options = {}; this.options = options; } apply(compiler) { compiler.hooks.compilation.tap( "ModuleConcatenationPlugin", (compilation, { normalModuleFactory }) => { const handler = (parser, parserOptions) => { parser.hooks.call.for("eval").tap("ModuleConcatenationPlugin", () => { // Because of variable renaming we can't use modules with eval. parser.state.module.buildMeta.moduleConcatenationBailout = "eval()"; }); }; normalModuleFactory.hooks.parser .for("javascript/auto") .tap("ModuleConcatenationPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") .tap("ModuleConcatenationPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/esm") .tap("ModuleConcatenationPlugin", handler); const bailoutReasonMap = new Map(); const setBailoutReason = (module, reason) => { bailoutReasonMap.set(module, reason); module.optimizationBailout.push( typeof reason === "function" ? rs => formatBailoutReason(reason(rs)) : formatBailoutReason(reason) ); }; const getBailoutReason = (module, requestShortener) => { const reason = bailoutReasonMap.get(module); if (typeof reason === "function") return reason(requestShortener); return reason; }; compilation.hooks.optimizeChunkModules.tap( "ModuleConcatenationPlugin", (chunks, modules) => { const relevantModules = []; const possibleInners = new Set(); for (const module of modules) { // Only harmony modules are valid for optimization if ( !module.buildMeta || module.buildMeta.exportsType !== "namespace" || !module.dependencies.some( d => d instanceof HarmonyCompatibilityDependency ) ) { setBailoutReason(module, "Module is not an ECMAScript module"); continue; } // Some expressions are not compatible with module concatenation // because they may produce unexpected results. The plugin bails out // if some were detected upfront. if ( module.buildMeta && module.buildMeta.moduleConcatenationBailout ) { setBailoutReason( module, `Module uses ${module.buildMeta.moduleConcatenationBailout}` ); continue; } // Exports must be known (and not dynamic) if (!Array.isArray(module.buildMeta.providedExports)) { setBailoutReason(module, "Module exports are unknown"); continue; } // Using dependency variables is not possible as this wraps the code in a function if (module.variables.length > 0) { setBailoutReason( module, `Module uses injected variables (${module.variables .map(v => v.name) .join(", ")})` ); continue; } // Hot Module Replacement need it's own module to work correctly if ( module.dependencies.some( dep => dep instanceof ModuleHotAcceptDependency || dep instanceof ModuleHotDeclineDependency ) ) { setBailoutReason(module, "Module uses Hot Module Replacement"); continue; } relevantModules.push(module); // Module must not be the entry points if (module.isEntryModule()) { setBailoutReason(module, "Module is an entry point"); continue; } // Module must be in any chunk (we don't want to do useless work) if (module.getNumberOfChunks() === 0) { setBailoutReason(module, "Module is not in any chunk"); continue; } // Module must only be used by Harmony Imports const nonHarmonyReasons = module.reasons.filter( reason => !reason.dependency || !(reason.dependency instanceof HarmonyImportDependency) ); if (nonHarmonyReasons.length > 0) { const importingModules = new Set( nonHarmonyReasons.map(r => r.module).filter(Boolean) ); const importingExplanations = new Set( nonHarmonyReasons.map(r => r.explanation).filter(Boolean) ); const importingModuleTypes = new Map( Array.from(importingModules).map( m => /** @type {[string, Set]} */ ([ m, new Set( nonHarmonyReasons .filter(r => r.module === m) .map(r => r.dependency.type) .sort() ) ]) ) ); setBailoutReason(module, requestShortener => { const names = Array.from(importingModules) .map( m => `${m.readableIdentifier( requestShortener )} (referenced with ${Array.from( importingModuleTypes.get(m) ).join(", ")})` ) .sort(); const explanations = Array.from(importingExplanations).sort(); if (names.length > 0 && explanations.length === 0) { return `Module is referenced from these modules with unsupported syntax: ${names.join( ", " )}`; } else if (names.length === 0 && explanations.length > 0) { return `Module is referenced by: ${explanations.join( ", " )}`; } else if (names.length > 0 && explanations.length > 0) { return `Module is referenced from these modules with unsupported syntax: ${names.join( ", " )} and by: ${explanations.join(", ")}`; } else { return "Module is referenced in a unsupported way"; } }); continue; } possibleInners.add(module); } // sort by depth // modules with lower depth are more likely suited as roots // this improves performance, because modules already selected as inner are skipped relevantModules.sort((a, b) => { return a.depth - b.depth; }); const concatConfigurations = []; const usedAsInner = new Set(); for (const currentRoot of relevantModules) { // when used by another configuration as inner: // the other configuration is better and we can skip this one if (usedAsInner.has(currentRoot)) continue; // create a configuration with the root const currentConfiguration = new ConcatConfiguration(currentRoot); // cache failures to add modules const failureCache = new Map(); // try to add all imports for (const imp of this._getImports(compilation, currentRoot)) { const problem = this._tryToAdd( compilation, currentConfiguration, imp, possibleInners, failureCache ); if (problem) { failureCache.set(imp, problem); currentConfiguration.addWarning(imp, problem); } } if (!currentConfiguration.isEmpty()) { concatConfigurations.push(currentConfiguration); for (const module of currentConfiguration.getModules()) { if (module !== currentConfiguration.rootModule) { usedAsInner.add(module); } } } } // HACK: Sort configurations by length and start with the longest one // to get the biggers groups possible. Used modules are marked with usedModules // TODO: Allow to reuse existing configuration while trying to add dependencies. // This would improve performance. O(n^2) -> O(n) concatConfigurations.sort((a, b) => { return b.modules.size - a.modules.size; }); const usedModules = new Set(); for (const concatConfiguration of concatConfigurations) { if (usedModules.has(concatConfiguration.rootModule)) continue; const modules = concatConfiguration.getModules(); const rootModule = concatConfiguration.rootModule; const newModule = new ConcatenatedModule( rootModule, Array.from(modules), ConcatenatedModule.createConcatenationList( rootModule, modules, compilation ) ); for (const warning of concatConfiguration.getWarningsSorted()) { newModule.optimizationBailout.push(requestShortener => { const reason = getBailoutReason(warning[0], requestShortener); const reasonWithPrefix = reason ? ` (<- ${reason})` : ""; if (warning[0] === warning[1]) { return formatBailoutReason( `Cannot concat with ${warning[0].readableIdentifier( requestShortener )}${reasonWithPrefix}` ); } else { return formatBailoutReason( `Cannot concat with ${warning[0].readableIdentifier( requestShortener )} because of ${warning[1].readableIdentifier( requestShortener )}${reasonWithPrefix}` ); } }); } const chunks = concatConfiguration.rootModule.getChunks(); for (const m of modules) { usedModules.add(m); for (const chunk of chunks) { chunk.removeModule(m); } } for (const chunk of chunks) { chunk.addModule(newModule); newModule.addChunk(chunk); if (chunk.entryModule === concatConfiguration.rootModule) { chunk.entryModule = newModule; } } compilation.modules.push(newModule); for (const reason of newModule.reasons) { if (reason.dependency.module === concatConfiguration.rootModule) reason.dependency.module = newModule; if ( reason.dependency.redirectedModule === concatConfiguration.rootModule ) reason.dependency.redirectedModule = newModule; } // TODO: remove when LTS node version contains fixed v8 version // @see https://github.com/webpack/webpack/pull/6613 // Turbofan does not correctly inline for-of loops with polymorphic input arrays. // Work around issue by using a standard for loop and assigning dep.module.reasons for (let i = 0; i < newModule.dependencies.length; i++) { let dep = newModule.dependencies[i]; if (dep.module) { let reasons = dep.module.reasons; for (let j = 0; j < reasons.length; j++) { let reason = reasons[j]; if (reason.dependency === dep) { reason.module = newModule; } } } } } compilation.modules = compilation.modules.filter( m => !usedModules.has(m) ); } ); } ); } _getImports(compilation, module) { return new Set( module.dependencies // Get reference info only for harmony Dependencies .map(dep => { if (!(dep instanceof HarmonyImportDependency)) return null; if (!compilation) return dep.getReference(); return compilation.getDependencyReference(module, dep); }) // Reference is valid and has a module // Dependencies are simple enough to concat them .filter( ref => ref && ref.module && (Array.isArray(ref.importedNames) || Array.isArray(ref.module.buildMeta.providedExports)) ) // Take the imported module .map(ref => ref.module) ); } _tryToAdd(compilation, config, module, possibleModules, failureCache) { const cacheEntry = failureCache.get(module); if (cacheEntry) { return cacheEntry; } // Already added? if (config.has(module)) { return null; } // Not possible to add? if (!possibleModules.has(module)) { failureCache.set(module, module); // cache failures for performance return module; } // module must be in the same chunks if (!config.rootModule.hasEqualsChunks(module)) { failureCache.set(module, module); // cache failures for performance return module; } // Clone config to make experimental changes const testConfig = config.clone(); // Add the module testConfig.add(module); // Every module which depends on the added module must be in the configuration too. for (const reason of module.reasons) { // Modules that are not used can be ignored if ( reason.module.factoryMeta.sideEffectFree && reason.module.used === false ) continue; const problem = this._tryToAdd( compilation, testConfig, reason.module, possibleModules, failureCache ); if (problem) { failureCache.set(module, problem); // cache failures for performance return problem; } } // Commit experimental changes config.set(testConfig); // Eagerly try to add imports too if possible for (const imp of this._getImports(compilation, module)) { const problem = this._tryToAdd( compilation, config, imp, possibleModules, failureCache ); if (problem) { config.addWarning(imp, problem); } } return null; } } class ConcatConfiguration { constructor(rootModule, cloneFrom) { this.rootModule = rootModule; if (cloneFrom) { this.modules = cloneFrom.modules.createChild(5); this.warnings = cloneFrom.warnings.createChild(5); } else { this.modules = new StackedSetMap(); this.modules.add(rootModule); this.warnings = new StackedSetMap(); } } add(module) { this.modules.add(module); } has(module) { return this.modules.has(module); } isEmpty() { return this.modules.size === 1; } addWarning(module, problem) { this.warnings.set(module, problem); } getWarningsSorted() { return new Map( this.warnings.asPairArray().sort((a, b) => { const ai = a[0].identifier(); const bi = b[0].identifier(); if (ai < bi) return -1; if (ai > bi) return 1; return 0; }) ); } getModules() { return this.modules.asSet(); } clone() { return new ConcatConfiguration(this.rootModule, this); } set(config) { this.rootModule = config.rootModule; this.modules = config.modules; this.warnings = config.warnings; } } module.exports = ModuleConcatenationPlugin;
var pbkdf2Sync = require('pbkdf2').pbkdf2Sync var MAX_VALUE = 0x7fffffff // N = Cpu cost, r = Memory cost, p = parallelization cost function scrypt (key, salt, N, r, p, dkLen, progressCallback) { if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2') if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large') if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large') var XY = new Buffer(256 * r) var V = new Buffer(128 * r * N) // pseudo global var B32 = new Int32Array(16) // salsa20_8 var x = new Int32Array(16) // salsa20_8 var _X = new Buffer(64) // blockmix_salsa8 // pseudo global var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256') var tickCallback if (progressCallback) { var totalOps = p * N * 2 var currentOp = 0 tickCallback = function () { ++currentOp // send progress notifications once every 1,000 ops if (currentOp % 1000 === 0) { progressCallback({ current: currentOp, total: totalOps, percent: (currentOp / totalOps) * 100.0 }) } } } for (var i = 0; i < p; i++) { smix(B, i * 128 * r, r, N, V, XY) } return pbkdf2Sync(key, B, 1, dkLen, 'sha256') // all of these functions are actually moved to the top // due to function hoisting function smix (B, Bi, r, N, V, XY) { var Xi = 0 var Yi = 128 * r var i B.copy(XY, Xi, Bi, Bi + Yi) for (i = 0; i < N; i++) { XY.copy(V, i * Yi, Xi, Xi + Yi) blockmix_salsa8(XY, Xi, Yi, r) if (tickCallback) tickCallback() } for (i = 0; i < N; i++) { var offset = Xi + (2 * r - 1) * 64 var j = XY.readUInt32LE(offset) & (N - 1) blockxor(V, j * Yi, XY, Xi, Yi) blockmix_salsa8(XY, Xi, Yi, r) if (tickCallback) tickCallback() } XY.copy(B, Bi, Xi, Xi + Yi) } function blockmix_salsa8 (BY, Bi, Yi, r) { var i arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64) for (i = 0; i < 2 * r; i++) { blockxor(BY, i * 64, _X, 0, 64) salsa20_8(_X) arraycopy(_X, 0, BY, Yi + (i * 64), 64) } for (i = 0; i < r; i++) { arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64) } for (i = 0; i < r; i++) { arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64) } } function R (a, b) { return (a << b) | (a >>> (32 - b)) } function salsa20_8 (B) { var i for (i = 0; i < 16; i++) { B32[i] = (B[i * 4 + 0] & 0xff) << 0 B32[i] |= (B[i * 4 + 1] & 0xff) << 8 B32[i] |= (B[i * 4 + 2] & 0xff) << 16 B32[i] |= (B[i * 4 + 3] & 0xff) << 24 // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js } arraycopy(B32, 0, x, 0, 16) for (i = 8; i > 0; i -= 2) { x[ 4] ^= R(x[ 0] + x[12], 7) x[ 8] ^= R(x[ 4] + x[ 0], 9) x[12] ^= R(x[ 8] + x[ 4], 13) x[ 0] ^= R(x[12] + x[ 8], 18) x[ 9] ^= R(x[ 5] + x[ 1], 7) x[13] ^= R(x[ 9] + x[ 5], 9) x[ 1] ^= R(x[13] + x[ 9], 13) x[ 5] ^= R(x[ 1] + x[13], 18) x[14] ^= R(x[10] + x[ 6], 7) x[ 2] ^= R(x[14] + x[10], 9) x[ 6] ^= R(x[ 2] + x[14], 13) x[10] ^= R(x[ 6] + x[ 2], 18) x[ 3] ^= R(x[15] + x[11], 7) x[ 7] ^= R(x[ 3] + x[15], 9) x[11] ^= R(x[ 7] + x[ 3], 13) x[15] ^= R(x[11] + x[ 7], 18) x[ 1] ^= R(x[ 0] + x[ 3], 7) x[ 2] ^= R(x[ 1] + x[ 0], 9) x[ 3] ^= R(x[ 2] + x[ 1], 13) x[ 0] ^= R(x[ 3] + x[ 2], 18) x[ 6] ^= R(x[ 5] + x[ 4], 7) x[ 7] ^= R(x[ 6] + x[ 5], 9) x[ 4] ^= R(x[ 7] + x[ 6], 13) x[ 5] ^= R(x[ 4] + x[ 7], 18) x[11] ^= R(x[10] + x[ 9], 7) x[ 8] ^= R(x[11] + x[10], 9) x[ 9] ^= R(x[ 8] + x[11], 13) x[10] ^= R(x[ 9] + x[ 8], 18) x[12] ^= R(x[15] + x[14], 7) x[13] ^= R(x[12] + x[15], 9) x[14] ^= R(x[13] + x[12], 13) x[15] ^= R(x[14] + x[13], 18) } for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i] for (i = 0; i < 16; i++) { var bi = i * 4 B[bi + 0] = (B32[i] >> 0 & 0xff) B[bi + 1] = (B32[i] >> 8 & 0xff) B[bi + 2] = (B32[i] >> 16 & 0xff) B[bi + 3] = (B32[i] >> 24 & 0xff) // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js } } // naive approach... going back to loop unrolling may yield additional performance function blockxor (S, Si, D, Di, len) { for (var i = 0; i < len; i++) { D[Di + i] ^= S[Si + i] } } } function arraycopy (src, srcPos, dest, destPos, length) { if (Buffer.isBuffer(src) && Buffer.isBuffer(dest)) { src.copy(dest, destPos, srcPos, srcPos + length) } else { while (length--) { dest[destPos++] = src[srcPos++] } } } module.exports = scrypt
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EmitterSize = void 0; var SizeMode_1 = require("../../../Enums/SizeMode"); var EmitterSize = (function () { function EmitterSize() { this.mode = SizeMode_1.SizeMode.percent; this.height = 0; this.width = 0; } EmitterSize.prototype.load = function (data) { if (data !== undefined) { if (data.mode !== undefined) { this.mode = data.mode; } if (data.height !== undefined) { this.height = data.height; } if (data.width !== undefined) { this.width = data.width; } } }; return EmitterSize; }()); exports.EmitterSize = EmitterSize;
'use strict'; var expect = require('expect.js'); var Support = require(__dirname + '/../support'); var helpers = require(__dirname + '/../support/helpers'); var gulp = require('gulp'); var _ = require('lodash'); ([ 'model:create', 'model:generate' ]).forEach(function (flag) { describe(Support.getTestDialectTeaser(flag), function () { var combineFlags = function (flags) { var result = flag; _.forEach(flags || {}, function (value, key) { result = result + ' --' + key + ' ' + value; }); return result; }; var prepare = function (options, callback) { options = _.assign({ flags: {}, cli: { pipeStdout: true } }, options || {}); gulp .src(Support.resolveSupportPath('tmp')) .pipe(helpers.clearDirectory()) .pipe(helpers.runCli('init')) .pipe(helpers.runCli(combineFlags(options.flags), options.cli)) .pipe(helpers.teardown(callback)); }; describe('name', function () { describe('when missing', function () { it('exits with an error code', function (done) { prepare({ flags: { attributes: 'first_name:string' }, cli: { exitCode: 1 } }, done); }); it('notifies the user about a missing name flag', function (done) { prepare({ flags: { attributes: 'first_name:string' }, cli: { pipeStderr: true } }, function (err, stdout) { expect(stdout).to.match(/Unspecified flag.*name/); done(); }); }); }); }); describe('attributes', function () { describe('when missing', function () { it('exits with an error code', function (done) { prepare({ flags: { name: 'User' }, cli: { exitCode: 1 } }, done); }); it('notifies the user about a missing attributes flag', function (done) { prepare({ flags: { name: 'User' }, cli: { pipeStderr: true } }, function (err, stdout) { expect(stdout).to.match(/Unspecified flag.*attributes/); done(); }); }); }); ;([ 'first_name:string,last_name:string,bio:text', '\'first_name:string last_name:string bio:text\'', '\'first_name:string, last_name:string, bio:text\'' ]).forEach(function (attributes) { describe('--attributes ' + attributes, function () { it('exits with exit code 0', function (done) { prepare({ flags: { name: 'User', attributes: attributes }, cli: { exitCode: 0 } }, done); }); it('creates the model file', function (done) { prepare({ flags: { name: 'User', attributes: attributes } }, function () { gulp .src(Support.resolveSupportPath('tmp', 'models')) .pipe(helpers.listFiles()) .pipe(helpers.ensureContent('user.js')) .pipe(helpers.teardown(done)); }); }); it('generates the model attributes correctly', function (done) { prepare({ flags: { name: 'User', attributes: attributes } }, function () { gulp .src(Support.resolveSupportPath('tmp', 'models')) .pipe(helpers.readFile('user.js')) .pipe(helpers.ensureContent('sequelize.define(\'User\'')) .pipe(helpers.ensureContent('first_name: DataTypes.STRING')) .pipe(helpers.ensureContent('last_name: DataTypes.STRING')) .pipe(helpers.ensureContent('bio: DataTypes.TEXT')) .pipe(helpers.teardown(done)); }); }); it('creates the migration file', function (done) { prepare({ flags: { name: 'User', attributes: attributes } }, function () { gulp .src(Support.resolveSupportPath('tmp', 'migrations')) .pipe(helpers.listFiles()) .pipe(helpers.ensureContent(/\d+-create-user.js/)) .pipe(helpers.teardown(done)); }); }); ([ { underscored: true, createdAt: 'created_at', updatedAt: 'updated_at'}, { underscored: false, createdAt: 'createdAt', updatedAt: 'updatedAt'} ]).forEach(function (attrUnd) { describe((attrUnd.underscored ? '' : 'without ') + '--underscored', function () { it('generates the migration content correctly', function (done) { var flags = { name: 'User', attributes: attributes }; if ( attrUnd.underscored ) { flags.underscored = attrUnd.underscored; } prepare({ flags: flags }, function () { gulp .src(Support.resolveSupportPath('tmp', 'migrations')) .pipe(helpers.readFile('*-create-user.js')) .pipe(helpers.ensureContent('return queryInterface')) .pipe(helpers.ensureContent('.createTable(\'Users\', {')) .pipe(helpers.ensureContent( 'first_name: {\n type: Sequelize.STRING\n },' )) .pipe(helpers.ensureContent( 'last_name: {\n type: Sequelize.STRING\n },' )) .pipe(helpers.ensureContent( 'bio: {\n type: Sequelize.TEXT\n },' )) .pipe(helpers.ensureContent([ ' id: {', ' allowNull: false,', ' autoIncrement: true,', ' primaryKey: true,', ' type: Sequelize.INTEGER', ' },' ].join('\n'))) .pipe(helpers.ensureContent([ ' ' + attrUnd.createdAt + ': {', ' allowNull: false,', ' type: Sequelize.DATE', ' },' ].join('\n'))) .pipe(helpers.ensureContent([ ' ' + attrUnd.updatedAt + ': {', ' allowNull: false,', ' type: Sequelize.DATE', ' }' ].join('\n'))) .pipe(helpers.ensureContent('});')) .pipe(helpers.ensureContent('.dropTable(\'Users\')')) .pipe(helpers.teardown(done)); }); }); it('generates the model content correctly', function (done) { var flags = { name: 'User', attributes: attributes }; var targetContent = attrUnd.underscored ? 'underscored: true' : '{\n classMethods'; if ( attrUnd.underscored ) { flags.underscored = attrUnd.underscored; } prepare({ flags: flags }, function () { gulp .src(Support.resolveSupportPath('tmp', 'models')) .pipe(helpers.readFile('user.js')) .pipe(helpers.ensureContent(targetContent)) .pipe(helpers.teardown(done)); }); }); }); }); describe('when called twice', function () { beforeEach(function (done) { this.flags = { name: 'User', attributes: attributes }; prepare({ flags: this.flags }, done); }); it('exits with an error code', function (done) { gulp .src(Support.resolveSupportPath('tmp')) .pipe(helpers.runCli(combineFlags(this.flags), { exitCode: 1 })) .pipe(helpers.teardown(done)); }); it('notifies the user about the possibility of --flags', function (done) { gulp .src(Support.resolveSupportPath('tmp')) .pipe(helpers.runCli(combineFlags(this.flags), { pipeStderr: true })) .pipe(helpers.teardown(function (err, stderr) { expect(stderr).to.contain('already exists'); done(); })); }); }); }); }); }); }); });
describe("toHaveBeenCalledWith", function() { it("passes when the actual was called with matching parameters", function() { var util = { contains: jasmine.createSpy('delegated-contains').and.returnValue(true) }, matcher = jasmineUnderTest.matchers.toHaveBeenCalledWith(util), calledSpy = jasmineUnderTest.createSpy('called-spy'), result; calledSpy('a', 'b'); result = matcher.compare(calledSpy, 'a', 'b'); expect(result.pass).toBe(true); expect(result.message()).toEqual("Expected spy called-spy not to have been called with [ 'a', 'b' ] but it was."); }); it("passes through the custom equality testers", function() { var util = { contains: jasmine.createSpy('delegated-contains').and.returnValue(true) }, customEqualityTesters = [function() { return true; }], matcher = jasmineUnderTest.matchers.toHaveBeenCalledWith(util, customEqualityTesters), calledSpy = jasmineUnderTest.createSpy('called-spy'); calledSpy('a', 'b'); matcher.compare(calledSpy, 'a', 'b'); expect(util.contains).toHaveBeenCalledWith([['a', 'b']], ['a', 'b'], customEqualityTesters); }); it("fails when the actual was not called", function() { var util = { contains: jasmine.createSpy('delegated-contains').and.returnValue(false) }, matcher = jasmineUnderTest.matchers.toHaveBeenCalledWith(util), uncalledSpy = jasmineUnderTest.createSpy('uncalled spy'), result; result = matcher.compare(uncalledSpy); expect(result.pass).toBe(false); expect(result.message()).toEqual("Expected spy uncalled spy to have been called with [ ] but it was never called."); }); it("fails when the actual was called with different parameters", function() { var util = { contains: jasmine.createSpy('delegated-contains').and.returnValue(false) }, matcher = jasmineUnderTest.matchers.toHaveBeenCalledWith(util), calledSpy = jasmineUnderTest.createSpy('called spy'), result; calledSpy('a'); calledSpy('c', 'd'); result = matcher.compare(calledSpy, 'a', 'b'); expect(result.pass).toBe(false); expect(result.message()).toEqual("Expected spy called spy to have been called with [ 'a', 'b' ] but actual calls were [ 'a' ], [ 'c', 'd' ]."); }); it("throws an exception when the actual is not a spy", function() { var matcher = jasmineUnderTest.matchers.toHaveBeenCalledWith(), fn = function() {}; expect(function() { matcher.compare(fn) }).toThrowError(/Expected a spy, but got Function./); }); });
/*! * Ext JS Library 3.3.1 * Copyright(c) 2006-2010 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /** * Tests Ext.data.Store functionality * @author Ed Spencer */ (function() { var suite = Ext.test.session.getSuite('Ext.layout.ContainerLayout'), assert = Y.Assert; function buildLayout(config) { var layout = new Ext.layout.FormLayout(config || {}); //give a mock container layout.container = { itemCls: 'ctCls' }; return layout; }; suite.add(new Y.Test.Case({ name: 'parseMargins', setUp: function() { this.cont = new Ext.layout.ContainerLayout(); }, testParseFromNumber: function() { var res = this.cont.parseMargins(10); assert.areEqual(10, res.top); assert.areEqual(10, res.right); assert.areEqual(10, res.bottom); assert.areEqual(10, res.left); }, testParseFromString: function() { var res = this.cont.parseMargins("10"); assert.areEqual(10, res.top); assert.areEqual(10, res.right); assert.areEqual(10, res.bottom); assert.areEqual(10, res.left); }, testParseFromTwoArgString: function() { var res = this.cont.parseMargins("10 5"); assert.areEqual(10, res.top); assert.areEqual(5, res.right); assert.areEqual(10, res.bottom); assert.areEqual(5, res.left); }, testParseFromThreeArgString: function() { var res = this.cont.parseMargins("10 5 2"); assert.areEqual(10, res.top); assert.areEqual(5, res.right); assert.areEqual(2, res.bottom); assert.areEqual(5, res.left); }, testParseFromFourArgString: function() { var res = this.cont.parseMargins("10 5 2 1"); assert.areEqual(10, res.top); assert.areEqual(5, res.right); assert.areEqual(2, res.bottom); assert.areEqual(1, res.left); } })); suite.add(new Y.Test.Case({ name: 'configureItem', setUp: function() { this.layout = new Ext.layout.ContainerLayout({ extraCls: 'myExtraClass' }); //mock component object this.component = { addClass: Ext.emptyFn, doLayout: Ext.emptyFn }; }, testAddsExtraCls: function() { var layout = this.layout; var addedClass = ""; //mock component object c = { addClass: function(cls) { addedClass = cls; } }; layout.configureItem(c, 0); assert.areEqual('myExtraClass', addedClass); }, testAddsExtraClsToPositionEl: function() { var layout = this.layout; var addedClass = ""; //mock component object c = { getPositionEl: function() { return posEl; } }; //mock position el posEl = { addClass: function(cls) { addedClass = cls; } }; layout.configureItem(c, 0); assert.areEqual('myExtraClass', addedClass); }, testLaysOutIfForced: function() { var laidOut = false; var layout = this.layout, comp = this.component; //mock component object comp.doLayout = function() { laidOut = true; }; layout.configureItem(comp, 0); assert.isFalse(laidOut); layout.forceLayout = true; layout.configureItem(comp, 0); assert.isTrue(laidOut); }, testHidesIfRenderHidden: function() { } })); })();
"use strict"; var _ = require("underscore"); var errors = { // JSHint options E001: "Bad option: '{a}'.", E002: "Bad option value.", // JSHint input E003: "Expected a JSON value.", E004: "Input is neither a string nor an array of strings.", E005: "Input is empty.", E006: "Unexpected early end of program.", // Strict mode E007: "Missing \"use strict\" statement.", E008: "Strict violation.", E009: "Option 'validthis' can't be used in a global scope.", E010: "'with' is not allowed in strict mode.", // Constants E011: "const '{a}' has already been declared.", E012: "const '{a}' is initialized to 'undefined'.", E013: "Attempting to override '{a}' which is a constant.", // Regular expressions E014: "A regular expression literal can be confused with '/='.", E015: "Unclosed regular expression.", E016: "Invalid regular expression.", // Tokens E017: "Unclosed comment.", E018: "Unbegun comment.", E019: "Unmatched '{a}'.", E020: "Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.", E021: "Expected '{a}' and instead saw '{b}'.", E022: "Line breaking error '{a}'.", E023: "Missing '{a}'.", E024: "Unexpected '{a}'.", E025: "Missing ':' on a case clause.", E026: "Missing '}' to match '{' from line {a}.", E027: "Missing ']' to match '[' form line {a}.", E028: "Illegal comma.", E029: "Unclosed string.", // Everything else E030: "Expected an identifier and instead saw '{a}'.", E031: "Bad assignment.", // FIXME: Rephrase E032: "Expected a small integer or 'false' and instead saw '{a}'.", E033: "Expected an operator and instead saw '{a}'.", E034: "get/set are ES5 features.", E035: "Missing property name.", E036: "Expected to see a statement and instead saw a block.", E037: null, // Vacant E038: null, // Vacant E039: "Function declarations are not invocable. Wrap the whole function invocation in parens.", E040: "Each value should have its own case label.", E041: "Unrecoverable syntax error.", E042: "Stopping.", E043: "Too many errors.", E044: "'{a}' is already defined and can't be redefined.", E045: "Invalid for each loop.", E046: "A yield statement shall be within a generator function (with syntax: `function*`)", E047: "A generator function shall contain a yield statement.", E048: "Let declaration not directly within block.", E049: "A {a} cannot be named '{b}'.", E050: "Mozilla requires the yield expression to be parenthesized here." }; var warnings = { W001: "'hasOwnProperty' is a really bad name.", W002: "Value of '{a}' may be overwritten in IE 8 and earlier.", W003: "'{a}' was used before it was defined.", W004: "'{a}' is already defined.", W005: "A dot following a number can be confused with a decimal point.", W006: "Confusing minuses.", W007: "Confusing pluses.", W008: "A leading decimal point can be confused with a dot: '{a}'.", W009: "The array literal notation [] is preferrable.", W010: "The object literal notation {} is preferrable.", W011: "Unexpected space after '{a}'.", W012: "Unexpected space before '{a}'.", W013: "Missing space after '{a}'.", W014: "Bad line breaking before '{a}'.", W015: "Expected '{a}' to have an indentation at {b} instead at {c}.", W016: "Unexpected use of '{a}'.", W017: "Bad operand.", W018: "Confusing use of '{a}'.", W019: "Use the isNaN function to compare with NaN.", W020: "Read only.", W021: "'{a}' is a function.", W022: "Do not assign to the exception parameter.", W023: "Expected an identifier in an assignment and instead saw a function invocation.", W024: "Expected an identifier and instead saw '{a}' (a reserved word).", W025: "Missing name in function declaration.", W026: "Inner functions should be listed at the top of the outer function.", W027: "Unreachable '{a}' after '{b}'.", W028: "Label '{a}' on {b} statement.", W030: "Expected an assignment or function call and instead saw an expression.", W031: "Do not use 'new' for side effects.", W032: "Unnecessary semicolon.", W033: "Missing semicolon.", W034: "Unnecessary directive \"{a}\".", W035: "Empty block.", W036: "Unexpected /*member '{a}'.", W037: "'{a}' is a statement label.", W038: "'{a}' used out of scope.", W039: "'{a}' is not allowed.", W040: "Possible strict violation.", W041: "Use '{a}' to compare with '{b}'.", W042: "Avoid EOL escaping.", W043: "Bad escaping of EOL. Use option multistr if needed.", W044: "Bad or unnecessary escaping.", W045: "Bad number '{a}'.", W046: "Don't use extra leading zeros '{a}'.", W047: "A trailing decimal point can be confused with a dot: '{a}'.", W048: "Unexpected control character in regular expression.", W049: "Unexpected escaped character '{a}' in regular expression.", W050: "JavaScript URL.", W051: "Variables should not be deleted.", W052: "Unexpected '{a}'.", W053: "Do not use {a} as a constructor.", W054: "The Function constructor is a form of eval.", W055: "A constructor name should start with an uppercase letter.", W056: "Bad constructor.", W057: "Weird construction. Is 'new' unnecessary?", W058: "Missing '()' invoking a constructor.", W059: "Avoid arguments.{a}.", W060: "document.write can be a form of eval.", W061: "eval can be harmful.", W062: "Wrap an immediate function invocation in parens " + "to assist the reader in understanding that the expression " + "is the result of a function, and not the function itself.", W063: "Math is not a function.", W064: "Missing 'new' prefix when invoking a constructor.", W065: "Missing radix parameter.", W066: "Implied eval. Consider passing a function instead of a string.", W067: "Bad invocation.", W068: "Wrapping non-IIFE function literals in parens is unnecessary.", W069: "['{a}'] is better written in dot notation.", W070: "Extra comma. (it breaks older versions of IE)", W071: "This function has too many statements. ({a})", W072: "This function has too many parameters. ({a})", W073: "Blocks are nested too deeply. ({a})", W074: "This function's cyclomatic complexity is too high. ({a})", W075: "Duplicate key '{a}'.", W076: "Unexpected parameter '{a}' in get {b} function.", W077: "Expected a single parameter in set {a} function.", W078: "Setter is defined without getter.", W079: "Redefinition of '{a}'.", W080: "It's not necessary to initialize '{a}' to 'undefined'.", W081: "Too many var statements.", W082: "Function declarations should not be placed in blocks. " + "Use a function expression or move the statement to the top of " + "the outer function.", W083: "Don't make functions within a loop.", W084: "Expected a conditional expression and instead saw an assignment.", W085: "Don't use 'with'.", W086: "Expected a 'break' statement before '{a}'.", W087: "Forgotten 'debugger' statement?", W088: "Creating global 'for' variable. Should be 'for (var {a} ...'.", W089: "The body of a for in should be wrapped in an if statement to filter " + "unwanted properties from the prototype.", W090: "'{a}' is not a statement label.", W091: "'{a}' is out of scope.", W092: "Wrap the /regexp/ literal in parens to disambiguate the slash operator.", W093: "Did you mean to return a conditional instead of an assignment?", W094: "Unexpected comma.", W095: "Expected a string and instead saw {a}.", W096: "The '{a}' key may produce unexpected results.", W097: "Use the function form of \"use strict\".", W098: "'{a}' is defined but never used.", W099: "Mixed spaces and tabs.", W100: "This character may get silently deleted by one or more browsers.", W101: "Line is too long.", W102: "Trailing whitespace.", W103: "The '{a}' property is deprecated.", W104: "'{a}' is only available in JavaScript 1.7.", W105: "Unexpected {a} in '{b}'.", W106: "Identifier '{a}' is not in camel case.", W107: "Script URL.", W108: "Strings must use doublequote.", W109: "Strings must use singlequote.", W110: "Mixed double and single quotes.", W112: "Unclosed string.", W113: "Control character in string: {a}.", W114: "Avoid {a}.", W115: "Octal literals are not allowed in strict mode.", W116: "Expected '{a}' and instead saw '{b}'.", W117: "'{a}' is not defined.", W118: "'{a}' is only available in Mozilla JavaScript extensions (use moz option).", W119: "'{a}' is only available in ES6 (use esnext option).", W120: "You might be leaking a variable ({a}) here." }; var info = { I001: "Comma warnings can be turned off with 'laxcomma'.", I002: "Reserved words as properties can be used under the 'es5' option.", I003: "ES5 option is now set per default" }; exports.errors = {}; exports.warnings = {}; exports.info = {}; _.each(errors, function (desc, code) { exports.errors[code] = { code: code, desc: desc }; }); _.each(warnings, function (desc, code) { exports.warnings[code] = { code: code, desc: desc }; }); _.each(info, function (desc, code) { exports.info[code] = { code: code, desc: desc }; });
/* */ "format cjs"; "use strict"; var _toolsProtectJs2 = require("./../tools/protect.js"); var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2); exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _path = require("./path"); var _path2 = _interopRequireDefault(_path); var _types = require("../types"); var t = _interopRequireWildcard(_types); _toolsProtectJs3["default"](module); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var TraversalContext = (function () { function TraversalContext(scope, opts, state, parentPath) { _classCallCheck(this, TraversalContext); this.parentPath = parentPath; this.scope = scope; this.state = state; this.opts = opts; this.queue = null; } TraversalContext.prototype.shouldVisit = function shouldVisit(node) { var opts = this.opts; if (opts.enter || opts.exit) return true; if (opts[node.type]) return true; var keys = t.VISITOR_KEYS[node.type]; if (!keys || !keys.length) return false; var _arr = keys; for (var _i = 0; _i < _arr.length; _i++) { var key = _arr[_i]; if (node[key]) return true; } return false; }; TraversalContext.prototype.create = function create(node, obj, key, listKey) { var path = _path2["default"].get({ parentPath: this.parentPath, parent: node, container: obj, key: key, listKey: listKey }); path.unshiftContext(this); return path; }; TraversalContext.prototype.visitMultiple = function visitMultiple(container, parent, listKey) { // nothing to traverse! if (container.length === 0) return false; var visited = []; var queue = this.queue = []; var stop = false; // build up initial queue for (var key = 0; key < container.length; key++) { var self = container[key]; if (self && this.shouldVisit(self)) { queue.push(this.create(parent, container, key, listKey)); } } // visit the queue var _arr2 = queue; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var path = _arr2[_i2]; path.resync(); if (visited.indexOf(path.node) >= 0) continue; visited.push(path.node); if (path.visit()) { stop = true; break; } } var _arr3 = queue; for (var _i3 = 0; _i3 < _arr3.length; _i3++) { var path = _arr3[_i3]; path.shiftContext(); } this.queue = null; return stop; }; TraversalContext.prototype.visitSingle = function visitSingle(node, key) { if (this.shouldVisit(node[key])) { var path = this.create(node, node, key); path.visit(); path.shiftContext(); } }; TraversalContext.prototype.visit = function visit(node, key) { var nodes = node[key]; if (!nodes) return; if (Array.isArray(nodes)) { return this.visitMultiple(nodes, node, key); } else { return this.visitSingle(node, key); } }; return TraversalContext; })(); exports["default"] = TraversalContext; module.exports = exports["default"];