diff --git a/amplify/amplify-tests.ts b/amplify/amplify-tests.ts index 62584ec98b..edf2988122 100644 --- a/amplify/amplify-tests.ts +++ b/amplify/amplify-tests.ts @@ -26,7 +26,7 @@ amplify.subscribe("dataexample2", (param1, param2) => { alert(param1 + param2); // barbaz }); -//... +// ... amplify.publish("dataexample2", "bar", "baz"); @@ -176,7 +176,7 @@ amplify.request("twitter-mentions", { user: "amplifyjs" }); // Setting up and using decoders -//Example: +// Example: var appEnvelopeDecoder: amplify.Decoder = (data, status, xhr, success, error) => { if (data.status === "success") { @@ -188,7 +188,7 @@ var appEnvelopeDecoder: amplify.Decoder = (data, status, xhr, success, error) => } }; -//a new decoder can be added to the amplifyDecoders interface +// a new decoder can be added to the amplifyDecoders interface declare module "amplify" { interface Decoders { appEnvelope: amplify.Decoder; @@ -197,7 +197,7 @@ declare module "amplify" { amplify.request.decoders.appEnvelope = appEnvelopeDecoder; -//but you can also just add it via an index +// but you can also just add it via an index amplify.request.decoders['appEnvelopeStr'] = appEnvelopeDecoder; @@ -250,7 +250,7 @@ amplify.request({ // amplify.request comes with built in support for status.The status parameter appears in the default success or error callbacks when using an ajax definition. amplify.request.define("statusExample1", "ajax", { - //... + // ... }); amplify.request({ diff --git a/amqplib/amqplib-tests.ts b/amqplib/amqplib-tests.ts index b17128653a..24dade85dc 100644 --- a/amqplib/amqplib-tests.ts +++ b/amqplib/amqplib-tests.ts @@ -31,11 +31,11 @@ var anqpAssertExchangeReplies: amqp.Replies.AssertExchange; import amqpcb = require('amqplib/callback_api'); amqpcb.connect('amqp://localhost', (err, connection) => { - if(!err) { + if (!err) { connection.createChannel((err, channel) => { if (!err) { channel.assertQueue('myQueue', {}, (err, ok) => { - if(!err) { + if (!err) { channel.sendToQueue('myQueue', new Buffer(msg)); } }); @@ -45,11 +45,11 @@ amqpcb.connect('amqp://localhost', (err, connection) => { }); amqpcb.connect('amqp://localhost', (err, connection) => { - if(!err) { + if (!err) { connection.createChannel((err, channel) => { if (!err) { channel.assertQueue('myQueue', {}, (err, ok) => { - if(!err) { + if (!err) { channel.consume('myQueue', newMsg => console.log('New Message: ' + newMsg.content.toString())); } }); diff --git a/angular/angular-tests.ts b/angular/angular-tests.ts index bcf9501846..4e1f33ce47 100644 --- a/angular/angular-tests.ts +++ b/angular/angular-tests.ts @@ -28,7 +28,7 @@ class AuthService { $get = [ '$rootScope', '$injector', ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) => { - let $http: ng.IHttpService; //initialized later because of circular dependency problem + let $http: ng.IHttpService; // initialized later because of circular dependency problem function retry(config: ng.IRequestConfig, deferred: ng.IDeferred) { $http = $http || $injector.get('$http'); $http(config).then(response => { @@ -275,7 +275,7 @@ foo.then((x) => { }).then((x) => { // Object is inferred here x.a = 123; - //Try a promise + // Try a promise var y: ng.IPromise; var condition: boolean; return condition ? y : x.a; // IPromise | T, both are good for the 1st arg of .then() @@ -590,7 +590,7 @@ function test_angular_forEach() { angular.forEach(values, (value, key) => { this.push(key + ': ' + value); }, log); - //expect(log).toEqual(['name: misko', 'gender: male']); + // expect(log).toEqual(['name: misko', 'gender: male']); } // angular.element() tests diff --git a/angular/index.d.ts b/angular/index.d.ts index 67979435f1..bbbbdb021a 100644 --- a/angular/index.d.ts +++ b/angular/index.d.ts @@ -411,8 +411,8 @@ declare namespace angular { $invalid: boolean; } - //Allows tuning how model updates are done. - //https://docs.angularjs.org/api/ng/directive/ngModelOptions + // Allows tuning how model updates are done. + // https://docs.angularjs.org/api/ng/directive/ngModelOptions interface INgModelOptions { updateOn?: string; debounce?: any; @@ -1192,7 +1192,7 @@ declare namespace angular { */ size: number; - //...: any additional properties from the options object when creating the cache. + // ...: any additional properties from the options object when creating the cache. }; /** @@ -2035,7 +2035,7 @@ declare namespace angular { declare global { interface JQuery { // TODO: events, how to define? - //$destroy + // $destroy find(element: any): JQuery; find(obj: JQuery): JQuery; diff --git a/arcgis-rest-api/index.d.ts b/arcgis-rest-api/index.d.ts index 2b28b32fac..19aa499afa 100644 --- a/arcgis-rest-api/index.d.ts +++ b/arcgis-rest-api/index.d.ts @@ -168,12 +168,12 @@ export interface SimpleFillSymbol extends Symbol { "type": "esriSFS"; "style"?: SimpleFillSymbolStyle; "color"?: Color; - "outline"?: SimpleLineSymbol; //if outline has been specified + "outline"?: SimpleLineSymbol; // if outline has been specified } export interface PictureSourced { - "url"?: string; //Relative URL for static layers and full URL for dynamic layers. Access relative URL using http:////images/ - "imageData"?: string; //""; + "url"?: string; // Relative URL for static layers and full URL for dynamic layers. Access relative URL using http:////images/ + "imageData"?: string; // ""; "contentType"?: string; "width"?: number; "height"?: number; @@ -189,14 +189,14 @@ export interface PictureMarkerSymbol extends MarkerSymbol, PictureSourced { export interface PictureFillSymbol extends Symbol, PictureSourced { "type": "esriPFS"; - "outline"?: SimpleLineSymbol; //if outline has been specified + "outline"?: SimpleLineSymbol; // if outline has been specified "xscale"?: number; "yscale"?: number; } export interface Font { - "family"?: string; //""; - "size"?: number; //; + "family"?: string; // ""; + "size"?: number; // ; "style"?: "italic" | "normal" | "oblique"; "weight"?: "bold" | "bolder" | "lighter" | "normal"; "decoration"?: "line-through" | "underline" | "none"; @@ -215,5 +215,5 @@ export interface TextSymbol extends MarkerSymbol { "rightToLeft"?: boolean; "kerning"?: boolean; "font"?: Font; - "text"?: string; //only applicable when specified as a client-side graphic. + "text"?: string; // only applicable when specified as a client-side graphic. } \ No newline at end of file diff --git a/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts b/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts index 48a06fcd02..2e9337793a 100644 --- a/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts +++ b/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts @@ -1,14 +1,14 @@ import utils = require("arcgis-to-geojson-utils"); import arcgisApi = require("arcgis-rest-api"); -let arcgisPoint: arcgisApi.Point = { +const arcgisPoint: arcgisApi.Point = { x: -122.6764, y: 45.5165, spatialReference: { wkid: 4326 } }; -let geojsonPoint: GeoJSON.Point = { +const geojsonPoint: GeoJSON.Point = { type: "Point", coordinates: [45.5165, -122.6764] }; diff --git a/array-find-index/array-find-index-tests.ts b/array-find-index/array-find-index-tests.ts index 1443c50b77..0c7508af5e 100644 --- a/array-find-index/array-find-index-tests.ts +++ b/array-find-index/array-find-index-tests.ts @@ -3,6 +3,6 @@ import arrayFindIndex = require("array-find-index"); arrayFindIndex(['rainbow', 'unicorn', 'pony'], x => x === 'unicorn'); const ctx = {foo: 'rainbow'}; -arrayFindIndex(['rainbow', 'unicorn', 'pony'], function (x) { +arrayFindIndex(['rainbow', 'unicorn', 'pony'], function(x) { return x === this.foo; }, ctx); diff --git a/artyom.js/artyom.js-tests.ts b/artyom.js/artyom.js-tests.ts index e70704ad4e..67e5908883 100644 --- a/artyom.js/artyom.js-tests.ts +++ b/artyom.js/artyom.js-tests.ts @@ -1,7 +1,7 @@ import artyomjs = require('artyom.js'); // Get an unique ArtyomJS instance -let artyom = artyomjs.ArtyomBuilder.getInstance(); +const artyom = artyomjs.ArtyomBuilder.getInstance(); // Add a command (not smart) artyom.addCommands({ diff --git a/artyom.js/index.d.ts b/artyom.js/index.d.ts index 860cb123b8..0b0f253827 100644 --- a/artyom.js/index.d.ts +++ b/artyom.js/index.d.ts @@ -508,6 +508,6 @@ declare namespace Artyom { } -//tslint:disable-next-line:export-just-namespace +// tslint:disable-next-line:export-just-namespace export = Artyom; export as namespace Artyom; diff --git a/assert-plus/assert-plus-tests.ts b/assert-plus/assert-plus-tests.ts index ec1036e56f..f9f0b2fe3b 100644 --- a/assert-plus/assert-plus-tests.ts +++ b/assert-plus/assert-plus-tests.ts @@ -1,5 +1,5 @@ import * as assert from 'assert-plus'; -let arr = ['one', 'two']; +const arr = ['one', 'two']; assert.array(arr, ''); diff --git a/base-64/base-64-tests.ts b/base-64/base-64-tests.ts index d5b6d6520e..3435ae8265 100644 --- a/base-64/base-64-tests.ts +++ b/base-64/base-64-tests.ts @@ -10,4 +10,4 @@ encoded = 'Zm9vIMKpIGJhciDwnYyGIGJheg=='; bytes = base64.decode(encoded); text = utf8.decode(bytes); -let version = base64.version; +const version = base64.version; diff --git a/bitcoinjs-lib/bitcoinjs-lib-tests.ts b/bitcoinjs-lib/bitcoinjs-lib-tests.ts index b9efec2f9d..d62ccb42e2 100644 --- a/bitcoinjs-lib/bitcoinjs-lib-tests.ts +++ b/bitcoinjs-lib/bitcoinjs-lib-tests.ts @@ -13,7 +13,7 @@ describe('bitcoinjs-lib (basic)', () => { function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); } // generate random keyPair - var keyPair = bitcoin.ECPair.makeRandom({ rng: rng }); + var keyPair = bitcoin.ECPair.makeRandom({ rng }); var address = keyPair.getAddress(); assert.strictEqual(address, '1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64'); @@ -35,7 +35,7 @@ describe('bitcoinjs-lib (basic)', () => { var litecoin = bitcoin.networks.litecoin; - var keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng: rng }); + var keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng }); var wif = keyPair.toWIF(); var address = keyPair.getAddress(); diff --git a/camelcase-keys/camelcase-keys-tests.ts b/camelcase-keys/camelcase-keys-tests.ts index 7388950bb6..ed2865e9ce 100644 --- a/camelcase-keys/camelcase-keys-tests.ts +++ b/camelcase-keys/camelcase-keys-tests.ts @@ -1,10 +1,10 @@ import camelcaseKeys = require('camelcase-keys'); camelcaseKeys({'foo-bar': true}); -//=> {fooBar: true} +// => {fooBar: true} camelcaseKeys({'foo-bar': true, 'nested': {unicorn_rainbow: true}}, {deep: true}); -//=> {fooBar: true, nested: {unicornRainbow: true}} +// => {fooBar: true, nested: {unicornRainbow: true}} camelcaseKeys({'_': [], 'foo-bar': true}); -//=> {_: [], fooBar: true} \ No newline at end of file +// => {_: [], fooBar: true} \ No newline at end of file diff --git a/chai-json-schema/chai-json-schema-tests.ts b/chai-json-schema/chai-json-schema-tests.ts index aacd40bf15..5d4715a76e 100644 --- a/chai-json-schema/chai-json-schema-tests.ts +++ b/chai-json-schema/chai-json-schema-tests.ts @@ -42,14 +42,14 @@ const fruitSchema = { } }; -//bdd style +// bdd style expect(goodApple).to.be.jsonSchema(fruitSchema); expect(badApple).to.not.be.jsonSchema(fruitSchema); goodApple.should.be.jsonSchema(fruitSchema); badApple.should.not.be.jsonSchema(fruitSchema); -//tdd style +// tdd style assert.jsonSchema(goodApple, fruitSchema); assert.notJsonSchema(badApple, fruitSchema); diff --git a/chai-xml/chai-xml-tests.ts b/chai-xml/chai-xml-tests.ts index 492e671bbe..c217662316 100644 --- a/chai-xml/chai-xml-tests.ts +++ b/chai-xml/chai-xml-tests.ts @@ -2,10 +2,10 @@ import * as chai from 'chai'; import chaiXml = require('chai-xml'); chai.use(chaiXml); -let expect = chai.expect; +const expect = chai.expect; function test_chaiXml() { - let testXml = 'test'; + const testXml = 'test'; expect('nope').xml.not.to.be.valid(); expect(testXml).xml.to.be.valid(); expect(testXml).xml.to.equal('\ntest\n'); diff --git a/chunked-dc/chunked-dc-tests.ts b/chunked-dc/chunked-dc-tests.ts index 8e1ee9f00f..1bedf11c5a 100644 --- a/chunked-dc/chunked-dc-tests.ts +++ b/chunked-dc/chunked-dc-tests.ts @@ -1,11 +1,11 @@ // Chunker -let chunker = new Chunker(1337, Uint8Array.of(1,2,3), 2); -for (let chunk of chunker) { +let chunker = new Chunker(1337, Uint8Array.of(1, 2, 3), 2); +for (const chunk of chunker) { // Do smoething with chunk } while (chunker.hasNext) { - let chunk = chunker.next().value; + const chunk = chunker.next().value; } // Unchunker @@ -14,6 +14,6 @@ let unchunker = new Unchunker(); unchunker.onMessage = (message: Uint8Array, context: any[]) => { // Do something with the received message }; -let chunk = Uint8Array.of(1,2).buffer; +let chunk = Uint8Array.of(1, 2).buffer; unchunker.add(chunk); unchunker.gc(1024); diff --git a/chunked-dc/index.d.ts b/chunked-dc/index.d.ts index 2b38bef438..ab3acd6901 100644 --- a/chunked-dc/index.d.ts +++ b/chunked-dc/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chunked-dc v0.1.2 +// Type definitions for chunked-dc 0.1 // Project: https://github.com/saltyrtc/chunked-dc-js // Definitions by: Danilo Bargen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -21,7 +21,7 @@ declare namespace chunkedDc { } interface ChunkerStatic { - new(id: number, message: Uint8Array, chunkSize: number): Chunker + new(id: number, message: Uint8Array, chunkSize: number): Chunker; } /** unchunker.ts **/ @@ -35,14 +35,14 @@ declare namespace chunkedDc { } interface UnchunkerStatic { - new(): Unchunker + new(): Unchunker; } /** main.ts **/ interface Standalone { - Chunker: ChunkerStatic, - Unchunker: UnchunkerStatic, + Chunker: ChunkerStatic; + Unchunker: UnchunkerStatic; } } diff --git a/chunked-dc/tsconfig.json b/chunked-dc/tsconfig.json index 0adf199b05..55832d5160 100644 --- a/chunked-dc/tsconfig.json +++ b/chunked-dc/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6" ], diff --git a/chunked-dc/tslint.json b/chunked-dc/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/chunked-dc/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/clndr/clndr-tests.ts b/clndr/clndr-tests.ts index ea6c624ee8..828dfdf2a7 100644 --- a/clndr/clndr-tests.ts +++ b/clndr/clndr-tests.ts @@ -1,6 +1,6 @@ import * as Clndr from 'clndr'; -let options: Clndr.ClndrOptions = { +const options: Clndr.ClndrOptions = { template: '', startWithMonth: "YYYY-MM-DD", weekOffset: 0, @@ -69,7 +69,7 @@ let options: Clndr.ClndrOptions = { moment: null }; -let myCalendar = $('.parent-element').clndr(options); +const myCalendar = $('.parent-element').clndr(options); myCalendar .forward() diff --git a/co-views/co-views-tests.ts b/co-views/co-views-tests.ts index ec5f53ae7c..35f12bbe99 100644 --- a/co-views/co-views-tests.ts +++ b/co-views/co-views-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as views from 'co-views'; const render = views('views', { @@ -15,7 +12,6 @@ const locals = {}; // template locals data async function test() { const html = await render(fileName, locals); - console.log(html); } // or use generator diff --git a/co-views/index.d.ts b/co-views/index.d.ts index f5b8c3d3e0..5df2238c12 100644 --- a/co-views/index.d.ts +++ b/co-views/index.d.ts @@ -1,50 +1,44 @@ -// Type definitions for co-views v2.1 +// Type definitions for co-views 2.1 // Project: https://github.com/tj/co-views/ // Definitions by: devlee , Joshua DeVinney // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace CoViews { - - /** - * Pass views `dir` and `opts` to return a render function. - */ - export interface Views { - (dir?: string, opts?: CoViewsOptions): { (view: string, locals?: Object): any } - } - - export interface CoViewsOptions { + export interface Options { + /** + * default extname + */ + ext?: string; /** * default extname */ - ext?: string, - - /** - * default extname - */ - default?: string, + default?: string; /** * engine map */ - map?: Object, + map?: Object; /** * proxy partials */ - partials?: Object, + partials?: Object; /** * cache compiled templates */ - cache?: boolean, + cache?: boolean; /** * common locals data */ - locals?: Object + locals?: Object; } } -declare var CoViews: CoViews.Views; +/** + * Pass views `dir` and `opts` to return a render function. + */ +declare function CoViews(dir?: string, opts?: CoViews.Options): (view: string, locals?: Object) => any; export = CoViews; diff --git a/co-views/tsconfig.json b/co-views/tsconfig.json index a3aec989e0..5a319edbcf 100644 --- a/co-views/tsconfig.json +++ b/co-views/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6" ], diff --git a/co-views/tslint.json b/co-views/tslint.json new file mode 100644 index 0000000000..0f47deabb4 --- /dev/null +++ b/co-views/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} \ No newline at end of file diff --git a/code/code-tests.ts b/code/code-tests.ts index fd49303d77..c3455577d9 100644 --- a/code/code-tests.ts +++ b/code/code-tests.ts @@ -16,7 +16,7 @@ expect([1, 2, 3]).to.part.include([1, 4]); expect(10, "Age").to.be.above(5); -const func = function () { return arguments; }; +const func = function() { return arguments; }; expect(func()).to.be.arguments(); expect([1, 2]).to.be.an.array(); diff --git a/coinstring/coinstring-tests.ts b/coinstring/coinstring-tests.ts index 83bddf31f0..ab11a44fb7 100644 --- a/coinstring/coinstring-tests.ts +++ b/coinstring/coinstring-tests.ts @@ -5,32 +5,32 @@ import cs = require('coinstring'); var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd"; var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex'); -var version = 0x80; //Bitcoin private key +var version = 0x80; // Bitcoin private key console.log(cs.encode(privateKeyHexBuf, version)); // => 5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD -var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; //hash representing uncompressed +var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; // hash representing uncompressed var hash160Buf = new Buffer(hash160, 'hex'); -var version = 0x00; //Bitcoin public address +var version = 0x00; // Bitcoin public address console.log(cs.encode(hash160Buf, version)); // => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd"; -//for compressed, append "01" +// for compressed, append "01" privateKeyHex += '01'; var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex'); -var version = 0x80; //Bitcoin private key +var version = 0x80; // Bitcoin private key console.log(cs.encode(privateKeyHexBuf, version)); // => KwomKti1X3tYJUUMb1TGSM2mrZk1wb1aHisUNHCQXTZq5auC2qc3 -var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; //hash representing uncompressed +var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; // hash representing uncompressed var hash160Buf = new Buffer(hash160, 'hex'); -var version = 0x1E; //Dogecoin public address +var version = 0x1E; // Dogecoin public address console.log(cs.encode(hash160Buf, version)); // => DAcq9oJpZZAjr56RmF7Y5zmWboZWQ4HAsW @@ -38,7 +38,7 @@ console.log(cs.encode(hash160Buf, version)); var data = "000000000000000000873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d50800e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35"; var buffer = new Buffer(data, 'hex'); -var versionBuffer = new Buffer('0488ade4', 'hex'); //0488ade4 is a consant listed in the aforementioned bip32 wiki. +var versionBuffer = new Buffer('0488ade4', 'hex'); // 0488ade4 is a consant listed in the aforementioned bip32 wiki. console.log(cs.encode(buffer, versionBuffer)); // => xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi @@ -46,24 +46,24 @@ console.log(cs.encode(buffer, versionBuffer)); var privateKeyHex = "1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd"; var privateKeyHexBuf = new Buffer(privateKeyHex, 'hex'); -var version = 0x80; //Bitcoin private key +var version = 0x80; // Bitcoin private key var toBtcWif = cs.createEncoder(version); -//later in your program +// later in your program console.log(toBtcWif(privateKeyHexBuf)); // => 5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD var wif = "5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD"; -var version = 0x80; //Bitcoin private key +var version = 0x80; // Bitcoin private key var fromBtcWif = cs.createDecoder(version); -var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; //hash representing uncompressed +var hash160 = "3c176e659bea0f29a3e9bf7880c112b1b31b4dc8"; // hash representing uncompressed var hash160Buf = new Buffer(hash160, 'hex'); -var version = 0x6F; //Bitcoin Testnet Address +var version = 0x6F; // Bitcoin Testnet Address var testnetAddressValidator = cs.createValidator(version); console.log(testnetAddressValidator("mkzgubTA5Ahi6BPSkE6MN9pEafRutznkMe")); // => true \ No newline at end of file diff --git a/concat-stream/concat-stream-tests.ts b/concat-stream/concat-stream-tests.ts index dc01583a79..4f3bf839e0 100644 --- a/concat-stream/concat-stream-tests.ts +++ b/concat-stream/concat-stream-tests.ts @@ -14,7 +14,7 @@ class MyReadable extends Readable { } } -let myReadable = new MyReadable(); +const myReadable = new MyReadable(); myReadable.pipe(concat((buf) => console.log(buf.toString()))); myReadable.pipe(concat({}, (buf) => console.log(buf.toString()))); diff --git a/core-decorators/core-decorators-tests.ts b/core-decorators/core-decorators-tests.ts index 86df21fc6d..04a22c19cf 100644 --- a/core-decorators/core-decorators-tests.ts +++ b/core-decorators/core-decorators-tests.ts @@ -17,8 +17,8 @@ class Person { } } -let person = new Person(); -let { getPerson, getPersonAgain } = person; +const person = new Person(); +const { getPerson, getPersonAgain } = person; getPerson() === person; @@ -81,7 +81,7 @@ class Person2 { facepalmHarder() {} } -let person2 = new Person2(); +const person2 = new Person2(); person2.facepalm(); // DEPRECATION Person#facepalm: This function will be removed in future versions. @@ -144,7 +144,7 @@ class Person3 { } } -let person3 = new Person3(); +const person3 = new Person3(); person3.facepalmWithoutWarning(); // no warning is logged @@ -242,7 +242,7 @@ editor.hugeBuffer; // already initialized and equals our buffer, so // createHugeBuffer() is not called again -//TODO: For @mixin, I don't know how we can make it work for TypeScript... +// TODO: For @mixin, I don't know how we can make it work for TypeScript... // // @mixin (alias: @mixins) // @@ -265,7 +265,7 @@ const FlyMixin = { @mixin(SingerMixin, FlyMixin) class Bird { singMatingCall() { - //TODO: For @mixin, I don't know how we can make it work for TypeScript... + // TODO: For @mixin, I don't know how we can make it work for TypeScript... // this.sing('tweet tweet'); } } @@ -280,10 +280,10 @@ bird.singMatingCall(); import { time } from 'core-decorators'; -let myConsole = { - time: function(label: string) { /* custom time() method */ }, - timeEnd: function(label: string) { /* custom timeEnd method */ }, - log: function(str: any) { /* custom log method */ } +const myConsole = { + time(label: string) { /* custom time() method */ }, + timeEnd(label: string) { /* custom timeEnd method */ }, + log(str: any) { /* custom log method */ } }; class Bird2 { diff --git a/core-decorators/index.d.ts b/core-decorators/index.d.ts index 18fcc95a27..d0a51009eb 100644 --- a/core-decorators/index.d.ts +++ b/core-decorators/index.d.ts @@ -1,8 +1,8 @@ -// Type definitions for core-decorators.js v0.10 +// Type definitions for core-decorators.js 0.10 // Project: https://github.com/jayphelps/core-decorators.js // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.1 export interface ClassDecorator { (target: TFunction): TFunction | void; diff --git a/core-decorators/tsconfig.json b/core-decorators/tsconfig.json index dee0784eed..1c0b389c96 100644 --- a/core-decorators/tsconfig.json +++ b/core-decorators/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/core-decorators/tslint.json b/core-decorators/tslint.json new file mode 100644 index 0000000000..e6de75c9f2 --- /dev/null +++ b/core-decorators/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "callable-types": false, + "forbidden-types": false + } +} \ No newline at end of file diff --git a/csv-stringify/csv-stringify-tests.ts b/csv-stringify/csv-stringify-tests.ts index 7ffd1f6e3e..bd6873affb 100644 --- a/csv-stringify/csv-stringify-tests.ts +++ b/csv-stringify/csv-stringify-tests.ts @@ -19,6 +19,6 @@ stream = stringify({ delimiter: "," }); stream.write(["1", "2", "3"]); -let transform: NodeJS.ReadWriteStream = stream; +const transform: NodeJS.ReadWriteStream = stream; stream = stringify(); diff --git a/d3-axis/d3-axis-tests.ts b/d3-axis/d3-axis-tests.ts index 9e50c05c7c..1a4077d690 100644 --- a/d3-axis/d3-axis-tests.ts +++ b/d3-axis/d3-axis-tests.ts @@ -54,9 +54,9 @@ axisScaleString = scalePoint(); // -------------------------------------------------------------------------- let containerElement: d3Axis.AxisContainerElement; -const svg: SVGSVGElement = select('svg').node() !; //mock -const g: SVGGElement = select('g').node() !; //mock -const canvas: HTMLCanvasElement = select('canvas').node() !; //mock +const svg: SVGSVGElement = select('svg').node() !; // mock +const g: SVGGElement = select('g').node() !; // mock +const canvas: HTMLCanvasElement = select('canvas').node() !; // mock containerElement = svg; containerElement = g; @@ -78,7 +78,7 @@ let leftAxis: d3Axis.Axis = d3Axis.axisLeft(scal // scale(...) ---------------------------------------------------------------- leftAxis = leftAxis.scale(scalePow()); -let powerScale: ScalePower = leftAxis.scale>(); +const powerScale: ScalePower = leftAxis.scale>(); // powerScale = leftAxis.scale(); // fails, without casting as AxisScale is purposely generic @@ -86,8 +86,8 @@ let powerScale: ScalePower = leftAxis.scale()); // bottomAxis = bottomAxis.scale(scalePow()) // fails, domain of scale incompatible with domain of axis -let axisScale: d3Axis.AxisScale = bottomAxis.scale(); -let ordinalScale: ScaleOrdinal = bottomAxis.scale>(); +const axisScale: d3Axis.AxisScale = bottomAxis.scale(); +const ordinalScale: ScaleOrdinal = bottomAxis.scale>(); // ordinalScale = bottomAxis.scale(); // fails, without casting as AxisScale is purposely generic // ticks(...) ---------------------------------------------------------------- @@ -102,7 +102,7 @@ topAxis = topAxis.tickArguments([20, 's']); rightAxis = rightAxis.tickArguments([timeMinute.every(5)]); -let tickArguments: any[] = leftAxis.tickArguments(); +const tickArguments: any[] = leftAxis.tickArguments(); // tickValues(...) ---------------------------------------------------------------- @@ -112,14 +112,14 @@ bottomAxis = bottomAxis.tickValues(['strongly negative', 'strongly positive']); leftAxis = leftAxis.tickValues(null); -let tickValues: Date[] | null = rightAxis.tickValues(); +const tickValues: Date[] | null = rightAxis.tickValues(); // tickFormat(...) ---------------------------------------------------------------- topAxis = topAxis.tickFormat(format(',.0f')); topAxis = topAxis.tickFormat(null); -let formatFn: ((domainValue: string, index: number) => string) | null = bottomAxis.tickFormat(); +const formatFn: ((domainValue: string, index: number) => string) | null = bottomAxis.tickFormat(); bottomAxis.tickFormat((d, i) => '#' + i); bottomAxis.tickFormat(d => d + '!'); @@ -147,20 +147,20 @@ num = rightAxis.tickPadding(); // Test Apply Axis // -------------------------------------------------------------------------- -let gSelection: Selection = select('g'); -let gTransition = gSelection.transition(); +const gSelection: Selection = select('g'); +const gTransition = gSelection.transition(); gSelection.call(topAxis); gTransition.call(topAxis); -let svgSelection: Selection = select('g'); -let svgTransition = svgSelection.transition(); +const svgSelection: Selection = select('g'); +const svgTransition = svgSelection.transition(); svgSelection.call(leftAxis); svgTransition.call(leftAxis); -let canvasSelection: Selection = select('canvas'); -let canvasTransition = canvasSelection.transition(); +const canvasSelection: Selection = select('canvas'); +const canvasTransition = canvasSelection.transition(); // canvasSelection.call(rightAxis); // fails, incompatible context container element // canvasTransition.call(rightAxis); // fails, incompatible context container element diff --git a/d3-brush/d3-brush-tests.ts b/d3-brush/d3-brush-tests.ts index a4b0526a9d..367cc05d1b 100644 --- a/d3-brush/d3-brush-tests.ts +++ b/d3-brush/d3-brush-tests.ts @@ -26,9 +26,9 @@ interface BrushDatum { let brush: d3Brush.BrushBehavior = d3Brush.brush(); -let brushX: d3Brush.BrushBehavior = d3Brush.brushX(); +const brushX: d3Brush.BrushBehavior = d3Brush.brushX(); -let brushY: d3Brush.BrushBehavior = d3Brush.brushY(); +const brushY: d3Brush.BrushBehavior = d3Brush.brushY(); // extent() ---------------------------------------------------------------------- @@ -50,7 +50,7 @@ brush = brush.extent(function(d, i, group) { brush = brush.filter(function(d, i, group) { // Cast d3 event to D3ZoomEvent to be used in filter logic - let e = > event; + const e = > event; console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement return e.sourceEvent.type !== 'zoom' || !d.filterZoomEvent; // datum type is BrushDatum (as propagated to SVGGElement with brush event attached) @@ -63,17 +63,17 @@ filterFn = brush.filter(); // chainable brush = brush.handleSize(7); -let handleSize: number = brush.handleSize(); +const handleSize: number = brush.handleSize(); // on() ------------------------------------------------------------------------ let brushed: ((this: SVGGElement, datum: BrushDatum, index: number, group: SVGGElement[] | ArrayLike) => void) | undefined; -brushed = function(d, i, group) { +brushed = (d, i, group) => { // do anything }; -let wrongHandler1: (this: SVGSVGElement, datum: BrushDatum, index: number, group: SVGSVGElement[] | ArrayLike) => void; -let wrongHandler2: (this: SVGGElement, datum: { test: string }, index: number, group: SVGGElement[] | ArrayLike) => void; +// let wrongHandler1: (this: SVGSVGElement, datum: BrushDatum, index: number, group: SVGSVGElement[] | ArrayLike) => void; +// let wrongHandler2: (this: SVGGElement, datum: { test: string }, index: number, group: SVGGElement[] | ArrayLike) => void; // chainable brush = brush.on('end', brushed); @@ -88,10 +88,10 @@ brush = brush.on('end', null); // re-apply brush.on('end', function(d, i, g) { - let that: SVGGElement = this; - let datum: BrushDatum = d; - let index: number = i; - let group: SVGGElement[] | ArrayLike = g; + const that: SVGGElement = this; + const datum: BrushDatum = d; + const index: number = i; + const group: SVGGElement[] | ArrayLike = g; console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement console.log('Extent as per data: ', d.extent); // datum of type BrushDatum // do anything @@ -103,7 +103,7 @@ brush.on('end', function(d, i, g) { // Test Attach Brush Behavior // ----------------------------------------------------------------------------- -let g = select('svg') +const g = select('svg') .append('g') .classed('brush', true) .datum({ @@ -113,7 +113,7 @@ let g = select('svg') g.call(brush); -let gX = select('svg') +const gX = select('svg') .append('g') .classed('brush', true) .datum({ @@ -129,13 +129,13 @@ gX.call(brushX); // Test Use Brush Behavior // ----------------------------------------------------------------------------- -let gTransition = g.transition(); +const gTransition = g.transition(); // 2d brush move with Selection brush.move(g, [[10, 10], [50, 50]]); // two-dimensional brush -brush.move(g, function (d, i, group) { +brush.move(g, function(d, i, group) { console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement - let selection: [[number, number], [number, number]] = [[0, 0], [0, 0]]; + const selection: [[number, number], [number, number]] = [[0, 0], [0, 0]]; selection[0][0] = d.extent[0][0] + 10; // datum type is brushDatum selection[0][1] = d.extent[0][1] + 10; selection[1][0] = d.extent[0][0] + 40; @@ -145,9 +145,9 @@ brush.move(g, function (d, i, group) { // 2d brush move with Transition brush.move(gTransition, [[10, 10], [50, 50]]); // two-dimensional brush -brush.move(gTransition, function (d, i, group) { +brush.move(gTransition, function(d, i, group) { console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement - let selection: [[number, number], [number, number]] = [[0, 0], [0, 0]]; + const selection: [[number, number], [number, number]] = [[0, 0], [0, 0]]; selection[0][0] = d.extent[0][0] + 10; // datum type is brushDatum selection[0][1] = d.extent[0][1] + 10; selection[1][0] = d.extent[0][0] + 40; @@ -156,13 +156,13 @@ brush.move(gTransition, function (d, i, group) { }); -let gXTransition = gX.transition(); +const gXTransition = gX.transition(); // 1d brush move with Selection brush.move(gX, [10, 40]); // two-dimensional brush -brush.move(gX, function (d, i, group) { +brush.move(gX, function(d, i, group) { console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement - let selection: [number, number] = [0, 0]; + const selection: [number, number] = [0, 0]; selection[0] = d.extent[0][0] + 10; // datum type is brushDatum selection[1] = d.extent[0][0] + 40; return selection; @@ -170,9 +170,9 @@ brush.move(gX, function (d, i, group) { // 1d brush move with Transition brush.move(gXTransition, [10, 40]); // two-dimensional brush -brush.move(gXTransition, function (d, i, group) { +brush.move(gXTransition, function(d, i, group) { console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement - let selection: [number, number] = [0, 0]; + const selection: [number, number] = [0, 0]; selection[0] = d.extent[0][0] + 10; // datum type is brushDatum selection[1] = d.extent[0][0] + 40; return selection; @@ -184,10 +184,10 @@ brush.move(gXTransition, function (d, i, group) { // ----------------------------------------------------------------------------- -let e: d3Brush.D3BrushEvent = event; +const e: d3Brush.D3BrushEvent = event; -let target: d3Brush.BrushBehavior = e.target; -let type: 'start' | 'brush' | 'end' | string = e.type; -let brushSelection: d3Brush.BrushSelection = e.selection; -let sourceEvent: any = e.sourceEvent; +const target: d3Brush.BrushBehavior = e.target; +const type: 'start' | 'brush' | 'end' | string = e.type; +const brushSelection: d3Brush.BrushSelection = e.selection; +const sourceEvent: any = e.sourceEvent; diff --git a/d3-chord/d3-chord-tests.ts b/d3-chord/d3-chord-tests.ts index 5bde46600c..c826c81fac 100644 --- a/d3-chord/d3-chord-tests.ts +++ b/d3-chord/d3-chord-tests.ts @@ -23,7 +23,7 @@ let chord: d3Chord.Chord; let chordSubgroup: d3Chord.ChordSubgroup; let num: number; -let matrix: number[][] = [ +const matrix: number[][] = [ [11975, 5871, 8916, 2868], [1951, 10048, 2060, 6171], [8010, 16145, 8090, 8045], @@ -79,7 +79,7 @@ chords = chordLayout(matrix); // Test supporting interfaces ========================================== -let length: number = chords.length; +const length: number = chords.length; chordGroups = chords.groups; @@ -145,7 +145,7 @@ subgroupAccessor = svgRibbon.target(); canvasRibbon = canvasRibbon.radius(30); -svgRibbon = svgRibbon.radius(function (d) { +svgRibbon = svgRibbon.radius(function(d) { console.log('SVGPathElement createSVGPathSegCurvetoCubicAbs method:', this.createSVGPathSegCurvetoCubicAbs); // this type SVGPathElement console.log('Subgroup startAngle', d.startAngle); // datum is of type Chord return 30; @@ -157,7 +157,7 @@ numAccessor = svgRibbon.radius(); canvasRibbon = canvasRibbon.startAngle(0); -svgRibbon = svgRibbon.startAngle(function (d) { +svgRibbon = svgRibbon.startAngle(function(d) { console.log('SVGPathElement createSVGPathSegCurvetoCubicAbs method:', this.createSVGPathSegCurvetoCubicAbs); // this type SVGPathElement return d.startAngle; // datum is of type ChordSubgroup }); @@ -168,7 +168,7 @@ numAccessor = svgRibbon.startAngle(); canvasRibbon = canvasRibbon.endAngle(Math.PI); -svgRibbon = svgRibbon.endAngle(function (d) { +svgRibbon = svgRibbon.endAngle(function(d) { console.log('SVGPathElement createSVGPathSegCurvetoCubicAbs method:', this.createSVGPathSegCurvetoCubicAbs); // this type SVGPathElement return d.endAngle; // datum is of type ChordSubgroup }); @@ -178,7 +178,7 @@ numAccessor = svgRibbon.endAngle(); // Use RibbonGenerator ================================================= // use canvas -let ribbon: d3Chord.Ribbon = { +const ribbon: d3Chord.Ribbon = { source: {startAngle: 0.7524114, endAngle: 1.1212972, radius: 240}, target: {startAngle: 1.8617078, endAngle: 1.9842927, radius: 240} }; @@ -199,6 +199,6 @@ let ribbonPaths: Selection('g') .datum(chords) .selectAll() - .data(function (chords) { return chords; }) + .data(chords => chords) .enter().append('path') .attr('d', svgRibbon); diff --git a/d3-drag/d3-drag-tests.ts b/d3-drag/d3-drag-tests.ts index 71ae3d0a29..ddaeaa74a0 100644 --- a/d3-drag/d3-drag-tests.ts +++ b/d3-drag/d3-drag-tests.ts @@ -38,9 +38,9 @@ interface CustomSubject { r: number; } -let svg: SVGSVGElement = select('svg').node()!; // mock +const svg: SVGSVGElement = select('svg').node()!; // mock -let circles: Selection = select('svg').selectAll('circle'); // mock +const circles: Selection = select('svg').selectAll('circle'); // mock // ----------------------------------------------------------------------------- // Test Define DragBehavior @@ -110,11 +110,11 @@ filterFn = circleDrag.filter(); circleCustomDrag.subject(function(d, i, g) { // Cast event type for completeness, otherwise event is of type any. - let e = > event; - let that: SVGCircleElement = this; - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; + const e = > event; + const that: SVGCircleElement = this; + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; if (d == null) { return { x: e.x, y: e.y }; @@ -139,14 +139,14 @@ subjectAccessor = circleCustomDrag.subject(); function dragstarted(this: SVGCircleElement, d: CircleDatum) { // cast d3 event to drag event. Otherwise, d3 event is currently defined as type 'any' - let e = > event; + const e = > event; e.sourceEvent.stopPropagation(); select(this).classed('dragging', true); } function dragged(this: SVGCircleElement, d: CircleDatum) { // cast d3 event to drag event. Otherwise, d3 event is currently defined as type 'any' - let e = > event; + const e = > event; select(this).attr('cx', d.x = e.x).attr('cy', d.y = e.y); } @@ -183,7 +183,7 @@ let handler: ((this: SVGCircleElement, d: CircleDatum, i: number, group: SVGCirc circles.call(circleDrag); -let wrongSelection: Selection = select('div'); +const wrongSelection: Selection = select('div'); // wrongSelection.call(circleDrag); // fails, as dragged elements are not of type specified for drag behavior @@ -197,15 +197,15 @@ let e: d3Drag.D3DragEvent { - let rr: d3Dsv.DSVRowString = rawRow; - let i: number = index; - let c: string[] = columns; - let pr: ParsedTestObject; - - pr = { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: string[] = columns; + const pr: ParsedTestObject = { year: new Date(+rr['Year'], 0, 1), make: rr['Make'], model: rr['Model'], length: +rr['Length'] }; - return pr; - }); columns = parseMappedArray.columns; @@ -95,19 +91,15 @@ str = parseRowsArray[0][0]; // 'Year' of first row // with row mapper --------------------------------------------------------------------------- parseRowsMappedArray = d3Dsv.csvParseRows(csvTestString, (rawRow, index) => { - let rr: string[] = rawRow; - let i: number = index; - let pr: ParsedTestObject; - - pr = { + const rr: string[] = rawRow; + const i: number = index; + const pr: ParsedTestObject = { year: new Date(+rr[0], 0, 1), make: rr[1], model: rr[2], length: +rr[3] }; - return pr; - }); date = parseRowsMappedArray[0].year; @@ -147,20 +139,16 @@ str = parseArray[0]['Year']; // with row mapper --------------------------------------------------------------------------- parseMappedArray = d3Dsv.tsvParse(tsvTestStringWithHeader, (rawRow, index, columns) => { - let rr: d3Dsv.DSVRowString = rawRow; - let i: number = index; - let c: string[] = columns; - let pr: ParsedTestObject; - - pr = { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: string[] = columns; + const pr: ParsedTestObject = { year: new Date(+rr['Year'], 0, 1), make: rr['Make'], model: rr['Model'], length: +rr['Length'] }; - return pr; - }); columns = parseMappedArray.columns; @@ -184,19 +172,15 @@ str = parseRowsArray[0][0]; // 'Year' of first row // with row mapper --------------------------------------------------------------------------- parseRowsMappedArray = d3Dsv.tsvParseRows(tsvTestString, (rawRow, index) => { - let rr: string[] = rawRow; - let i: number = index; - let pr: ParsedTestObject; - - pr = { + const rr: string[] = rawRow; + const i: number = index; + const pr: ParsedTestObject = { year: new Date(+rr[0], 0, 1), make: rr[1], model: rr[2], length: +rr[3] }; - return pr; - }); date = parseRowsMappedArray[0].year; @@ -241,20 +225,16 @@ str = parseArray[0]['Year']; // with row mapper --------------------------------------------------------------------------- parseMappedArray = dsv.parse(pipedTestStringWithHeader, (rawRow, index, columns) => { - let rr: d3Dsv.DSVRowString = rawRow; - let i: number = index; - let c: string[] = columns; - let pr: ParsedTestObject; - - pr = { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: string[] = columns; + const pr: ParsedTestObject = { year: new Date(+rr['Year'], 0, 1), make: rr['Make'], model: rr['Model'], length: +rr['Length'] }; - return pr; - }); columns = parseMappedArray.columns; @@ -278,19 +258,15 @@ str = parseRowsArray[0][0]; // 'Year' of first row // with row mapper --------------------------------------------------------------------------- parseRowsMappedArray = dsv.parseRows(pipedTestString, (rawRow, index) => { - let rr: string[] = rawRow; - let i: number = index; - let pr: ParsedTestObject; - - pr = { + const rr: string[] = rawRow; + const i: number = index; + const pr: ParsedTestObject = { year: new Date(+rr[0], 0, 1), make: rr[1], model: rr[2], length: +rr[3] }; - return pr; - }); date = parseRowsMappedArray[0].year; diff --git a/d3-ease/d3-ease-tests.ts b/d3-ease/d3-ease-tests.ts index 84e34aa064..b50ceba9a4 100644 --- a/d3-ease/d3-ease-tests.ts +++ b/d3-ease/d3-ease-tests.ts @@ -8,7 +8,7 @@ import * as d3Ease from 'd3-ease'; -let t_in: number = 0.5; +const t_in: number = 0.5; let t_out: number; t_out = d3Ease.easeLinear(t_in); diff --git a/d3-force/d3-force-tests.ts b/d3-force/d3-force-tests.ts index 92feada8da..0ecd7555d3 100644 --- a/d3-force/d3-force-tests.ts +++ b/d3-force/d3-force-tests.ts @@ -31,7 +31,7 @@ interface Graph { } -let graph: Graph = { +const graph: Graph = { nodes: [ { id: 'Myriel', group: 1, r: 5 }, { id: 'Napoleon', group: 1, r: 10 }, @@ -55,10 +55,10 @@ let simLinks: SimLink[]; let num: number; -let canvas = document.querySelector('canvas')!; -let context = canvas.getContext('2d'); -let width = canvas.width; -let height = canvas.height; +const canvas = document.querySelector('canvas')!; +const context = canvas.getContext('2d'); +const width = canvas.width; +const height = canvas.height; // ------------------------------------------------------------------------------------- // Test Pre-Defined Forces @@ -106,9 +106,9 @@ forceCollide = d3Force.forceCollide(15); // with radius accessor function forceCollide = d3Force.forceCollide((node, index, nodes) => { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return n.r; }); @@ -121,9 +121,9 @@ let radiusAccessor: (node: SimNode, i: number, nodes: SimNode[]) => number; forceCollide = forceCollide.radius(20); forceCollide = forceCollide.radius((node, index, nodes) => { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return 2 * n.r; }); @@ -161,7 +161,7 @@ forceLink = d3Force.forceLink(graph.links); // Configure Link force ----------------------------------------------------------- let linkNumberAccessor: (link: SimLink, i: number, links: SimLink[]) => number; -let nodeIdAccessor: (node: SimNode, i: number, nodes: SimNode[]) => number | string; +// let nodeIdAccessor: (node: SimNode, i: number, nodes: SimNode[]) => number | string; // links @@ -174,7 +174,7 @@ simLink = simLinks[0]; simNode = (typeof simLink.source !== 'number' && typeof simLink.source !== 'string') ? simLink.source : undefined; simNode = (typeof simLink.target !== 'number' && typeof simLink.target !== 'string') ? simLink.target : undefined; -let maybeNum: number | undefined = simLink.index; // Ex-ante type before initialization of links +const maybeNum: number | undefined = simLink.index; // Ex-ante type before initialization of links num = simLink.index!; // Ex-post after link initialization, use ! non-null assertion operator to narrow to number num = simLink.value; @@ -185,9 +185,9 @@ num = simLink.s; // id (node id accessor) forceLink = forceLink.id((node, index, nodes) => { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return n.id; }); @@ -195,9 +195,9 @@ forceLink = forceLink.id((node, index, nodes) => { forceLink = forceLink.distance(50); forceLink = forceLink.distance((link, index, links) => { - let l: SimLink = link; - let i: number = index; - let ls: SimLink[] = links; + const l: SimLink = link; + const i: number = index; + const ls: SimLink[] = links; return l.d; }); @@ -207,9 +207,9 @@ linkNumberAccessor = forceLink.distance(); forceLink = forceLink.strength(0.95); forceLink = forceLink.strength((link, index, links) => { - let l: SimLink = link; - let i: number = index; - let ls: SimLink[] = links; + const l: SimLink = link; + const i: number = index; + const ls: SimLink[] = links; return l.s; }); @@ -243,9 +243,9 @@ let simNodeNumberAccessor: (node: SimNode, i: number, nodes: SimNode[]) => numbe forceCharge = forceCharge.strength(-3000); forceCharge = forceCharge.strength((node, index, nodes) => { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return -1000 * n.group; }); simNodeNumberAccessor = forceCharge.strength(); @@ -287,9 +287,9 @@ forcePosX = d3Force.forceX(); forcePosX = forcePosX.strength(0.2); forcePosX = forcePosX.strength((node, index, nodes) => { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return 0.1 * n.group; }); simNodeNumberAccessor = forcePosX.strength(); @@ -298,9 +298,9 @@ simNodeNumberAccessor = forcePosX.strength(); forcePosX = forcePosX.x(100); forcePosX = forcePosX.x((node, index, nodes) => { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; let target: number; switch (n.group) { case 1: @@ -342,9 +342,9 @@ forcePosY = d3Force.forceY(); forcePosY = forcePosY.strength(0.2); forcePosY = forcePosY.strength((node, index, nodes) => { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; return 0.1 * n.group; }); simNodeNumberAccessor = forcePosY.strength(); @@ -353,9 +353,9 @@ simNodeNumberAccessor = forcePosY.strength(); forcePosY = forcePosY.y(100); forcePosY = forcePosY.y((node, index, nodes) => { - let n: SimNode = node; - let i: number = index; - let ns: SimNode[] = nodes; + const n: SimNode = node; + const i: number = index; + const ns: SimNode[] = nodes; let target: number; switch (n.group) { case 1: @@ -503,7 +503,7 @@ function drawNode(d: SimNode) { nodeLinkSimulation = nodeLinkSimulation.on('tick', function ticked() { - let that: d3Force.Simulation = this; + const that: d3Force.Simulation = this; if (context) { context.clearRect(0, 0, width, height); @@ -525,7 +525,7 @@ nodeLinkSimulation = nodeLinkSimulation.on('tick', function ticked() { nodeSimulation = nodeSimulation.on('tick', null); // get listener -let listener: ((this: d3Force.Simulation) => void) | undefined = nodeSimulation.on('tick'); +const listener: ((this: d3Force.Simulation) => void) | undefined = nodeSimulation.on('tick'); // Configure and Use Force Simulation =================================================== diff --git a/d3-scale/d3-scale-tests.ts b/d3-scale/d3-scale-tests.ts index d5b4aad712..c1feb4766a 100644 --- a/d3-scale/d3-scale-tests.ts +++ b/d3-scale/d3-scale-tests.ts @@ -37,7 +37,6 @@ class StringCoercible { } let num: number; -let str: string; let date: Date; let clampFlag: boolean; @@ -46,7 +45,7 @@ let outputNumber: number; let outputString: string; let domainNumbers: number[] = [1, 100]; -let domainNumeric: NumCoercible[] = [new NumCoercible(0), new NumCoercible(100)]; +const domainNumeric: NumCoercible[] = [new NumCoercible(0), new NumCoercible(100)]; let domainStrings: string[]; let domainDates: Date[] = [new Date(2016, 0, 15), new Date(2016, 5, 15)]; @@ -165,7 +164,7 @@ outputString = linearScaleNumString(10); // copy(...) ----------------------------------------------------------------- -let copiedLinearScale: d3Scale.ScaleLinear = linearScaleNumString.copy(); +const copiedLinearScale: d3Scale.ScaleLinear = linearScaleNumString.copy(); // ------------------------------------------------------------------------------- // Power Scale Factories @@ -194,7 +193,7 @@ squarerootScaleNumString = d3Scale.scaleSqrt(); // exponent -------------------------------------------------------------------- -let exponent: number = squarerootScaleNumber.exponent(); +const exponent: number = squarerootScaleNumber.exponent(); powerScaleNumber = powerScaleNumber.exponent(5); @@ -277,7 +276,7 @@ outputString = powerScaleNumString(10); // copy(...) ----------------------------------------------------------------- -let copiedPowerScale: d3Scale.ScalePower = powerScaleNumString.copy(); +const copiedPowerScale: d3Scale.ScalePower = powerScaleNumString.copy(); // ------------------------------------------------------------------------------- // Logarithmic Scale Factory @@ -299,7 +298,7 @@ logScaleNumString = d3Scale.scaleLog(); // base -------------------------------------------------------------------- -let base: number = logScaleNumber.base(); +const base: number = logScaleNumber.base(); logScaleNumber = logScaleNumber.base(42); @@ -382,7 +381,7 @@ outputString = logScaleNumString(10); // copy(...) ----------------------------------------------------------------- -let copiedLogScale: d3Scale.ScaleLogarithmic = logScaleNumString.copy(); +const copiedLogScale: d3Scale.ScaleLogarithmic = logScaleNumString.copy(); // ------------------------------------------------------------------------------- // Identity Scale Factory @@ -438,7 +437,7 @@ outputNumber = identityScale(10); // copy(...) ----------------------------------------------------------------- -let copiedIdentityScale: d3Scale.ScaleIdentity = identityScale.copy(); +const copiedIdentityScale: d3Scale.ScaleIdentity = identityScale.copy(); // ------------------------------------------------------------------------------- @@ -555,7 +554,7 @@ outputString = localTimeScaleNumString(new Date(2016, 6, 4)); // copy(...) ----------------------------------------------------------------- -let copiedTimeScale: d3Scale.ScaleTime = localTimeScaleNumString.copy(); +const copiedTimeScale: d3Scale.ScaleTime = localTimeScaleNumString.copy(); // ------------------------------------------------------------------------------- // Sequential Scale Factory @@ -574,7 +573,7 @@ sequentialScaleColorString = d3Scale.scaleSequential(d3Scale.interpolateCool); / sequentialScaleColorString = sequentialScaleColorString.domain([0, 1]); sequentialScaleColorString = sequentialScaleColorString.domain([new NumCoercible(0), new NumCoercible(100)]); -let domainSequential: [number, number] = sequentialScaleColorString.domain(); +const domainSequential: [number, number] = sequentialScaleColorString.domain(); // clamp(...) ----------------------------------------------------------------- @@ -594,7 +593,7 @@ outputString = sequentialScaleColorString(10); // copy(...) ----------------------------------------------------------------- -let copiedSequentialScale: d3Scale.ScaleSequential = sequentialScaleColorString.copy(); +const copiedSequentialScale: d3Scale.ScaleSequential = sequentialScaleColorString.copy(); @@ -640,7 +639,7 @@ quantizeScaleString = d3Scale.scaleQuantize(); quantizeScaleNumber = quantizeScaleNumber.domain([0, 1]); quantizeScaleNumber = quantizeScaleNumber.domain([new NumCoercible(0), new NumCoercible(100)]); -let domainQuantize: [number, number] = quantizeScaleNumber.domain(); +const domainQuantize: [number, number] = quantizeScaleNumber.domain(); // range(...) ----------------------------------------------------------------- @@ -680,7 +679,7 @@ outputNumber = quantizeScaleNumber(0.51); // copy(...) ----------------------------------------------------------------- -let copiedQuantizeScale: d3Scale.ScaleQuantize = quantizeScaleNumber.copy(); +const copiedQuantizeScale: d3Scale.ScaleQuantize = quantizeScaleNumber.copy(); // ------------------------------------------------------------------------------- @@ -724,7 +723,7 @@ numExtent = quantileScaleString.invertExtent('q50'); // quantile() ----------------------------------------------------------------------- -let quantiles: number[] = quantileScaleNumber.quantiles(); +const quantiles: number[] = quantileScaleNumber.quantiles(); // (...) value mapping from domain to output ----------------------------------- @@ -732,7 +731,7 @@ outputNumber = quantileScaleNumber(0.51); // copy(...) ----------------------------------------------------------------- -let copiedQuantileScale: d3Scale.ScaleQuantile = quantileScaleNumber.copy(); +const copiedQuantileScale: d3Scale.ScaleQuantile = quantileScaleNumber.copy(); // ------------------------------------------------------------------------------- @@ -780,7 +779,7 @@ outputString = thresholdScaleNumberString(0.9); // copy(...) ----------------------------------------------------------------- -let copiedThresholdScale: d3Scale.ScaleThreshold = thresholdScaleNumberString.copy(); +const copiedThresholdScale: d3Scale.ScaleThreshold = thresholdScaleNumberString.copy(); // ------------------------------------------------------------------------------- @@ -816,13 +815,13 @@ rangeNumbers = ordinalScaleStringNumber.range(); // unknown(...) and d3Scale.scaleImplicit -------------------------------------- -let implicit: { name: 'implicit' } = d3Scale.scaleImplicit; +const implicit: { name: 'implicit' } = d3Scale.scaleImplicit; ordinalScaleStringString = ordinalScaleStringString.unknown(d3Scale.scaleImplicit); ordinalScaleStringNumber = ordinalScaleStringNumber.unknown(0); -let unknownValue: string | { name: 'implicit' } = ordinalScaleStringString.unknown(); +const unknownValue: string | { name: 'implicit' } = ordinalScaleStringString.unknown(); if (typeof unknownValue === 'string') { console.log(unknownValue); @@ -838,7 +837,7 @@ outputNumber = ordinalScaleStringNumber('negative'); // copy(...) ----------------------------------------------------------------- -let copiedOrdinalScale: d3Scale.ScaleOrdinal = ordinalScaleStringNumber.copy(); +const copiedOrdinalScale: d3Scale.ScaleOrdinal = ordinalScaleStringNumber.copy(); // ------------------------------------------------------------------------------- @@ -920,7 +919,7 @@ outputNumberMaybe = bandScaleCoercible(new StringCoercible('negative')); // copy(...) ----------------------------------------------------------------- -let copiedBandScale: d3Scale.ScaleBand = bandScaleCoercible.copy(); +const copiedBandScale: d3Scale.ScaleBand = bandScaleCoercible.copy(); // ------------------------------------------------------------------------------- @@ -991,7 +990,7 @@ outputNumberMaybe = pointScaleCoercible(new StringCoercible('negative')); // copy(...) ----------------------------------------------------------------- -let copiedPointScale: d3Scale.ScalePoint = pointScaleCoercible.copy(); +const copiedPointScale: d3Scale.ScalePoint = pointScaleCoercible.copy(); // ------------------------------------------------------------------------------- // Categorical Color Schemas for Ordinal Scales diff --git a/d3-selection-multi/d3-selection-multi-tests.ts b/d3-selection-multi/d3-selection-multi-tests.ts index 5f8259052d..515dd8e92e 100644 --- a/d3-selection-multi/d3-selection-multi-tests.ts +++ b/d3-selection-multi/d3-selection-multi-tests.ts @@ -34,10 +34,10 @@ selection = selection.attrs({ }); // Function that returns a map -selection = selection.attrs(function (d, i, g) { - let that: HTMLAnchorElement = this; - let index: number = i; - let group: HTMLAnchorElement[] | ArrayLike = g; +selection = selection.attrs(function(d, i, g) { + const that: HTMLAnchorElement = this; + const index: number = i; + const group: HTMLAnchorElement[] | ArrayLike = g; return this.id ? {} : { id: d }; }); @@ -67,11 +67,11 @@ selection = selection.styles({ }, 'important'); // Functions that return a map -selection.styles(function (d) { +selection.styles(function(d) { return this.id ? { color: 'red' } : { color: d }; }); -selection = selection.styles(function (d) { +selection = selection.styles(function(d) { return this.id ? { color: 'red' } : { color: d }; }, 'important'); @@ -89,10 +89,10 @@ selection = selection.properties({ }); // Function that returns an object -selection = selection.properties(function (d, i, g) { - let that: HTMLAnchorElement = this; - let index: number = i; - let group: HTMLAnchorElement[] | ArrayLike = g; +selection = selection.properties(function(d, i, g) { + const that: HTMLAnchorElement = this; + const index: number = i; + const group: HTMLAnchorElement[] | ArrayLike = g; return that.href ? {} : { href: d }; }); @@ -112,16 +112,16 @@ transition = transition.attrs({ foo: () => 1, bar: (d) => d, baz: (d, i) => i !== 0, - bat: function () { + bat() { return this.href; }, }); // Function that returns a map -transition = transition.attrs(function (d, i, g) { - let that: HTMLAnchorElement = this; - let index: number = i; - let group: HTMLAnchorElement[] | ArrayLike = g; +transition = transition.attrs(function(d, i, g) { + const that: HTMLAnchorElement = this; + const index: number = i; + const group: HTMLAnchorElement[] | ArrayLike = g; return this.id ? {} : { id: d }; }); @@ -151,11 +151,11 @@ transition = transition.styles({ }, 'important'); // Function that returns a map -transition = transition.styles(function (d) { +transition = transition.styles(function(d) { return this.id ? { color: 'red' } : { color: d }; }); -transition = transition.styles(function (d) { +transition = transition.styles(function(d) { return this.id ? { color: 'red' } : { color: d }; }, 'important'); @@ -174,22 +174,22 @@ valueMap = { foo2: 2, foo3: true, foo4: null, - bar1: function (d) { - let that: SVGCircleElement = this; - let datum: SampleDatum = d; + bar1(d) { + const that: SVGCircleElement = this; + const datum: SampleDatum = d; return d.name; }, - bar2: function (d, i) { - let that: SVGCircleElement = this; - let datum: SampleDatum = d; - let index: number = i; + bar2(d, i) { + const that: SVGCircleElement = this; + const datum: SampleDatum = d; + const index: number = i; return d.r; }, - bar3: function (d, i, g) { - let that: SVGCircleElement = this; - let datum: SampleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | ArrayLike = g; + bar3(d, i, g) { + const that: SVGCircleElement = this; + const datum: SampleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | ArrayLike = g; return d.filled; } }; @@ -200,7 +200,7 @@ valueMap = { // valueMap = { // fails, as a ValueFunction returning an array is not a permissible value type // foo1: function (d) { -// let that: SVGCircleElement = this; +// const that: SVGCircleElement = this; // let datum: SampleDatum = d; // return [1, 2]; // } diff --git a/d3-selection/d3-selection-tests.ts b/d3-selection/d3-selection-tests.ts index 9c4a2bb6e2..aaa5e6e84a 100644 --- a/d3-selection/d3-selection-tests.ts +++ b/d3-selection/d3-selection-tests.ts @@ -15,7 +15,7 @@ import * as d3Selection from 'd3-selection'; // --------------------------------------------------------------------------------------- // Generic DOM related variables -let xDoc: Document = document; +const xDoc: Document = document; let xWindow: Window = window; interface BodyDatum { @@ -59,14 +59,14 @@ interface CircleDatumAlternative { // test top-level .selection() ----------------------------------------------------------- -let topSelection: d3Selection.Selection = d3Selection.selection(); +const topSelection: d3Selection.Selection = d3Selection.selection(); // test top-level select() --------------------------------------------------------------- // Using select() with string argument and no type parameters creates selection // with Group element of type BaseType and datum of type 'any'. The parent element is of type HTMLElement with datum of type 'any' -let baseTypeEl: d3Selection.Selection = d3Selection.select('body'); +const baseTypeEl: d3Selection.Selection = d3Selection.select('body'); // Using select() with string argument and type parameters creates selection // with Group element of type HTMLBodyElement and datum of BodyDatum type. The parent element is of type HTMLElement with datum of type 'any' @@ -76,18 +76,18 @@ let body: d3Selection.Selection = // Using select() with node argument and no type parameters creates selection // with Group element of type BaseType and datum of type 'any' The parent element is of type 'null' with datum of type 'undefined' -let baseTypeEl2: d3Selection.Selection = d3Selection.select(baseTypeEl.node()); +const baseTypeEl2: d3Selection.Selection = d3Selection.select(baseTypeEl.node()); // let body2: d3Selection.Selection = d3Selection.select(baseTypeEl.node()); // fails as baseTypeEl.node() is of type cannot be assigned to HTMLElement -let body3: d3Selection.Selection = d3Selection.select(body.node()!); // element types match, but datum is of type 'any' as it cannot be inferred from .node() +const body3: d3Selection.Selection = d3Selection.select(body.node()!); // element types match, but datum is of type 'any' as it cannot be inferred from .node() // Using select() with node argument and type parameters creates selection // with Group element of type HTMLBodyElement and datum of BodyDatum type. The parent element is of type 'null' with datum of type 'undefined' -let body4: d3Selection.Selection = d3Selection.select(body.node()!); +const body4: d3Selection.Selection = d3Selection.select(body.node()!); // Explicitly cast body.node() to HTMLBodyElement to narrow selection definition. -let body5: d3Selection.Selection = d3Selection.select(body.node()!); +const body5: d3Selection.Selection = d3Selection.select(body.node()!); // d3Selection.select(baseTypeEl.node()!); // fails as baseTypeEl.node() is not of type HTMLBodyElement @@ -119,26 +119,26 @@ emptyRootSelection = d3Selection.selectAll(undefined); // Using selectAll(...) with string argument and no type parameters creates selection // with Group elements of type BaseType and datum of type 'any'. The parent element is of type HTMLElement with datum of type 'any' -let baseTypeElements: d3Selection.Selection = d3Selection.selectAll('div'); +const baseTypeElements: d3Selection.Selection = d3Selection.selectAll('div'); // Using selectAll() with string argument and type parameters creates selection // with Group element of type HTMLDivElement and datum of DivDatum type. The parent element is of type HTMLElement with datum of type 'any' -let divElements: d3Selection.Selection = d3Selection.selectAll('div'); +const divElements: d3Selection.Selection = d3Selection.selectAll('div'); // Using selectAll(...) with node array argument and no type parameters creates selection // with Group element of type BaseType and datum of type 'any' The parent element is of type 'null' with datum of type 'undefined' -let baseTypeElements2: d3Selection.Selection = d3Selection.selectAll(baseTypeElements.nodes()); +const baseTypeElements2: d3Selection.Selection = d3Selection.selectAll(baseTypeElements.nodes()); // let divElements2: d3Selection.Selection = d3Selection.selectAll(baseTypeElements.nodes()); // fails, group elements types not of compatible for baseTypeElements -let divElements3: d3Selection.Selection = d3Selection.selectAll(divElements.nodes()); // element types match, but datum is of type 'any' as it cannot be inferred from .nodes() +const divElements3: d3Selection.Selection = d3Selection.selectAll(divElements.nodes()); // element types match, but datum is of type 'any' as it cannot be inferred from .nodes() // Using selectAll(...) with node array argument and type parameters creates selection // with Group element of type HTMLDivElement and datum of DivDatum type. The parent element is of type 'null' with datum of type 'undefined' -let divElements4: d3Selection.Selection = d3Selection.selectAll(divElements.nodes()); +const divElements4: d3Selection.Selection = d3Selection.selectAll(divElements.nodes()); // d3Selection.selectAll(baseTypeElements.nodes()); // fails as baseTypeEl.node() is not of type HTMLBodyElement @@ -146,12 +146,12 @@ let divElements4: d3Selection.Selection argument -let xSVGCircleElementList: NodeListOf = document.querySelectorAll('circle'); -let circleSelection: d3Selection.Selection = d3Selection.selectAll(xSVGCircleElementList); +const xSVGCircleElementList: NodeListOf = document.querySelectorAll('circle'); +const circleSelection: d3Selection.Selection = d3Selection.selectAll(xSVGCircleElementList); // selectAll(...) accepts HTMLCollection, HTMLCollectionOf<...> argument -let documentLinks: d3Selection.Selection = d3Selection.selectAll(document.links); +const documentLinks: d3Selection.Selection = d3Selection.selectAll(document.links); @@ -168,7 +168,7 @@ let documentLinks: d3Selection.Selection = d3Selection.select('svg'); +const svgEl: d3Selection.Selection = d3Selection.select('svg'); let firstG: d3Selection.Selection = svgEl.select('g'); // let firstG_2: d3Selection.Selection = svgEl.select('g'); // fails, parent element of selection does not change with .select(...) @@ -187,19 +187,19 @@ function svgGroupSelector(this: SVGSVGElement, d: SVGDatum, i: number, groups: S firstG = svgEl.select(svgGroupSelector); -firstG = svgEl.select(function () { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch +firstG = svgEl.select(function() { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement return this.querySelector('g')!; // this of type SVGSVGElement by type inference }); -firstG = svgEl.select(function (d, i, g) { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: SVGDatum = d; - let index: number = i; - let group: SVGSVGElement[] | d3Selection.ArrayLike = g; +firstG = svgEl.select(function(d, i, g) { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: SVGDatum = d; + const index: number = i; + const group: SVGSVGElement[] | d3Selection.ArrayLike = g; console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement console.log('Width in datum:', d.width); // d is type of originating selection element Datum: SVGDatum if (g.length > 1) { @@ -246,19 +246,19 @@ function wrongSvgGroupSelectorAll(this: HTMLElement, d: SVGDatum, i: number, gro } // gElementsOldData = svgEl.selectAll(wrongSvgGroupSelectorAll); // fails, wrong this context -gElementsOldData = svgEl.selectAll(function () { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch +gElementsOldData = svgEl.selectAll(function() { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement return this.querySelectorAll('g'); // this of type SVGSVGElement by type inference }); -gElementsOldData = svgEl.selectAll(function (d, i, g) { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: SVGDatum = d; - let index: number = i; - let group: SVGSVGElement[] | d3Selection.ArrayLike = g; +gElementsOldData = svgEl.selectAll(function(d, i, g) { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: SVGDatum = d; + const index: number = i; + const group: SVGSVGElement[] | d3Selection.ArrayLike = g; console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement console.log('Width in datum:', d.width); // type of d is SVGDatum if (g.length > 1) { @@ -277,9 +277,9 @@ gElementsOldData = svgEl.selectAll(function (d, i, g) elementsUnknownData = svgEl.selectAll(svgGroupSelectorAll); -elementsUnknownData = svgEl.selectAll(function () { - let that: SVGSVGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch +elementsUnknownData = svgEl.selectAll(function() { + const that: SVGSVGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement return this.querySelectorAll('g'); // this of type SVGSVGElement by type inference }); @@ -288,13 +288,13 @@ elementsUnknownData = svgEl.selectAll(function () { // return this.querySelectorAll('a'); // }); -maybeG.selectAll(function (d, i, g) { - let that: SVGGElement | null = this; - // let that2: SVGGElement = this; // fails with strictNullChecks - // let that3: HTMLElement | null = this; // fails, type mismatch - let datum: SVGDatum = d; - let index: number = i; - let group: Array | d3Selection.ArrayLike = g; +maybeG.selectAll(function(d, i, g) { + const that: SVGGElement | null = this; + // const that2: SVGGElement = this; // fails with strictNullChecks + // const that3: HTMLElement | null = this; // fails, type mismatch + const datum: SVGDatum = d; + const index: number = i; + const group: Array | d3Selection.ArrayLike = g; return that ? that.querySelectorAll('circle') : []; }); @@ -319,12 +319,12 @@ let filterdGElements: d3Selection.Selection = g; +filterdGElements = gElementsOldData.filter(function(d, i, g) { + const that: SVGGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGGElement[] | d3Selection.ArrayLike = g; console.log('Element Id of DOM element: ', this.id); // this context SVGGElement if (g.length > 0) { console.log('Element Id of first DOM element in group: ', g[0].id); // group: Array @@ -341,11 +341,11 @@ filterdGElements2 = d3Selection.selectAll('.any-svg-type').filt // filterdGElements2 = d3Selection.selectAll('.any-type').filter('g'); // fails without using narrowing generic on filter method filterdGElements2 = d3Selection.selectAll('.any-svg-type').filter(function(){ - let that: SVGElement = this; + const that: SVGElement = this; return that.tagName === 'g' || that.tagName === 'G'; }); // filterdGElements2 = d3Selection.selectAll('.any-svg-type').filter(function(){ -// let that: SVGElement = this; +// const that: SVGElement = this; // return that.tagName === 'g'|| that.tagName === 'G'; // }); // fails without using narrowing generic on filter method @@ -385,27 +385,23 @@ circles = d3Selection.selectAll('circl .attr('stroke', 'blue'); // string circles = circles // re-assignment test chaining return-type - .attr('cx', function (d, i, g) { - let that: SVGGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGGElement[] | d3Selection.ArrayLike = g; + .attr('cx', function(d, i, g) { + const that: SVGGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGGElement[] | d3Selection.ArrayLike = g; console.log('Pre-change center x-coordinate: ', this.cx.baseVal.value); // this context SVGCircleElement if (g.length > 0) { console.log('Owner SVG Element of first group element:', g[0].ownerSVGElement); // group : Array } return d.cx; // numeric return value }) - .attr('stroke', function (d) { - return d.color; // string return value - }); + .attr('stroke', d => d.color); // string return value divs = d3Selection.selectAll('div') .attr('contenteditable', false) // boolean - .attr('contenteditable', function () { - return false; // boolean return value - }); + .attr('contenteditable', () => false); // boolean return value // classed(...) Tests @@ -413,12 +409,12 @@ divs = divs .classed('success', true); divs = divs - .classed('zero-px-padding', function (d, i, g) { - let that: HTMLDivElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: DivDatum = d; - let index: number = i; - let group: HTMLDivElement[] | d3Selection.ArrayLike = g; + .classed('zero-px-padding', function(d, i, g) { + const that: HTMLDivElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: DivDatum = d; + const index: number = i; + const group: HTMLDivElement[] | d3Selection.ArrayLike = g; console.log('Client Rectangle Top: ', this.getBoundingClientRect().top); // this context HTMLDivElement if (g.length > 0) { console.log('Alignment of first group element:', g[0].align); // group : Array @@ -436,23 +432,21 @@ divs = divs .style('color', 'green', 'important'); divs = divs - .style('padding', function (d, i, g) { - let that: HTMLDivElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: DivDatum = d; - let index: number = i; - let group: HTMLDivElement[] | d3Selection.ArrayLike = g; + .style('padding', function(d, i, g) { + const that: HTMLDivElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: DivDatum = d; + const index: number = i; + const group: HTMLDivElement[] | d3Selection.ArrayLike = g; console.log('Client Rectangle Top: ', this.getBoundingClientRect().top); // this context HTMLDivElement if (g.length > 0) { console.log('Alignment of first group element:', g[0].align); // group : Array } return d.padding; // string return value }) - .style('hidden', function () { - return true; - }, null) // boolean return + test: priority = null - // .style('color', function () { return 'green'; }, 'test') // fails, test: invalid priority value - .style('color', function () { return 'green'; }, 'important'); // boolean return + test: priority = 'important'; + .style('hidden', () => true, null) // boolean return + test: priority = null + // .style('color', function() { return 'green'; }, 'test') // fails, test: invalid priority value + .style('color', () => 'green', 'important'); // boolean return + test: priority = 'important'; // property(...) Tests @@ -464,12 +458,12 @@ circles = circles }); // any circles = circles - .property('__hitchhikersguide__', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatumAlternative = d; - let index: number = i; - let group: SVGCircleElement[] | d3Selection.ArrayLike = g; + .property('__hitchhikersguide__', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatumAlternative = d; + const index: number = i; + const group: SVGCircleElement[] | d3Selection.ArrayLike = g; console.log('Pre-change center x-coordinate: ', this.cx.baseVal.value); // this context SVGCircleElement if (g.length > 0) { console.log('Owner SVG Element of first group element:', g[0].ownerSVGElement); // group : Array @@ -488,32 +482,28 @@ body = body .text(true); // boolean will be converted to string by D3 body = body - .text(function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; + .text(function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; console.log('Body background color: ', this.bgColor); // this context HTMLBodyElement return d.foo; // BodyDatum }) - .text(function (d) { - return 42; // number will be converted to string by D3 - }) - .text(function (d) { - return true; // boolean will be converted to string by D3 - }); + .text(d => 42) // number will be converted to string by D3 + .text(d => true); // boolean will be converted to string by D3 body = body .html('
42
'); body = body - .html(function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; + .html(function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; return '
Body Background Color: ' + this.bgColor + ', Foo Datum: ' + d.foo + '
'; // this context HTMLBodyElement, datum BodyDatum }); @@ -522,13 +512,13 @@ body = body // --------------------------------------------------------------------------------------- -let data: CircleDatum[] = [ +const data: CircleDatum[] = [ { nodeId: 'c1', cx: 10, cy: 10, r: 5, name: 'foo', label: 'Foo' }, { nodeId: 'c2', cx: 20, cy: 20, r: 5, name: 'bar', label: 'Bar' }, { nodeId: 'c3', cx: 30, cy: 30, r: 5, name: 'fooBar', label: 'Foo Bar' } ]; -let data2: CircleDatumAlternative[] = [ +const data2: CircleDatumAlternative[] = [ { nodeId: 'c1', cx: 10, cy: 10, r: 5, name: 'foo', label: 'Foo', color: 'seagreen' }, { nodeId: 'c2', cx: 20, cy: 20, r: 5, name: 'bar', label: 'Bar', color: 'midnightblue' }, { nodeId: 'c4', cx: 10, cy: 15, r: 10, name: 'newbie', label: 'Newbie', color: 'red' } @@ -538,7 +528,7 @@ let data2: CircleDatumAlternative[] = [ // Tests of Datum ----------------------------------------------------------------------- // TEST GETTER -let bodyDatum: BodyDatum = body.datum(); +const bodyDatum: BodyDatum = body.datum(); // TEST REMOVE DATUM body.datum(null); // removes datum, i.e. return type has group datum type 'undefined' @@ -555,18 +545,18 @@ newBodyDatum = body.datum({ newFoo: 'new foo' }).datum(); // inferred type // function-based -newBodyDatum = body.datum(function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; +newBodyDatum = body.datum(function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; console.log('HTML5 Custom Data Attributes of body: ', this.dataset); // this typings HTMLBodyElement console.log('Old foo:', d.foo); // current data of type BodyDatum return { newFoo: 'new foo' }; }).datum(); // inferred type -// newBodyDatum = body.datum(function (d) { // fails, data type incompatible with return value type +// newBodyDatum = body.datum(function(d) { // fails, data type incompatible with return value type // console.log('HTML5 Custom Data Attributes of body: ', this.dataset); // this typings HTMLBodyElement // return { newFoo: 'new foo' }; // }).datum(); // inferred type @@ -579,7 +569,7 @@ newBodyDatum = body.datum(function (d, i, g) { d3Selection.select('#svg-1') .select('g.circles-group') // first matching element only .datum(data2) - .classed('has-transform-property', function (d) { + .classed('has-transform-property', function(d) { console.log('Color of first data element array', d.length > 0 ? d[0].color : 'Data array empty'); return this.transform !== undefined; }); @@ -589,12 +579,12 @@ d3Selection.select('#svg-1') d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain .select('g.circles-group') .datum(data2) // new data type inferred - .classed('has-transform-property', function (d, i, g) { - let that: SVGGElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatumAlternative[] = d; - let index: number = i; - let group: SVGGElement[] | d3Selection.ArrayLike = g; + .classed('has-transform-property', function(d, i, g) { + const that: SVGGElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatumAlternative[] = d; + const index: number = i; + const group: SVGGElement[] | d3Selection.ArrayLike = g; console.log('Color of first data element array', d.length > 0 ? d[0].color : 'Data array empty'); // CircleDatumAlternative type return this.transform !== undefined; }); @@ -604,7 +594,7 @@ d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in la // d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain // .select('g.circles-group') // missing typing of selected DOM element for use in .classed(...) // .datum(data2) // new data type inferred -// .classed('has-transform-property', function (d) { +// .classed('has-transform-property', function(d) { // console.log('Color of first data element array', d.length > 0? d[0].color: 'Data array empty'); // CircleDatumAlternative type // return this.transform !== undefined; // }); @@ -614,12 +604,12 @@ d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in la d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain .select('g.circles-group') // irrelevant typing to get contextual typing in last step of chain .datum(data2) // new data type inferred - .classed('has-green-first-data-element', function (d, i, g) { - let that: d3Selection.BaseType = this; - // let that2: Element = this; // fails, type mismatch - let datum: CircleDatumAlternative[] = d; - let index: number = i; - let group: d3Selection.BaseType[] | d3Selection.ArrayLike = g; + .classed('has-green-first-data-element', function(d, i, g) { + const that: d3Selection.BaseType = this; + // const that2: Element = this; // fails, type mismatch + const datum: CircleDatumAlternative[] = d; + const index: number = i; + const group: d3Selection.BaseType[] | d3Selection.ArrayLike = g; return d.length > 0 && d[0].color === 'green'; }); @@ -627,12 +617,12 @@ d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in la // Tests of Data Join -------------------------------------------------------------------- -let dimensions: SVGDatum = { +const dimensions: SVGDatum = { width: 500, height: 300 }; -let startCircleData: CircleDatumAlternative[] = [ +const startCircleData: CircleDatumAlternative[] = [ { nodeId: 'n1', name: 'node_1', @@ -652,7 +642,7 @@ let startCircleData: CircleDatumAlternative[] = [ color: 'slateblue' } ]; -let endCircleData: CircleDatumAlternative[] = [ +const endCircleData: CircleDatumAlternative[] = [ { nodeId: 'n1', name: 'node_1', @@ -683,8 +673,8 @@ let circles2: d3Selection.Selection('#svg2') .datum(dimensions) - .attr('width', function (d) { return d.width; }) - .attr('height', function (d) { return d.height; }) + .attr('width', d => d.width) + .attr('height', d => d.height) .selectAll() // create empty Selection .data(startCircleData) // assign data for circles to be added (no previous circles) .enter() // obtain enter selection @@ -694,9 +684,9 @@ circles2 = d3Selection.select('#svg2') // Assign new data and use key(...) function for mapping circles2 = circles2 // returned update selection has the same type parameters as original selection, if data type is unchanged - .data(endCircleData, function (d) { return d.nodeId; }); + .data(endCircleData, d => d.nodeId); -// circles2.data(endCircleData, function (d) { return d.nodeId; }); // fails, forced data type parameter and data argument mismatch +// circles2.data(endCircleData, function(d) { return d.nodeId; }); // fails, forced data type parameter and data argument mismatch // ENTER-selection ----------------------------------------------------------------- @@ -706,27 +696,27 @@ let enterElements: d3Selection.Selection('circle') // enter selection with materialized DOM elements (svg circles) - .attr('cx', function (d) { return d.cx; }) - .attr('cy', function (d) { return d.cy; }) - .attr('r', function (d) { return d.r; }) - .style('stroke', function (d) { return d.color; }) - .style('fill', function (d) { return d.color; }); + .attr('cx', d => d.cx) + .attr('cy', d => d.cy) + .attr('r', d => d.r) + .style('stroke', d => d.color) + .style('fill', d => d.color); // EXIT-selection ---------------------------------------------------------------------- // tests exit(...) and remove() -let exitCircles = circles2.exit(); // Note: need to re-type datum type, as the exit selection elements have the 'old data' +const exitCircles = circles2.exit(); // Note: need to re-type datum type, as the exit selection elements have the 'old data' exitCircles - .style('opacity', function (d, i, g) { - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatumAlternative = d; - let index: number = i; - let group: SVGCircleElement[] | d3Selection.ArrayLike = g; + .style('opacity', function(d, i, g) { + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatumAlternative = d; + const index: number = i; + const group: SVGCircleElement[] | d3Selection.ArrayLike = g; console.log('Circle Radius exit node: ', this.r.baseVal.value); // this type is SVGCircleElement return d.color === 'green' ? 1 : 0; // data type as per .exit<...>() parameterization }) @@ -737,7 +727,7 @@ exitCircles // let exitCircles2 = circles2.exit(); // Note: Without explicit re-typing to the old data type, the data type default to '{}' // exitCircles2 -// .style('opacity', function (d) { +// .style('opacity', function(d) { // console.log('Circle Radius exit node: ', this.r.baseVal.value); // return d.color === 'green' ? 1 : 0; // fails, as data type is defaulted to {}. If datum access is required, this should trigger the thought to type .exit<...> // }); @@ -775,14 +765,14 @@ nMatrix = tr.data(); // i.e. matrix let td: d3Selection.Selection; td = tr.selectAll() - .data(function (d) { return d; }) // d : Array inferred (Array[4] of number per parent ) + .data(d => d) // d : Array inferred (Array[4] of number per parent ) .enter().append('td') - .text(function (d, i, g) { - let that: HTMLTableDataCellElement = this; - // let that2: Element = this; // fails, type mismatch - let datum: number = d; - let index: number = i; - let group: HTMLTableDataCellElement[] | d3Selection.ArrayLike = g; + .text(function(d, i, g) { + const that: HTMLTableDataCellElement = this; + // const that2: Element = this; // fails, type mismatch + const datum: number = d; + const index: number = i; + const group: HTMLTableDataCellElement[] | d3Selection.ArrayLike = g; console.log('Abbreviated text for object', this.abbr); // this-type HTMLTableDataCellElement (demonstration only) return d; }); // d:number inferred @@ -791,7 +781,7 @@ nRow = td.data(); // flattened matrix (Array[16] of number) // SCENARIO 2 - Completely inferred types, when there is no need for `this` typings -let tr2 = d3Selection.select('body') +const tr2 = d3Selection.select('body') .append('table') .selectAll('tr') .data(matrix) @@ -799,10 +789,10 @@ let tr2 = d3Selection.select('body') nMatrix = tr2.data(); // i.e. matrix -let td2 = tr2.selectAll('td') - .data(function (d) { return d; }) // d : Array inferred (Array[4] of number per parent ) +const td2 = tr2.selectAll('td') + .data(d => d) // d : Array inferred (Array[4] of number per parent ) .enter().append('td') - .text(function (d) { return d; }); // d:number inferred + .text(d => d); // d:number inferred nRow = td2.data(); // flattened matrix (Array[16] of number) @@ -823,12 +813,12 @@ newDiv2 = body.append('div'); newDiv2 = body.append(d3Selection.creator('div')); // newDiv2 = body.append(d3Selection.creator('div')); // fails, as creator returns BaseType element, but HTMLDivElement is expected. -newDiv2 = body.append(function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; +newDiv2 = body.append(function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; console.log('Body element foo property: ', d.foo); // data of type BodyDatum return this.ownerDocument.createElement('div'); // this-type HTMLBodyElement }); @@ -850,7 +840,7 @@ newParagraph = body.insert('p'); // Two arguments; the first can be string, selection , or a -const typeValueFunction = function ( +const typeValueFunction = function( this: HTMLBodyElement, d: BodyDatum, i: number, @@ -859,7 +849,7 @@ const typeValueFunction = function ( return this.ownerDocument.createElement('p'); // this-type HTMLParagraphElement }; -const beforeValueFunction = function ( +const beforeValueFunction = function( this: HTMLBodyElement, d: BodyDatum, i: number, @@ -887,9 +877,7 @@ newParagraph2 = body.insert(typeValueFunction); // sort(...) ----------------------------------------------------------------------------- // NB: Return new selection of same type -circles2 = circles2.sort(function (a, b) { - return (b.r - a.r); -}); +circles2 = circles2.sort((a, b) => b.r - a.r); // order(...) ---------------------------------------------------------------------------- @@ -911,27 +899,27 @@ circles2 = circles2.lower(); // --------------------------------------------------------------------------------------- // empty() ------------------------------------------------------------------------------- -let emptyFlag = gElementsOldData.empty(); +const emptyFlag = gElementsOldData.empty(); // node() and nodes() -------------------------------------------------------------------- -let bodyNode: HTMLBodyElement | null = body.node(); +const bodyNode: HTMLBodyElement | null = body.node(); -let gElementsNodes: SVGGElement[] = gElementsOldData.nodes(); +const gElementsNodes: SVGGElement[] = gElementsOldData.nodes(); // size() -------------------------------------------------------------------------------- -let size: number = gElementsOldData.size(); +const size: number = gElementsOldData.size(); // each() ------------------------------------------------------------------------------- // returns 'this' selection -circles = circles.each(function (d, i, g) { // check chaining return type by re-assigning - let that: SVGCircleElement = this; - // let that2: HTMLElement = this; // fails, type mismatch - let datum: CircleDatum = d; - let index: number = i; - let group: SVGCircleElement[] | d3Selection.ArrayLike = g; +circles = circles.each(function(d, i, g) { // check chaining return type by re-assigning + const that: SVGCircleElement = this; + // const that2: HTMLElement = this; // fails, type mismatch + const datum: CircleDatum = d; + const index: number = i; + const group: SVGCircleElement[] | d3Selection.ArrayLike = g; if (this.r.baseVal.value < d.r) { // this of type SVGCircleElement, datum of type CircleDatumAlternative d3Selection.select(this).attr('r', d.r); } @@ -942,8 +930,8 @@ circles = circles.each(function (d, i, g) { // check chaining return type by re function enforceMinRadius(selection: d3Selection.Selection, minRadius: number): void { - selection.attr('r', function (d) { - let r: number = +d3Selection.select(this).attr('r'); + selection.attr('r', function(d) { + const r: number = +d3Selection.select(this).attr('r'); return Math.max(r, minRadius); }); @@ -952,11 +940,11 @@ function enforceMinRadius(selection: d3Selection.Selection):void { +// circles.call(function(selection: d3Selection.Selection):void { // // fails, group element types of selection not compatible: SVGCircleElement v HTMLDivElement // }); -// circles.call(function (selection: d3Selection.Selection):void { +// circles.call(function(selection: d3Selection.Selection):void { // // fails, group datum types of selection not compatible: CircleDatumAlternative v DivDatum // }); @@ -969,12 +957,12 @@ circles = circles.call(enforceMinRadius, 40); // check chaining return type by r let listener: undefined | ((this: HTMLBodyElement, datum: BodyDatum, index: number, group: HTMLBodyElement[] | ArrayLike) => void); -body = body.on('click', function (d, i, g) { - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | ArrayLike = g; +body = body.on('click', function(d, i, g) { + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | ArrayLike = g; console.log('onclick print body background color: ', this.bgColor); // HTMLBodyElement console.log('onclick print "foo" datum property: ', d.foo); // BodyDatum type }); @@ -993,7 +981,7 @@ body = body.on('click', null); // check chaining return type by re-assigning // dispatch(...) ------------------------------------------------------------------------- -let fooEventParam: d3Selection.CustomEventParameters = { +const fooEventParam: d3Selection.CustomEventParameters = { cancelable: true, bubbles: true, detail: [1, 2, 3, 4] @@ -1002,12 +990,12 @@ let fooEventParam: d3Selection.CustomEventParameters = { // returns 'this' selection body = body.dispatch('fooEvent', fooEventParam); // re-assign for chaining test; -body = body.dispatch('fooEvent', function (d, i, g) { // re-assign for chaining test; - let that: HTMLBodyElement = this; - // let that2: SVGElement = this; // fails, type mismatch - let datum: BodyDatum = d; - let index: number = i; - let group: HTMLBodyElement[] | d3Selection.ArrayLike = g; +body = body.dispatch('fooEvent', function(d, i, g) { // re-assign for chaining test; + const that: HTMLBodyElement = this; + // const that2: SVGElement = this; // fails, type mismatch + const datum: BodyDatum = d; + const index: number = i; + const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; let eParam: d3Selection.CustomEventParameters; console.log('fooEvent dispatch body background color', this.bgColor); eParam = { @@ -1030,17 +1018,17 @@ interface SuccessEvent { team: string; sourceEvent?: any; } -let successEvent = { type: 'wonEuro2016', team: 'Island' }; +const successEvent = { type: 'wonEuro2016', team: 'Island' }; let customListener: (this: HTMLBodyElement, finalOpponent: string) => string; -customListener = function (finalOpponent) { - let e = d3Selection.event; +customListener = finalOpponent => { + const e = d3Selection.event; return e.team + ' defeated ' + finalOpponent + ' in the EURO 2016 Cup. Who would have thought!!!'; }; -let resultText: string = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); +const resultText: string = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); // let result = d3Selection.customEvent(successEvent, customListener, circles.nodes()[0], 'Wales'); // fails, incompatible 'this' context in call // let resultValue: number = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); // fails, incompatible return types @@ -1051,10 +1039,10 @@ let resultText: string = d3Selection.customEvent(successEvent, customListener, b // mouse() --------------------------------------------------------------------------------- let position: [number, number] | null; -let svg: SVGSVGElement = d3Selection.select('svg').node()!; -let g: SVGGElement = d3Selection.select('g').node()!; -let h: HTMLElement = d3Selection.select('div').node()!; -let changedTouches: TouchList = new TouchList(); // dummy +const svg: SVGSVGElement = d3Selection.select('svg').node()!; +const g: SVGGElement = d3Selection.select('g').node()!; +const h: HTMLElement = d3Selection.select('div').node()!; +const changedTouches: TouchList = new TouchList(); // dummy position = d3Selection.mouse(svg); position = d3Selection.mouse(g); @@ -1084,9 +1072,9 @@ positions = d3Selection.touches(h, changedTouches); // Tests of Local // --------------------------------------------------------------------------------------- -let xElement: Element = d3Selection.select('foo').node()!; -let foo: d3Selection.Local = d3Selection.local(); -let propName: string = foo.toString(); +let xElement: Element = d3Selection.select('foo').node()!; +const foo: d3Selection.Local = d3Selection.local(); +const propName: string = foo.toString(); // direct set & get on Local object xElement = foo.set(xElement, [1, 2, 3]); @@ -1104,7 +1092,7 @@ foo.remove(xElement); // Tests of Namespace // --------------------------------------------------------------------------------------- -let predefinedNamespaces: d3Selection.NamespaceMap = d3Selection.namespaces; +const predefinedNamespaces: d3Selection.NamespaceMap = d3Selection.namespaces; const svgNamespace: string = predefinedNamespaces['svg']; diff --git a/d3-shape/d3-shape-tests.ts b/d3-shape/d3-shape-tests.ts index 046a08af0f..642f47c035 100644 --- a/d3-shape/d3-shape-tests.ts +++ b/d3-shape/d3-shape-tests.ts @@ -16,7 +16,6 @@ import { path } from 'd3-path'; let context: CanvasRenderingContext2D | null = document.querySelector('canvas')!.getContext('2d'); let num: number; -let pathString: string; let pathStringMaybe: string | null; // ----------------------------------------------------------------------------------- @@ -39,7 +38,7 @@ let arcDefaultDatum: d3Shape.DefaultArcObject = { padAngle: 0.03 }; -let arcDatum: ArcDatum = { +const arcDatum: ArcDatum = { iRadius: 40, oRadius: 60, sAngle: 0, diff --git a/d3/d3-tests.ts b/d3/d3-tests.ts index ed90cbec40..ca4932d27c 100644 --- a/d3/d3-tests.ts +++ b/d3/d3-tests.ts @@ -7,6 +7,6 @@ import * as d3 from 'd3'; // Ability to access d3-select related properties -let d: d3.Selection = d3.selection(); +const d: d3.Selection = d3.selection(); diff --git a/fusioncharts/fusioncharts-tests.ts b/fusioncharts/fusioncharts-tests.ts index b35dd875cd..af71a2378a 100644 --- a/fusioncharts/fusioncharts-tests.ts +++ b/fusioncharts/fusioncharts-tests.ts @@ -14,7 +14,7 @@ FusionCharts('chartId').render(); FusionCharts["debugger"].enable(true); -let chartData = { +const chartData = { type: 'column2d', renderAt: 'chart-container', width: '450', @@ -36,7 +36,7 @@ let chartData = { } }; -let chart = new FusionCharts(chartData); +const chart = new FusionCharts(chartData); chart.render(); chart.isActive(); chart.addEventListener('ready', eventObject => { diff --git a/geolib/geolib-tests.ts b/geolib/geolib-tests.ts index 2dac05162f..f6283d4f6f 100644 --- a/geolib/geolib-tests.ts +++ b/geolib/geolib-tests.ts @@ -70,12 +70,12 @@ posAsDecimal = geolib.getCenterOfBounds([ -let bound: Bound = geolib.getBounds([ +const bound: Bound = geolib.getBounds([ {latitude: 52.516272, longitude: 13.377722, elevation: 1}, {latitude: 51.515, longitude: 7.453619, elevation: 1}, {latitude: 51.503333, longitude: -0.119722, elevation: 1}]); -let isInside: boolean = geolib.isPointInside( +const isInside: boolean = geolib.isPointInside( {latitude: 51.5125, longitude: 7.485}, [ {latitude: 51.50, longitude: 7.40}, @@ -86,7 +86,7 @@ let isInside: boolean = geolib.isPointInside( ); // -> true // checks if 51.525, 7.4575 is within a radius of 5km from 51.5175, 7.4678 -let boolResult: boolean = geolib.isPointInCircle( +const boolResult: boolean = geolib.isPointInCircle( {latitude: 51.525, longitude: 7.4575}, {latitude: 51.5175, longitude: 7.4678}, 5000 @@ -129,7 +129,7 @@ distanceArray = geolib.orderByDistance({latitude: 51.515, longitude: 7.453619}, // in this case set offset to 1 otherwise the nearest point will always be your reference point -let posAsDecimalArray: Distance[] = geolib.findNearest( +const posAsDecimalArray: Distance[] = geolib.findNearest( {latitude: 51.515, longitude: 7.453619}, [ {latitude: 52.516272, longitude: 13.377722}, @@ -164,15 +164,15 @@ speed = geolib.getSpeed( ] ); // -> 66.9408 (mph) -let point1 = {latitude: 0.5, longitude: 0}; -let point2 = {latitude: 0, longitude: 10}; -let point3 = {latitude: 0, longitude: 15.5}; -let start = {latitude: 0, longitude: 0}; -let end = {latitude: 0, longitude: 15}; +const point1 = {latitude: 0.5, longitude: 0}; +const point2 = {latitude: 0, longitude: 10}; +const point3 = {latitude: 0, longitude: 15.5}; +const start = {latitude: 0, longitude: 0}; +const end = {latitude: 0, longitude: 15}; -let isInLine1 = geolib.isPointInLine(point1, start, end); //-> false; -let isInLine2 = geolib.isPointInLine(point2, start, end); //-> true; -let isInLine3 = geolib.isPointInLine(point3, start, end); //-> false; +const isInLine1 = geolib.isPointInLine(point1, start, end); //-> false; +const isInLine2 = geolib.isPointInLine(point2, start, end); //-> true; +const isInLine3 = geolib.isPointInLine(point3, start, end); //-> false; let convertResult: number = geolib.convertUnit('km', 14213, 2); // -> 14,21 @@ -180,7 +180,7 @@ convertResult = geolib.convertUnit('km', 14213); // -> 14,21 let result: number = geolib.sexagesimal2decimal("51° 29' 46\" N"); -let resultString: string = geolib.decimal2sexagesimal(51.49611111); // -> 51° 29' 46.00 +const resultString: string = geolib.decimal2sexagesimal(51.49611111); // -> 51° 29' 46.00 result = geolib.latitude({lat: 51.49611, lng: 7.38896}); // -> 51.49611 result = geolib.longitude({lat: 51.49611, lng: 7.38896}); // -> 7.38896 @@ -190,8 +190,8 @@ result = geolib.useDecimal(51.59611111); // -> 51.59611111 result = geolib.elevation({lat: 51.49611, lng: 7.38896}); -let initialPoint = {latitude: 51.516272, longitude: 0.45425}; -let radius = 100; +const initialPoint = {latitude: 51.516272, longitude: 0.45425}; +const radius = 100; dist = 1234; bearing = 45; diff --git a/globule/globule-tests.ts b/globule/globule-tests.ts index d0e1eb3ccb..78697ba199 100644 --- a/globule/globule-tests.ts +++ b/globule/globule-tests.ts @@ -18,9 +18,9 @@ bResult = globule.isMatch('*.js', '/home/code'); bResult = globule.isMatch('*.js', '/home/code', { matchBase: true }); let mappings = globule.mapping(['*.js']); -let len = mappings.length; -let src = mappings[0].src; -let dest = mappings[0].dest; +const len = mappings.length; +const src = mappings[0].src; +const dest = mappings[0].dest; mappings = globule.mapping(['*.js'], { srcBase: '/home/code' }); mappings = globule.mapping(['*.js', '*.less']); diff --git a/graphql-relay/graphql-relay-tests.ts b/graphql-relay/graphql-relay-tests.ts index f1b18a4521..bd42318e95 100644 --- a/graphql-relay/graphql-relay-tests.ts +++ b/graphql-relay/graphql-relay-tests.ts @@ -43,13 +43,13 @@ forwardConnectionArgs.first = 10; backwardConnectionArgs.before = "b"; backwardConnectionArgs.last = 10; // connectionDefinitions returns a connectionType and its associated edgeType, given a node type. -let resolve: GraphQLFieldResolver = (source, args, context, info) => { +const resolve: GraphQLFieldResolver = (source, args, context, info) => { info.fieldName = "f"; }; const fields: GraphQLFieldConfigMap = {}; let t: GraphQLObjectType; let e: GraphQLObjectType; -let def = connectionDefinitions({ +const def = connectionDefinitions({ connectionFields: fields, edgeFields: fields, name: "N", @@ -89,7 +89,7 @@ conn2.then((res) => { // cursorForObjectInConnection is a helper method that takes an array and a member object, and returns a cursor for use in the mutation payload. cursorForObjectInConnection(["a"], "b").toLowerCase(); // An example usage of these methods from the test schema: -let shipType: GraphQLObjectType = new GraphQLObjectType({ +const shipType: GraphQLObjectType = new GraphQLObjectType({ name: "ShipType", fields: {}, }); diff --git a/hoek/hoek-tests.ts b/hoek/hoek-tests.ts index e4ea5aef83..bb2ac87389 100644 --- a/hoek/hoek-tests.ts +++ b/hoek/hoek-tests.ts @@ -50,16 +50,16 @@ console.log(copy.x.b); // results in 100 // merge(target, source, isNullOverride, isMergeArrays) -let target = { a: 1, b: 2 }; -let source = { a: 0, c: 5 }; -let source2 = { a: null, c: 5 }; +const target = { a: 1, b: 2 }; +const source = { a: 0, c: 5 }; +const source2 = { a: null, c: 5 }; Hoek.merge(target, source); // results in {a: 0, b: 2, c: 5} Hoek.merge(target, source2); // results in {a: null, b: 2, c: 5} Hoek.merge(target, source2, false); // results in {a: 1, b: 2, c: 5} -let targetArray = [1, 2, 3]; -let sourceArray = [4, 5]; +const targetArray = [1, 2, 3]; +const sourceArray = [4, 5]; Hoek.merge(targetArray, sourceArray); // results in [1, 2, 3, 4, 5] Hoek.merge(targetArray, sourceArray, true, false); // results in [4, 5] @@ -67,18 +67,18 @@ Hoek.merge(targetArray, sourceArray, true, false); // results in [4, 5] // applyToDefaults(defaults, options, isNullOverride) let defaults = { host: "localhost", port: 8000 }; -let options = { port: 8080 }; +const options = { port: 8080 }; let config = Hoek.applyToDefaults(defaults, options); // results in { host: "localhost", port: 8080 } defaults = { host: "localhost", port: 8000 }; -let options1 = { host: null, port: 8080 }; +const options1 = { host: null, port: 8080 }; config = Hoek.applyToDefaults(defaults, options1, true); // results in { host: null, port: 8080 } // applyToDefaultsWithShallow(defaults, options, keys) -let defaults1 = { +const defaults1 = { server: { host: "localhost", port: 8000 @@ -86,25 +86,25 @@ let defaults1 = { name: 'example' }; -let options2 = { server: { port: 8080 } }; +const options2 = { server: { port: 8080 } }; -let config1 = Hoek.applyToDefaultsWithShallow(defaults1, options2, ['server']); // results in { server: { port: 8080 }, name: 'example' } +const config1 = Hoek.applyToDefaultsWithShallow(defaults1, options2, ['server']); // results in { server: { port: 8080 }, name: 'example' } // deepEqual(b, a, [options]) -Hoek.deepEqual({ a: [1, 2], b: 'string', c: { d: true } }, { a: [1, 2], b: 'string', c: { d: true } }); //results in true -Hoek.deepEqual(Object.create(null), {}, { prototype: false }); //results in true -Hoek.deepEqual(Object.create(null), {}); //results in false +Hoek.deepEqual({ a: [1, 2], b: 'string', c: { d: true } }, { a: [1, 2], b: 'string', c: { d: true } }); // results in true +Hoek.deepEqual(Object.create(null), {}, { prototype: false }); // results in true +Hoek.deepEqual(Object.create(null), {}); // results in false // unique(array, key) let array = [1, 2, 2, 3, 3, 4, 5, 6]; -let newArray = Hoek.unique(array); // results in [1,2,3,4,5,6] +const newArray = Hoek.unique(array); // results in [1,2,3,4,5,6] let array1 = [{ id: 1 }, { id: 1 }, { id: 2 }]; -let newArray1 = Hoek.unique(array1, "id"); // results in [{id: 1}, {id: 2}] +const newArray1 = Hoek.unique(array1, "id"); // results in [{id: 1}, {id: 2}] // mapToObject(array, key) @@ -117,9 +117,9 @@ newObject = Hoek.mapToObject(array1, "id"); // results in {"1": true, "2": true} // intersect(array1, array2) array = [1, 2, 3]; -let array2 = [1, 4, 5]; +const array2 = [1, 4, 5]; -let newArray2 = Hoek.intersect(array, array2); // results in [1] +const newArray2 = Hoek.intersect(array, array2); // results in [1] // contain(ref, values, [options]) @@ -135,7 +135,7 @@ let array3 = [1, [2, 3]]; let flattenedArray = Hoek.flatten(array); // results in [1, 2, 3] array3 = [1, [2, 3]]; -let target1 = [4, [5]]; +const target1 = [4, [5]]; flattenedArray = Hoek.flatten(array3, target1); // results in [4, [5], 1, 2, 3] @@ -147,7 +147,7 @@ let obj = { a: { b: { c: 1 } } }; Hoek.reach(obj, chain); // returns 1 chain = 'a.b.-1'; -let obj1 = { a: { b: [2, 3, 6] } }; +const obj1 = { a: { b: [2, 3, 6] } }; Hoek.reach(obj1, chain); // returns 6 @@ -160,7 +160,7 @@ Hoek.reachTemplate(obj, '1+{a.b.c}=2'); // returns '1+1=2' // transform(obj, transform, [options]) -let source1 = { +const source1 = { address: { one: '123 main street', two: 'PO Box 1234' @@ -189,7 +189,7 @@ let result = Hoek.transform(source1, { // shallow(obj) -let shallow = Hoek.shallow({ a: { b: 1 } }); +const shallow = Hoek.shallow({ a: { b: 1 } }); // stringify(obj) @@ -199,13 +199,13 @@ Hoek.stringify(a); // Returns '[Cannot display object: Converting circular // Timer -let timerObj = new Hoek.Timer(); +const timerObj = new Hoek.Timer(); console.log("Time is now: " + timerObj.ts); console.log("Elapsed time from initialization: " + timerObj.elapsed() + 'milliseconds'); // Bench -let benchObj = new Hoek.Bench(); +const benchObj = new Hoek.Bench(); console.log("Elapsed time from initialization: " + benchObj.elapsed() + 'milliseconds'); // base64urlEncode(value) @@ -218,12 +218,12 @@ Hoek.base64urlDecode("aG9law=="); // escapeHtml(string) -let string = ' hey '; -let escapedString = Hoek.escapeHtml(string); // returns <html> hey </html> +const string = ' hey '; +const escapedString = Hoek.escapeHtml(string); // returns <html> hey </html> // escapeHeaderAttribute(attribute) -a = Hoek.escapeHeaderAttribute('I said "go w\\o me"'); //returns I said \"go w\\o me\" +a = Hoek.escapeHeaderAttribute('I said "go w\\o me"'); // returns I said \"go w\\o me\" // escapeRegex(string) @@ -231,7 +231,7 @@ a = Hoek.escapeRegex('4^f$s.4*5+-_?%=#!:@|~\\/`"(>)[<]d{}s,'); // returns 4\^f\ // assert(condition, message) -let x = 1, y = 2; +const x = 1, y = 2 as number; Hoek.assert(x === y, 'x should equal y'); // Throws 'x should equal y' @@ -243,12 +243,12 @@ Hoek.abort("Error message"); // displayStack(slice) -let stack = Hoek.displayStack(); +const stack = Hoek.displayStack(); console.log(stack); // callStack(slice) -let stack2 = Hoek.callStack(); +const stack2 = Hoek.callStack(); console.log(stack2); // nextTick(fn) @@ -257,7 +257,7 @@ let myFn = () => { console.log('Do this later'); }; -let nextFn = Hoek.nextTick(myFn); +const nextFn = Hoek.nextTick(myFn); nextFn(); console.log('Do this first'); @@ -273,7 +273,7 @@ myFn = () => { console.log('Ran myFn'); }; -let onceFn = Hoek.once(myFn); +const onceFn = Hoek.once(myFn); onceFn(); // results in "Ran myFn" onceFn(); // results in undefined @@ -283,7 +283,7 @@ Hoek.ignore(); // uniqueFilename(path, extension) -let result1 = Hoek.uniqueFilename('./test/modules', 'txt'); // results in "full/path/test/modules/{random}.txt" +const result1 = Hoek.uniqueFilename('./test/modules', 'txt'); // results in "full/path/test/modules/{random}.txt" // isInteger(value) diff --git a/http-assert/http-assert-tests.ts b/http-assert/http-assert-tests.ts index 06974e7b12..bfb12e650a 100644 --- a/http-assert/http-assert-tests.ts +++ b/http-assert/http-assert-tests.ts @@ -4,7 +4,7 @@ import { HttpError } from 'http-errors'; try { httpAssert.equal('hello', 'hello'); httpAssert(false, 401, 'authentication failed'); -} catch(err) { +} catch (err) { console.log(( err).status); console.log(( err).message); console.log(( err).expose); diff --git a/indent-string/indent-string-tests.ts b/indent-string/indent-string-tests.ts index ea473a2814..6e5e764cb4 100644 --- a/indent-string/indent-string-tests.ts +++ b/indent-string/indent-string-tests.ts @@ -1,9 +1,9 @@ import indentString = require('indent-string'); indentString('Unicorns\nRainbows', 4); -//=> ' Unicorns' -//=> ' Rainbows' +// => ' Unicorns' +// => ' Rainbows' indentString('Unicorns\nRainbows', 4, '♥'); -//=> '♥♥♥♥Unicorns' -//=> '♥♥♥♥Rainbows' \ No newline at end of file +// => '♥♥♥♥Unicorns' +// => '♥♥♥♥Rainbows' \ No newline at end of file diff --git a/is-absolute-url/is-absolute-url-tests.ts b/is-absolute-url/is-absolute-url-tests.ts index 8ddf3e2514..47c5f007ed 100644 --- a/is-absolute-url/is-absolute-url-tests.ts +++ b/is-absolute-url/is-absolute-url-tests.ts @@ -1,10 +1,10 @@ import isAbsoluteUrl = require('is-absolute-url'); isAbsoluteUrl('http://sindresorhus.com/foo/bar'); -//=> true +// => true isAbsoluteUrl('//sindresorhus.com'); -//=> false +// => false isAbsoluteUrl('foo/bar'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/is-archive/is-archive-tests.ts b/is-archive/is-archive-tests.ts index 30be8dc06e..332deae7ec 100644 --- a/is-archive/is-archive-tests.ts +++ b/is-archive/is-archive-tests.ts @@ -1,7 +1,7 @@ import isArchive = require('is-archive'); isArchive('src/unicorn.zip'); -//=> true +// => true isArchive('src/unicorn.txt'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/is-binary-path/is-binary-path-tests.ts b/is-binary-path/is-binary-path-tests.ts index 967346a35a..43505a5b32 100644 --- a/is-binary-path/is-binary-path-tests.ts +++ b/is-binary-path/is-binary-path-tests.ts @@ -1,5 +1,5 @@ import isBinaryPath = require("is-binary-path"); -let a: boolean = isBinaryPath("src/unicorn.png"); +const a: boolean = isBinaryPath("src/unicorn.png"); -let b: boolean = isBinaryPath("src/unicorn.txt"); \ No newline at end of file +const b: boolean = isBinaryPath("src/unicorn.txt"); \ No newline at end of file diff --git a/is-compressed/is-compressed-tests.ts b/is-compressed/is-compressed-tests.ts index 11a2e67294..7720b334a4 100644 --- a/is-compressed/is-compressed-tests.ts +++ b/is-compressed/is-compressed-tests.ts @@ -1,7 +1,7 @@ import isCompressed = require('is-compressed'); isCompressed('src/unicorn.zip'); -//=> true +// => true isCompressed('src/unicorn.txt'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/is-relative-url/is-relative-url-tests.ts b/is-relative-url/is-relative-url-tests.ts index 293c621872..8835694624 100644 --- a/is-relative-url/is-relative-url-tests.ts +++ b/is-relative-url/is-relative-url-tests.ts @@ -1,10 +1,10 @@ import isRelativeUrl = require('is-relative-url'); isRelativeUrl('foo/bar'); -//=> true +// => true isRelativeUrl('http://sindresorhus.com/foo/bar'); -//=> false +// => false isRelativeUrl('//sindresorhus.com'); -//=> true \ No newline at end of file +// => true \ No newline at end of file diff --git a/is-root-path/is-root-path-tests.ts b/is-root-path/is-root-path-tests.ts index 0a577aee5a..3e050cd162 100644 --- a/is-root-path/is-root-path-tests.ts +++ b/is-root-path/is-root-path-tests.ts @@ -1,7 +1,7 @@ import isRootPath = require('is-root-path'); isRootPath('/'); -//=> true +// => true isRootPath('/Users'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/is-root/is-root-tests.ts b/is-root/is-root-tests.ts index 42fc3ee4f3..b53d07a0ac 100644 --- a/is-root/is-root-tests.ts +++ b/is-root/is-root-tests.ts @@ -2,4 +2,4 @@ import isRoot = require('is-root'); isRoot(); -//=> true \ No newline at end of file +// => true \ No newline at end of file diff --git a/is-text-path/is-text-path-tests.ts b/is-text-path/is-text-path-tests.ts index cd71933ec2..f7c417fe51 100644 --- a/is-text-path/is-text-path-tests.ts +++ b/is-text-path/is-text-path-tests.ts @@ -1,7 +1,7 @@ import isTextPath = require('is-text-path'); isTextPath('src/unicorn.txt'); -//=> true +// => true isTextPath('src/unicorn.png'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/jasmine-ajax/index.d.ts b/jasmine-ajax/index.d.ts index 72a3348afc..6ec4020d00 100644 --- a/jasmine-ajax/index.d.ts +++ b/jasmine-ajax/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for jasmine-ajax 3.1.1 +// Type definitions for jasmine-ajax 3.1 // Project: https://github.com/jasmine/jasmine-ajax // Definitions by: Louis Grignon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 interface JasmineAjaxResponse { status?: number; @@ -74,7 +75,7 @@ declare class MockAjax { stubRequest(url: RegExp, data?: string, method?: string): JasmineAjaxRequestStub; stubRequest(url: string, data?: string, method?: string): JasmineAjaxRequestStub; - + stubRequest(url: RegExp, data?: RegExp, method?: string): JasmineAjaxRequestStub; stubRequest(url: string, data?: RegExp, method?: string): JasmineAjaxRequestStub; diff --git a/jasmine-ajax/jasmine-ajax-tests.ts b/jasmine-ajax/jasmine-ajax-tests.ts index 890a724420..d94b205d13 100644 --- a/jasmine-ajax/jasmine-ajax-tests.ts +++ b/jasmine-ajax/jasmine-ajax-tests.ts @@ -8,31 +8,31 @@ declare function getJasmineRequireObj(); -describe('StubTracker', function() { - beforeEach(function() { +describe('StubTracker', () => { + beforeEach(() => { var Constructor = getJasmineRequireObj().AjaxStubTracker(); this.tracker = new Constructor(); }); - it('finds nothing if no stubs are added', function() { + it('finds nothing if no stubs are added', () => { expect(this.tracker.findStub()).toBeUndefined(); }); - it('finds an added stub', function() { - var stub = { matches: function() { return true; } }; + it('finds an added stub', () => { + var stub = { matches: () => true }; this.tracker.addStub(stub); expect(this.tracker.findStub()).toBe(stub); }); - it('skips an added stub that does not match', function() { - var stub = { matches: function() { return false; } }; + it('skips an added stub that does not match', () => { + var stub = { matches: () => false }; this.tracker.addStub(stub); expect(this.tracker.findStub()).toBeUndefined(); }); - it('passes url, data, and method to the stub', function() { + it('passes url, data, and method to the stub', () => { var stub = { matches: jasmine.createSpy('matches') }; this.tracker.addStub(stub); @@ -41,7 +41,7 @@ describe('StubTracker', function() { expect(stub.matches).toHaveBeenCalledWith('url', 'data', 'method'); }); - it('can clear out all stubs', function() { + it('can clear out all stubs', () => { var stub = { matches: jasmine.createSpy('matches') }; this.tracker.addStub(stub); @@ -57,10 +57,10 @@ describe('StubTracker', function() { expect(stub.matches).not.toHaveBeenCalled(); }); - it('uses the most recently added stub that matches', function() { - var stub1 = { matches: function() { return true; } }; - var stub2 = { matches: function() { return true; } }; - var stub3 = { matches: function() { return false; } }; + it('uses the most recently added stub that matches', () => { + var stub1 = { matches: () => true }; + var stub2 = { matches: () => false }; + var stub3 = { matches: () => false }; this.tracker.addStub(stub1); this.tracker.addStub(stub2); @@ -70,22 +70,22 @@ describe('StubTracker', function() { }); }); -describe('FakeRequest', function() { - beforeEach(function() { +describe('FakeRequest', () => { + beforeEach(() => { this.requestTracker = { track: jasmine.createSpy('trackRequest') }; - this.stubTracker = { findStub: function() { } }; + this.stubTracker = { findStub() { } }; var parserInstance = this.parserInstance = jasmine.createSpy('parse'); - this.paramParser = { findParser: function() { return { parse: parserInstance }; } }; + this.paramParser = { findParser: () => ({ parse: parserInstance }) }; var eventBus = this.fakeEventBus = { addEventListener: jasmine.createSpy('addEventListener'), trigger: jasmine.createSpy('trigger'), removeEventListener: jasmine.createSpy('removeEventListener') }; - this.eventBusFactory = function() { + this.eventBusFactory = () => { return eventBus; }; this.fakeGlobal = { - XMLHttpRequest: function() { + XMLHttpRequest: () => { this.extraAttribute = 'my cool attribute'; }, DOMParser: window['DOMParser'], @@ -94,13 +94,13 @@ describe('FakeRequest', function() { this.FakeRequest = getJasmineRequireObj().AjaxFakeRequest(this.eventBusFactory)(this.fakeGlobal, this.requestTracker, this.stubTracker, this.paramParser); }); - it('extends from the global XMLHttpRequest', function() { + it('extends from the global XMLHttpRequest', () => { var request = new this.FakeRequest(); expect(request.extraAttribute).toEqual('my cool attribute'); }); - it('skips XMLHttpRequest attributes that IE does not want copied', function() { + it('skips XMLHttpRequest attributes that IE does not want copied', () => { // use real window here so it will correctly go red on IE if it breaks var FakeRequest = getJasmineRequireObj().AjaxFakeRequest(this.eventBusFactory)(window, this.requestTracker, this.stubTracker, this.paramParser); var request = new FakeRequest(); @@ -110,20 +110,20 @@ describe('FakeRequest', function() { expect(request.statusText).toBeUndefined(); }); - it('tracks the request', function() { + it('tracks the request', () => { var request = new this.FakeRequest(); expect(this.requestTracker.track).toHaveBeenCalledWith(request); }); - it('has default request headers and override mime type', function() { + it('has default request headers and override mime type', () => { var request = new this.FakeRequest(); expect(request.requestHeaders).toEqual({}); expect(request.overriddenMimeType).toBeNull(); }); - it('saves request information when opened', function() { + it('saves request information when opened', () => { var request = new this.FakeRequest(); request.open('METHOD', 'URL', 'ignore_async', 'USERNAME', 'PASSWORD'); @@ -133,7 +133,7 @@ describe('FakeRequest', function() { expect(request.password).toEqual('PASSWORD'); }); - it('saves an override mime type', function() { + it('saves an override mime type', () => { var request = new this.FakeRequest(); request.overrideMimeType('application/text; charset: utf-8'); @@ -141,7 +141,7 @@ describe('FakeRequest', function() { expect(request.overriddenMimeType).toBe('application/text; charset: utf-8'); }); - it('saves request headers', function() { + it('saves request headers', () => { var request = new this.FakeRequest(); request.setRequestHeader('X-Header-1', 'value1'); @@ -153,7 +153,7 @@ describe('FakeRequest', function() { }); }); - it('combines request headers with the same header name', function() { + it('combines request headers with the same header name', () => { var request = new this.FakeRequest(); request.setRequestHeader('X-Header', 'value1'); @@ -162,7 +162,7 @@ describe('FakeRequest', function() { expect(request.requestHeaders['X-Header']).toEqual('value1, value2'); }); - it('finds the content-type request header', function() { + it('finds the content-type request header', () => { var request = new this.FakeRequest(); request.setRequestHeader('ContEnt-tYPe', 'application/text+xml'); @@ -170,24 +170,24 @@ describe('FakeRequest', function() { expect(request.contentType()).toEqual('application/text+xml'); }); - describe('managing readyState', function() { - beforeEach(function() { + describe('managing readyState', () => { + beforeEach(() => { this.request = new this.FakeRequest(); }); - it('has an initial ready state of 0 (uninitialized)', function() { + it('has an initial ready state of 0 (uninitialized)', () => { expect(this.request.readyState).toBe(0); expect(this.fakeEventBus.trigger).not.toHaveBeenCalled(); }); - it('has a ready state of 1 (open) when opened', function() { + it('has a ready state of 1 (open) when opened', () => { this.request.open(); expect(this.request.readyState).toBe(1); expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 0 (uninitialized) when aborted', function() { + it('has a ready state of 0 (uninitialized) when aborted', () => { this.request.open(); this.fakeEventBus.trigger.calls.reset(); @@ -197,7 +197,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 1 (sent) when sent', function() { + it('has a ready state of 1 (sent) when sent', () => { this.request.open(); this.fakeEventBus.trigger.calls.reset(); @@ -208,7 +208,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).not.toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 4 (loaded) when timed out', function() { + it('has a ready state of 4 (loaded) when timed out', () => { this.request.open(); this.request.send(); this.fakeEventBus.trigger.calls.reset(); @@ -221,7 +221,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange', 'timeout'); }); - it('has a ready state of 4 (loaded) when network erroring', function() { + it('has a ready state of 4 (loaded) when network erroring', () => { this.request.open(); this.request.send(); this.fakeEventBus.trigger.calls.reset(); @@ -232,7 +232,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 4 (loaded) when responding', function() { + it('has a ready state of 4 (loaded) when responding', () => { this.request.open(); this.request.send(); this.fakeEventBus.trigger.calls.reset(); @@ -243,7 +243,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('has a ready state of 2, then 4 (loaded) when responding', function() { + it('has a ready state of 2, then 4 (loaded) when responding', () => { this.request.open(); this.request.send(); this.fakeEventBus.trigger.calls.reset(); @@ -254,7 +254,7 @@ describe('FakeRequest', function() { { name: 'X-Header', value: 'foo' } ]; - this.fakeEventBus.trigger.and.callFake(function(event) { + this.fakeEventBus.trigger.and.callFake(event => { if (event === 'readystatechange') { events.push({ readyState: request.readyState, @@ -280,41 +280,41 @@ describe('FakeRequest', function() { ]); }); - it('throws an error when timing out a request that has completed', function() { + it('throws an error when timing out a request that has completed', () => { this.request.open(); this.request.send(); this.request.respondWith({}); var request = this.request; - expect(function() { + expect(() => { request.responseTimeout(); }).toThrowError('FakeXMLHttpRequest already completed'); }); - it('throws an error when responding to a request that has completed', function() { + it('throws an error when responding to a request that has completed', () => { this.request.open(); this.request.send(); this.request.respondWith({}); var request = this.request; - expect(function() { + expect(() => { request.respondWith({}); }).toThrowError('FakeXMLHttpRequest already completed'); }); - it('throws an error when erroring a request that has completed', function() { + it('throws an error when erroring a request that has completed', () => { this.request.open(); this.request.send(); this.request.respondWith({}); var request = this.request; - expect(function() { + expect(() => { request.responseError({}); }).toThrowError('FakeXMLHttpRequest already completed'); }); }); - it('registers on-style callback with the event bus', function() { + it('registers on-style callback with the event bus', () => { this.request = new this.FakeRequest(); expect(this.fakeEventBus.addEventListener).toHaveBeenCalledWith('readystatechange', jasmine.any(Function)); @@ -336,16 +336,13 @@ describe('FakeRequest', function() { this.request.onloadend = jasmine.createSpy('loadend'); var args = this.fakeEventBus.addEventListener.calls.allArgs(); - for (var i = 0; i < args.length; i++) { - var eventName = args[i][0], - busCallback = args[i][1]; - + for (const [eventName, busCallback] of args) { busCallback(); expect(this.request['on' + eventName]).toHaveBeenCalled(); } }); - it('delegates addEventListener to the eventBus', function() { + it('delegates addEventListener to the eventBus', () => { this.request = new this.FakeRequest(); this.request.addEventListener('foo', 'bar'); @@ -353,7 +350,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.addEventListener).toHaveBeenCalledWith('foo', 'bar'); }); - it('delegates removeEventListener to the eventBus', function() { + it('delegates removeEventListener to the eventBus', () => { this.request = new this.FakeRequest(); this.request.removeEventListener('foo', 'bar'); @@ -361,18 +358,18 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.removeEventListener).toHaveBeenCalledWith('foo', 'bar'); }); - describe('triggering progress events', function() { - beforeEach(function() { + describe('triggering progress events', () => { + beforeEach(() => { this.request = new this.FakeRequest(); }); - it('should not trigger any events to start', function() { + it('should not trigger any events to start', () => { this.request.open(); expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('readystatechange'); }); - it('should trigger loadstart when sent', function() { + it('should trigger loadstart when sent', () => { this.request.open(); this.fakeEventBus.trigger.calls.reset(); @@ -389,7 +386,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).not.toHaveBeenCalledWith('loadend'); }); - it('should trigger abort, progress, loadend when aborted', function() { + it('should trigger abort, progress, loadend when aborted', () => { this.request.open(); this.request.send(); @@ -407,7 +404,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('loadend'); }); - it('should trigger error, progress, loadend when network error', function() { + it('should trigger error, progress, loadend when network error', () => { this.request.open(); this.request.send(); @@ -425,7 +422,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('loadend'); }); - it('should trigger timeout, progress, loadend when timing out', function() { + it('should trigger timeout, progress, loadend when timing out', () => { this.request.open(); this.request.send(); @@ -445,7 +442,7 @@ describe('FakeRequest', function() { expect(this.fakeEventBus.trigger).toHaveBeenCalledWith('loadend'); }); - it('should trigger load, progress, loadend when responding', function() { + it('should trigger load, progress, loadend when responding', () => { this.request.open(); this.request.send(); @@ -464,7 +461,7 @@ describe('FakeRequest', function() { }); }); - it('ticks the jasmine clock on timeout', function() { + it('ticks the jasmine clock on timeout', () => { var clock = { tick: jasmine.createSpy('tick') }; spyOn(jasmine, 'clock').and.returnValue(clock); @@ -477,13 +474,13 @@ describe('FakeRequest', function() { expect(clock.tick).toHaveBeenCalledWith(30000); }); - it('has an initial status of null', function() { + it('has an initial status of null', () => { var request = new this.FakeRequest(); expect(request.status).toBeNull(); }); - it('has an aborted status', function() { + it('has an aborted status', () => { var request = new this.FakeRequest(); request.abort(); @@ -492,7 +489,7 @@ describe('FakeRequest', function() { expect(request.statusText).toBe('abort'); }); - it('has a status from the response', function() { + it('has a status from the response', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -503,7 +500,7 @@ describe('FakeRequest', function() { expect(request.statusText).toBe(''); }); - it('has a statusText from the response', function() { + it('has a statusText from the response', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -514,7 +511,7 @@ describe('FakeRequest', function() { expect(request.statusText).toBe('OK'); }); - it('saves off any data sent to the server', function() { + it('saves off any data sent to the server', () => { var request = new this.FakeRequest(); request.open(); request.send('foo=bar&baz=quux'); @@ -522,7 +519,7 @@ describe('FakeRequest', function() { expect(request.params).toBe('foo=bar&baz=quux'); }); - it('parses data sent to the server', function() { + it('parses data sent to the server', () => { var request = new this.FakeRequest(); request.open(); request.send('foo=bar&baz=quux'); @@ -532,7 +529,7 @@ describe('FakeRequest', function() { expect(request.data()).toBe('parsed'); }); - it('skips parsing if no data was sent', function() { + it('skips parsing if no data was sent', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -541,7 +538,7 @@ describe('FakeRequest', function() { expect(this.parserInstance).not.toHaveBeenCalled(); }); - it('saves responseText', function() { + it('saves responseText', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -551,7 +548,7 @@ describe('FakeRequest', function() { expect(request.responseText).toBe('foobar'); }); - it('defaults responseText if none is given', function() { + it('defaults responseText if none is given', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -561,7 +558,7 @@ describe('FakeRequest', function() { expect(request.responseText).toBe(''); }); - it('retrieves individual response headers', function() { + it('retrieves individual response headers', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -576,7 +573,7 @@ describe('FakeRequest', function() { expect(request.getResponseHeader('X-Header')).toBe('foo'); }); - it('retrieves individual response headers case-insensitively', function() { + it('retrieves individual response headers case-insensitively', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -591,7 +588,7 @@ describe('FakeRequest', function() { expect(request.getResponseHeader('x-header')).toBe('foo'); }); - it('retrieves a combined response header', function() { + it('retrieves a combined response header', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -607,7 +604,7 @@ describe('FakeRequest', function() { expect(request.getResponseHeader('x-header')).toBe('foo, bar'); }); - it("doesn't pollute the response headers of other XHRs", function() { + it("doesn't pollute the response headers of other XHRs", () => { var request1 = new this.FakeRequest(); request1.open(); request1.send(); @@ -623,7 +620,7 @@ describe('FakeRequest', function() { expect(request2.getAllResponseHeaders()).toBe("X-Baz: quux\r\n"); }); - it('retrieves all response headers', function() { + it('retrieves all response headers', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -640,7 +637,7 @@ describe('FakeRequest', function() { expect(request.getAllResponseHeaders()).toBe("X-Header-1: foo\r\nX-Header-2: bar\r\nX-Header-1: baz\r\n"); }); - it('sets the content-type header to the specified contentType when no other headers are supplied', function() { + it('sets the content-type header to the specified contentType when no other headers are supplied', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -651,7 +648,7 @@ describe('FakeRequest', function() { expect(request.getAllResponseHeaders()).toBe("Content-Type: text/plain\r\n"); }); - it('sets a default content-type header if no contentType and headers are supplied', function() { + it('sets a default content-type header if no contentType and headers are supplied', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -662,7 +659,7 @@ describe('FakeRequest', function() { expect(request.getAllResponseHeaders()).toBe("Content-Type: application/json\r\n"); }); - it('has no responseXML by default', function() { + it('has no responseXML by default', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -672,7 +669,7 @@ describe('FakeRequest', function() { expect(request.responseXML).toBeNull(); }); - it('parses a text/xml document into responseXML', function() { + it('parses a text/xml document into responseXML', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -689,7 +686,7 @@ describe('FakeRequest', function() { } }); - it('parses an application/xml document into responseXML', function() { + it('parses an application/xml document into responseXML', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -706,7 +703,7 @@ describe('FakeRequest', function() { } }); - it('parses a custom blah+xml document into responseXML', function() { + it('parses a custom blah+xml document into responseXML', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -723,7 +720,7 @@ describe('FakeRequest', function() { } }); - it('defaults the response attribute to the responseText', function() { + it('defaults the response attribute to the responseText', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -733,7 +730,7 @@ describe('FakeRequest', function() { expect(request.response).toEqual('foo'); }); - it('has a text response when the responseType is blank', function() { + it('has a text response when the responseType is blank', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -743,7 +740,7 @@ describe('FakeRequest', function() { expect(request.response).toEqual('foo'); }); - it('has a text response when the responseType is text', function() { + it('has a text response when the responseType is text', () => { var request = new this.FakeRequest(); request.open(); request.send(); @@ -755,14 +752,14 @@ describe('FakeRequest', function() { }); -describe("Jasmine Mock Ajax (for toplevel)", function() { +describe("Jasmine Mock Ajax (for toplevel)", () => { var request, anotherRequest, response; var success, error, complete; var client, onreadystatechange; var sharedContext: any = {}; var fakeGlobal, mockAjax; - beforeEach(function() { + beforeEach(() => { var fakeXMLHttpRequest = jasmine.createSpy('realFakeXMLHttpRequest'); fakeGlobal = { XMLHttpRequest: fakeXMLHttpRequest, @@ -776,7 +773,7 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { error = jasmine.createSpy("onFailure"); complete = jasmine.createSpy("onComplete"); - onreadystatechange = function() { + onreadystatechange = () => { if (this.readyState === (this.DONE || 4)) { // IE 8 doesn't support DONE if (this.status === 200) { success(this.responseText, this.textStatus, this); @@ -789,8 +786,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { }; }); - describe("when making a request", function() { - beforeEach(function() { + describe("when making a request", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -798,24 +795,24 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { request = mockAjax.requests.mostRecent(); }); - it("should store URL and transport", function() { + it("should store URL and transport", () => { expect(request.url).toEqual("example.com/someApi"); }); - it("should queue the request", function() { + it("should queue the request", () => { expect(mockAjax.requests.count()).toEqual(1); }); - it("should allow access to the queued request", function() { + it("should allow access to the queued request", () => { expect(mockAjax.requests.first()).toEqual(request); }); - it("should allow access to the queued request via index", function() { + it("should allow access to the queued request via index", () => { expect(mockAjax.requests.at(0)).toEqual(request); }); - describe("and then another request", function() { - beforeEach(function() { + describe("and then another request", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -824,26 +821,26 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { anotherRequest = mockAjax.requests.mostRecent(); }); - it("should queue the next request", function() { + it("should queue the next request", () => { expect(mockAjax.requests.count()).toEqual(2); }); - it("should allow access to the other queued request", function() { + it("should allow access to the other queued request", () => { expect(mockAjax.requests.first()).toEqual(request); expect(mockAjax.requests.mostRecent()).toEqual(anotherRequest); }); }); - describe("mockAjax.requests.mostRecent()", function() { + describe("mockAjax.requests.mostRecent()", () => { - describe("when there is one request queued", function() { - it("should return the request", function() { + describe("when there is one request queued", () => { + it("should return the request", () => { expect(mockAjax.requests.mostRecent()).toEqual(request); }); }); - describe("when there is more than one request", function() { - beforeEach(function() { + describe("when there is more than one request", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -851,37 +848,37 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { anotherRequest = mockAjax.requests.mostRecent(); }); - it("should return the most recent request", function() { + it("should return the most recent request", () => { expect(mockAjax.requests.mostRecent()).toEqual(anotherRequest); }); }); - describe("when there are no requests", function() { - beforeEach(function() { + describe("when there are no requests", () => { + beforeEach(() => { mockAjax.requests.reset(); }); - it("should return null", function() { + it("should return null", () => { expect(mockAjax.requests.mostRecent()).toBeUndefined(); }); }); }); - describe("clearAjaxRequests()", function() { - beforeEach(function() { + describe("clearAjaxRequests()", () => { + beforeEach(() => { mockAjax.requests.reset(); }); - it("should remove all requests", function() { + it("should remove all requests", () => { expect(mockAjax.requests.count()).toEqual(0); expect(mockAjax.requests.mostRecent()).toBeUndefined(); }); }); }); - describe("when simulating a response with request.response", function() { - describe("and the response is Success", function() { - beforeEach(function() { + describe("when simulating a response with request.response", () => { + describe("and the response is Success", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -900,23 +897,23 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseType = response.responseType; }); - it("should call the success handler", function() { + it("should call the success handler", () => { expect(success).toHaveBeenCalled(); }); - it("should not call the failure handler", function() { + it("should not call the failure handler", () => { expect(error).not.toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); sharedAjaxResponseBehaviorForZepto_Success(sharedContext); }); - describe("and the response is Success, but with JSON", function() { - beforeEach(function() { + describe("and the response is Success, but with JSON", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -938,19 +935,19 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { response = success.calls.mostRecent().args[2]; }); - it("should call the success handler", function() { + it("should call the success handler", () => { expect(success).toHaveBeenCalled(); }); - it("should not call the failure handler", function() { + it("should not call the failure handler", () => { expect(error).not.toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); - it("should return a JavaScript object for XHR2 response", function() { + it("should return a JavaScript object for XHR2 response", () => { var responseText = sharedContext.responseText; expect(success.calls.mostRecent().args[0]).toEqual(responseText); @@ -961,8 +958,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedAjaxResponseBehaviorForZepto_Success(sharedContext); }); - describe("and the response is Success, and response is overriden", function() { - beforeEach(function() { + describe("and the response is Success, and response is overriden", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -984,7 +981,7 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { response = success.calls.mostRecent().args[2]; }); - it("should return the provided override for the XHR2 response", function() { + it("should return the provided override for the XHR2 response", () => { var responseText = sharedContext.responseText; expect(response.responseText).toEqual(responseText); @@ -994,8 +991,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedAjaxResponseBehaviorForZepto_Success(sharedContext); }); - describe("response with unique header names using an object", function() { - beforeEach(function() { + describe("response with unique header names using an object", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com"); @@ -1013,13 +1010,13 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { response = success.calls.mostRecent().args[2]; }); - it("getResponseHeader should return the each value", function() { + it("getResponseHeader should return the each value", () => { expect(response.getResponseHeader('X-Header1')).toBe('header 1 value'); expect(response.getResponseHeader('X-Header2')).toBe('header 2 value'); expect(response.getResponseHeader('X-Header3')).toBe('header 3 value'); }); - it("getAllResponseHeaders should return all values", function() { + it("getAllResponseHeaders should return all values", () => { expect(response.getAllResponseHeaders()).toBe([ "X-Header1: header 1 value", "X-Header2: header 2 value", @@ -1028,8 +1025,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { }); }); - describe("response with multiple headers of the same name using an array of objects", function() { - beforeEach(function() { + describe("response with multiple headers of the same name using an array of objects", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com"); @@ -1046,11 +1043,11 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { response = success.calls.mostRecent().args[2]; }); - it("getResponseHeader should return all values comma separated", function() { + it("getResponseHeader should return all values comma separated", () => { expect(response.getResponseHeader('X-Header')).toBe('header value 1, header value 2'); }); - it("getAllResponseHeaders should return all values", function() { + it("getAllResponseHeaders should return all values", () => { expect(response.getAllResponseHeaders()).toBe([ "X-Header: header value 1", "X-Header: header value 2" @@ -1058,8 +1055,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { }); }); - describe("the content type defaults to application/json", function() { - beforeEach(function() { + describe("the content type defaults to application/json", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -1078,23 +1075,23 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseText = response.responseText; }); - it("should call the success handler", function() { + it("should call the success handler", () => { expect(success).toHaveBeenCalled(); }); - it("should not call the failure handler", function() { + it("should not call the failure handler", () => { expect(error).not.toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); sharedAjaxResponseBehaviorForZepto_Success(sharedContext); }); - describe("and the status/response code is 0", function() { - beforeEach(function() { + describe("and the status/response code is 0", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -1113,15 +1110,15 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseType = response.responseType; }); - it("should call the success handler", function() { + it("should call the success handler", () => { expect(success).not.toHaveBeenCalled(); }); - it("should not call the failure handler", function() { + it("should not call the failure handler", () => { expect(error).toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); @@ -1129,8 +1126,8 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { }); }); - describe("and the response is error", function() { - beforeEach(function() { + describe("and the response is error", () => { + beforeEach(() => { client = new fakeGlobal.XMLHttpRequest(); client.onreadystatechange = onreadystatechange; client.open("GET", "example.com/someApi"); @@ -1138,7 +1135,7 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { client.send(); request = mockAjax.requests.mostRecent(); - response = { status: 500, statusText: "SERVER ERROR", contentType: "text/html", responseText: "(._){",responseType: "json"}; + response = { status: 500, statusText: "SERVER ERROR", contentType: "text/html", responseText: "(._){", responseType: "json"}; request.respondWith(response); sharedContext.responseCallback = error; @@ -1149,23 +1146,23 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseType = response.responseType; }); - it("should not call the success handler", function() { + it("should not call the success handler", () => { expect(success).not.toHaveBeenCalled(); }); - it("should call the failure handler", function() { + it("should call the failure handler", () => { expect(error).toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); sharedAjaxResponseBehaviorForZepto_Failure(sharedContext); }); - describe('when simulating a response with request.responseTimeout', function() { - beforeEach(function() { + describe('when simulating a response with request.responseTimeout', () => { + beforeEach(() => { jasmine.clock().install(); client = new fakeGlobal.XMLHttpRequest(); @@ -1186,19 +1183,19 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { sharedContext.responseType = response.responseType; }); - afterEach(function() { + afterEach(() => { jasmine.clock().uninstall(); }); - it("should not call the success handler", function() { + it("should not call the success handler", () => { expect(success).not.toHaveBeenCalled(); }); - it("should call the failure handler", function() { + it("should call the failure handler", () => { expect(error).toHaveBeenCalled(); }); - it("should call the complete handler", function() { + it("should call the complete handler", () => { expect(complete).toHaveBeenCalled(); }); }); @@ -1206,74 +1203,74 @@ describe("Jasmine Mock Ajax (for toplevel)", function() { function sharedAjaxResponseBehaviorForZepto_Success(context) { - describe("the success response", function() { + describe("the success response", () => { var xhr; - beforeEach(function() { + beforeEach(() => { xhr = context.responseCallback.calls.mostRecent().args[2]; }); - it("should have the expected status code", function() { + it("should have the expected status code", () => { expect(xhr.status).toEqual(context.status); }); - it("should have the expected content type", function() { + it("should have the expected content type", () => { expect(xhr.getResponseHeader('Content-Type')).toEqual(context.contentType); }); - it("should have the expected xhr2 response", function() { + it("should have the expected xhr2 response", () => { var expected = context.response || context.responseType === 'json' ? JSON.parse(context.responseText) : context.responseText; expect(xhr.response).toEqual(expected); }); - it("should have the expected response text", function() { + it("should have the expected response text", () => { expect(xhr.responseText).toEqual(context.responseText); }); - it("should have the expected status text", function() { + it("should have the expected status text", () => { expect(xhr.statusText).toEqual(context.statusText); }); }); } function sharedAjaxResponseBehaviorForZepto_Failure(context) { - describe("the failure response", function() { + describe("the failure response", () => { var xhr; - beforeEach(function() { + beforeEach(() => { xhr = context.responseCallback.calls.mostRecent().args[0]; }); - it("should have the expected status code", function() { + it("should have the expected status code", () => { expect(xhr.status).toEqual(context.status); }); - it("should have the expected content type", function() { + it("should have the expected content type", () => { expect(xhr.getResponseHeader('Content-Type')).toEqual(context.contentType); }); - it("should have the expected xhr2 response", function() { + it("should have the expected xhr2 response", () => { var expected = context.response || xhr.responseType === 'json' ? JSON.parse(xhr.responseText) : xhr.responseText; expect(xhr.response).toEqual(expected); }); - it("should have the expected response text", function() { + it("should have the expected response text", () => { expect(xhr.responseText).toEqual(context.responseText); }); - it("should have the expected status text", function() { + it("should have the expected status text", () => { expect(xhr.statusText).toEqual(context.statusText); }); }); } -describe('ParamParser', function() { - beforeEach(function() { +describe('ParamParser', () => { + beforeEach(() => { var Constructor = getJasmineRequireObj().AjaxParamParser(); expect(Constructor).toEqual(jasmine.any(Function)); this.parser = new Constructor(); }); - it('has a default parser', function() { - var parser = this.parser.findParser({ contentType: function() { } }), + it('has a default parser', () => { + var parser = this.parser.findParser({ contentType: () => { } }), parsed = parser.parse('3+stooges=shemp&3+stooges=larry%20%26%20moe%20%26%20curly&some%3Dthing=else+entirely'); expect(parsed).toEqual({ @@ -1282,7 +1279,7 @@ describe('ParamParser', function() { }); }); - it('should detect and parse json', function() { + it('should detect and parse json', () => { var data = { foo: 'bar', baz: ['q', 'u', 'u', 'x'], @@ -1292,13 +1289,13 @@ describe('ParamParser', function() { } } }, - parser = this.parser.findParser({ contentType: function() { return 'application/json'; } }), + parser = this.parser.findParser({ contentType: () => 'application/json' }), parsed = parser.parse(JSON.stringify(data)); expect(parsed).toEqual(data); }); - it('should parse json with further qualifiers on content-type', function() { + it('should parse json with further qualifiers on content-type', () => { var data = { foo: 'bar', baz: ['q', 'u', 'u', 'x'], @@ -1308,13 +1305,13 @@ describe('ParamParser', function() { } } }, - parser = this.parser.findParser({ contentType: function() { return 'application/json; charset=utf-8'; } }), + parser = this.parser.findParser({ contentType: () => 'application/json; charset=utf-8' }), parsed = parser.parse(JSON.stringify(data)); expect(parsed).toEqual(data); }); - it('should have custom parsers take precedence', function() { + it('should have custom parsers take precedence', () => { var custom = { test: jasmine.createSpy('test').and.returnValue(true), parse: jasmine.createSpy('parse').and.returnValue('parsedFormat') @@ -1322,7 +1319,7 @@ describe('ParamParser', function() { this.parser.add(custom); - var parser = this.parser.findParser({ contentType: function() { } }), + var parser = this.parser.findParser({ contentType: () => { } }), parsed = parser.parse('custom_format'); expect(parsed).toEqual('parsedFormat'); @@ -1330,7 +1327,7 @@ describe('ParamParser', function() { expect(custom.parse).toHaveBeenCalledWith('custom_format'); }); - it('should skip custom parsers that do not match', function() { + it('should skip custom parsers that do not match', () => { var custom = { test: jasmine.createSpy('test').and.returnValue(false), parse: jasmine.createSpy('parse').and.returnValue('parsedFormat') @@ -1338,7 +1335,7 @@ describe('ParamParser', function() { this.parser.add(custom); - var parser = this.parser.findParser({ contentType: function() { } }), + var parser = this.parser.findParser({ contentType: () => { } }), parsed = parser.parse('custom_format'); expect(parsed).toEqual({ custom_format: ['undefined'] }); @@ -1346,7 +1343,7 @@ describe('ParamParser', function() { expect(custom.parse).not.toHaveBeenCalled(); }); - it('removes custom parsers when reset', function() { + it('removes custom parsers when reset', () => { var custom = { test: jasmine.createSpy('test').and.returnValue(true), parse: jasmine.createSpy('parse').and.returnValue('parsedFormat') @@ -1354,7 +1351,7 @@ describe('ParamParser', function() { this.parser.add(custom); - var parser = this.parser.findParser({ contentType: function() { } }), + var parser = this.parser.findParser({ contentType: () => { } }), parsed = parser.parse('custom_format'); expect(parsed).toEqual('parsedFormat'); @@ -1364,7 +1361,7 @@ describe('ParamParser', function() { this.parser.reset(); - parser = this.parser.findParser({ contentType: function() { } }); + parser = this.parser.findParser({ contentType: () => { } }); parsed = parser.parse('custom_format'); expect(parsed).toEqual({ custom_format: ['undefined'] }); @@ -1373,14 +1370,14 @@ describe('ParamParser', function() { }); }); -describe('RequestStub', function() { - beforeEach(function() { +describe('RequestStub', () => { + beforeEach(() => { this.RequestStub = getJasmineRequireObj().AjaxRequestStub(); jasmine.addMatchers({ - toMatchRequest: function(a, b) { + toMatchRequest(a, b) { return { - compare: function(actual): jasmine.CustomMatcherResult { + compare(actual): jasmine.CustomMatcherResult { return { message: '', pass: actual.matches.apply(actual, Array.prototype.slice.call(arguments, 1)) @@ -1391,31 +1388,31 @@ describe('RequestStub', function() { }); }); - it('matches just by exact url', function() { + it('matches just by exact url', () => { var stub = new this.RequestStub('www.example.com/foo'); expect(stub)['toMatchRequest']('www.example.com/foo'); }); - it('does not match if the url differs', function() { + it('does not match if the url differs', () => { var stub = new this.RequestStub('www.example.com/foo'); expect(stub).not['toMatchRequest']('www.example.com/bar'); }); - it('matches unordered query params', function() { + it('matches unordered query params', () => { var stub = new this.RequestStub('www.example.com?foo=bar&baz=quux'); expect(stub)['toMatchRequest']('www.example.com?baz=quux&foo=bar'); }); - it('requires all specified query params to be there', function() { + it('requires all specified query params to be there', () => { var stub = new this.RequestStub('www.example.com?foo=bar&baz=quux'); expect(stub).not['toMatchRequest']('www.example.com?foo=bar'); }); - it('can match the url with a RegExp', function() { + it('can match the url with a RegExp', () => { var stub = new this.RequestStub(/ba[rz]/); expect(stub)['toMatchRequest']('bar'); @@ -1423,7 +1420,7 @@ describe('RequestStub', function() { expect(stub).not['toMatchRequest']('foo'); }); - it('requires the method to match if supplied', function() { + it('requires the method to match if supplied', () => { var stub = new this.RequestStub('www.example.com/foo', null, 'POST'); expect(stub).not['toMatchRequest']('www.example.com/foo'); @@ -1431,7 +1428,7 @@ describe('RequestStub', function() { expect(stub)['toMatchRequest']('www.example.com/foo', null, 'POST'); }); - it('requires the data submitted to match if supplied', function() { + it('requires the data submitted to match if supplied', () => { var stub = new this.RequestStub('/foo', 'foo=bar&baz=quux'); expect(stub)['toMatchRequest']('/foo', 'baz=quux&foo=bar'); @@ -1439,13 +1436,13 @@ describe('RequestStub', function() { }); }); -describe('RequestTracker', function() { - beforeEach(function() { +describe('RequestTracker', () => { + beforeEach(() => { var Constructor = getJasmineRequireObj().AjaxRequestTracker(); this.tracker = new Constructor(); }); - it('tracks the number of times ajax requests are made', function() { + it('tracks the number of times ajax requests are made', () => { expect(this.tracker.count()).toBe(0); this.tracker.track(); @@ -1453,29 +1450,29 @@ describe('RequestTracker', function() { expect(this.tracker.count()).toBe(1); }); - it('simplifies access to the last (most recent) request', function() { + it('simplifies access to the last (most recent) request', () => { this.tracker.track(); this.tracker.track('request'); expect(this.tracker.mostRecent()).toEqual('request'); }); - it('returns a useful falsy value when there is no last (most recent) request', function() { + it('returns a useful falsy value when there is no last (most recent) request', () => { expect(this.tracker.mostRecent()).toBeFalsy(); }); - it('simplifies access to the first (oldest) request', function() { + it('simplifies access to the first (oldest) request', () => { this.tracker.track('request'); this.tracker.track(); expect(this.tracker.first()).toEqual('request'); }); - it('returns a useful falsy value when there is no first (oldest) request', function() { + it('returns a useful falsy value when there is no first (oldest) request', () => { expect(this.tracker.first()).toBeFalsy(); }); - it('allows the requests list to be reset', function() { + it('allows the requests list to be reset', () => { this.tracker.track(); this.tracker.track(); @@ -1486,7 +1483,7 @@ describe('RequestTracker', function() { expect(this.tracker.count()).toBe(0); }); - it('allows retrieval of an arbitrary request by index', function() { + it('allows retrieval of an arbitrary request by index', () => { this.tracker.track('1'); this.tracker.track('2'); this.tracker.track('3'); @@ -1494,14 +1491,14 @@ describe('RequestTracker', function() { expect(this.tracker.at(1)).toEqual('2'); }); - it('allows retrieval of all requests that are for a given url', function() { + it('allows retrieval of all requests that are for a given url', () => { this.tracker.track({ url: 'foo' }); this.tracker.track({ url: 'bar' }); expect(this.tracker.filter('bar')).toEqual([{ url: 'bar' }]); }); - it('allows retrieval of all requests that match a given RegExp', function() { + it('allows retrieval of all requests that match a given RegExp', () => { this.tracker.track({ url: 'foo' }); this.tracker.track({ url: 'bar' }); this.tracker.track({ url: 'baz' }); @@ -1509,29 +1506,27 @@ describe('RequestTracker', function() { expect(this.tracker.filter(/ba[rz]/)).toEqual([{ url: 'bar' }, { url: 'baz' }]); }); - it('allows retrieval of all requests that match based on a function', function() { + it('allows retrieval of all requests that match based on a function', () => { this.tracker.track({ url: 'foo' }); this.tracker.track({ url: 'bar' }); this.tracker.track({ url: 'baz' }); - var func = function(request) { - return request.url === 'bar'; - }; + var func = request => request.url === 'bar'; expect(this.tracker.filter(func)).toEqual([{ url: 'bar' }]); }); - it('filters to nothing if no requests have been tracked', function() { + it('filters to nothing if no requests have been tracked', () => { expect(this.tracker.filter('foo')).toEqual([]); }); }); -describe('EventBus', function() { - beforeEach(function() { +describe('EventBus', () => { + beforeEach(() => { this.bus = getJasmineRequireObj().AjaxEventBus()(); }); - it('calls an event listener', function() { + it('calls an event listener', () => { var callback = jasmine.createSpy('callback'); this.bus.addEventListener('foo', callback); @@ -1540,7 +1535,7 @@ describe('EventBus', function() { expect(callback).toHaveBeenCalled(); }); - it('calls an event listener with additional arguments', function() { + it('calls an event listener with additional arguments', () => { var callback = jasmine.createSpy('callback'); this.bus.addEventListener('foo', callback); @@ -1549,7 +1544,7 @@ describe('EventBus', function() { expect(callback).toHaveBeenCalledWith('bar'); }); - it('only triggers callbacks for the specified event', function() { + it('only triggers callbacks for the specified event', () => { var fooCallback = jasmine.createSpy('foo'), barCallback = jasmine.createSpy('bar'); @@ -1562,7 +1557,7 @@ describe('EventBus', function() { expect(barCallback).not.toHaveBeenCalled(); }); - it('calls all the callbacks for the specified event', function() { + it('calls all the callbacks for the specified event', () => { var callback1 = jasmine.createSpy('callback'); var callback2 = jasmine.createSpy('otherCallback'); @@ -1575,14 +1570,14 @@ describe('EventBus', function() { expect(callback2).toHaveBeenCalled(); }); - it('works if there are no callbacks for the event', function() { + it('works if there are no callbacks for the event', () => { var bus = this.bus; - expect(function() { + expect(() => { bus.trigger('notActuallyThere'); }).not.toThrow(); }); - it('does not call listeners that have been removed', function() { + it('does not call listeners that have been removed', () => { var callback = jasmine.createSpy('callback'); this.bus.addEventListener('foo', callback); @@ -1592,7 +1587,7 @@ describe('EventBus', function() { expect(callback).not.toHaveBeenCalled(); }); - it('only removes the specified callback', function() { + it('only removes the specified callback', () => { var callback1 = jasmine.createSpy('callback'); var callback2 = jasmine.createSpy('otherCallback'); @@ -1607,14 +1602,14 @@ describe('EventBus', function() { }); }); -describe("Webmock style mocking", function() { +describe("Webmock style mocking", () => { var successSpy, errorSpy, response, fakeGlobal, mockAjax; var sendRequest = function(fakeGlobal, url?, method?) { url = url || "http://example.com/someApi"; method = method || 'GET'; var xhr = new fakeGlobal.XMLHttpRequest(); - xhr.onreadystatechange = function(args) { + xhr.onreadystatechange = args => { if (this.readyState === (this.DONE || 4)) { // IE 8 doesn't support DONE response = this; successSpy(); @@ -1625,7 +1620,7 @@ describe("Webmock style mocking", function() { xhr.send(); }; - beforeEach(function() { + beforeEach(() => { successSpy = jasmine.createSpy('success'); fakeGlobal = { XMLHttpRequest: jasmine.createSpy('realXMLHttpRequest') }; mockAjax = new MockAjax(fakeGlobal); @@ -1634,33 +1629,33 @@ describe("Webmock style mocking", function() { mockAjax.stubRequest("http://example.com/someApi").andReturn({ responseText: "hi!" }); }); - it("allows a url to be setup as a stub", function() { + it("allows a url to be setup as a stub", () => { sendRequest(fakeGlobal); expect(successSpy).toHaveBeenCalled(); }); - it("should allow you to clear all the ajax stubs", function() { + it("should allow you to clear all the ajax stubs", () => { mockAjax.stubs.reset(); sendRequest(fakeGlobal); expect(successSpy).not.toHaveBeenCalled(); }); - it("should set the contentType", function() { + it("should set the contentType", () => { sendRequest(fakeGlobal); expect(response.getResponseHeader('Content-Type')).toEqual('application/json'); }); - it("should set the responseText", function() { + it("should set the responseText", () => { sendRequest(fakeGlobal); expect(response.responseText).toEqual('hi!'); }); - it("should default the status to 200", function() { + it("should default the status to 200", () => { sendRequest(fakeGlobal); expect(response.status).toEqual(200); }); - it("should set the responseHeaders", function() { + it("should set the responseHeaders", () => { mockAjax.stubRequest("http://example.com/someApi").andReturn({ responseText: "hi!", responseHeaders: [{ name: "X-Custom", value: "header value" }] @@ -1669,37 +1664,37 @@ describe("Webmock style mocking", function() { expect(response.getResponseHeader('X-Custom')).toEqual('header value'); }); - describe("with another stub for the same url", function() { - beforeEach(function() { + describe("with another stub for the same url", () => { + beforeEach(() => { mockAjax.stubRequest("http://example.com/someApi").andReturn({ responseText: "no", status: 403 }); sendRequest(fakeGlobal); }); - it("should set the status", function() { + it("should set the status", () => { expect(response.status).toEqual(403); }); - it("should allow the latest stub to win", function() { + it("should allow the latest stub to win", () => { expect(response.responseText).toEqual('no'); }); }); }); -describe("withMock", function() { - var sendRequest = function(fakeGlobal) { +describe("withMock", () => { + var sendRequest = fakeGlobal => { var xhr = new fakeGlobal.XMLHttpRequest(); xhr.open("GET", "http://example.com/someApi"); xhr.send(); }; - it("installs the mock for passed in function, and uninstalls when complete", function() { + it("installs the mock for passed in function, and uninstalls when complete", () => { var xmlHttpRequest = jasmine.createSpyObj('XMLHttpRequest', ['open', 'send']), - xmlHttpRequestCtor = spyOn(window, 'XMLHttpRequest').and.returnValue(xmlHttpRequest), + xmlHttpRequestCtor = spyOn(window as any, 'XMLHttpRequest').and.returnValue(xmlHttpRequest), fakeGlobal = { XMLHttpRequest: xmlHttpRequestCtor }, mockAjax = new MockAjax(fakeGlobal); - mockAjax.withMock(function() { + mockAjax.withMock(() => { sendRequest(fakeGlobal); expect(xmlHttpRequest.open).not.toHaveBeenCalled(); }); @@ -1708,15 +1703,15 @@ describe("withMock", function() { expect(xmlHttpRequest.open).toHaveBeenCalled(); }); - it("properly uninstalls when the passed in function throws", function() { + it("properly uninstalls when the passed in function throws", () => { var xmlHttpRequest = jasmine.createSpyObj('XMLHttpRequest', ['open', 'send']), - xmlHttpRequestCtor = spyOn(window, 'XMLHttpRequest').and.returnValue(xmlHttpRequest), + xmlHttpRequestCtor = spyOn(window as any, 'XMLHttpRequest').and.returnValue(xmlHttpRequest), fakeGlobal = { XMLHttpRequest: xmlHttpRequestCtor }, mockAjax = new MockAjax(fakeGlobal); - expect(function() { - mockAjax.withMock(function() { - throw "error"; + expect(() => { + mockAjax.withMock(() => { + throw "error"; // tslint:disable-line:no-string-throw }); }).toThrow("error"); @@ -1725,8 +1720,8 @@ describe("withMock", function() { }); }); -describe("mockAjax", function() { - it("throws an error if installed multiple times", function() { +describe("mockAjax", () => { + it("throws an error if installed multiple times", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); @@ -1739,7 +1734,7 @@ describe("mockAjax", function() { expect(doubleInstall).toThrow(); }); - it("does not throw an error if uninstalled between installs", function() { + it("does not throw an error if uninstalled between installs", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); @@ -1753,7 +1748,7 @@ describe("mockAjax", function() { expect(sequentialInstalls).not.toThrow(); }); - it("does not replace XMLHttpRequest until it is installed", function() { + it("does not replace XMLHttpRequest until it is installed", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); @@ -1767,7 +1762,7 @@ describe("mockAjax", function() { expect(fakeXmlHttpRequest).not.toHaveBeenCalled(); }); - it("replaces the global XMLHttpRequest on uninstall", function() { + it("replaces the global XMLHttpRequest on uninstall", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); @@ -1779,14 +1774,14 @@ describe("mockAjax", function() { expect(fakeXmlHttpRequest).toHaveBeenCalledWith('foo'); }); - it("clears requests and stubs upon uninstall", function() { + it("clears requests and stubs upon uninstall", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); mockAjax.install(); - mockAjax.requests.track({ url: '/testurl' }); + mockAjax.requests.track( { url: '/testurl' }); mockAjax.stubRequest('/bobcat'); expect(mockAjax.requests.count()).toEqual(1); @@ -1798,25 +1793,25 @@ describe("mockAjax", function() { expect(mockAjax.stubs.findStub('/bobcat')).not.toBeDefined(); }); - it("allows the httpRequest to be retrieved", function() { + it("allows the httpRequest to be retrieved", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); mockAjax.install(); - var request = new (fakeGlobal.XMLHttpRequest)(); + var request = new ( fakeGlobal.XMLHttpRequest)(); expect(mockAjax.requests.count()).toBe(1); expect(mockAjax.requests.mostRecent()).toBe(request); }); - it("allows the httpRequests to be cleared", function() { + it("allows the httpRequests to be cleared", () => { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, mockAjax = new MockAjax(fakeGlobal); mockAjax.install(); - var request = new (fakeGlobal.XMLHttpRequest)(); + var request = new ( fakeGlobal.XMLHttpRequest)(); expect(mockAjax.requests.mostRecent()).toBe(request); mockAjax.requests.reset(); diff --git a/jasmine-ajax/tslint.json b/jasmine-ajax/tslint.json new file mode 100644 index 0000000000..2d6cd90f81 --- /dev/null +++ b/jasmine-ajax/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "unified-signatures": false + } +} \ No newline at end of file diff --git a/jasmine-data_driven_tests/index.d.ts b/jasmine-data_driven_tests/index.d.ts index 9874f61cb8..a2a7415093 100644 --- a/jasmine-data_driven_tests/index.d.ts +++ b/jasmine-data_driven_tests/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jasmine Data Driven Tests +// Type definitions for Jasmine Data Driven Tests 1.0 // Project: https://github.com/gburghardt/jasmine-data_driven_tests // Definitions by: Anthony MacKinnon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/jasmine-data_driven_tests/tslint.json b/jasmine-data_driven_tests/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/jasmine-data_driven_tests/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/jasmine-fixture/index.d.ts b/jasmine-fixture/index.d.ts index 77d9c740b1..8ea5956f1e 100644 --- a/jasmine-fixture/index.d.ts +++ b/jasmine-fixture/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jasmine-fixture 1.0.7 +// Type definitions for Jasmine-fixture 1.0 // Project: https://github.com/searls/jasmine-fixture // Definitions by: Craig Brett // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/jasmine-fixture/tslint.json b/jasmine-fixture/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/jasmine-fixture/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/jasminewd2/tslint.json b/jasminewd2/tslint.json index fb5d5e3b22..b7c74ace1d 100644 --- a/jasminewd2/tslint.json +++ b/jasminewd2/tslint.json @@ -2,6 +2,7 @@ "extends": "../tslint.json", "rules": { "callable-types": false, + "prefer-const": false, "void-return": false } } \ No newline at end of file diff --git a/json-stable-stringify/index.d.ts b/json-stable-stringify/index.d.ts index 79402210f3..3339d8f28e 100644 --- a/json-stable-stringify/index.d.ts +++ b/json-stable-stringify/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for json-stable-stringify 1.0.0 +// Type definitions for json-stable-stringify 1.0 // Project: https://github.com/substack/json-stable-stringify // Definitions by: Matt Frantz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -14,13 +14,9 @@ declare namespace stringify { value: any; } - interface Comparator { - (a: Element, b: Element): number; - } + type Comparator = (a: Element, b: Element) => number; - interface Replacer { - (key: string, value: any): any; - } + type Replacer = (key: string, value: any) => any; interface Options { cmp?: Comparator; diff --git a/json-stable-stringify/json-stable-stringify-tests.ts b/json-stable-stringify/json-stable-stringify-tests.ts index dfd2ced587..761d01d06a 100644 --- a/json-stable-stringify/json-stable-stringify-tests.ts +++ b/json-stable-stringify/json-stable-stringify-tests.ts @@ -1,6 +1,6 @@ import stringify = require('json-stable-stringify'); -var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; +var obj = { c: 8, b: [{z: 6, y: 5, x: 4}, 7], a: 3 }; { console.log(stringify(obj)); diff --git a/json-stable-stringify/tsconfig.json b/json-stable-stringify/tsconfig.json index 65e9568adf..9ce550b0e8 100644 --- a/json-stable-stringify/tsconfig.json +++ b/json-stable-stringify/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/json-stable-stringify/tslint.json b/json-stable-stringify/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/json-stable-stringify/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/jui-core/jui-core-tests.ts b/jui-core/jui-core-tests.ts index 3430d718e8..c0677926e6 100644 --- a/jui-core/jui-core-tests.ts +++ b/jui-core/jui-core-tests.ts @@ -4,10 +4,10 @@ jui.ready(["util.color"], (color: UtilColor) => { console.log(color.rgb("#ff0000")); }); -let _: UtilBase = jui.include("util.base"); +const _: UtilBase = jui.include("util.base"); -let str: string = "10"; +const str: string = "10"; console.log(_.typeCheck("string", str)); -let i: number = 10; +const i: number = 10; console.log(_.typeCheck("string", i)); diff --git a/jui-grid/jui-grid-tests.ts b/jui-grid/jui-grid-tests.ts index f8c256d098..1fb65c4b97 100644 --- a/jui-grid/jui-grid-tests.ts +++ b/jui-grid/jui-grid-tests.ts @@ -5,7 +5,7 @@ import {GridTable, GridXTable, GridRow} from "./index"; jui.ready([ "grid.table" ], (table: GridTable) => { - let table_1: GridTable = table("#table_1", { + const table_1: GridTable = table("#table_1", { data: [ { name: "Hong", age: "20", location: "Ilsan" }, { name: "Jung", age: "30", location: "Seoul" }, @@ -22,7 +22,7 @@ jui.ready([ "grid.table" ], (table: GridTable) => { }); jui.ready([ "grid.table" ], (table: GridTable) => { - let table_3: GridTable = table("#table_3", { + const table_3: GridTable = table("#table_3", { event: { expand(row: any, e: any): void { $(row.list[0]).html(""); @@ -40,13 +40,13 @@ jui.ready([ "grid.table" ], (table: GridTable) => { { name: "Park", age: "10", location: "Dangjin" } ]); - let table_3_submit: Function = (index: number) => { + const table_3_submit: Function = (index: number) => { var name = $(table_3.root).find(".name").val(), age = $(table_3.root).find(".age").val(), location = $(table_3.root).find(".location").val(); //noinspection TypeScriptValidateTypes - table_3.update(index, { name: name, age: age, location: location }); + table_3.update(index, { name, age, location }); table_3.hideExpand(); }; }); @@ -54,7 +54,7 @@ jui.ready([ "grid.table" ], (table: GridTable) => { jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { var page = 1; - let xtable_2: GridXTable = xtable("#xtable_2", { + const xtable_2: GridXTable = xtable("#xtable_2", { fields: [ "name", "age", "location" ], resize: true, sort: true, @@ -62,10 +62,10 @@ jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { bufferCount: 20 }); - let xtable_2_submit: Function = () => { + const xtable_2_submit: Function = () => { var result: any[] = []; - for(var i = 0; i < 1000000; i++) { + for (var i = 0; i < 1000000; i++) { result.push({ name: "Alvin" + i, age: Math.floor(Math.random() * 100) + 1, location: "LA" }); } @@ -74,7 +74,7 @@ jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { xtable_2.resize(); }; - let xtable_2_page: Function = (no: number) => { + const xtable_2_page: Function = (no: number) => { page += no; page = (page < 1) ? 1 : page; xtable_2.page(page); @@ -83,7 +83,7 @@ jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { - let xtable_4: GridXTable = xtable("#xtable_4", { + const xtable_4: GridXTable = xtable("#xtable_4", { fields: [ "name", "age", "location" ], data: [ { name: "Hong", age: "20", location: "Ilsan" }, @@ -96,16 +96,16 @@ jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { bufferCount: 20 }); - let xtable_4_submit: Function = (isMulti: boolean) => { - if(isMulti) { + const xtable_4_submit: Function = (isMulti: boolean) => { + if (isMulti) { xtable_4.filter((data: any) => { - if(data.age >= 30 || data.name.indexOf("ng") !== -1) { + if (data.age >= 30 || data.name.indexOf("ng") !== -1) { return true; } }); } else { xtable_4.filter((data: any) => { - if(data.location.indexOf("eo") !== -1) { + if (data.location.indexOf("eo") !== -1) { return true; } }); @@ -114,7 +114,7 @@ jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { }); jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { - let xtable_6: GridXTable = xtable("#xtable_6", { + const xtable_6: GridXTable = xtable("#xtable_6", { fields: [ "name", "age", "location" ], resize: true, sort: true, @@ -129,10 +129,10 @@ jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { } }); - let xtable_6_submit: Function = () => { + const xtable_6_submit: Function = () => { var result: any[] = []; - for(var i = 0; i < 1000000; i++) { + for (var i = 0; i < 1000000; i++) { result.push({ name: "Alvin" + i, age: Math.floor(Math.random() * 100) + 1, location: "LA" }); } @@ -141,7 +141,7 @@ jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { }); jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { - let xtable_8: GridXTable = xtable("#xtable_8", { + const xtable_8: GridXTable = xtable("#xtable_8", { fields: [ "url", "count" ], resize: true, buffer: "vscroll", @@ -153,7 +153,7 @@ jui.ready([ "grid.xtable" ], (xtable: GridXTable) => { }, event: { select(row: GridRow, e: any) { - if(row.type === "fold") { + if (row.type === "fold") { xtable_8.open(row.index); } else { xtable_8.fold(row.index); diff --git a/jui/jui-tests.ts b/jui/jui-tests.ts index 37247083e0..8a7a5d03f4 100644 --- a/jui/jui-tests.ts +++ b/jui/jui-tests.ts @@ -31,31 +31,31 @@ jui.ready([ property: UIProperty, select: UISelect ) => { - let a: UIAccordion = accordion("#test", { + const a: UIAccordion = accordion("#test", { multipanel: false }); console.log(a.activeIndex()); - let autoComplete: UIAutoComplete = autocomplete("#test", { + const autoComplete: UIAutoComplete = autocomplete("#test", { words : [] }); autoComplete.update([]); - let colorPicker: UIColorPicker = colorpicker("#test", { + const colorPicker: UIColorPicker = colorpicker("#test", { color: '#FFFF00' }); console.log(colorPicker.getColor('hex')); - let comboInstance: UICombo = combo("#test", { + const comboInstance: UICombo = combo("#test", { keydown: true }); console.log(comboInstance.getValue()); - let datePicker: UIDatePicker = datepicker("#test", { + const datePicker: UIDatePicker = datepicker("#test", { type: "daily" }); @@ -65,7 +65,7 @@ jui.ready([ datePicker.select(new Date()); - let dropdownInstance: UIDropdown = dropdown("#test", { + const dropdownInstance: UIDropdown = dropdown("#test", { width: 100 }); @@ -75,17 +75,17 @@ jui.ready([ dropdownInstance.reload(); - let m: UIModal = modal("#test", {autoHide: true}); + const m: UIModal = modal("#test", {autoHide: true}); m.show(); - let n: UINotify = notify("#test"); + const n: UINotify = notify("#test"); n.add({ title: "Caution message Send!!!", message: "Feb 15, 2013-12-24 02:24:19", color: 'warning' }, 1000); n.add({ title: "Caution message Send!!!", message: "Feb 15, 2013-12-24 02:24:19", color: 'success' }, 1000); n.reset(); - let p: UIPaging = paging("#test", { count: 100, pageCount : 5 }); + const p: UIPaging = paging("#test", { count: 100, pageCount : 5 }); p.first(); p.last(); @@ -93,13 +93,13 @@ jui.ready([ p.prev(); p.page(10); - let prog: UIProgress = progress("#test", { striped: true }); + const prog: UIProgress = progress("#test", { striped: true }); console.log(prog.getValue()); prog.setValue(100); - let propertyView: UIProperty = property("#test", { + const propertyView: UIProperty = property("#test", { items : [ { type : 'group', title : 'Sample Category'}, { type : 'text', title : 'Category Name', key: 'sample-category-name', value : 'test'} @@ -108,7 +108,7 @@ jui.ready([ console.log(propertyView.getValue()); - let selectInstance: UISelect = select("#test", { + const selectInstance: UISelect = select("#test", { items : [ { type : 'item', value : '0', text : 'first', html : '
test
', selected : true }, { type : 'divider' } diff --git a/keycloak-js/keycloak-js-tests.ts b/keycloak-js/keycloak-js-tests.ts index dc97d8da18..f0c78392b7 100644 --- a/keycloak-js/keycloak-js-tests.ts +++ b/keycloak-js/keycloak-js-tests.ts @@ -14,5 +14,5 @@ import { import * as KeycloakAuthorization from 'keycloak-js/keycloak-authz'; import { KeycloakAuthorizationPromise } from 'keycloak-js/keycloak-authz'; -let keycloak = Keycloak(); -let keycloakAuthz = KeycloakAuthorization(keycloak); +const keycloak = Keycloak(); +const keycloakAuthz = KeycloakAuthorization(keycloak); diff --git a/keygrip/keygrip-tests.ts b/keygrip/keygrip-tests.ts index afa66e04b1..d8447867b5 100644 --- a/keygrip/keygrip-tests.ts +++ b/keygrip/keygrip-tests.ts @@ -1,4 +1,4 @@ import * as Keygrip from 'keygrip'; -let keys = Keygrip(['123']); -let hash = keys.sign('abc'); +const keys = Keygrip(['123']); +const hash = keys.sign('abc'); diff --git a/koa-json-error/index.d.ts b/koa-json-error/index.d.ts index f1a54470ca..dfe23c26b0 100644 --- a/koa-json-error/index.d.ts +++ b/koa-json-error/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for koa-json-error v3.x +// Type definitions for koa-json-error 3.1 // Project: https://github.com/koajs/json-error // Definitions by: Mudkip // Definitions: https://github.com/mudkipme/DefinitelyTyped @@ -10,23 +10,23 @@ interface JSONErrorOptions { /** * Perform some task before calling `options.format`. Must be a function with the original err as its only argument. */ - preFormat?: { (err: Error): any }; + preFormat?: (err: Error) => any; /** * Runs inmediatly after `options.preFormat`. It receives two arguments: the original `err` and the output of `options.preFormat`. It should `return` a newly formatted error. */ - format?: { (err: Error, obj: any): any }; + format?: (err: Error, obj: any) => any; /** * Runs inmediatly after `options.format`. It receives two arguments: the original `err` and the output of `options.format`. It should `return` a newly formatted error. */ - postFormat?: { (err: Error, obj: any): any }; + postFormat?: (err: Error, obj: any) => any; } /** * Error handler for pure Koa 2.0.0+ JSON apps */ -declare function jsonError(options?: JSONErrorOptions) : Koa.Middleware; +declare function jsonError(options?: JSONErrorOptions): Koa.Middleware; declare namespace jsonError {} export = jsonError; diff --git a/koa-json-error/koa-json-error-tests.ts b/koa-json-error/koa-json-error-tests.ts index 07ac0fd129..77a13a1f64 100644 --- a/koa-json-error/koa-json-error-tests.ts +++ b/koa-json-error/koa-json-error-tests.ts @@ -1,9 +1,8 @@ import * as Koa from "koa"; import * as error from "koa-json-error"; -import { assign } from "lodash"; const app = new Koa(); app.use(error({ - preFormat: err => assign({}, err) + preFormat: err => Object.assign({}, err) })); \ No newline at end of file diff --git a/koa-json-error/tslint.json b/koa-json-error/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/koa-json-error/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/libpq/libpq-tests.ts b/libpq/libpq-tests.ts index 76e133f384..8a9aced3c3 100644 --- a/libpq/libpq-tests.ts +++ b/libpq/libpq-tests.ts @@ -5,7 +5,8 @@ import {Buffer} from 'buffer'; import * as assert from 'assert'; import * as async from 'async'; import * as PQ from 'libpq'; -import * as _ from 'lodash'; + +declare const _: { times(n: number, f: () => T): T[] }; declare const ok: Function; @@ -126,7 +127,7 @@ const consume = (pq: PQ, cb: Function) => { }; describe('async simple query', () => { - let pq: PQ; + const pq: PQ = null as any; it('dispatches simple query', (done: Function) => { assert(pq.setNonBlocking(true)); @@ -167,30 +168,30 @@ describe('async simple query', () => { consume(pq, () => { assert.ifError(pq.errorMessage()); - //first time there should be a result + // first time there should be a result assert(pq.getResult()); - //call 'getResult' until it returns false indicating - //there is no more input to consume + // call 'getResult' until it returns false indicating + // there is no more input to consume assert.strictEqual(pq.getResult(), false); - //since we only prepared a statement there should be - //0 tuples in the result + // since we only prepared a statement there should be + // 0 tuples in the result assert.equal(pq.ntuples(), 0); - //now execute the previously prepared statement + // now execute the previously prepared statement const success = pq.sendQueryPrepared(statementName, ['Brian']); assert(success, pq.errorMessage()); assert.strictEqual(pq.flush(), 0, 'Should have flushed parameters'); consume(pq, () => { assert.ifError(pq.errorMessage()); - //consume the result of the query execution + // consume the result of the query execution assert(pq.getResult()); assert.equal(pq.ntuples(), 1); assert.equal(pq.getvalue(0, 0), 'Brian'); - //call 'getResult' again to ensure we're finished + // call 'getResult' again to ensure we're finished assert.strictEqual(pq.getResult(), false); done(); }); diff --git a/lodash/tslint.json b/lodash/tslint.json index b896f97736..c84a64fedb 100644 --- a/lodash/tslint.json +++ b/lodash/tslint.json @@ -3,12 +3,14 @@ "rules": { "array-type": false, "callable-types": false, + "comment-format": false, "forbidden-types": false, "interface-name": false, "interface-over-type-literal": false, "no-empty-interface": false, "object-literal-key-quotes": false, "one-line": false, + "prefer-const": false, "semicolon": false, "triple-equals": false, "typedef-whitespace": false, diff --git a/mailgen/mailgen-tests.ts b/mailgen/mailgen-tests.ts index b7c8afd244..fd9429b770 100644 --- a/mailgen/mailgen-tests.ts +++ b/mailgen/mailgen-tests.ts @@ -8,7 +8,7 @@ const generator: Mailgen = new Mailgen({ } }); -let content: Mailgen.Content = { +const content: Mailgen.Content = { body: { name: "Hi", intro: "test", diff --git a/memoizee/memoizee-tests.ts b/memoizee/memoizee-tests.ts index b6272aa762..c78c240ac9 100644 --- a/memoizee/memoizee-tests.ts +++ b/memoizee/memoizee-tests.ts @@ -42,7 +42,7 @@ memoized(String({ toString() { return "12"; } }), Number({})); var afn = (a: number, b: number) => { return new Promise(res => { res(a + b); }); }; - let memoized = memoize(afn, { promise: true }); + const memoized = memoize(afn, { promise: true }); memoized(3, 7); memoized(3, 7); } diff --git a/merge-descriptors/index.d.ts b/merge-descriptors/index.d.ts index d9ccc201a1..82ded472b0 100644 --- a/merge-descriptors/index.d.ts +++ b/merge-descriptors/index.d.ts @@ -1,12 +1,7 @@ -// Type definitions for merge-descriptors +// Type definitions for merge-descriptors 1.0 // Project: https://github.com/component/merge-descriptors // Definitions by: Zhiyuan Wang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -declare function merge(destination: Object, source: Object): Object; - -declare function merge(destination: Object, source: Object, redefine: boolean): Object; - +declare function merge(destination: Object, source: Object, redefine?: boolean): Object; export = merge; diff --git a/merge-descriptors/merge-descriptors-tests.ts b/merge-descriptors/merge-descriptors-tests.ts index ca2e326f3b..df8f444fa9 100644 --- a/merge-descriptors/merge-descriptors-tests.ts +++ b/merge-descriptors/merge-descriptors-tests.ts @@ -6,7 +6,7 @@ function testAssertion(condition: boolean, errorMessage: string) { } } -interface IMergedObject { +interface MergedObject { InSrc?: string; name: string; InTarget: string; @@ -17,9 +17,9 @@ var src = { get name(): string { return 'from src name'; } -} +}; -var target: IMergedObject = { name: 'my target name', InTarget: 'target' }; +var target: MergedObject = { name: 'my target name', InTarget: 'target' }; var target2 = mixin(target, src, true); @@ -30,5 +30,5 @@ testAssertion(target.name === 'from src name', "[redfine]=true, source member wi testAssertion(target.InTarget === 'target', "overwrite do not affect members only in [destination]"); testAssertion(target['InSrc'] === 'src', "members from [source] must be copied to [destination]"); -var nameProperty:PropertyDescriptor = Object.getOwnPropertyDescriptor(target, "name"); +var nameProperty: PropertyDescriptor = Object.getOwnPropertyDescriptor(target, "name"); testAssertion(nameProperty.set === undefined, "member descriptor must be overwritten"); \ No newline at end of file diff --git a/merge-descriptors/tsconfig.json b/merge-descriptors/tsconfig.json index 50246ffb88..4e224b187b 100644 --- a/merge-descriptors/tsconfig.json +++ b/merge-descriptors/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/merge-descriptors/tslint.json b/merge-descriptors/tslint.json new file mode 100644 index 0000000000..0f47deabb4 --- /dev/null +++ b/merge-descriptors/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} \ No newline at end of file diff --git a/openfin/openfin-tests.ts b/openfin/openfin-tests.ts index 60b156ecf1..63a53f7cb5 100644 --- a/openfin/openfin-tests.ts +++ b/openfin/openfin-tests.ts @@ -82,7 +82,7 @@ console.log("failure:", err); }); // removeEventListener - let previousCallback = (event: fin.WindowEvent) => { }; + const previousCallback = (event: fin.WindowEvent) => { }; application.removeEventListener("closed", previousCallback, () => { console.log("The unregistration was successful"); }, err => { @@ -142,7 +142,7 @@ function test_external_application() { console.log(`Error Message: ${err.message} Error Stack: ${err.stack}`); }); // removeEventListener - let previousCallback = () => { }; + const previousCallback = () => { }; externalApp.removeEventListener('connected', previousCallback, () => { console.log('The unregistration was successful'); }, (reason, err) => { @@ -160,7 +160,7 @@ function test_inter_application_bus() { console.log("The application " + uuid + " has unsubscribed to " + topic); }); // removeSubscribeListener - let aRegisteredListener = (uuid: string, topic: string, name: string) => { }; + const aRegisteredListener = (uuid: string, topic: string, name: string) => { }; fin.desktop.InterApplicationBus.removeSubscribeListener(aRegisteredListener); // removeUnsubscribeListener fin.desktop.InterApplicationBus.removeUnsubscribeListener(aRegisteredListener); @@ -179,7 +179,7 @@ function test_inter_application_bus() { console.log("The application " + uuid + " sent this message: " + message); }); // unsubscribe - let aRegisteredMessageListener = (message: any, senderUuid: string) => { + const aRegisteredMessageListener = (message: any, senderUuid: string) => { console.log(message, senderUuid); }; fin.desktop.InterApplicationBus.unsubscribe("*", "a topic", aRegisteredMessageListener); @@ -197,9 +197,9 @@ function test_notification() { url: "http://localhost:5000/Account/Register", message: "Hello", onShow: () => { }, - //onClose: () => { }, + // onClose: () => { }, onDismiss: () => { }, - //onClick: () => { }, + // onClick: () => { }, onMessage: () => { }, onError: () => { } }); @@ -231,7 +231,7 @@ function test_system() { console.log("failure: " + err); }); // downloadAsset - let dirAppAsset = { + const dirAppAsset = { src: 'http://local:8000/dir.zip', alias: 'dirApp', version: '1.23.24', @@ -239,12 +239,12 @@ function test_system() { args: '' }; fin.desktop.System.downloadAsset(dirAppAsset, progress => { - let downloadedPercent = Math.floor((progress.downloadedBytes / progress.totalBytes) * 100); + const downloadedPercent = Math.floor((progress.downloadedBytes / progress.totalBytes) * 100); console.log(`Downloaded ${downloadedPercent}%`); }, p => { console.log(`Downlod complete, can be found on ${p.path}`); - //lets launch our application asset. - //launchDirApp(); + // lets launch our application asset. + // launchDirApp(); }, (reason, err) => { console.log(reason, err); }); @@ -350,9 +350,9 @@ function test_system() { }); // fin.desktop.System.launchExternalProcess({ - //Additionally note that the executable found in the zip file specified in appAssets - //will default to the one mentioned by appAssets.target - //If the the path below refers to a specific path it will override this default + // Additionally note that the executable found in the zip file specified in appAssets + // will default to the one mentioned by appAssets.target + // If the the path below refers to a specific path it will override this default alias: "myApp", listener(result) { console.log('the exit code', result.exitCode); @@ -428,7 +428,7 @@ function test_system() { }, result => { console.log("Result UUID is " + result.uuid); - //release it. + // release it. fin.desktop.System.releaseExternalProcess(result.uuid, () => { console.log("Process has been unmapped!"); }, reason => { @@ -436,7 +436,7 @@ function test_system() { }); }); // removeEventListener - let aRegisteredListener = (event: fin.SystemBaseEvent) => { }; + const aRegisteredListener = (event: fin.SystemBaseEvent) => { }; fin.desktop.System.removeEventListener("monitor-info-changed", aRegisteredListener, () => { console.log("successful"); }, err => { @@ -654,7 +654,7 @@ function test_window() { }, () => { // When finWindow moves or is moved, secondWindow moves by the same amount secondWindow.joinGroup(finWindow, () => { - //once we are in the group, lets leave it. + // once we are in the group, lets leave it. secondWindow.leaveGroup(); }); }); @@ -662,22 +662,22 @@ function test_window() { finWindow.maximize(); // mergeGroups { - let finWindowOne = new fin.desktop.Window({ + const finWindowOne = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowOne", autoShow: true }); - let finWindowTwo = new fin.desktop.Window({ + const finWindowTwo = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowTwo", autoShow: true }); - let finWindowThree = new fin.desktop.Window({ + const finWindowThree = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowThree", autoShow: true }); - let finWindowFour = new fin.desktop.Window({ + const finWindowFour = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowFour", autoShow: true @@ -696,7 +696,7 @@ function test_window() { // moveTo finWindow.moveTo(100, 200); // removeEventListener - let aRegisteredListener = (event: fin.WindowBaseEvent) => { }; + const aRegisteredListener = (event: fin.WindowBaseEvent) => { }; finWindow.removeEventListener("bounds-changed", aRegisteredListener); // resizeBy finWindow.resizeBy(10, 10, "top-right"); diff --git a/openfin/v15/openfin-tests.ts b/openfin/v15/openfin-tests.ts index 7aa2930089..69b024ce90 100644 --- a/openfin/v15/openfin-tests.ts +++ b/openfin/v15/openfin-tests.ts @@ -13,10 +13,10 @@ function test_application() { defaultLeft: 300, autoShow: true } - }, function (successObj) { + }, successObj => { console.log("Application successfully created, HTTP response code:", successObj); application.run(); - }, function (error) { + }, error => { console.log("Error creating application:", error); }); // getCurrent @@ -26,84 +26,84 @@ function test_application() { // getWindow application.getWindow(); // addEventListener - application.addEventListener("closed", function (event) { + application.addEventListener("closed", event => { console.log("The application has closed"); - }, function () { + }, () => { console.log("The registration was successful"); - }, function (reason) { + }, reason => { console.log("failure: " + reason); }); // close application.close(); // getChildWindows - application.getChildWindows(function (children) { - children.forEach(function (childWindow) { + application.getChildWindows(children => { + children.forEach(childWindow => { console.log("Showing child: " + childWindow.name); childWindow.show(); }); }); // getGroups - application.getGroups(function (allGroups) { + application.getGroups(allGroups => { console.log("There are a total of " + allGroups.length + " groups."); var groupCounter = 1; - allGroups.forEach(function (windowGroup) { + allGroups.forEach(windowGroup => { console.log("Group " + groupCounter + " contains " + windowGroup.length + " windows."); ++groupCounter; }); }); // getManifest - application.getManifest(function (manifest) { + application.getManifest(manifest => { console.log("Application manifest:"); console.log(manifest); }); // getParentUuid - application.getParentUuid(function (parentUuid) { + application.getParentUuid(parentUuid => { console.log("UUID of parent application:"); console.log(parentUuid); }); // getShortcuts - application.getShortcuts(function (config) { + application.getShortcuts(config => { console.log("Desktop shortcut is enabled: ", config.desktop); console.log("Start Menu shortcut is enabled: ", config.startMenu); console.log("System Startup shortcut is enabled: ", config.systemStartup); }); // isRunning - application.isRunning(function (running) { + application.isRunning(running => { console.log("the application is", running ? "running" : "not running"); }); // registerCustomData application.registerCustomData({ someData: "this is custom" - }, function () { + }, () => { console.log("You will not read this."); - }, function (err) { + }, err => { console.log("failure:", err); }); // removeEventListener - let previousCallback = function (event: fin.WindowEvent) { }; - application.removeEventListener("closed", previousCallback, function () { + const previousCallback = (event: fin.WindowEvent) => { }; + application.removeEventListener("closed", previousCallback, () => { console.log("The unregistration was successful"); - }, function (err) { + }, err => { console.log("failure:", err); }); // removeTrayIcon - application.removeTrayIcon(function () { + application.removeTrayIcon(() => { console.log("Removed the tray icon."); - }, function (err) { + }, err => { console.log("failure:", err); }); // restart - application.restart(function () { + application.restart(() => { console.log("You will not read this."); - }, function (err) { + }, err => { console.log("failure:", err); }); // schedule restart - application.scheduleRestart(function () { + application.scheduleRestart(() => { console.log("You will not read this."); - }, function (err) { + }, err => { console.log("failure:", err); }); // setShortcuts @@ -111,19 +111,19 @@ function test_application() { desktop: true, startMenu: false, systemStartup: true - }, function () { + }, () => { console.log("Successfully set new shortcut states"); - }, function (error) { + }, error => { console.log("Failed to set new shortcut states. Error: ", error); }); // setTrayIcon - application.setTrayIcon("https://developer.openf.in/download/openfin.png", function (clickInfo) { + application.setTrayIcon("https://developer.openf.in/download/openfin.png", clickInfo => { console.log("The mouse has clicked at (" + clickInfo.x + "," + clickInfo.y + ")"); }); // terminate application.terminate(); // wait - application.addEventListener("not-responding", function () { + application.addEventListener("not-responding", () => { console.log("waiting for hung application"); application.wait(); }); @@ -142,7 +142,7 @@ function test_external_application() { console.log(`Error Message: ${err.message} Error Stack: ${err.stack}`); }); // removeEventListener - let previousCallback = function () { }; + const previousCallback = () => { }; externalApp.removeEventListener('connected', previousCallback, () => { console.log('The unregistration was successful'); }, (reason, err) => { @@ -152,15 +152,15 @@ function test_external_application() { function test_inter_application_bus() { // addSubscribeListener - fin.desktop.InterApplicationBus.addSubscribeListener(function (uuid, topic, name) { + fin.desktop.InterApplicationBus.addSubscribeListener((uuid, topic, name) => { console.log("The application " + uuid + " has subscribed to " + topic); }); // addUnsubscribeListener - fin.desktop.InterApplicationBus.addUnsubscribeListener(function (uuid, topic, name) { + fin.desktop.InterApplicationBus.addUnsubscribeListener((uuid, topic, name) => { console.log("The application " + uuid + " has unsubscribed to " + topic); }); // removeSubscribeListener - let aRegisteredListener = function (uuid: string, topic: string, name: string) { }; + const aRegisteredListener = (uuid: string, topic: string, name: string) => { }; fin.desktop.InterApplicationBus.removeSubscribeListener(aRegisteredListener); // removeUnsubscribeListener fin.desktop.InterApplicationBus.removeUnsubscribeListener(aRegisteredListener); @@ -175,11 +175,11 @@ function test_inter_application_bus() { field2: "value2" }); // subscribe - fin.desktop.InterApplicationBus.subscribe("*", "a topic", function (message, uuid, name) { + fin.desktop.InterApplicationBus.subscribe("*", "a topic", (message, uuid, name) => { console.log("The application " + uuid + " sent this message: " + message); }); // unsubscribe - let aRegisteredMessageListener = function (message: any, senderUuid: string) { + const aRegisteredMessageListener = (message: any, senderUuid: string) => { console.log(message, senderUuid); }; fin.desktop.InterApplicationBus.unsubscribe("*", "a topic", aRegisteredMessageListener); @@ -197,9 +197,9 @@ function test_notification() { url: "http://localhost:5000/Account/Register", message: "Hello", onShow: () => { }, - //onClose: () => { }, + // onClose: () => { }, onDismiss: () => { }, - //onClick: () => { }, + // onClick: () => { }, onMessage: () => { }, onError: () => { } }); @@ -209,11 +209,11 @@ function test_notification() { function test_system() { // addEventListener - fin.desktop.System.addEventListener('monitor-info-changed', function (event) { + fin.desktop.System.addEventListener('monitor-info-changed', event => { console.log("The monitor information has changed to: ", event); - }, function () { + }, () => { console.log("The registration was successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // clearCache @@ -225,38 +225,38 @@ function test_system() { userData: true }); // deleteCacheOnExit - fin.desktop.System.deleteCacheOnExit(function () { + fin.desktop.System.deleteCacheOnExit(() => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // downloadAsset - let dirAppAsset = { - 'src': 'http://local:8000/dir.zip', - 'alias': 'dirApp', - 'version': '1.23.24', - 'target': 'dir.bat', - 'args': '' + const dirAppAsset = { + src: 'http://local:8000/dir.zip', + alias: 'dirApp', + version: '1.23.24', + target: 'dir.bat', + args: '' }; fin.desktop.System.downloadAsset(dirAppAsset, progress => { - let downloadedPercent = Math.floor((progress.downloadedBytes / progress.totalBytes) * 100); + const downloadedPercent = Math.floor((progress.downloadedBytes / progress.totalBytes) * 100); console.log(`Downloaded ${downloadedPercent}%`); }, p => { console.log(`Downlod complete, can be found on ${p.path}`); - //lets launch our application asset. - //launchDirApp(); + // lets launch our application asset. + // launchDirApp(); }, (reason, err) => { console.log(reason, err); }); // exit - fin.desktop.System.exit(function () { + fin.desktop.System.exit(() => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // getAllApplications - fin.desktop.System.getAllApplications(function (applicationInfoList) { - applicationInfoList.forEach(function (applicationInfo) { + fin.desktop.System.getAllApplications(applicationInfoList => { + applicationInfoList.forEach(applicationInfo => { console.log("Showing information for application with uuid: " + applicationInfo.uuid); console.log("isRunning: ", applicationInfo.isRunning); @@ -269,32 +269,32 @@ function test_system() { }); }); // getAllWindows - fin.desktop.System.getAllWindows(function (windowInfoList) { - windowInfoList.forEach(function (windowInfo) { + fin.desktop.System.getAllWindows(windowInfoList => { + windowInfoList.forEach(windowInfo => { console.log("Showing information for application with uuid: ", windowInfo.uuid); console.log("Main window: ", windowInfo.mainWindow); console.log("Child windows: ", windowInfo.childWindows); }); }); // getCommandLineArguments - fin.desktop.System.getCommandLineArguments(function (args) { + fin.desktop.System.getCommandLineArguments(args => { console.log("The command line arguments are " + args); }); // getDeviceId - fin.desktop.System.getDeviceId(function (id) { + fin.desktop.System.getDeviceId(id => { console.log("The id of the device is: " + id); }); // getEnvironmentVariable - fin.desktop.System.getEnvironmentVariable("APPDATA", function (variable) { + fin.desktop.System.getEnvironmentVariable("APPDATA", variable => { console.log("this is the APPDATA value", variable); }); // getLog - fin.desktop.System.getLog('debug-2015-01-08-22-27-53.log', function (log) { + fin.desktop.System.getLog('debug-2015-01-08-22-27-53.log', log => { console.log(log); }); // getLogList - fin.desktop.System.getLogList(function (logList) { - logList.forEach(function (logInfo) { + fin.desktop.System.getLogList(logList => { + logList.forEach(logInfo => { console.log("The filename of the log is " + logInfo.name + ", the size is " + logInfo.size + ", and the date of creation is " + @@ -302,70 +302,70 @@ function test_system() { }); }); // getMonitorInfo - fin.desktop.System.getMonitorInfo(function (monitorInfo) { + fin.desktop.System.getMonitorInfo(monitorInfo => { console.log("This object contains information about all monitors: ", monitorInfo); }); // getMousePosition - fin.desktop.System.getMousePosition(function (mousePosition) { + fin.desktop.System.getMousePosition(mousePosition => { console.log("The mouse is located at left: " + mousePosition.left + ", top: " + mousePosition.top); }); // getProcessList - fin.desktop.System.getProcessList(function (list) { - list.forEach(function (process) { + fin.desktop.System.getProcessList(list => { + list.forEach(process => { console.log("UUID: " + process.uuid + ", Application Name: " + process.name); }); }); // getProxySettings - fin.desktop.System.getProxySettings(function (proxy) { + fin.desktop.System.getProxySettings(proxy => { console.log(proxy); }); // getRvmInfo - fin.desktop.System.getRvmInfo(function (rvmInfoObject) { + fin.desktop.System.getRvmInfo(rvmInfoObject => { console.log("RVM version:", rvmInfoObject.version); console.log("RVM has been running since:", rvmInfoObject["start-time"]); - }, function (err) { + }, err => { console.log("Failed to get rvm info, error message:", err); }); // getVersion - fin.desktop.System.getVersion(function (version) { + fin.desktop.System.getVersion(version => { console.log("The version is " + version); }); // launchExternalProcess fin.desktop.System.launchExternalProcess({ path: "notepad", arguments: "", - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log('Success:', payload.uuid); - }, function (error) { + }, error => { console.log('Error:', error); }); // fin.desktop.System.launchExternalProcess({ - //Additionally note that the executable found in the zip file specified in appAssets - //will default to the one mentioned by appAssets.target - //If the the path below refers to a specific path it will override this default + // Additionally note that the executable found in the zip file specified in appAssets + // will default to the one mentioned by appAssets.target + // If the the path below refers to a specific path it will override this default alias: "myApp", - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log('Success:', payload.uuid); - }, function (error) { + }, error => { console.log('Error:', error); }); // fin.desktop.System.launchExternalProcess({ alias: "myApp", arguments: "e f g", - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log('Success:', payload.uuid); - }, function (error) { + }, error => { console.log('Error:', error); }); // @@ -377,94 +377,94 @@ function test_system() { subject: 'O=OpenFin INC., L=New York, S=NY, C=US', thumbprint: '‎3c a5 28 19 83 05 fe 69 88 e6 8f 4b 3a af c5 c5 1b 07 80 5b' }, - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log('Success:', payload.uuid); - }, function (error) { + }, error => { console.log('Error:', error); }); // log - fin.desktop.System.log("info", "An example log message", function () { + fin.desktop.System.log("info", "An example log message", () => { console.log("message successfully logged"); - }, function (err) { + }, err => { console.log(err); }); // monitorExternalProcess fin.desktop.System.monitorExternalProcess({ pid: 2508, - listener: function (result) { + listener(result) { console.log('the exit code', result.exitCode); } - }, function (payload) { + }, payload => { console.log("The process is now being monitored: ", payload.uuid); - }, function (error) { + }, error => { console.log("Error:", error); }); // openUrlWithBrowser - fin.desktop.System.openUrlWithBrowser("https://developer.openf.in/", function () { + fin.desktop.System.openUrlWithBrowser("https://developer.openf.in/", () => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // registerExternalConnection - fin.desktop.System.registerExternalConnection("remote-connection-uuid", function () { - console.log(arguments); + fin.desktop.System.registerExternalConnection("remote-connection-uuid", (...args: any[]) => { + console.log(args); }); // releaseExternalProcess fin.desktop.System.launchExternalProcess({ path: "notepad", arguments: "", - listener: function (result) { + listener(result) { console.log("The exit code", result.exitCode); } - }, function (result) { + }, result => { console.log("Result UUID is " + result.uuid); - //release it. - fin.desktop.System.releaseExternalProcess(result.uuid, function () { + // release it. + fin.desktop.System.releaseExternalProcess(result.uuid, () => { console.log("Process has been unmapped!"); - }, function (reason) { + }, reason => { console.log("failure: " + reason); }); }); // removeEventListener - let aRegisteredListener = (event: fin.SystemBaseEvent) => { }; - fin.desktop.System.removeEventListener("monitor-info-changed", aRegisteredListener, function () { + const aRegisteredListener = (event: fin.SystemBaseEvent) => { }; + fin.desktop.System.removeEventListener("monitor-info-changed", aRegisteredListener, () => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); // showDeveloperTools - fin.desktop.System.showDeveloperTools("uuid", "name", function () { + fin.desktop.System.showDeveloperTools("uuid", "name", () => { console.log("successful"); - }, function (err) { + }, err => { console.log("failure: " + err); }); - // terminateExternalProcess + // terminateExternalProcess fin.desktop.System.launchExternalProcess({ // notepad is in the system’s PATH path: "notepad", arguments: "", - listener: function (result) { + listener(result) { console.log("The exit code", result.exitCode); } - }, function (result) { + }, result => { console.log("Result UUID is " + result.uuid); // Attempt to close the process. Terminate after 4 seconds if it // has not done so. - fin.desktop.System.terminateExternalProcess(result.uuid, 4000, function (info) { + fin.desktop.System.terminateExternalProcess(result.uuid, 4000, info => { console.log("Termination result " + info.result); - }, function (reason) { + }, reason => { console.log("failure: " + reason); }); }); // updateProxySettings - fin.desktop.System.updateProxySettings("type", "proxyAddress", 8080, function () { + fin.desktop.System.updateProxySettings("type", "proxyAddress", 8080, () => { console.log('success'); - }, function (err) { + }, err => { console.log(err); }); } @@ -537,10 +537,10 @@ function test_window() { frame: false, resizable: false, state: "normal" - }, function () { + }, () => { var _win = finWindow.getNativeWindow(); - _win.addEventListener("DOMContentLoaded", function () { finWindow.show(); }); - }, function (error) { + _win.addEventListener("DOMContentLoaded", () => { finWindow.show(); }); + }, error => { console.log("Error creating window:", error); }); // getCurrent @@ -557,11 +557,11 @@ function test_window() { // wrap finWindow = fin.desktop.Window.wrap("uuid", "name"); // addEventListener - finWindow.addEventListener("bounds-changed", function (event) { + finWindow.addEventListener("bounds-changed", event => { console.log("The window has been moved or resized"); - }, function () { + }, () => { console.log("The registration was successful"); - }, function (reason) { + }, reason => { console.log("failure:" + reason); }); // animate @@ -577,7 +577,7 @@ function test_window() { } }, { interrupt: false - }, function (evt) { + }, evt => { // Callback will only fire after both "opacity" and "position" have finished animating. }); // authenticate @@ -601,34 +601,34 @@ function test_window() { // focus finWindow.focus(); // getBounds - finWindow.getBounds(function (bounds) { + finWindow.getBounds(bounds => { console.log("top: " + bounds.top + "left: " + bounds.left + "height: " + bounds.height + "width: " + bounds.width); }); // getOptions - finWindow.getOptions(function (options) { + finWindow.getOptions(options => { console.log(options); }); // getSnapshot - finWindow.getSnapshot(function (base64Snapshot) { + finWindow.getSnapshot(base64Snapshot => { console.log("data:image/png;base64," + base64Snapshot); }); // getState - finWindow.getState(function (state) { + finWindow.getState(state => { console.log("state: " + state); }); // getZoomLevel - finWindow.getZoomLevel(function (level) { + finWindow.getZoomLevel(level => { console.log("zoom level: " + level); - }, function (error) { + }, error => { console.log('error:', error); }); // hide finWindow.hide(); // isShowing - finWindow.isShowing(function (showing) { + finWindow.isShowing(showing => { console.log("the window is " + (showing ? "showing" : "hidden")); }); // joinGroup @@ -636,7 +636,7 @@ function test_window() { url: "http://www.openfin.co", name: "secondWindow", autoShow: true - }, function () { + }, () => { // When mainWindow moves or is moved, secondWindow moves by the same amount secondWindow.joinGroup(finWindow); }); @@ -645,10 +645,10 @@ function test_window() { url: "http://www.openfin.co", name: "secondWindow", autoShow: true - }, function () { + }, () => { // When finWindow moves or is moved, secondWindow moves by the same amount - secondWindow.joinGroup(finWindow, function () { - //once we are in the group, lets leave it. + secondWindow.joinGroup(finWindow, () => { + // once we are in the group, lets leave it. secondWindow.leaveGroup(); }); }); @@ -656,22 +656,22 @@ function test_window() { finWindow.maximize(); // mergeGroups { - let finWindowOne = new fin.desktop.Window({ + const finWindowOne = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowOne", autoShow: true }); - let finWindowTwo = new fin.desktop.Window({ + const finWindowTwo = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowTwo", autoShow: true }); - let finWindowThree = new fin.desktop.Window({ + const finWindowThree = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowThree", autoShow: true }); - let finWindowFour = new fin.desktop.Window({ + const finWindowFour = new fin.desktop.Window({ url: "http://www.openfin.co", name: "finWindowFour", autoShow: true @@ -690,7 +690,7 @@ function test_window() { // moveTo finWindow.moveTo(100, 200); // removeEventListener - let aRegisteredListener = (event: fin.WindowBaseEvent) => { }; + const aRegisteredListener = (event: fin.WindowBaseEvent) => { }; finWindow.removeEventListener("bounds-changed", aRegisteredListener); // resizeBy finWindow.resizeBy(10, 10, "top-right"); diff --git a/path-is-absolute/path-is-absolute-tests.ts b/path-is-absolute/path-is-absolute-tests.ts index fe7d177cc2..6948e290fa 100644 --- a/path-is-absolute/path-is-absolute-tests.ts +++ b/path-is-absolute/path-is-absolute-tests.ts @@ -2,22 +2,22 @@ import pathIsAbsolute = require('path-is-absolute'); // Running on Linux pathIsAbsolute('/home/foo'); -//=> true +// => true pathIsAbsolute('C:/Users/foo'); -//=> false +// => false // Running on Windows pathIsAbsolute('C:/Users/foo'); -//=> true +// => true pathIsAbsolute('/home/foo'); -//=> false +// => false // Running on any OS pathIsAbsolute.posix('/home/foo'); -//=> true +// => true pathIsAbsolute.posix('C:/Users/foo'); -//=> false +// => false pathIsAbsolute.win32('C:/Users/foo'); -//=> true +// => true pathIsAbsolute.win32('/home/foo'); -//=> false \ No newline at end of file +// => false \ No newline at end of file diff --git a/pem/pem-tests.ts b/pem/pem-tests.ts index 86e00b34bf..689dc42ad9 100644 --- a/pem/pem-tests.ts +++ b/pem/pem-tests.ts @@ -137,7 +137,7 @@ const tests = { 'Create CSR with own encrypted key': (test: any) => { var password = 'my:secure! "password\'s\nawesome'; - pem.createPrivateKey(2048, { cipher: 'des3', password: password }, (error: any, data: any) => { + pem.createPrivateKey(2048, { cipher: 'des3', password }, (error: any, data: any) => { var key = (data && data.key || '').toString(); pem.createCSR({ diff --git a/pixi.js/index.d.ts b/pixi.js/index.d.ts index 54a49de471..bacdfd23aa 100644 --- a/pixi.js/index.d.ts +++ b/pixi.js/index.d.ts @@ -2604,7 +2604,7 @@ export namespace utils { export var TextureCache: any; export var BaseTextureCache: any; - //https://github.com/kaimallea/isMobile + // https://github.com/kaimallea/isMobile export namespace isMobile { export var apple: { phone: boolean; diff --git a/pixi.js/pixi.js-tests.ts b/pixi.js/pixi.js-tests.ts index 6b416319b1..7ed32a29df 100644 --- a/pixi.js/pixi.js-tests.ts +++ b/pixi.js/pixi.js-tests.ts @@ -31,7 +31,7 @@ namespace basics { this.bunny.position.x = 200; this.bunny.position.y = 150; - //add it to the stage + // add it to the stage this.stage.addChild(this.bunny); this.animate(); @@ -76,10 +76,10 @@ namespace basics { this.sprite.on('mousedown', this.onDown, this); this.sprite.on('touchstart', this.onDown, this); - //add it to the stage + // add it to the stage this.stage.addChild(this.sprite); - //start animatng + // start animatng this.animate(); } @@ -414,7 +414,7 @@ namespace basics { this.movie.rotation += 0.01; - //render the stage container + // render the stage container this.renderer.render(this.stage); requestAnimationFrame(this.animate); @@ -537,7 +537,7 @@ namespace basics { this.graphics.y = this.strip.y; this.stage.addChild(this.graphics); - //start animating + // start animating this.animate(); } @@ -546,13 +546,13 @@ namespace basics { this.count += 0.1; - //make the snake + // make the snake for (var i = 0; i < this.points.length; i++) { this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; this.points[i].x = i * this.ropeLength + Math.cos((i * 0.3) + this.count) * 20; } - //render the stage + // render the stage this.renderer.render(this.stage); this.renderPoints(); @@ -604,7 +604,7 @@ namespace basics { // create the root of the scene graph this.stage = new PIXI.Container(); - //create a texture from an image path + // create a texture from an image path this.texture = PIXI.Texture.fromImage('../../_assets/p2.jpeg'); /* create a tiling sprite ... @@ -661,10 +661,10 @@ namespace basics { // create the root of the scene graph this.stage = new PIXI.Container(); - //create a video texture from a path + // create a video texture from a path this.texture = PIXI.Texture.fromVideo('../../_assets/testVideo.mp4'); - //create a new sprite using the video texture (yes it's that easy) + // create a new sprite using the video texture (yes it's that easy) this.videoSprite = new PIXI.Sprite(this.texture); this.videoSprite.width = this.renderer.width; this.videoSprite.height = this.renderer.height; @@ -678,7 +678,7 @@ namespace basics { private animate = (): void => { - //render the stage + // render the stage this.renderer.render(this.stage); requestAnimationFrame(this.animate); @@ -1096,11 +1096,11 @@ namespace demos { this.alienContainer.cacheAsBitmap = !this.alienContainer.cacheAsBitmap; - //feel free to play with what's below - //var sprite = new PIXI.Sprite(this.alienContainer.generateTexture()); - //this.stage.addChild(sprite); - //sprite.position.x = Math.random() * 800; - //sprite.position.y = Math.random() * 600; + // feel free to play with what's below + // var sprite = new PIXI.Sprite(this.alienContainer.generateTexture()); + // this.stage.addChild(sprite); + // sprite.position.x = Math.random() * 800; + // sprite.position.y = Math.random() * 600; } @@ -1168,7 +1168,7 @@ namespace demos { export class DraggableBunny extends PIXI.Sprite { - //todo I dont know what event.data is at this time + // todo I dont know what event.data is at this time private data: any; private dragging: boolean; @@ -1218,7 +1218,7 @@ namespace demos { private onDragEnd = (event: PIXI.interaction.InteractionEvent): void => { - //set interactiondata to null + // set interactiondata to null this.data = null; this.alpha = 1; this.dragging = false; @@ -1255,7 +1255,7 @@ namespace demos { // create the root of the scene graph this.stage = new PIXI.Container(); - //create a texture from an image + // create a texture from an image this.texture = PIXI.Texture.fromImage('../../_assets/bunny.png'); for (var i = 0; i < 10; i++) { @@ -1549,7 +1549,7 @@ namespace demos { .on('mouseout', this.onButtonOut); // you can also listen to click and tap events : - //.on('click', this.noop) + // .on('click', this.noop) } @@ -2137,7 +2137,7 @@ namespace demos { this.bol = false; - //an image path + // an image path this.texture = PIXI.Texture.fromImage('../../_assets/flowerTop.png'); // create a second texture @@ -2410,7 +2410,7 @@ namespace filters { this.count = 0; - //nimate + // nimate this.animate(); } @@ -2680,7 +2680,7 @@ namespace filters { this.stage.addChild(this.help); - //nimate + // animate this.animate(); } diff --git a/pixi.js/v3/index.d.ts b/pixi.js/v3/index.d.ts index 695dab82d2..aa573b2201 100644 --- a/pixi.js/v3/index.d.ts +++ b/pixi.js/v3/index.d.ts @@ -83,7 +83,7 @@ declare namespace PIXI { export function autoDetectRenderer(width: number, height: number, options?: PIXI.RendererOptions, noWebGL?: boolean): PIXI.WebGLRenderer | PIXI.CanvasRenderer; export var loader: PIXI.loaders.Loader; - //https://github.com/primus/eventemitter3 + // https://github.com/primus/eventemitter3 export class EventEmitter { listeners(event: string): Function[]; @@ -102,11 +102,11 @@ declare namespace PIXI { ////////////////////////////////CORE////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - //display + // display export class DisplayObject extends EventEmitter implements interaction.InteractiveTarget { - //begin extras.cacheAsBitmap see https://github.com/pixijs/pixi-typescript/commit/1207b7f4752d79a088d6a9a465a3ec799906b1db + // begin extras.cacheAsBitmap see https://github.com/pixijs/pixi-typescript/commit/1207b7f4752d79a088d6a9a465a3ec799906b1db protected _originalRenderWebGL: WebGLRenderer; protected _originalRenderCanvas: CanvasRenderer; protected _originalUpdateTransform: boolean; @@ -123,7 +123,7 @@ declare namespace PIXI { protected _getCachedBounds(): Rectangle; protected _destroyCachedDisplayObject(): void; protected _cacheAsBitmapDestroy(): void; - //end extras.cacheAsBitmap + // end extras.cacheAsBitmap protected _sr: number; protected _cr: number; @@ -246,7 +246,7 @@ declare namespace PIXI { } - //graphics + // graphics export class GraphicsData { @@ -297,7 +297,7 @@ declare namespace PIXI { drawEllipse(x: number, y: number, width: number, height: number): Graphics; drawPolygon(path: number[] | Point[]): Graphics; clear(): Graphics; - //todo + // todo generateTexture(renderer: WebGLRenderer | CanvasRenderer, resolution?: number, scaleMode?: number): Texture; getBounds(matrix?: Matrix): Rectangle; containsPoint(point: Point): boolean; @@ -306,13 +306,13 @@ declare namespace PIXI { } export interface GraphicsRenderer extends ObjectRenderer { - //yikes todo + // yikes todo } export interface WebGLGraphicsData { - //yikes todo! + // yikes todo! } - //math + // math export class Point { @@ -442,7 +442,7 @@ declare namespace PIXI { } - //particles + // particles export interface ParticleContainerProperties { @@ -500,7 +500,7 @@ declare namespace PIXI { } - //renderers + // renderers export interface RendererOptions { @@ -533,7 +533,7 @@ declare namespace PIXI { resolution: number; transparent: boolean; autoResize: boolean; - blendModes: any; //todo? + blendModes: any; // todo? preserveDrawingBuffer: boolean; clearBeforeRender: boolean; roundPixels: boolean; @@ -856,7 +856,7 @@ declare namespace PIXI { } - //sprites + // sprites export class Sprite extends Container { @@ -909,7 +909,7 @@ declare namespace PIXI { } - //text + // text export interface TextStyle { @@ -959,7 +959,7 @@ declare namespace PIXI { } - //textures + // textures export class BaseTexture extends EventEmitter { @@ -1100,7 +1100,7 @@ declare namespace PIXI { } - //utils + // utils export class utils { @@ -1203,9 +1203,9 @@ declare namespace PIXI { } export class TilingSprite extends Sprite { - //This is really unclean but is the only way :( - //See http://stackoverflow.com/questions/29593905/typescript-declaration-extending-class-with-static-method/29595798#29595798 - //Thanks bas! + // This is really unclean but is the only way :( + // See http://stackoverflow.com/questions/29593905/typescript-declaration-extending-class-with-static-method/29595798#29595798 + // Thanks bas! static fromFrame(frameId: string): Sprite; static fromFrame(frameId: string, width?: number, height?: number): TilingSprite; @@ -1531,7 +1531,7 @@ declare namespace PIXI { ////////////////////////////////////////////////////////////////////////////// ///////////////////////////////LOADER///////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - //https://github.com/englercj/resource-loader/blob/master/src/Loader.js + // https://github.com/englercj/resource-loader/blob/master/src/Loader.js export namespace loaders { export interface LoaderOptions { @@ -1556,7 +1556,7 @@ declare namespace PIXI { add(name: string, url: string, options?: LoaderOptions, cb?: () => void): Loader; add(url: string, options?: LoaderOptions, cb?: () => void): Loader; - //todo I am not sure of object literal notional (or its options) so just allowing any but would love to improve this + // todo I am not sure of object literal notional (or its options) so just allowing any but would love to improve this add(obj: any, options?: LoaderOptions, cb?: () => void): Loader; on(event: 'complete', fn: (loader: loaders.Loader, object: any) => void, context?: any): EventEmitter; diff --git a/pixi.js/v3/pixi.js-tests.ts b/pixi.js/v3/pixi.js-tests.ts index afb61a43d8..ec4c5329c0 100644 --- a/pixi.js/v3/pixi.js-tests.ts +++ b/pixi.js/v3/pixi.js-tests.ts @@ -30,7 +30,7 @@ namespace basics { this.bunny.position.x = 200; this.bunny.position.y = 150; - //add it to the stage + // add it to the stage this.stage.addChild(this.bunny); this.animate(); @@ -75,10 +75,10 @@ namespace basics { this.sprite.on('mousedown', this.onDown, this); this.sprite.on('touchstart', this.onDown, this); - //add it to the stage + // add it to the stage this.stage.addChild(this.sprite); - //start animatng + // start animatng this.animate(); } @@ -133,9 +133,9 @@ namespace basics { bunny.y = 40 * j; this.container.addChild(bunny); - }; + } - }; + } /* * All the bunnies are added to the container with the addChild method @@ -225,7 +225,7 @@ namespace basics { type: '1f', value: 0 } - }) + }); } } @@ -332,9 +332,9 @@ namespace basics { bunny.rotation = Math.random() * (Math.PI * 2); this.container.addChild(bunny); - }; + } - }; + } this.renderTexture = new PIXI.RenderTexture(this.renderer, 300, 200, PIXI.SCALE_MODES.LINEAR, 0.1); @@ -421,7 +421,7 @@ namespace basics { this.movie.rotation += 0.01; - //render the stage container + // render the stage container this.renderer.render(this.stage); requestAnimationFrame(this.animate); @@ -529,7 +529,7 @@ namespace basics { for (var i = 0; i < 25; i++) { this.points.push(new PIXI.Point(i * this.ropeLength, 0)); - }; + } this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage('../../_assets/snake.png'), this.points); this.strip.position.x = -40; @@ -541,7 +541,7 @@ namespace basics { this.graphics.y = this.strip.y; this.stage.addChild(this.graphics); - //start animating + // start animating this.animate(); } @@ -550,16 +550,16 @@ namespace basics { this.count += 0.1; - //make the snake + // make the snake for (var i = 0; i < this.points.length; i++) { this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; this.points[i].x = i * this.ropeLength + Math.cos((i * 0.3) + this.count) * 20; - }; + } - //render the stage + // render the stage this.renderer.render(this.stage); this.renderPoints(); @@ -577,13 +577,13 @@ namespace basics { for (var i = 1; i < this.points.length; i++) { this.graphics.lineTo(this.points[i].x, this.points[i].y); - }; + } for (var i = 1; i < this.points.length; i++) { this.graphics.beginFill(0xff0022); this.graphics.drawCircle(this.points[i].x, this.points[i].y, 10); this.graphics.endFill(); - }; + } } @@ -613,7 +613,7 @@ namespace basics { // create the root of the scene graph this.stage = new PIXI.Container(); - //create a texture from an image path + // create a texture from an image path this.texture = PIXI.Texture.fromImage('../../_assets/p2.jpeg'); /* create a tiling sprite ... @@ -670,10 +670,10 @@ namespace basics { // create the root of the scene graph this.stage = new PIXI.Container(); - //create a video texture from a path + // create a video texture from a path this.texture = PIXI.Texture.fromVideo('../../_assets/testVideo.mp4'); - //create a new sprite using the video texture (yes it's that easy) + // create a new sprite using the video texture (yes it's that easy) this.videoSprite = new PIXI.Sprite(this.texture); this.videoSprite.width = this.renderer.width; this.videoSprite.height = this.renderer.height; @@ -687,7 +687,7 @@ namespace basics { private animate = (): void => { - //render the stage + // render the stage this.renderer.render(this.stage); requestAnimationFrame(this.animate); @@ -868,9 +868,7 @@ namespace demos { private animate = (): void => { // iterate through the sprites and update their position - for (var i = 0; i < this.maggots.length; i++) { - - var dude = this.maggots[i]; + for (const dude of this.maggots) { dude.scale.y = 0.95 + Math.sin(this.tick + dude.offset) * 0.05; dude.direction += dude.turningSpeed * 0.01; dude.position.x += Math.sin(dude.direction) * (dude.speed * dude.scale.y); @@ -880,15 +878,13 @@ namespace demos { // wrap the maggots if (dude.position.x < this.dudeBounds.x) { dude.position.x += this.dudeBounds.width; - } - else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { dude.position.x -= this.dudeBounds.width; } if (dude.position.y < this.dudeBounds.y) { dude.position.y += this.dudeBounds.height; - } - else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { dude.position.y -= this.dudeBounds.height; } } @@ -1008,9 +1004,7 @@ namespace demos { private animate = (): void => { // iterate through the dudes and update the positions - for (var i = 0; i < this.dudeArray.length; i++) { - - var dude = this.dudeArray[i]; + for (const dude of this.dudeArray) { dude.direction += dude.turningSpeed * 0.01; dude.position.x += Math.sin(dude.direction) * dude.speed; dude.position.y += Math.cos(dude.direction) * dude.speed; @@ -1019,15 +1013,13 @@ namespace demos { // wrap the dudes by testing their bounds... if (dude.position.x < this.dudeBounds.x) { dude.position.x += this.dudeBounds.width; - } - else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { dude.position.x -= this.dudeBounds.width; } if (dude.position.y < this.dudeBounds.y) { dude.position.y += this.dudeBounds.height; - } - else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { dude.position.y -= this.dudeBounds.height; } } @@ -1113,11 +1105,11 @@ namespace demos { this.alienContainer.cacheAsBitmap = !this.alienContainer.cacheAsBitmap; - //feel free to play with what's below - //var sprite = new PIXI.Sprite(this.alienContainer.generateTexture()); - //this.stage.addChild(sprite); - //sprite.position.x = Math.random() * 800; - //sprite.position.y = Math.random() * 600; + // feel free to play with what's below + // var sprite = new PIXI.Sprite(this.alienContainer.generateTexture()); + // this.stage.addChild(sprite); + // sprite.position.x = Math.random() * 800; + // sprite.position.y = Math.random() * 600; } @@ -1185,7 +1177,7 @@ namespace demos { export class DraggableBunny extends PIXI.Sprite { - //todo I dont know what event.data is at this time + // todo I dont know what event.data is at this time private data: any; private dragging: boolean; @@ -1235,7 +1227,7 @@ namespace demos { private onDragEnd = (event: PIXI.interaction.InteractionEvent): void => { - //set interactiondata to null + // set interactiondata to null this.data = null; this.alpha = 1; this.dragging = false; @@ -1272,7 +1264,7 @@ namespace demos { // create the root of the scene graph this.stage = new PIXI.Container(); - //create a texture from an image + // create a texture from an image this.texture = PIXI.Texture.fromImage('../../_assets/bunny.png'); for (var i = 0; i < 10; i++) { @@ -1563,10 +1555,10 @@ namespace demos { .on('mouseover', this.onButtonOver) // set the mouseout callback... - .on('mouseout', this.onButtonOut) + .on('mouseout', this.onButtonOut); // you can also listen to click and tap events : - //.on('click', this.noop) + // .on('click', this.noop) } @@ -1584,8 +1576,7 @@ namespace demos { if (this.isOver) { this.texture = this.textureButtonOver; - } - else { + } else { this.texture = this.textureButton; } } @@ -1750,8 +1741,7 @@ namespace demos { if (!this.container.mask) { this.container.mask = this.thing; - } - else { + } else { this.container.mask = null; } } @@ -1923,9 +1913,8 @@ namespace demos { private animate = (): void => { - for (var i = 0; i < this.items.length; i++) { + for (const item of this.items) { // rotate each item - var item = this.items[i]; item.rotation += 0.1; } @@ -2157,7 +2146,7 @@ namespace demos { this.bol = false; - //an image path + // an image path this.texture = PIXI.Texture.fromImage('../../_assets/flowerTop.png'); // create a second texture @@ -2183,8 +2172,7 @@ namespace demos { if (this.bol) { this.dude.texture = this.secondTexture; - } - else { + } else { this.dude.texture = this.texture; } }); @@ -2286,9 +2274,7 @@ namespace demos { private animate = (): void => { // iterate through the dudes and update their position - for (var i = 0; i < this.aliens.length; i++) { - - var dude = this.aliens[i]; + for (const dude of this.aliens) { dude.direction += dude.turningSpeed * 0.01; dude.position.x += Math.sin(dude.direction) * dude.speed; dude.position.y += Math.cos(dude.direction) * dude.speed; @@ -2297,15 +2283,13 @@ namespace demos { // wrap the dudes by testing their bounds... if (dude.position.x < this.dudeBounds.x) { dude.position.x += this.dudeBounds.width; - } - else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + } else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { dude.position.x -= this.dudeBounds.width; } if (dude.position.y < this.dudeBounds.y) { dude.position.y += this.dudeBounds.height; - } - else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + } else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { dude.position.y -= this.dudeBounds.height; } @@ -2435,7 +2419,7 @@ namespace filters { this.count = 0; - //nimate + // nimate this.animate(); } @@ -2568,15 +2552,13 @@ namespace filters { this.ring.position.x = eventData.data.global.x - 25; this.ring.position.y = eventData.data.global.y; - }; + } private animate = (): void => { this.count += 0.05; - for (var i = 0; i < this.maggots.length; i++) { - var maggot = this.maggots[i]; - + for (const maggot of this.maggots) { maggot.direction += maggot.turnSpeed * 0.01; maggot.position.x += Math.sin(maggot.direction) * maggot.speed; maggot.position.y += Math.cos(maggot.direction) * maggot.speed; @@ -2588,15 +2570,13 @@ namespace filters { // wrap the maggots around as the crawl if (maggot.position.x < this.bounds.x) { maggot.position.x += this.bounds.width; - } - else if (maggot.position.x > this.bounds.x + this.bounds.width) { + } else if (maggot.position.x > this.bounds.x + this.bounds.width) { maggot.position.x -= this.bounds.width; } if (maggot.position.y < this.bounds.y) { maggot.position.y += this.bounds.height; - } - else if (maggot.position.y > this.bounds.y + this.bounds.height) { + } else if (maggot.position.y > this.bounds.y + this.bounds.height) { maggot.position.y -= this.bounds.height; } } @@ -2605,7 +2585,7 @@ namespace filters { requestAnimationFrame(this.animate); - }; + } } @@ -2709,7 +2689,7 @@ namespace filters { this.stage.addChild(this.help); - //nimate + // animate this.animate(); } @@ -2720,8 +2700,7 @@ namespace filters { if (!this.switchy) { this.stage.filters = [this.filter]; - } - else { + } else { this.stage.filters = null; } diff --git a/progressbar/progressbar-tests.ts b/progressbar/progressbar-tests.ts index f6cfa4dac4..46dcc60732 100644 --- a/progressbar/progressbar-tests.ts +++ b/progressbar/progressbar-tests.ts @@ -2,8 +2,8 @@ import { Progressbar, create } from 'progressbar'; let str: string = '', progressbar: Progressbar, - num: number = 1, - fn: () => void = () => {}; + num: number = 1; +const fn: () => void = () => {}; progressbar = create(); progressbar = progressbar.step(str); diff --git a/python-shell/python-shell-tests.ts b/python-shell/python-shell-tests.ts index 33a7c0eba1..859ea102e2 100644 --- a/python-shell/python-shell-tests.ts +++ b/python-shell/python-shell-tests.ts @@ -1,6 +1,6 @@ import * as ps from 'python-shell'; -let PythonShell = ps.PythonShell; +const PythonShell = ps.PythonShell; ps.run('my_script.py', err => { if (err) throw err; diff --git a/readline-sync/readline-sync-tests.ts b/readline-sync/readline-sync-tests.ts index a56d4140f6..7800fda39a 100644 --- a/readline-sync/readline-sync-tests.ts +++ b/readline-sync/readline-sync-tests.ts @@ -1,14 +1,14 @@ import readlineSync = require('readline-sync'); -let result: string = readlineSync.question('Which program starts do you want? ', { +const result: string = readlineSync.question('Which program starts do you want? ', { defaultInput: 'firefox' }); -let result2: string = readlineSync.prompt({prompt: '$$'}); +const result2: string = readlineSync.prompt({prompt: '$$'}); -let result3: string = readlineSync.keyIn('Press a key', { limit: '$<1-5>' }); +const result3: string = readlineSync.keyIn('Press a key', { limit: '$<1-5>' }); -let result4: {} = readlineSync.setDefaultOptions({ +const result4: {} = readlineSync.setDefaultOptions({ prompt: '$$', hideEchoBack: true, mask: '*', @@ -37,15 +37,15 @@ let result4: {} = readlineSync.setDefaultOptions({ guide: false, }); -let result5: string = readlineSync.questionEMail('Enter email'); +const result5: string = readlineSync.questionEMail('Enter email'); -let result6: string = readlineSync.questionNewPassword('PASSWORD: ', {charlist: '$#$@%'}); +const result6: string = readlineSync.questionNewPassword('PASSWORD: ', {charlist: '$#$@%'}); -let result7: number = readlineSync.questionInt('Enter an integer', { limitMessage: 'Enter a valid integer' }); +const result7: number = readlineSync.questionInt('Enter an integer', { limitMessage: 'Enter a valid integer' }); -let result8: number = readlineSync.questionFloat('Enter a float', { limitMessage: 'Enter a valid float' }); +const result8: number = readlineSync.questionFloat('Enter a float', { limitMessage: 'Enter a valid float' }); -let result9: string = readlineSync.questionPath('Save to: ', { +const result9: string = readlineSync.questionPath('Save to: ', { isDirectory: true, exists: null, create: true @@ -83,18 +83,18 @@ readlineSync.promptCLLoop({ bye: () => true }); -let result10: string = readlineSync.promptSimShell(); +const result10: string = readlineSync.promptSimShell(); -let result11: (boolean | string) = readlineSync.keyInYN('Do you want to install this?'); +const result11: (boolean | string) = readlineSync.keyInYN('Do you want to install this?'); -let result12: boolean = readlineSync.keyInYNStrict('Do you want to install this?', { guide: true }); +const result12: boolean = readlineSync.keyInYNStrict('Do you want to install this?', { guide: true }); readlineSync.keyInPause({ guide: true }); -let frameworks = ['Express', 'hapi', 'flatiron', 'MEAN.JS', 'locomotive']; -let result13: number = readlineSync.keyInSelect(frameworks, 'Which framework?'); +const frameworks = ['Express', 'hapi', 'flatiron', 'MEAN.JS', 'locomotive']; +const result13: number = readlineSync.keyInSelect(frameworks, 'Which framework?'); -let result14: string = readlineSync.getRawInput(); +const result14: string = readlineSync.getRawInput(); readlineSync.setPrint((display: string, encoding: string) => { console.log(display); }); diff --git a/redux-ui/index.d.ts b/redux-ui/index.d.ts index f38cd16ec1..3b1f8f4a58 100644 --- a/redux-ui/index.d.ts +++ b/redux-ui/index.d.ts @@ -1,53 +1,50 @@ -// Type definitions for redux-ui 0.0.15 +// Type definitions for redux-ui 0.0 // Project: https://github.com/tonyhb/redux-ui // Definitions by: Andy Shu Xin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "redux-ui" { +import * as Redux from 'redux'; - import * as Redux from 'redux'; +export interface uiParams { + // optional key which is used to determine the UI path in which state will + // be stored. if omitted this is randomly generated. + key?: string; - export interface uiParams { - // optional key which is used to determine the UI path in which state will - // be stored. if omitted this is randomly generated. - key?: string; + // optional persist, defaults to false. if set to true persist will keep UI + // state for this component after it unmounts. if set to false the UI state + // will be deleted and recreated when the component remounts + persist?: boolean; - // optional persist, defaults to false. if set to true persist will keep UI - // state for this component after it unmounts. if set to false the UI state - // will be deleted and recreated when the component remounts - persist?: boolean; + // **required**: UI state for the component + state: UIStateShape; - // **required**: UI state for the component - state: UIStateShape; + // optional mergeProps passed to react-redux' @connect + mergeProps?: (stateProps: any, dispatchProps: any, ownProps: any) => any; - // optional mergeProps passed to react-redux' @connect - mergeProps?: (stateProps: any, dispatchProps: any, ownProps: any) => any; - - // optional `options` passed to react-redux @connect - options?: { - pure?: boolean; - withRef?: boolean; - }; - } - - export interface ReduxUIProps { - // The key passed to the decorator from the decorator - // (eg. 'some-decorator' with `@ui('some-decorator')` - uiKey: string; - - // The UI state for the component's `uiKey` - ui: UIStateShape; - - // A function accepting either a name/value pair or object which updates - // state within `uiKey` - updateUI(obj: UIStateShape): void; - updateUI(key: string, value: any): void; - - // A function which resets the state within `uiKey` to its default - resetUI(): void; - } - - export const reducer: Redux.Reducer; - - export default function ui(params?: uiParams): (component: T) => T; + // optional `options` passed to react-redux @connect + options?: { + pure?: boolean; + withRef?: boolean; + }; } + +export interface ReduxUIProps { + // The key passed to the decorator from the decorator + // (eg. 'some-decorator' with `@ui('some-decorator')` + uiKey: string; + + // The UI state for the component's `uiKey` + ui: UIStateShape; + + // A function accepting either a name/value pair or object which updates + // state within `uiKey` + updateUI(obj: UIStateShape): void; + updateUI(key: string, value: any): void; + + // A function which resets the state within `uiKey` to its default + resetUI(): void; +} + +export const reducer: Redux.Reducer; + +export default function ui(params?: uiParams): (component: T) => T; diff --git a/redux-ui/redux-ui-tests.ts b/redux-ui/redux-ui-tests.ts index 63ac16c84e..352e70576d 100644 --- a/redux-ui/redux-ui-tests.ts +++ b/redux-ui/redux-ui-tests.ts @@ -1,10 +1,10 @@ -import * as React from 'react' -import * as Redux from 'redux' -import ui, { ReduxUIProps, reducer } from 'redux-ui' +import * as React from 'react'; +import * as Redux from 'redux'; +import ui, { ReduxUIProps, reducer } from 'redux-ui'; -type UIShape = { +interface UIShape { s: string; -}; +} @ui({ key: 'Root', diff --git a/redux-ui/tslint.json b/redux-ui/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/redux-ui/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/reflux/index.d.ts b/reflux/index.d.ts index 4cef17c03b..58177ee7fe 100644 --- a/reflux/index.d.ts +++ b/reflux/index.d.ts @@ -1,64 +1,59 @@ -// Type definitions for RefluxJS +// Type definitions for RefluxJS 0.4 // Project: https://github.com/reflux/refluxjs // Definitions by: Maurice de Beijer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export = RefluxCore; export as namespace Reflux; -declare module RefluxCore { - - interface StoreDefinition { - listenables?: any[], - init?: Function, - getInitialState?: Function, - [propertyName: string]: any; - } - - interface ListenFn { - (...params: any[]):any, - completed: Function, - failed: Function - } - interface Listenable { - listen: ListenFn - } - - interface Subscription { - stop: Function, - listenable: Listenable - } - - interface Store { - hasListener(listenable: Listenable): boolean, - listenToMany(listenables: Listenable[]): void, - validateListening(listenable: Listenable): string, - listenTo(listenable: Listenable, callback: Function, defaultCallback?: Function): Subscription, - stopListeningTo(listenable: Listenable): boolean, - stopListeningToAll(): void, - fetchInitialState(listenable: Listenable, defaultCallback: Function): void, - trigger(state: any):void; - listen(callback: Function, bindContext: any): Function; - } - - interface ActionsDefinition { - [index: string]:any - } - - interface Actions { - [index: string]: Listenable - } - - function createStore(definition: StoreDefinition): Store; - - function createAction(definition?: ActionsDefinition): any; - - function createActions(definition: ActionsDefinition): any; - function createActions(definitions: string[]): any; - - function connect(store: Store, key?: string):void; - function listenTo(store: Store, handler: string):void; - function setState(state: any):void; - - function ListenerMixin(): any; +interface StoreDefinition { + listenables?: any[]; + init?: Function; + getInitialState?: Function; + [propertyName: string]: any; } + +interface ListenFn { + (...params: any[]): any; + completed: Function; + failed: Function; +} +interface Listenable { + listen: ListenFn; +} + +interface Subscription { + stop: Function; + listenable: Listenable; +} + +interface Store { + hasListener(listenable: Listenable): boolean; + listenToMany(listenables: Listenable[]): void; + validateListening(listenable: Listenable): string; + listenTo(listenable: Listenable, callback: Function, defaultCallback?: Function): Subscription; + stopListeningTo(listenable: Listenable): boolean; + stopListeningToAll(): void; + fetchInitialState(listenable: Listenable, defaultCallback: Function): void; + trigger(state: any): void; + listen(callback: Function, bindContext: any): Function; +} + +interface ActionsDefinition { + [index: string]: any; +} + +interface Actions { + [index: string]: Listenable; +} + +export function createStore(definition: StoreDefinition): Store; + +export function createAction(definition?: ActionsDefinition): any; + +export function createActions(definitions: ActionsDefinition | string[]): any; + +export function connect(store: Store, key?: string): void; +export function listenTo(store: Store, handler: string): void; +export function setState(state: any): void; + +export function ListenerMixin(): any; diff --git a/reflux/reflux-tests.ts b/reflux/reflux-tests.ts index 5094ed9ecc..7a392282fa 100644 --- a/reflux/reflux-tests.ts +++ b/reflux/reflux-tests.ts @@ -1,6 +1,3 @@ - -/// - import Reflux = require("reflux"); import React = require("react"); @@ -15,7 +12,7 @@ var asyncActions = Reflux.createActions({ fireBall: {asyncResult: true} }); -asyncActions.fireBall.listen(function () { +asyncActions.fireBall.listen(function() { // Trigger async action setTimeout(() => this.completed(true), 1000); }); @@ -25,13 +22,12 @@ asyncActions.fireBall.listen(function () { var statusStore = Reflux.createStore({ // Initial setup - init: function () { - + init() { // Register statusUpdate action this.listenTo(asyncActions.fireBall, this.onFireBall); }, // Callback - onFireBall: function (flag: boolean) { + onFireBall(flag: boolean) { var status = flag ? 'ONLINE' : 'OFFLINE'; // Pass on to listeners @@ -48,13 +44,13 @@ var action = Reflux.createAction(); var actions = Reflux.createActions(["fireBall", "magicMissile"]); var Store = Reflux.createStore({ - init: function () { + init() { this.listenToMany(actions); }, - onFireBall: function () { + onFireBall() { // whoooosh! }, - onMagicMissile: function () { + onMagicMissile() { // bzzzzapp! } }); diff --git a/reflux/tslint.json b/reflux/tslint.json new file mode 100644 index 0000000000..0f47deabb4 --- /dev/null +++ b/reflux/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} \ No newline at end of file diff --git a/restify-plugins/index.d.ts b/restify-plugins/index.d.ts index 3ce557374f..0a2419d58e 100644 --- a/restify-plugins/index.d.ts +++ b/restify-plugins/index.d.ts @@ -6,7 +6,7 @@ import {RequestHandler, Server, Request, Response, Route} from 'restify'; import Logger = require('bunyan'); -//*************** This module includes the follow pre plugins, which are intended to be used prior to the routing of a request: +// *************** This module includes the follow pre plugins, which are intended to be used prior to the routing of a request: export namespace pre { /** @@ -45,7 +45,7 @@ export namespace pre { function userAgentConnection( options?: {userAgentRegExp: any} ): RequestHandler; } -//*************** This module includes the following header parser plugins: +// *************** This module includes the following header parser plugins: /** * Check the client's Accept header can be handled by this server. @@ -106,7 +106,7 @@ export function conditionalRequest(): RequestHandler[]; */ export function fullResponse(): RequestHandler; -//************ This module includes the following data parsing plugins: +// ************ This module includes the following data parsing plugins: interface BodyParserOptions { /** @@ -292,7 +292,7 @@ interface RequestLogger { */ export function requestLogger(options?: RequestLogger): RequestHandler; -//******************** The module includes the following response plugins: +// ******************** The module includes the following response plugins: /** * expires requests based on current time + delta diff --git a/rrule/test/commonJs.ts b/rrule/test/commonJs.ts index e6a2c86dac..f193febe91 100644 --- a/rrule/test/commonJs.ts +++ b/rrule/test/commonJs.ts @@ -1,2 +1,2 @@ import { RRule } from "rrule"; -let rule: RRule = new RRule({ freq: RRule.WEEKLY }); +const rule: RRule = new RRule({ freq: RRule.WEEKLY }); diff --git a/rrule/test/rrule.ts b/rrule/test/rrule.ts index 829c22f087..461283c45d 100644 --- a/rrule/test/rrule.ts +++ b/rrule/test/rrule.ts @@ -10,7 +10,7 @@ let rule: RRule = new RRule({ }); let x: Date[]; -let y: string[]; +const y: string[] = []; // Get all occurrence dates (Date instances): x = rule.all(); @@ -60,4 +60,4 @@ options.dtstart = new Date(2000, 1, 1); rule = new RRule(options); // Test arrays -let multipleInstance = new RRule({freq: 3, byhour: [6, 12, 18]}); +const multipleInstance = new RRule({freq: 3, byhour: [6, 12, 18]}); diff --git a/service_worker_api/service_worker_api-tests.ts b/service_worker_api/service_worker_api-tests.ts index b87342f0e9..5cfae785cc 100644 --- a/service_worker_api/service_worker_api-tests.ts +++ b/service_worker_api/service_worker_api-tests.ts @@ -107,7 +107,7 @@ self.addEventListener('activate', (event: ExtendableEvent) => { function sendMessage(message: any) { return new Promise((resolve, reject) => { var messageChannel = new MessageChannel(); - messageChannel.port1.onmessage = function(event) { + messageChannel.port1.onmessage = event => { if (event.data.error) { reject(event.data.error); } else { @@ -128,7 +128,7 @@ sendMessage('test').then((clientId: string) => { self.clients.matchAll({type: "test"}).then(clients => { for (var cli of clients) { - if(cli.url === 'index.html') { + if (cli.url === 'index.html') { self.clients.openWindow(cli.url); // or do something else involving the matching client } diff --git a/sharepoint/index.d.ts b/sharepoint/index.d.ts index 2bc22e9234..1908d46b0c 100644 --- a/sharepoint/index.d.ts +++ b/sharepoint/index.d.ts @@ -1,7 +1,7 @@ // Type definitions for SharePoint: 2010.1 / 2013.1 -// Project: https://github.com/gandjustas/sptypescript -// Definitions by: Stanislav Vyshchepan , Andrey Markeev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Project: https:// github.com/gandjustas/sptypescript +// Definitions by: Stanislav Vyshchepan , Andrey Markeev +// Definitions: https:// github.com/DefinitelyTyped/DefinitelyTyped /// @@ -34,17 +34,17 @@ declare namespace SP { } export enum ListLevelPermissionMask { - viewListItems, //: 1, - insertListItems, //: 2, - editListItems, //: 4, - deleteListItems, //: 8, - approveItems, //: 16, - openItems, //: 32, - viewVersions, //: 64, - deleteVersions, //: 128, - breakCheckout, //: 256, - managePersonalViews, //: 512, - manageLists //: 2048 + viewListItems, // : 1, + insertListItems, // : 2, + editListItems, // : 4, + deleteListItems, // : 8, + approveItems, // : 16, + openItems, // : 32, + viewVersions, // : 64, + deleteVersions, // : 128, + breakCheckout, // : 256, + managePersonalViews, // : 512, + manageLists // : 2048 } export class HtmlBuilder { @@ -154,32 +154,32 @@ declare class JSRequest { } declare class _spPageContextInfo { - static alertsEnabled: boolean; //true - static allowSilverlightPrompt: string; //"True" - static clientServerTimeDelta: number; //-182 - static crossDomainPhotosEnabled: boolean; //true - static currentCultureName: string; //"ru-RU" - static currentLanguage: number; //1049 - static currentUICultureName: string; //"ru-RU" - static layoutsUrl: string; //"_layouts/15" - static pageListId: string; //"{06ee6d96-f27f-4160-b6bb-c18f187b18a7}" + static alertsEnabled: boolean; // true + static allowSilverlightPrompt: string; // "True" + static clientServerTimeDelta: number; // -182 + static crossDomainPhotosEnabled: boolean; // true + static currentCultureName: string; // "ru-RU" + static currentLanguage: number; // 1049 + static currentUICultureName: string; // "ru-RU" + static layoutsUrl: string; // "_layouts/15" + static pageListId: string; // "{06ee6d96-f27f-4160-b6bb-c18f187b18a7}" static pageItemId: number; - static pagePersonalizationScope: string; //1 - static serverRequestPath: string; //"/SPTypeScript/Lists/ConditionalFormattingTasksList/AllItems.aspx" - static siteAbsoluteUrl: string; // "https://gandjustas-7b20d3715e8ed4.sharepoint.com" - static siteClientTag: string; //"0$$15.0.4454.1021" + static pagePersonalizationScope: string; // 1 + static serverRequestPath: string; // "/SPTypeScript/Lists/ConditionalFormattingTasksList/AllItems.aspx" + static siteAbsoluteUrl: string; // "https:// gandjustas-7b20d3715e8ed4.sharepoint.com" + static siteClientTag: string; // "0$$15.0.4454.1021" static siteServerRelativeUrl: string; // "/" - static systemUserKey: string; //"i:0h.f|membership|10033fff84e7cb2b@live.com" - static tenantAppVersion: string; //"0" - static userId: number; //12 - static webAbsoluteUrl: string; //"https://gandjustas-7b20d3715e8ed4.sharepoint.com/SPTypeScript" - static webLanguage: number; //1049 - static webLogoUrl: string; //"/_layouts/15/images/siteIcon.png?rev=23" + static systemUserKey: string; // "i:0h.f|membership|10033fff84e7cb2b@live.com" + static tenantAppVersion: string; // "0" + static userId: number; // 12 + static webAbsoluteUrl: string; // "https:// gandjustas-7b20d3715e8ed4.sharepoint.com/SPTypeScript" + static webLanguage: number; // 1049 + static webLogoUrl: string; // "/_layouts/15/images/siteIcon.png?rev=23" static webPermMasks: { High: number; Low: number; }; - static webServerRelativeUrl: string; //"/SPTypeScript" - static webTemplate: string; //"17" - static webTitle: string; //"SPTypeScript" - static webUIVersion: number; //15 + static webServerRelativeUrl: string; // "/SPTypeScript" + static webTemplate: string; // "17" + static webTitle: string; // "SPTypeScript" + static webUIVersion: number; // 15 } declare function STSHtmlEncode(value: string): string; @@ -268,7 +268,7 @@ interface ContextInfo extends SPClientTemplates.RenderContext { LastSelectedItemIID: number; LastRowIndexSelected: number; RowFocusTimerID: number; - ListData: any; //SPClientTemplates.ListData_InView | SPClientTemplates.ListData_InForm + ListData: any; // SPClientTemplates.ListData_InView | SPClientTemplates.ListData_InForm ListSchema: SPClientTemplates.ListSchema; ModerationStatus: number; PortalUrl: string; @@ -356,7 +356,7 @@ declare namespace SP { body?: string | Uint8Array; binaryStringRequestBody?: boolean; - /** Currently need fix to get ginary response. Details: http://techmikael.blogspot.ru/2013/07/how-to-copy-files-between-sites-using.html */ + /** Currently need fix to get ginary response. Details: http:// techmikael.blogspot.ru/2013/07/how-to-copy-files-between-sites-using.html */ binaryStringResponseBody?: boolean; timeout?: number; success?: (response: ResponseInfo) => void; @@ -810,7 +810,7 @@ declare namespace SPClientTemplates { export interface FieldSchema_InForm_Lookup extends FieldSchema_InForm { /** Specifies if the field allows multiple values */ AllowMultipleValues: boolean; - /** Returns base url for a list display form, e.g. "http://portal/web/_layouts/15/listform.aspx?PageType=4" + /** Returns base url for a list display form, e.g. "http:// portal/web/_layouts/15/listform.aspx?PageType=4" You must add "ListId" (Guid of the list) and "ID" (integer Id of the item) parameters in order to use this Url */ BaseDisplayFormUrl: string; /** Indicates if the field is a dependent lookup */ @@ -1464,13 +1464,13 @@ declare namespace SPClientForms { } export enum FormManagerEvents { - Event_OnControlValueChanged, //: 1, - Event_OnControlInitializedCallback, //: 2, - Event_OnControlFocusSetCallback, //: 3, - Event_GetControlValueCallback, //: 4, - Event_OnControlValidationError, //: 5, - Event_RegisterControlValidator, //: 6, - Event_GetHasValueChangedCallback //: 7 + Event_OnControlValueChanged, // : 1, + Event_OnControlInitializedCallback, // : 2, + Event_OnControlFocusSetCallback, // : 3, + Event_GetControlValueCallback, // : 4, + Event_OnControlValidationError, // : 5, + Event_RegisterControlValidator, // : 6, + Event_GetHasValueChangedCallback // : 7 } export class ClientForm { @@ -1734,11 +1734,11 @@ declare namespace SP { export class ClientObjectPropertyConditionalScope extends SP.ConditionalScopeBase { constructor(clientObject: SP.ClientObject, propertyName: string, comparisonOperator: string, valueToCompare: any, allowAllActions?: boolean); } - //export class ClientResult { + // export class ClientResult { // get_value(): any; // setValue(value: any): void; // constructor(); - //} + // } export class ClientResult { get_value(): T; setValue(value: T): void; @@ -5235,7 +5235,7 @@ declare namespace Microsoft.SharePoint.Client.Search { } export class QueryPersonalizationData extends SP.ClientObject { - //It's really empty; + // It's really empty; } export class QuerySuggestionResults extends SP.ClientValueObject { @@ -5561,7 +5561,7 @@ declare namespace Microsoft.SharePoint.Client.Search { } export class SearchConfigurationPortabilityPropertyNames { - static importWarnings: string; //= 'ImportWarnings' + static importWarnings: string; // = 'ImportWarnings' } } @@ -5890,12 +5890,12 @@ declare namespace SP { } // For some reasons this enum doesn't exist - //export enum SocialFollowResult { + // export enum SocialFollowResult { // ok = 0, // alreadyFollowing = 1, // limitReached = 2, // internalError = 3 - //} + // } /** Provides information about the feed. This type provides information about whether the feed on the server contains additional threads that were not returned. */ @@ -6619,7 +6619,7 @@ declare namespace SP { set_owner(value: string): void; get_terms(): TermCollection; createTerm(name: string, lcid: number, newTermId: SP.Guid): Term; - /*getTerms(pagingLimit: number): TermCollection;*/ //Moved to descendants to void TypeScript errors + /*getTerms(pagingLimit: number): TermCollection;*/ // Moved to descendants to void TypeScript errors reuseTerm(sourceTerm: Term, reuseBranch: boolean): Term; reuseTermWithPinning(sourceTerm: Term): Term; deleteCustomProperty(name: string): void; @@ -7683,7 +7683,7 @@ declare namespace SP { /** The Follow method adds the specified document or site to the list of followed content. @param url URL that identifies the item to follow. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= @param data Optional parameter that holds application-defined data for the item. */ follow(url: string, data?: FollowedItemData): FollowResult; @@ -7694,23 +7694,23 @@ declare namespace SP { /** Removes the specified document or site from list of followed content. @param url URL that identifies the item to stop following. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= */ + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= */ stopFollowing(url: string): void; /** Determines if the specified document or site is being followed. @param url URL that identifies the item that is supposed to be followed. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= */ + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= */ isFollowed(url: string): SP.BooleanResult; /** Retrieves the followed status of the specified document or site. Returns a value of type FollowedStatus, wrapped into a SP.IntResult object. @param url URL that identifies the followed item. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= */ + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= */ getFollowedStatus(url: string): SP.IntResult; /** Returns the followed item identified by a given URL or returns null if the item does not exist. @param url URL that identifies the followed item. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= */ + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= */ getItem(url: string): FollowedItem; /** Returns an array of zero or more followed items described by the type and subtype parameters. @param options Describes the type of item to return. @@ -7719,7 +7719,7 @@ declare namespace SP { /** Updates the properties for followed item with specified URL. @param url URL that identifies the followed item. The url parameter can identify an existing document or site using the url property of the original item. - The url parameter can also identify a document with the following format: http://host/site?listId=&itemId= + The url parameter can also identify a document with the following format: http:// host/site?listId=&itemId= @param data Application-defined data stored with the followed item. */ updateData(url: string, data: FollowedItemData): void; /** Returns the refreshed item that is being pointed to in the Social list. @@ -8936,9 +8936,9 @@ declare namespace SP { declare namespace SP { export namespace CompliancePolicy { export enum SPContainerType { - site, //: 0, - web, //: 1, - list //: 2 + site, // : 0, + web, // : 1, + list // : 2 } export class SPContainerId extends ClientObject { @@ -9203,10 +9203,10 @@ declare namespace SP { export namespace Discovery { export enum ExportStatus { - notStarted, //: 0, - started, //: 1, - complete, //: 2, - failed //: 3 + notStarted, // : 0, + started, // : 1, + complete, // : 2, + failed // : 3 } export class Case extends ClientObject { @@ -9261,11 +9261,11 @@ declare class SPClientAutoFill { Loading: number; }; - static KeyProperty: string; //= 'AutoFillKey'; - static DisplayTextProperty: string; //= 'AutoFillDisplayText'; - static SubDisplayTextProperty: string; //= 'AutoFillSubDisplayText'; - static TitleTextProperty: string; //= 'AutoFillTitleText'; - static MenuOptionTypeProperty: string; //= 'AutoFillMenuOptionType'; + static KeyProperty: string; // = 'AutoFillKey'; + static DisplayTextProperty: string; // = 'AutoFillDisplayText'; + static SubDisplayTextProperty: string; // = 'AutoFillSubDisplayText'; + static TitleTextProperty: string; // = 'AutoFillTitleText'; + static MenuOptionTypeProperty: string; // = 'AutoFillMenuOptionType'; static GetAutoFillObjFromInput(elmText: HTMLInputElement): SPClientAutoFill; static GetAutoFillObjFromContainer(elmChild: HTMLElement): SPClientAutoFill; @@ -9338,50 +9338,50 @@ declare class SPClientPeoplePicker { TopLevelElementId: string; // '', - EditorElementId: string; //'', - AutoFillElementId: string; //'', - ResolvedListElementId: string; //'', - InitialHelpTextElementId: string; //'', - WaitImageId: string; //'', - HiddenInputId: string; //'', - AllowEmpty: boolean; //true, - ForceClaims: boolean; //false, - AutoFillEnabled: boolean; //true, - AllowMultipleUsers: boolean; //false, + EditorElementId: string; // '', + AutoFillElementId: string; // '', + ResolvedListElementId: string; // '', + InitialHelpTextElementId: string; // '', + WaitImageId: string; // '', + HiddenInputId: string; // '', + AllowEmpty: boolean; // true, + ForceClaims: boolean; // false, + AutoFillEnabled: boolean; // true, + AllowMultipleUsers: boolean; // false, OnValueChangedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; OnUserResolvedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; OnControlValidateClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; - UrlZone: SP.UrlZone; //null, - AllUrlZones: boolean; //false, - SharePointGroupID: number; //0, - AllowEmailAddresses: boolean; //false, + UrlZone: SP.UrlZone; // null, + AllUrlZones: boolean; // false, + SharePointGroupID: number; // 0, + AllowEmailAddresses: boolean; // false, PPMRU: SPClientPeoplePickerMRU; - UseLocalSuggestionCache: boolean; //true, - CurrentQueryStr: string; //'', + UseLocalSuggestionCache: boolean; // true, + CurrentQueryStr: string; // '', LatestSearchQueryStr: string; // '', InitialSuggestions: ISPClientPeoplePickerEntity[]; CurrentLocalSuggestions: ISPClientPeoplePickerEntity[]; CurrentLocalSuggestionsDict: ISPClientPeoplePickerEntity; - VisibleSuggestions: number; //5, - PrincipalAccountType: string; //'', + VisibleSuggestions: number; // 5, + PrincipalAccountType: string; // '', PrincipalAccountTypeEnum: SP.Utilities.PrincipalType; - EnabledClaimProviders: string; //'', - SearchPrincipalSource: SP.Utilities.PrincipalSource; //null, - ResolvePrincipalSource: SP.Utilities.PrincipalSource; //null, - MaximumEntitySuggestions: number; //30, - EditorWidthSet: boolean; //false, - QueryScriptInit: boolean; //false, - AutoFillControl: SPClientAutoFill; //null, - TotalUserCount: number; //0, - UnresolvedUserCount: number; //0, + EnabledClaimProviders: string; // '', + SearchPrincipalSource: SP.Utilities.PrincipalSource; // null, + ResolvePrincipalSource: SP.Utilities.PrincipalSource; // null, + MaximumEntitySuggestions: number; // 30, + EditorWidthSet: boolean; // false, + QueryScriptInit: boolean; // false, + AutoFillControl: SPClientAutoFill; // null, + TotalUserCount: number; // 0, + UnresolvedUserCount: number; // 0, UserQueryDict: { [index: string]: SP.StringResult }; ProcessedUserList: { [index: string]: SPClientPeoplePickerProcessedUser }; - HasInputError: boolean; //false, - HasServerError: boolean; //false, - ShowUserPresence: boolean; //true, - TerminatingCharacter: string; //';', - UnresolvedUserElmIdToReplace: string; //'', - WebApplicationID: SP.Guid; //'{00000000-0000-0000-0000-000000000000}', + HasInputError: boolean; // false, + HasServerError: boolean; // false, + ShowUserPresence: boolean; // true, + TerminatingCharacter: string; // ';', + UnresolvedUserElmIdToReplace: string; // '', + WebApplicationID: SP.Guid; // '{00000000-0000-0000-0000-000000000000}', GetAllUserInfo(): ISPClientPeoplePickerEntity[]; SetInitialValue(entities: ISPClientPeoplePickerEntity[], initialErrorMsg?: string): void @@ -9482,9 +9482,9 @@ interface ISPClientPeoplePickerSchema { } declare class SPClientPeoplePickerMRU { - static PPMRUVersion: number; //= 1; - static MaxPPMRUItems: number; //= 200; - static PPMRUDomLocalStoreKey: string; //= "ClientPeoplePickerMRU"; + static PPMRUVersion: number; // = 1; + static MaxPPMRUItems: number; // = 200; + static PPMRUDomLocalStoreKey: string; // = "ClientPeoplePickerMRU"; static GetSPClientPeoplePickerMRU(): SPClientPeoplePickerMRU; GetItems(strKey: string): { Key: string, [name: string]: any }; @@ -9513,18 +9513,18 @@ interface ISPClientPeoplePickerEntity { } declare class SPClientPeoplePickerProcessedUser { - UserContainerElementId: string; //'', - DisplayElementId: string; //'', - PresenceElementId: string; //'', - DeleteUserElementId: string; //'', - SID: string; //'', - DisplayName: string; //'', - SIPAddress: string; //'', - UserInfo: ISPClientPeoplePickerEntity; //null, - ResolvedUser: boolean; //true, - Suggestions: ISPClientAutoFillData[]; //null, - ErrorDescription: string; //'', - ResolveText: string; //'', + UserContainerElementId: string; // '', + DisplayElementId: string; // '', + PresenceElementId: string; // '', + DeleteUserElementId: string; // '', + SID: string; // '', + DisplayName: string; // '', + SIPAddress: string; // '', + UserInfo: ISPClientPeoplePickerEntity; // null, + ResolvedUser: boolean; // true, + Suggestions: ISPClientAutoFillData[]; // null, + ErrorDescription: string; // '', + ResolveText: string; // '', UpdateResolvedUser(newUserInfo: ISPClientPeoplePickerEntity, strNewElementId: string): void; UpdateSuggestions(entity: ISPClientPeoplePickerEntity): void; BuildUserHTML(): string; @@ -9713,126 +9713,126 @@ declare namespace SP { export namespace JsGrid { export enum TextDirection { - Default, //0, - RightToLeft, //1, - LeftToRight //2 + Default, // 0, + RightToLeft, // 1, + LeftToRight // 2 } export enum PaneId { - MainGrid, //0, - PivotedGrid, //1, - Gantt //2 + MainGrid, // 0, + PivotedGrid, // 1, + Gantt // 2 } export enum PaneLayout { - GridOnly, //0, - GridAndGantt, //1, - GridAndPivotedGrid //2 + GridOnly, // 0, + GridAndGantt, // 1, + GridAndPivotedGrid // 2 } export enum EditMode { - ReadOnly, //0, - ReadWrite, //1, - ReadOnlyDefer, //2, - ReadWriteDefer, //3, - Defer //4 + ReadOnly, // 0, + ReadWrite, // 1, + ReadOnlyDefer, // 2, + ReadWriteDefer, // 3, + Defer // 4 } export enum GanttDrawBarFlags { - LeftLink, //0x01, - RightLink //0x02 + LeftLink, // 0x01, + RightLink // 0x02 } export enum GanttBarDateType { - Start, //0, - End //1 + Start, // 0, + End // 1 } export enum ValidationState { - Valid, //0, - Pending, //1, - Invalid //2 + Valid, // 0, + Pending, // 1, + Invalid // 2 } export enum HierarchyMode { - None, //0, - Standard, //1, - Grouping //2 + None, // 0, + Standard, // 1, + Grouping // 2 } export enum EditActorWriteType { - Both, //1, - LocalizedOnly, //2, - DataOnly, //3, - Either //4 + Both, // 1, + LocalizedOnly, // 2, + DataOnly, // 3, + Either // 4 } export enum EditActorReadType { - Both, //1, - LocalizedOnly, //2, - DataOnly //3 + Both, // 1, + LocalizedOnly, // 2, + DataOnly // 3 } export enum EditActorUpdateType { - Committed, //0, - Uncommitted, //1 + Committed, // 0, + Uncommitted, // 1 } export enum SortMode { - Ascending, //1, - Descending, //-1, - None //0 + Ascending, // 1, + Descending, // -1, + None // 0 } export namespace RowHeaderStyleId { - export var Transfer: string; //'Transfer', - export var Conflict: string; //'Conflict' + export var Transfer: string; // 'Transfer', + export var Conflict: string; // 'Conflict' } export namespace RowHeaderAutoStyleId { - export var Dirty: string; //'Dirty', - export var Error: string; //'Error', - export var NewRow: string; //'NewRow' + export var Dirty: string; // 'Dirty', + export var Error: string; // 'Error', + export var NewRow: string; // 'NewRow' } export enum RowHeaderStatePriorities { - Dirty, //10, - Transfer, //30, - CellError, //40, - Conflict, //50, - RowError, //60, - NewRow //90 + Dirty, // 10, + Transfer, // 30, + CellError, // 40, + Conflict, // 50, + RowError, // 60, + NewRow // 90 } export enum UpdateSerializeMode { - Cancel, //0, - Default, //1, - PropDataOnly, //2, - PropLocalizedOnly, //3, - PropBoth //4 + Cancel, // 0, + Default, // 1, + PropDataOnly, // 2, + PropLocalizedOnly, // 3, + PropBoth // 4 } export enum UpdateTrackingMode { - PropData, //2, - PropLocalized, //3, - PropBoth //4 + PropData, // 2, + PropLocalized, // 3, + PropBoth // 4 } export namespace UserAction { - export var UserEdit: string; //'User Edit':string; - export var DeleteRecord: string; //'Delete Record':string; - export var InsertRecord: string; //'Insert Record':string; - export var Indent: string; //'Indent':string; - export var Outdent: string; //'Outdent':string; - export var Fill: string; //'Fill':string; - export var Paste: string; //'Paste':string; - export var CutPaste: string; //'Cut/Paste' + export var UserEdit: string; // 'User Edit':string; + export var DeleteRecord: string; // 'Delete Record':string; + export var InsertRecord: string; // 'Insert Record':string; + export var Indent: string; // 'Indent':string; + export var Outdent: string; // 'Outdent':string; + export var Fill: string; // 'Fill':string; + export var Paste: string; // 'Paste':string; + export var CutPaste: string; // 'Cut/Paste' } export enum ReadOnlyActiveState { - ReadOnlyActive, //0, - ReadOnlyDisabled, //1 + ReadOnlyActive, // 0, + ReadOnlyDisabled, // 1 } // tslint:disable-next-line: interface-name @@ -10403,15 +10403,15 @@ declare namespace SP { gridFieldMap: { [name: string]: GridField }; columns: ColumnInfoCollection; - messageOverrides: any; //TODO - operationalConstantsFieldKeyMap: any; //TODO + messageOverrides: any; // TODO + operationalConstantsFieldKeyMap: any; // TODO ganttParams: GanttParameters; pivotedGridParams: PivotedGridParameters; rowViewParams: RowViewParameters; } export class PivotedGridParameters { - //this.dateRange = null; + // this.dateRange = null; // this.ganttBarStyles = null; // this.ganttZoomLevel = 3; // this.fnRenderGanttRow = null; @@ -10883,7 +10883,7 @@ declare namespace SP { bHyperlink: boolean; DataToLocalized(dataValue: any): string; GetAddress(dataValue: any): string; - /** Returns string like this: '"http://site.com, Site title"' */ + /** Returns string like this: '"http:// site.com, Site title"' */ GetCopyValue(record: IRecord, dataValue: any, locValue: string): string; toString(): string; } @@ -10950,7 +10950,7 @@ declare namespace SP { export interface IEditControlCellContext extends IEditActorCellContext { cellWidth: number; cellHeight: number; - cellStyle: any; //TODO: Determine correct type + cellStyle: any; // TODO: Determine correct type cellRect: any; NotifyExpandControl(): void; NotifyEditComplete(): void; diff --git a/sharepoint/sharepoint-tests.ts b/sharepoint/sharepoint-tests.ts index 9d75197d89..4c028d977c 100644 --- a/sharepoint/sharepoint-tests.ts +++ b/sharepoint/sharepoint-tests.ts @@ -3,8 +3,8 @@ import * as angular from 'angular'; import * as ng from 'angular'; -//code from http://sptypescript.codeplex.com/ -//BasicTasksJSOM.ts +// code from http://sptypescript.codeplex.com/ +// BasicTasksJSOM.ts // Website tasks function retrieveWebsite(resultpanel: HTMLElement) { var clientContext = SP.ClientContext.get_current(); @@ -613,7 +613,7 @@ namespace CSR { } - //typescripttempltes.ts + // typescripttempltes.ts declare var Strings: any; export function getFieldValue(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): any { if (ctx.ControlMode === SPClientTemplates.ClientControlMode.EditForm @@ -674,7 +674,7 @@ namespace CSR { export function getControl(schema: SPClientTemplates.FieldSchema_InForm): HTMLInputElement { var id = schema.Name + '_' + schema.Id + '_$' + schema.FieldType + 'Field'; - //TODO: Handle different input types + // TODO: Handle different input types return $get(id) as HTMLInputElement; } @@ -782,7 +782,7 @@ namespace CSR { return this.onPreRender((ctx: SPClientTemplates.RenderContext) => { var ctxInView = ctx as SPClientTemplates.RenderContext_InView; - //ListSchema schma exists in Form and in View render context + // ListSchema schma exists in Form and in View render context var fields = ctxInView.ListSchema.Field; if (fields) { for (var innerField of fields) { @@ -798,7 +798,7 @@ namespace CSR { return this.onPostRender((ctx: SPClientTemplates.RenderContext) => { var ctxInView = ctx as SPClientTemplates.RenderContext_InView; - //ListSchema schma exists in Form and in View render context + // ListSchema schma exists in Form and in View render context var fields = ctxInView.ListSchema.Field; if (fields) { for (var innerField of fields) { @@ -821,7 +821,7 @@ namespace CSR { if (ctx.ControlMode === SPClientTemplates.ClientControlMode.View) { var ctxInView = ctx as SPClientTemplates.RenderContext_InView; if (ctxInView.inGridMode) { - //TODO: Disable editing in grid mode + // TODO: Disable editing in grid mode } @@ -869,7 +869,7 @@ namespace CSR { var ctxInView = ctx as SPClientTemplates.RenderContext_InView; if (ctxInView.inGridMode) { - //TODO: Hide item in grid mode + // TODO: Hide item in grid mode } else { ctxInView.ListSchema.Field.splice(ctxInView.ListSchema.Field.indexOf(schema), 1); } @@ -1014,7 +1014,7 @@ namespace CSR { } else { var ctx = SP.ClientContext.get_current(); var web = ctx.get_web(); - //TODO: Handle lookup to another web + // TODO: Handle lookup to another web var list = web.get_lists().getById(listId); var item = list.getItemById(parseInt(value, 10)); var field = list.get_fields().getByInternalNameOrTitle(expressionParts.shift()); @@ -1059,7 +1059,7 @@ namespace CSR { pendingLoads++; var ctx = SP.ClientContext.get_current(); - //TODO: Handle lookup to another web + // TODO: Handle lookup to another web var web = ctx.get_web(); var listId = _schema.LookupListId; var list = !listname ? web.get_lists().getById(listId) : web.get_lists().getByTitle(listname); @@ -1070,7 +1070,7 @@ namespace CSR { return dependencyValues[expr] ? dependencyValues[expr] : ''; }); - //TODO: Handle ShowField attribure + // TODO: Handle ShowField attribure if (predicate.substr(0, 5) === ''); @@ -1336,14 +1336,14 @@ namespace CSR { query.set_queryText('contentclass:STS_ListItem ListID:{' + _schema.LookupListId + '} ' + value); var selectProps = query.get_selectProperties(); selectProps.clear(); - //TODO: Handle ShowField attribute + // TODO: Handle ShowField attribute selectProps.add('Title'); selectProps.add('ListItemId'); var executor = new Search.SearchExecutor(ctx); var result = executor.executeQuery(query); ctx.executeQueryAsync( () => { - //TODO: Discover proper way to load collection + // TODO: Discover proper way to load collection var tableCollection = new Search.ResultTableCollection(); tableCollection.initPropertiesFromJson(result.get_value()); @@ -1711,7 +1711,7 @@ if (typeof SP === 'object' && SP && typeof SP.SOD === 'object' && SP.SOD) { } -//mquery.ts +// mquery.ts @@ -1822,7 +1822,7 @@ m$.ready(() => { }); -//whoisapppart.ts +// whoisapppart.ts namespace _ { @@ -1842,7 +1842,7 @@ namespace _ { } }); - //Load the people picker + // Load the people picker function loadPeoplePicker(peoplePickerElementId: string) { var schema: ISPClientPeoplePickerSchema = { PrincipalAccountType: "User", @@ -1881,7 +1881,7 @@ namespace _ { var properties = personProperties.get_userProfileProperties(); var messageText = ""; for (var key in properties) { - if(properties.hasOwnProperty(key)) + if (properties.hasOwnProperty(key)) continue; messageText += "
[" + key + "]: \"" + properties[key] + "\""; } @@ -1916,12 +1916,12 @@ namespace _ { function prepareVisual() { if (isIframe) { - //Create a Link element for the defaultcss.ashx resource + // Create a Link element for the defaultcss.ashx resource var linkElement = document.createElement('link'); linkElement.setAttribute('rel', 'stylesheet'); linkElement.setAttribute('href', spHostUrl + '/_layouts/15/defaultcss.ashx'); - //Add the linkElement as a child to the head section of the html + // Add the linkElement as a child to the head section of the html document.head.appendChild(linkElement); } else { @@ -1953,7 +1953,7 @@ namespace _ { } } -//taxonomy +// taxonomy namespace MySP { // Class @@ -2261,7 +2261,7 @@ namespace _ { }; -//publishing.ts +// publishing.ts // Variables used in various callbacks JSRequest.EnsureSetup(); @@ -2332,7 +2332,7 @@ function createPage(evt) { }); } -//likes +// likes namespace SampleReputation { interface MyList extends SPClientTemplates.RenderContext_InView { @@ -2428,7 +2428,7 @@ namespace SampleReputation { -//code from https://github.com/gandjustas/SharePointAngularTS +// code from https://github.com/gandjustas/SharePointAngularTS namespace App { "use strict"; var app = angular.module("app", []); diff --git a/shipit/index.d.ts b/shipit/index.d.ts index 8c614f1627..32180d140d 100644 --- a/shipit/index.d.ts +++ b/shipit/index.d.ts @@ -7,57 +7,54 @@ import * as fs from "fs"; import * as child_process from "child_process"; +import * as shipit from "."; // Used for `typeof shipit` -declare namespace shipit { - type LocalOrRemoteCommand = (command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void) => PromiseLike; - type EmptyCallback = () => void; - type TaskExecution = (name: string, depsOrFn: string[] | EmptyCallback, fn: () => void) => any; +type LocalOrRemoteCommand = (command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void) => PromiseLike; +type EmptyCallback = () => void; +type TaskExecution = (name: string, depsOrFn: string[] | EmptyCallback, fn: () => void) => any; - interface Options { - environment: string; - stderr: fs.WriteStream; - stdout: fs.WriteStream; - } - - interface ShipitLocal { - child: child_process.ChildProcess; - stderr: fs.WriteStream; - stdout: fs.WriteStream; - } - - interface Tasks { - [name: string]: Task; - } - - interface Task { - blocking: boolean; - dep: string[]; - fn: () => void; - name: string; - } - - export function blTask(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): any; - export function emit(name: string): any; - export function initConfig(config: {}): typeof shipit; - export function local(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; - export function log(log: any): void; - export function log(...log: any[]): void; - export function on(name: string, callback: (e: any) => void): any; - export function remote(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; - export function remoteCopy(src: string, dest: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; - export function start(tasks: string | string[]): typeof shipit; - export function start(...tasks: string[]): typeof shipit; - export function task(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): typeof shipit; - - export var config: {}; - export var domain: any; - export var doneCallback: any; - export var environment: string; - export var seq: any[]; - export var tasks: Tasks; - export var isRunning: boolean; +interface Options { + environment: string; + stderr: fs.WriteStream; + stdout: fs.WriteStream; } -//tslint:disable-next-line:export-just-namespace -export = shipit; +interface ShipitLocal { + child: child_process.ChildProcess; + stderr: fs.WriteStream; + stdout: fs.WriteStream; +} + +interface Tasks { + [name: string]: Task; +} + +interface Task { + blocking: boolean; + dep: string[]; + fn: () => void; + name: string; +} + +export function blTask(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): any; +export function emit(name: string): any; +export function initConfig(config: {}): typeof shipit; +export function local(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; +export function log(log: any): void; +export function log(...log: any[]): void; +export function on(name: string, callback: (e: any) => void): any; +export function remote(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; +export function remoteCopy(src: string, dest: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; +export function start(tasks: string | string[]): typeof shipit; +export function start(...tasks: string[]): typeof shipit; +export function task(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): typeof shipit; + +export var config: {}; +export var domain: any; +export var doneCallback: any; +export var environment: string; +export var seq: any[]; +export var tasks: Tasks; +export var isRunning: boolean; + export as namespace shipit; diff --git a/simple-oauth2/simple-oauth2-tests.ts b/simple-oauth2/simple-oauth2-tests.ts index 5a733020cc..7a47078a71 100644 --- a/simple-oauth2/simple-oauth2-tests.ts +++ b/simple-oauth2/simple-oauth2-tests.ts @@ -13,7 +13,7 @@ const credentials = { }; // Initialize the OAuth2 Library -//const oauth2 = require('simple-oauth2').create(credentials); +// const oauth2 = require('simple-oauth2').create(credentials); import oauth2lib = require("simple-oauth2"); const oauth2 = oauth2lib.create(credentials); @@ -29,7 +29,7 @@ const oauth2 = oauth2lib.create(credentials); }); // Redirect example using Express (see http://expressjs.com/api.html#res.redirect) - //res.redirect(authorizationUri); + // res.redirect(authorizationUri); // Get the access token object (the authorization code is given from the previous step). const tokenConfig = { diff --git a/strip-ansi/strip-ansi-tests.ts b/strip-ansi/strip-ansi-tests.ts index 6d38a0ed49..12e60b5e82 100644 --- a/strip-ansi/strip-ansi-tests.ts +++ b/strip-ansi/strip-ansi-tests.ts @@ -1,4 +1,4 @@ import stripAnsi = require('strip-ansi'); stripAnsi('\u001b[4mcake\u001b[0m'); -//=> 'cake' \ No newline at end of file +// => 'cake' \ No newline at end of file diff --git a/strip-bom/strip-bom-tests.ts b/strip-bom/strip-bom-tests.ts index dc63d80303..79aaa3daae 100644 --- a/strip-bom/strip-bom-tests.ts +++ b/strip-bom/strip-bom-tests.ts @@ -1,4 +1,4 @@ import stripBom = require('strip-bom'); stripBom('\uFEFFunicorn'); -//=> 'unicorn' \ No newline at end of file +// => 'unicorn' \ No newline at end of file diff --git a/supertest-as-promised/index.d.ts b/supertest-as-promised/index.d.ts index db0bf18e81..385f25867b 100644 --- a/supertest-as-promised/index.d.ts +++ b/supertest-as-promised/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for SuperTest as Promised v2.0.2 +// Type definitions for SuperTest as Promised 2.0 // Project: https://github.com/WhoopInc/supertest-as-promised // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/supertest-as-promised/supertest-as-promised-tests.ts b/supertest-as-promised/supertest-as-promised-tests.ts index d6eb5771c9..c20f9a92b6 100644 --- a/supertest-as-promised/supertest-as-promised-tests.ts +++ b/supertest-as-promised/supertest-as-promised-tests.ts @@ -10,13 +10,13 @@ var app = express(); request(app) .get("/user") .expect(200) - .then(function (res) { + .then(res => { return request(app) .post("/kittens") .send({ userId: res}) .expect(201); }) - .then(function (res) { + .then(res => { // ... }); @@ -25,12 +25,12 @@ request(app) request(app) .get("/kittens") .expect(200) - .then(function (res) { + .then(res => { // ... }); -describe("GET /kittens", function () { - it("should work", function () { +describe("GET /kittens", () => { + it("should work", () => { return request(app).get("/kittens").expect(200); }); }); @@ -41,18 +41,18 @@ var agent = request.agent(app); agent .get("/ugly-kitteh") .expect(404) - .then(function () { + .then(() => { // ... - }) + }); // Promisey goodness request(app) .get("/kittens") .expect(201) - .then(function (res) { /* ... */ }) + .then(res => { /* ... */ }) // I'm a real promise now! - .catch(function (err) { /* ... */ }) + .catch(err => { /* ... */ }); request(app) .get("/kittens") @@ -60,4 +60,4 @@ request(app) .toPromise() // I'm a real promise now! .delay(10) - .then(function (res) { /* ... */ }) + .then(res => { /* ... */ }); diff --git a/supertest-as-promised/tslint.json b/supertest-as-promised/tslint.json new file mode 100644 index 0000000000..9bc375c06b --- /dev/null +++ b/supertest-as-promised/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "no-empty-interface": false + } +} \ No newline at end of file diff --git a/swagger-express-mw/swagger-express-mw-tests.ts b/swagger-express-mw/swagger-express-mw-tests.ts index 78fc26889c..a066071758 100644 --- a/swagger-express-mw/swagger-express-mw-tests.ts +++ b/swagger-express-mw/swagger-express-mw-tests.ts @@ -1,8 +1,8 @@ import * as SwaggerExpress from "swagger-express-mw"; import * as express from "express"; -let app = express(); -let config: SwaggerExpress.Config = { +const app = express(); +const config: SwaggerExpress.Config = { appRoot: __dirname }; @@ -17,12 +17,12 @@ SwaggerExpress.create(config, (err, middleware) => { }); -let swaggerSecurityHandlerCb = (err: Error) => { - //do nothing +const swaggerSecurityHandlerCb = (err: Error) => { + // do nothing }; -let configComplex: SwaggerExpress.Config = { +const configComplex: SwaggerExpress.Config = { appRoot: __dirname, configDir: "some/directory", controllersDirs: ["some/directory"], @@ -32,7 +32,7 @@ let configComplex: SwaggerExpress.Config = { swaggerSecurityHandlers: { // did not manage to research the typings of first 3 arguments someHandlerName: ({}, {}, {}, swaggerSecurityHandlerCb) => { - //do nothing + // do nothing } }, validateResponse: true diff --git a/swagger-hapi/swagger-hapi-tests.ts b/swagger-hapi/swagger-hapi-tests.ts index 0d3e56c40b..3d894aafba 100644 --- a/swagger-hapi/swagger-hapi-tests.ts +++ b/swagger-hapi/swagger-hapi-tests.ts @@ -19,7 +19,7 @@ SwaggerHapi.create(config, (err, swaggerHapi) => { // }; if (swaggerHapi.config.swagger !== undefined) { - let appRootFromMw = swaggerHapi.config.swagger.appRoot; + const appRootFromMw = swaggerHapi.config.swagger.appRoot; } app.register(swaggerHapi.plugin, err => { @@ -29,12 +29,12 @@ SwaggerHapi.create(config, (err, swaggerHapi) => { }); -let swaggerSecurityHandlerCb = (err: Error) => { - //do nothing +const swaggerSecurityHandlerCb = (err: Error) => { + // do nothing }; -let configComplex: SwaggerHapi.Config = { +const configComplex: SwaggerHapi.Config = { appRoot: __dirname, configDir: "some/directory", controllersDirs: ["some/directory"], @@ -44,7 +44,7 @@ let configComplex: SwaggerHapi.Config = { swaggerSecurityHandlers: { // did not manage to research the typings of first 3 arguments someHandlerName: ({}, {}, {}, swaggerSecurityHandlerCb) => { - //do nothing + // do nothing } }, validateResponse: true diff --git a/swagger-node-runner/swagger-node-runner-tests.ts b/swagger-node-runner/swagger-node-runner-tests.ts index 78e9783a45..cff8e9d570 100644 --- a/swagger-node-runner/swagger-node-runner-tests.ts +++ b/swagger-node-runner/swagger-node-runner-tests.ts @@ -5,17 +5,17 @@ import * as Hapi from "hapi"; import * as restify from "restify"; import * as sails from "sails.io.js"; -let config: SwaggerNodeRunner.Config = { +const config: SwaggerNodeRunner.Config = { appRoot: __dirname }; // Express middleware -let expressApp = express(); +const expressApp = express(); SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; // or handle error } - let expressMiddleware = runner.expressMiddleware(); + const expressMiddleware = runner.expressMiddleware(); expressMiddleware.register(expressApp); const port = process.env.PORT || 10010; @@ -23,14 +23,14 @@ SwaggerNodeRunner.create(config, (err, runner) => { }); -//Connect middleware -let connectApp = connect(); +// Connect middleware +const connectApp = connect(); SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; } - let conncetMiddleware = runner.connectMiddleware(); + const connectMiddleware = runner.connectMiddleware(); - conncetMiddleware.register(connectApp); + connectMiddleware.register(connectApp); var port = process.env.PORT || 10010; connectApp.listen(port); }); @@ -40,14 +40,14 @@ SwaggerNodeRunner.create(config, (err, runner) => { SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; } - let sailsMw = runner.sailsMiddleware(); - if(typeof sailsMw.chain !== 'function' || !sailsMw.runner) { + const sailsMw = runner.sailsMiddleware(); + if (typeof sailsMw.chain !== 'function' || !sailsMw.runner) { // do nothing } }); -//Hapi Middleware +// Hapi Middleware var hapiapp = new Hapi.Server(); SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; } @@ -57,13 +57,13 @@ SwaggerNodeRunner.create(config, (err, runner) => { // hapiapp.address = function() { // return { port }; // }; - let hapiMiddleware = runner.hapiMiddleware(); + const hapiMiddleware = runner.hapiMiddleware(); if (hapiMiddleware.config.swagger !== undefined) { - let appRootFromMw = hapiMiddleware.config.swagger.appRoot; + const appRootFromMw = hapiMiddleware.config.swagger.appRoot; } - let pluginAttributes = hapiMiddleware.plugin.register.attributes.name + hapiMiddleware.plugin.register.attributes.version; + const pluginAttributes = hapiMiddleware.plugin.register.attributes.name + hapiMiddleware.plugin.register.attributes.version; hapiapp.register(hapiMiddleware.plugin, err => { if (err) { return console.error("Failed to load plugin:", err); } @@ -73,25 +73,25 @@ SwaggerNodeRunner.create(config, (err, runner) => { // Restify Middelware -let app = restify.createServer(); +const app = restify.createServer(); SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; } - let restifyMiddelware = runner.restifyMiddleware(); + const restifyMiddelware = runner.restifyMiddleware(); restifyMiddelware.register(app); - let port = process.env.PORT || 10010; + const port = process.env.PORT || 10010; app.listen(port); }); -let swaggerSecurityHandlerCb = (err: Error) => { - //do nothing +const swaggerSecurityHandlerCb = (err: Error) => { + // do nothing }; -let configComplex: SwaggerNodeRunner.Config = { +const configComplex: SwaggerNodeRunner.Config = { appRoot: __dirname, configDir: "some/directory", controllersDirs: ["some/directory"], @@ -101,7 +101,7 @@ let configComplex: SwaggerNodeRunner.Config = { swaggerSecurityHandlers: { // did not manage to research the typings of first 3 arguments someHandlerName: ({}, {}, {}, swaggerSecurityHandlerCb) => { - //do nothing + // do nothing } }, validateResponse: true diff --git a/swagger-restify-mw/swagger-restify-mw-tests.ts b/swagger-restify-mw/swagger-restify-mw-tests.ts index f03793e0c9..73568b2153 100644 --- a/swagger-restify-mw/swagger-restify-mw-tests.ts +++ b/swagger-restify-mw/swagger-restify-mw-tests.ts @@ -1,9 +1,9 @@ import * as SwaggerRestify from "swagger-restify-mw"; import * as restify from "restify"; -let app = restify.createServer(); +const app = restify.createServer(); -let config = { +const config = { appRoot: __dirname // required config } as SwaggerRestify.Config; @@ -12,17 +12,17 @@ SwaggerRestify.create(config, (err, swaggerRestify) => { swaggerRestify.register(app); - let port = process.env.PORT || 10010; + const port = process.env.PORT || 10010; app.listen(port); }); -let swaggerSecurityHandlerCb = (err: Error) => { - //do nothing +const swaggerSecurityHandlerCb = (err: Error) => { + // do nothing }; -let configComplex: SwaggerRestify.Config = { +const configComplex: SwaggerRestify.Config = { appRoot: __dirname, configDir: "some/directory", controllersDirs: ["some/directory"], @@ -32,7 +32,7 @@ let configComplex: SwaggerRestify.Config = { swaggerSecurityHandlers: { // did not manage to research the typings of first 3 arguments someHandlerName: ({}, {}, {}, swaggerSecurityHandlerCb) => { - //do nothing + // do nothing } }, validateResponse: true diff --git a/swagger-sails-hook/swagger-sails-hook-tests.ts b/swagger-sails-hook/swagger-sails-hook-tests.ts index ee023047c3..c1b73a08b7 100644 --- a/swagger-sails-hook/swagger-sails-hook-tests.ts +++ b/swagger-sails-hook/swagger-sails-hook-tests.ts @@ -11,8 +11,8 @@ const mockSailsApp = { }; // create and register hook -let swaggerHookRef = swaggerSailsHook(mockSailsApp); -if(typeof swaggerHookRef.routes.after['/*'] === 'function') { +const swaggerHookRef = swaggerSailsHook(mockSailsApp); +if (typeof swaggerHookRef.routes.after['/*'] === 'function') { // right type } diff --git a/swiper/swiper-tests.ts b/swiper/swiper-tests.ts index babe40c5d1..6decd155e0 100644 --- a/swiper/swiper-tests.ts +++ b/swiper/swiper-tests.ts @@ -269,14 +269,14 @@ function thumbsGalleryLoop() { prevButton: '.swiper-button-prev', spaceBetween: 10, loop: true, - loopedSlides: 5, //looped slides should be the same + loopedSlides: 5, // looped slides should be the same }); var galleryThumbs = new Swiper('.gallery-thumbs', { spaceBetween: 10, slidesPerView: 4, touchRatio: 0.2, loop: true, - loopedSlides: 5, //looped slides should be the same + loopedSlides: 5, // looped slides should be the same slideToClickedSlide: true }); galleryTop.params.control = galleryThumbs; @@ -499,7 +499,7 @@ function autoheight() { paginationClickable: true, nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', - autoHeight: true, //enable auto height + autoHeight: true, // enable auto height }); } // 35-effect-flip.html diff --git a/table/table-tests.ts b/table/table-tests.ts index 4dc6541bb5..f3f4662b69 100644 --- a/table/table-tests.ts +++ b/table/table-tests.ts @@ -8,8 +8,6 @@ const data = [ ['john', 'doe'] ]; -const config: table.TableUserConfig = { - border: border -}; +const config: table.TableUserConfig = { border }; table.table(data, config); diff --git a/universal-router/index.d.ts b/universal-router/index.d.ts index 6acba5c179..e9f64a1846 100644 --- a/universal-router/index.d.ts +++ b/universal-router/index.d.ts @@ -1,70 +1,68 @@ -// Type definitions for universal-router +// Type definitions for universal-router 1.2 // Project: https://github.com/kriasoft/universal-router -// Definitions by: Jack Moore +// Definitions by: Jack Moore // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "universal-router" { - /** - * Params is a key/value object that represents extracted URL paramters. Each - * URL parameter resolves to a string. - */ - export interface Params { - [key: string]: string; - } +/** + * Params is a key/value object that represents extracted URL paramters. Each + * URL parameter resolves to a string. + */ +export interface Params { + [key: string]: string; +} - /** - * Context represents the context that is passed as the second argument - * passed to resolve. By default, it only is require to contain a path, but - * can be extended by the way of generics. - */ - export interface Context { - path: string; - } +/** + * Context represents the context that is passed as the second argument + * passed to resolve. By default, it only is require to contain a path, but + * can be extended by the way of generics. + */ +export interface Context { + path: string; +} - /** - * ActionContext is similar to Context, with the exception of an added params - * object. ActionContext is passed as the first argument to the action - * function. - */ - export interface ActionContext extends Context { - params: Params; - } +/** + * ActionContext is similar to Context, with the exception of an added params + * object. ActionContext is passed as the first argument to the action + * function. + */ +export interface ActionContext extends Context { + params: Params; +} - /** - * A Route is a singular route in your application. It contains a path, an - * action function, and optional children which are an array of Route. - * - * @template C User context that is made union with ActionContext. - * @template R Result that every action function resolves to. If the action - * returns a Promise, R can be the type the Promise resolves to. - */ - export interface Route { - path: string; - action: (ctx: ActionContext & C, params: Params) => R | Promise | void; - children?: Routes; - } +/** + * A Route is a singular route in your application. It contains a path, an + * action function, and optional children which are an array of Route. + * + * @template C User context that is made union with ActionContext. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + */ +export interface Route { + path: string; + action: (ctx: ActionContext & C, params: Params) => R | Promise | void; + children?: Routes; +} - /** - * Routes in an array of type Route. - * @template C User context that is made union with ActionContext. - * @template R Result that every action function resolves to. If the action - * returns a Promise, R can be the type the Promise resolves to. - */ - export type Routes = Route[]; +/** + * Routes in an array of type Route. + * @template C User context that is made union with ActionContext. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + */ +export type Routes = Array>; - /** - * Resolve function that is given routes and a path or context object. - * Returns a Promise that resolves to result of the action function of the - * matched route. - * - * @template C User context that is made union with Context. - * @template R Result that every action function resolves to. If the action - * returns a Promise, R can be the type the Promise resolves to. - * - * @param {Routes | Route} routes - Single route or array of routes. - * @param {string | String | Context & C} pathOrContext - path to resolve or - * context object that contains the path along with other data. - * @return {Promise} - Result of matched action function wrapped in a Promsie. - */ - export function resolve(routes: Routes | Route, pathOrContext: string | String | Context & C): Promise -} \ No newline at end of file +/** + * Resolve function that is given routes and a path or context object. + * Returns a Promise that resolves to result of the action function of the + * matched route. + * + * @template C User context that is made union with Context. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + * + * @param {Routes | Route} routes - Single route or array of routes. + * @param {string | String | Context & C} pathOrContext - path to resolve or + * context object that contains the path along with other data. + * @return {Promise} - Result of matched action function wrapped in a Promsie. + */ +export function resolve(routes: Routes | Route, pathOrContext: string | String | Context & C): Promise; diff --git a/universal-router/tsconfig.json b/universal-router/tsconfig.json index 18025f5a22..ca76eb8955 100644 --- a/universal-router/tsconfig.json +++ b/universal-router/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6", "dom" diff --git a/universal-router/tslint.json b/universal-router/tslint.json new file mode 100644 index 0000000000..0f47deabb4 --- /dev/null +++ b/universal-router/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} \ No newline at end of file diff --git a/universal-router/universal-router-tests.ts b/universal-router/universal-router-tests.ts index 2d8870952c..5964ee1a90 100644 --- a/universal-router/universal-router-tests.ts +++ b/universal-router/universal-router-tests.ts @@ -59,7 +59,7 @@ const routes5 = [ async action(ctx: ActionContext, { username }: Params) { const waitable = async (name: string) => { console.log(`Welcome ${name}`); - } + }; await waitable(username); } } diff --git a/webappsec-credential-management/webappsec-credential-management-tests.ts b/webappsec-credential-management/webappsec-credential-management-tests.ts index 2a13e943c3..69cae46daf 100644 --- a/webappsec-credential-management/webappsec-credential-management-tests.ts +++ b/webappsec-credential-management/webappsec-credential-management-tests.ts @@ -70,7 +70,7 @@ function passwordPostSignInConfirmation() { if (navigator.credentials) { e.preventDefault(); - let formElem = (e.target as HTMLFormElement); + const formElem = (e.target as HTMLFormElement); var c = new PasswordCredential(formElem); fetch(formElem.action, {method: 'POST', credentials: c}).then(r => { if (r.status === 200) { diff --git a/webpack/webpack-tests.ts b/webpack/webpack-tests.ts index cb1a264b1e..c1369f78bc 100644 --- a/webpack/webpack-tests.ts +++ b/webpack/webpack-tests.ts @@ -103,7 +103,7 @@ configuration = { } }; -let CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; +const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; configuration = { entry: { p1: "./page1", @@ -221,22 +221,22 @@ configuration = { // https://webpack.github.io/docs/list-of-plugins.html // -let resourceRegExp: any; -let newResource: any; -let contextRegExp: any; -let newContentResource: any; -let newContentRecursive: any; -let newContentRegExp: any; -let requestRegExp: any; -let options: any; -let definitions: any; -let paths: any; -let preferEntry = true; -let context: any; -let request: any; -let types: any; -let banner: any; -let plugins: webpack.Plugin[] = []; +declare const resourceRegExp: any; +declare const newResource: any; +declare const contextRegExp: any; +declare const newContentResource: any; +declare const newContentRecursive: any; +declare const newContentRegExp: any; +declare const requestRegExp: any; +declare const options: any; +declare const definitions: any; +declare const paths: any; +const preferEntry = true; +declare const context: any; +declare const request: any; +declare const types: any; +declare const banner: any; +const plugins: webpack.Plugin[] = []; plugin = new webpack.NormalModuleReplacementPlugin(resourceRegExp, newResource); plugin = new webpack.ContextReplacementPlugin( @@ -338,17 +338,17 @@ plugin = new webpack.ProvidePlugin({ plugin = new webpack.SourceMapDevToolPlugin({ //// asset matching test: /\.js$/, - //include: Condition | Condition[], + // include: Condition | Condition[], exclude: [ /node_modules/ ], // //// file and reference filename: null, // | string - //append: false | string, + // append: false | string, //// sources naming - //moduleFilenameTemplate: string, - //fallbackModuleFilenameTemplate: string, + // moduleFilenameTemplate: string, + // fallbackModuleFilenameTemplate: string, // //// quality/performance module: true, @@ -413,7 +413,7 @@ declare function successfullyCompiled(): void; webpack({ // configuration }, (err, stats) => { - if(err) + if (err) return handleFatalError(err); var jsonStats = stats.toJson(); var jsonStatsWithAllOptions = stats.toJson({ @@ -438,9 +438,9 @@ webpack({ version: true, warnings: true }); - if(jsonStats.errors.length > 0) + if (jsonStats.errors.length > 0) return handleSoftErrors(jsonStats.errors); - if(jsonStats.warnings.length > 0) + if (jsonStats.warnings.length > 0) handleWarnings(jsonStats.warnings); successfullyCompiled(); });