This commit is contained in:
Andy Hanson
2017-02-21 14:48:55 -08:00
parent 82de68c128
commit 59e9cba7cc
130 changed files with 1741 additions and 1783 deletions
+5 -5
View File
@@ -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({
+4 -4
View File
@@ -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()));
}
});
+3 -3
View File
@@ -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<any>) {
$http = $http || $injector.get<ng.IHttpService>('$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<number>;
var condition: boolean;
return condition ? y : x.a; // IPromise<T> | 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
+4 -4
View File
@@ -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;
+7 -7
View File
@@ -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://<mapservice-url>/<layerId1>/images/<imageUrl11>
"imageData"?: string; //"<base64EncodedImageData>";
"url"?: string; // Relative URL for static layers and full URL for dynamic layers. Access relative URL using http://<mapservice-url>/<layerId1>/images/<imageUrl11>
"imageData"?: string; // "<base64EncodedImageData>";
"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; //"<fontFamily>";
"size"?: number; //<fontSize>;
"family"?: string; // "<fontFamily>";
"size"?: number; // <fontSize>;
"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.
}
@@ -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]
};
+1 -1
View File
@@ -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);
+1 -1
View File
@@ -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({
+1 -1
View File
@@ -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;
+1 -1
View File
@@ -1,5 +1,5 @@
import * as assert from 'assert-plus';
let arr = ['one', 'two'];
const arr = ['one', 'two'];
assert.array(arr, '');
+1 -1
View File
@@ -10,4 +10,4 @@ encoded = 'Zm9vIMKpIGJhciDwnYyGIGJheg==';
bytes = base64.decode(encoded);
text = utf8.decode(bytes);
let version = base64.version;
const version = base64.version;
+2 -2
View File
@@ -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();
+3 -3
View File
@@ -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}
// => {_: [], fooBar: true}
+2 -2
View File
@@ -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);
+2 -2
View File
@@ -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 = '<a:test attribute1="1" xmlns:a="test"><a:h1><a:h2>test</a:h2></a:h1></a:test>';
const testXml = '<a:test attribute1="1" xmlns:a="test"><a:h1><a:h2>test</a:h2></a:h1></a:test>';
expect('nope').xml.not.to.be.valid();
expect(testXml).xml.to.be.valid();
expect(testXml).xml.to.equal('<a:test attribute1="1" xmlns:a="test">\n<a:h1><a:h2>test</a:h2></a:h1></a:test>\n');
+4 -4
View File
@@ -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);
+5 -5
View File
@@ -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 <https://github.com/dbrgn/>
// 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;
}
}
+1
View File
@@ -1,6 +1,7 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": [
"es6"
],
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+2 -2
View File
@@ -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()
-4
View File
@@ -1,6 +1,3 @@
/// <reference types="node" />
/// <reference types="co-views" />
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
+15 -21
View File
@@ -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 <https://github.com/devlee/>, Joshua DeVinney <https://github.com/geoffreak>
// 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;
+1
View File
@@ -1,6 +1,7 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": [
"es6"
],
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "../tslint.json",
"rules": {
"forbidden-types": false
}
}
+1 -1
View File
@@ -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();
+13 -13
View File
@@ -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
+1 -1
View File
@@ -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())));
+10 -10
View File
@@ -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 {
+2 -2
View File
@@ -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 <https://github.com/tkqubo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
export interface ClassDecorator {
<TFunction extends Function>(target: TFunction): TFunction | void;
+1
View File
@@ -1,6 +1,7 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": [
"es6",
"dom"
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../tslint.json",
"rules": {
"callable-types": false,
"forbidden-types": false
}
}
+1 -1
View File
@@ -19,6 +19,6 @@ stream = stringify({ delimiter: "," });
stream.write(["1", "2", "3"]);
let transform: NodeJS.ReadWriteStream = stream;
const transform: NodeJS.ReadWriteStream = stream;
stream = stringify();
+15 -15
View File
@@ -54,9 +54,9 @@ axisScaleString = scalePoint();
// --------------------------------------------------------------------------
let containerElement: d3Axis.AxisContainerElement;
const svg: SVGSVGElement = select<SVGSVGElement, any>('svg').node() !; //mock
const g: SVGGElement = select<SVGGElement, any>('g').node() !; //mock
const canvas: HTMLCanvasElement = select<HTMLCanvasElement, any>('canvas').node() !; //mock
const svg: SVGSVGElement = select<SVGSVGElement, any>('svg').node() !; // mock
const g: SVGGElement = select<SVGGElement, any>('g').node() !; // mock
const canvas: HTMLCanvasElement = select<HTMLCanvasElement, any>('canvas').node() !; // mock
containerElement = svg;
containerElement = g;
@@ -78,7 +78,7 @@ let leftAxis: d3Axis.Axis<number | { valueOf(): number }> = d3Axis.axisLeft(scal
// scale(...) ----------------------------------------------------------------
leftAxis = leftAxis.scale(scalePow());
let powerScale: ScalePower<number, number> = leftAxis.scale<ScalePower<number, number>>();
const powerScale: ScalePower<number, number> = leftAxis.scale<ScalePower<number, number>>();
// powerScale = leftAxis.scale(); // fails, without casting as AxisScale is purposely generic
@@ -86,8 +86,8 @@ let powerScale: ScalePower<number, number> = leftAxis.scale<ScalePower<number, n
bottomAxis = bottomAxis.scale(scaleOrdinal<number>());
// bottomAxis = bottomAxis.scale(scalePow()) // fails, domain of scale incompatible with domain of axis
let axisScale: d3Axis.AxisScale<string> = bottomAxis.scale();
let ordinalScale: ScaleOrdinal<string, number> = bottomAxis.scale<ScaleOrdinal<string, number>>();
const axisScale: d3Axis.AxisScale<string> = bottomAxis.scale();
const ordinalScale: ScaleOrdinal<string, number> = bottomAxis.scale<ScaleOrdinal<string, number>>();
// 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<SVGGElement, any, any, any> = select<SVGGElement, any>('g');
let gTransition = gSelection.transition();
const gSelection: Selection<SVGGElement, any, any, any> = select<SVGGElement, any>('g');
const gTransition = gSelection.transition();
gSelection.call(topAxis);
gTransition.call(topAxis);
let svgSelection: Selection<SVGSVGElement, any, any, any> = select<SVGSVGElement, any>('g');
let svgTransition = svgSelection.transition();
const svgSelection: Selection<SVGSVGElement, any, any, any> = select<SVGSVGElement, any>('g');
const svgTransition = svgSelection.transition();
svgSelection.call(leftAxis);
svgTransition.call(leftAxis);
let canvasSelection: Selection<HTMLCanvasElement, any, any, any> = select<HTMLCanvasElement, any>('canvas');
let canvasTransition = canvasSelection.transition();
const canvasSelection: Selection<HTMLCanvasElement, any, any, any> = select<HTMLCanvasElement, any>('canvas');
const canvasTransition = canvasSelection.transition();
// canvasSelection.call(rightAxis); // fails, incompatible context container element
// canvasTransition.call(rightAxis); // fails, incompatible context container element
+28 -28
View File
@@ -26,9 +26,9 @@ interface BrushDatum {
let brush: d3Brush.BrushBehavior<BrushDatum> = d3Brush.brush<BrushDatum>();
let brushX: d3Brush.BrushBehavior<BrushDatum> = d3Brush.brushX<BrushDatum>();
const brushX: d3Brush.BrushBehavior<BrushDatum> = d3Brush.brushX<BrushDatum>();
let brushY: d3Brush.BrushBehavior<BrushDatum> = d3Brush.brushY<BrushDatum>();
const brushY: d3Brush.BrushBehavior<BrushDatum> = d3Brush.brushY<BrushDatum>();
// 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 = <d3Brush.D3BrushEvent<BrushDatum>> event;
const e = <d3Brush.D3BrushEvent<BrushDatum>> 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<SVGGElement>) => void) | undefined;
brushed = function(d, i, group) {
brushed = (d, i, group) => {
// do anything
};
let wrongHandler1: (this: SVGSVGElement, datum: BrushDatum, index: number, group: SVGSVGElement[] | ArrayLike<SVGSVGElement>) => void;
let wrongHandler2: (this: SVGGElement, datum: { test: string }, index: number, group: SVGGElement[] | ArrayLike<SVGGElement>) => void;
// let wrongHandler1: (this: SVGSVGElement, datum: BrushDatum, index: number, group: SVGSVGElement[] | ArrayLike<SVGSVGElement>) => void;
// let wrongHandler2: (this: SVGGElement, datum: { test: string }, index: number, group: SVGGElement[] | ArrayLike<SVGGElement>) => 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<SVGGElement> = g;
const that: SVGGElement = this;
const datum: BrushDatum = d;
const index: number = i;
const group: SVGGElement[] | ArrayLike<SVGGElement> = 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<SVGSVGElement, any>('svg')
const g = select<SVGSVGElement, any>('svg')
.append<SVGGElement>('g')
.classed('brush', true)
.datum<BrushDatum>({
@@ -113,7 +113,7 @@ let g = select<SVGSVGElement, any>('svg')
g.call(brush);
let gX = select<SVGSVGElement, any>('svg')
const gX = select<SVGSVGElement, any>('svg')
.append<SVGGElement>('g')
.classed('brush', true)
.datum<BrushDatum>({
@@ -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<BrushDatum> = event;
const e: d3Brush.D3BrushEvent<BrushDatum> = event;
let target: d3Brush.BrushBehavior<BrushDatum> = 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<BrushDatum> = e.target;
const type: 'start' | 'brush' | 'end' | string = e.type;
const brushSelection: d3Brush.BrushSelection = e.selection;
const sourceEvent: any = e.sourceEvent;
+7 -7
View File
@@ -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<SVGPathElement, d3Chord.Chord, SVGGElement, d3Chord.C
ribbonPaths = select<SVGGElement, any>('g')
.datum(chords)
.selectAll()
.data(function (chords) { return chords; })
.data(chords => chords)
.enter().append<SVGPathElement>('path')
.attr('d', svgRibbon);
+20 -20
View File
@@ -38,9 +38,9 @@ interface CustomSubject {
r: number;
}
let svg: SVGSVGElement = select<SVGSVGElement, any>('svg').node()!; // mock
const svg: SVGSVGElement = select<SVGSVGElement, any>('svg').node()!; // mock
let circles: Selection<SVGCircleElement, CircleDatum, SVGSVGElement, any> = select<SVGSVGElement, any>('svg').selectAll<SVGCircleElement, CircleDatum>('circle'); // mock
const circles: Selection<SVGCircleElement, CircleDatum, SVGSVGElement, any> = select<SVGSVGElement, any>('svg').selectAll<SVGCircleElement, CircleDatum>('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 = <d3Drag.D3DragEvent<SVGCircleElement, CircleDatum, CustomSubject | d3Drag.SubjectPosition>> event;
let that: SVGCircleElement = this;
let datum: CircleDatum = d;
let index: number = i;
let group: SVGCircleElement[] | ArrayLike<SVGCircleElement> = g;
const e = <d3Drag.D3DragEvent<SVGCircleElement, CircleDatum, CustomSubject | d3Drag.SubjectPosition>> event;
const that: SVGCircleElement = this;
const datum: CircleDatum = d;
const index: number = i;
const group: SVGCircleElement[] | ArrayLike<SVGCircleElement> = 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 = <d3Drag.D3DragEvent<SVGCircleElement, CircleDatum, CircleDatum | d3Drag.SubjectPosition>> event;
const e = <d3Drag.D3DragEvent<SVGCircleElement, CircleDatum, CircleDatum | d3Drag.SubjectPosition>> 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 = <d3Drag.D3DragEvent<SVGCircleElement, CircleDatum, CircleDatum | d3Drag.SubjectPosition>> event;
const e = <d3Drag.D3DragEvent<SVGCircleElement, CircleDatum, CircleDatum | d3Drag.SubjectPosition>> 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<HTMLDivElement, any, any, any> = select<HTMLDivElement, any>('div');
const wrongSelection: Selection<HTMLDivElement, any, any, any> = select<HTMLDivElement, any>('div');
// wrongSelection.call(circleDrag); // fails, as dragged elements are not of type specified for drag behavior
@@ -197,15 +197,15 @@ let e: d3Drag.D3DragEvent<SVGCircleElement, CircleDatum, CircleDatum | d3Drag.Su
circleDrag = e.target; // target return drag behavior
let type: string = e.type;
let subject: CircleDatum | d3Drag.SubjectPosition = e.subject;
let x: number = e.x;
let y: number = e.y;
let dx: number = e.dx;
let dy: number = e.dy;
let identified: 'mouse' | number = e.identifier;
let active: number = e.active;
let sourceEvent: any = e.sourceEvent;
const type: string = e.type;
const subject: CircleDatum | d3Drag.SubjectPosition = e.subject;
const x: number = e.x;
const y: number = e.y;
const dx: number = e.dx;
const dy: number = e.dy;
const identified: 'mouse' | number = e.identifier;
const active: number = e.active;
const sourceEvent: any = e.sourceEvent;
// register temporary event listeners (i.e. for current drag gesture in progress only)
// As always, the below tests are for signature only, no functional purpose
@@ -226,7 +226,7 @@ handler = e.on('dragged');
// Test dragDisable() and dragEnable()
// -----------------------------------------------------------------------------
let w: Window = window;
const w: Window = window;
d3Drag.dragDisable(w);
+27 -51
View File
@@ -13,13 +13,13 @@ import * as d3Dsv from 'd3-dsv';
// ------------------------------------------------------------------------------------------
let csvTestString: string = '1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38';
let tsvTestString: string = '1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38';
let pipedTestString: string = '1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38';
const csvTestString: string = '1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38';
const tsvTestString: string = '1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38';
const pipedTestString: string = '1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38';
let csvTestStringWithHeader: string = 'Year,Make,Model,Length\n1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38';
let tsvTestStringWithHeader: string = 'Year\tMake\tModel\tLength\n1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38';
let pipedTestStringWithHeader: string = 'Year|Make|Model|Length\n1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38';
const csvTestStringWithHeader: string = 'Year,Make,Model,Length\n1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38';
const tsvTestStringWithHeader: string = 'Year\tMake\tModel\tLength\n1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38';
const pipedTestStringWithHeader: string = 'Year|Make|Model|Length\n1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38';
interface ParsedTestObject {
year: Date;
@@ -58,20 +58,16 @@ str = parseArray[0]['Year'];
// with row mapper ---------------------------------------------------------------------------
parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, (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;
@@ -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;
+1 -1
View File
@@ -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);
+39 -39
View File
@@ -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<SimNode>(15);
// with radius accessor function
forceCollide = d3Force.forceCollide<SimNode>((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<SimNode, SimLink>(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<SimNode>();
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<SimNode>();
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<SimNode, SimLink> = this;
const that: d3Force.Simulation<SimNode, SimLink> = 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<SimNode, undefined>) => void) | undefined = nodeSimulation.on('tick');
const listener: ((this: d3Force.Simulation<SimNode, undefined>) => void) | undefined = nodeSimulation.on('tick');
// Configure and Use Force Simulation ===================================================
+20 -21
View File
@@ -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<number, string> = linearScaleNumString.copy();
const copiedLinearScale: d3Scale.ScaleLinear<number, string> = linearScaleNumString.copy();
// -------------------------------------------------------------------------------
// Power Scale Factories
@@ -194,7 +193,7 @@ squarerootScaleNumString = d3Scale.scaleSqrt<number, string>();
// 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<number, string> = powerScaleNumString.copy();
const copiedPowerScale: d3Scale.ScalePower<number, string> = powerScaleNumString.copy();
// -------------------------------------------------------------------------------
// Logarithmic Scale Factory
@@ -299,7 +298,7 @@ logScaleNumString = d3Scale.scaleLog<number, string>();
// 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<number, string> = logScaleNumString.copy();
const copiedLogScale: d3Scale.ScaleLogarithmic<number, string> = 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<number, string> = localTimeScaleNumString.copy();
const copiedTimeScale: d3Scale.ScaleTime<number, string> = 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<string> = sequentialScaleColorString.copy();
const copiedSequentialScale: d3Scale.ScaleSequential<string> = sequentialScaleColorString.copy();
@@ -640,7 +639,7 @@ quantizeScaleString = d3Scale.scaleQuantize<string>();
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<number> = quantizeScaleNumber.copy();
const copiedQuantizeScale: d3Scale.ScaleQuantize<number> = 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<number> = quantileScaleNumber.copy();
const copiedQuantileScale: d3Scale.ScaleQuantile<number> = quantileScaleNumber.copy();
// -------------------------------------------------------------------------------
@@ -780,7 +779,7 @@ outputString = thresholdScaleNumberString(0.9);
// copy(...) -----------------------------------------------------------------
let copiedThresholdScale: d3Scale.ScaleThreshold<number, string> = thresholdScaleNumberString.copy();
const copiedThresholdScale: d3Scale.ScaleThreshold<number, string> = 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<string, number> = ordinalScaleStringNumber.copy();
const copiedOrdinalScale: d3Scale.ScaleOrdinal<string, number> = ordinalScaleStringNumber.copy();
// -------------------------------------------------------------------------------
@@ -920,7 +919,7 @@ outputNumberMaybe = bandScaleCoercible(new StringCoercible('negative'));
// copy(...) -----------------------------------------------------------------
let copiedBandScale: d3Scale.ScaleBand<StringCoercible> = bandScaleCoercible.copy();
const copiedBandScale: d3Scale.ScaleBand<StringCoercible> = bandScaleCoercible.copy();
// -------------------------------------------------------------------------------
@@ -991,7 +990,7 @@ outputNumberMaybe = pointScaleCoercible(new StringCoercible('negative'));
// copy(...) -----------------------------------------------------------------
let copiedPointScale: d3Scale.ScalePoint<StringCoercible> = pointScaleCoercible.copy();
const copiedPointScale: d3Scale.ScalePoint<StringCoercible> = pointScaleCoercible.copy();
// -------------------------------------------------------------------------------
// Categorical Color Schemas for Ordinal Scales
+30 -30
View File
@@ -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<HTMLAnchorElement> = g;
selection = selection.attrs(function(d, i, g) {
const that: HTMLAnchorElement = this;
const index: number = i;
const group: HTMLAnchorElement[] | ArrayLike<HTMLAnchorElement> = 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<HTMLAnchorElement> = g;
selection = selection.properties(function(d, i, g) {
const that: HTMLAnchorElement = this;
const index: number = i;
const group: HTMLAnchorElement[] | ArrayLike<HTMLAnchorElement> = 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<HTMLAnchorElement> = g;
transition = transition.attrs(function(d, i, g) {
const that: HTMLAnchorElement = this;
const index: number = i;
const group: HTMLAnchorElement[] | ArrayLike<HTMLAnchorElement> = 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<SVGCircleElement> = g;
bar3(d, i, g) {
const that: SVGCircleElement = this;
const datum: SampleDatum = d;
const index: number = i;
const group: SVGCircleElement[] | ArrayLike<SVGCircleElement> = 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];
// }
+199 -211
View File
@@ -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<HTMLElement, any, null, undefined> = d3Selection.selection();
const topSelection: d3Selection.Selection<HTMLElement, any, null, undefined> = 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.BaseType, any, HTMLElement, any> = d3Selection.select('body');
const baseTypeEl: d3Selection.Selection<d3Selection.BaseType, any, HTMLElement, any> = 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<HTMLBodyElement, BodyDatum, HTMLElement, any> =
// 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.BaseType, any, null, undefined> = d3Selection.select(baseTypeEl.node());
const baseTypeEl2: d3Selection.Selection<d3Selection.BaseType, any, null, undefined> = d3Selection.select(baseTypeEl.node());
// let body2: d3Selection.Selection<HTMLElement, any, null, undefined> = d3Selection.select(baseTypeEl.node()); // fails as baseTypeEl.node() is of type cannot be assigned to HTMLElement
let body3: d3Selection.Selection<HTMLBodyElement, any, null, undefined> = d3Selection.select(body.node()!); // element types match, but datum is of type 'any' as it cannot be inferred from .node()
const body3: d3Selection.Selection<HTMLBodyElement, any, null, undefined> = 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<HTMLBodyElement, BodyDatum, null, undefined> = d3Selection.select<HTMLBodyElement, BodyDatum>(body.node()!);
const body4: d3Selection.Selection<HTMLBodyElement, BodyDatum, null, undefined> = d3Selection.select<HTMLBodyElement, BodyDatum>(body.node()!);
// Explicitly cast body.node() to HTMLBodyElement to narrow selection definition.
let body5: d3Selection.Selection<HTMLBodyElement, BodyDatum, null, undefined> = d3Selection.select<HTMLBodyElement, BodyDatum>(body.node()!);
const body5: d3Selection.Selection<HTMLBodyElement, BodyDatum, null, undefined> = d3Selection.select<HTMLBodyElement, BodyDatum>(body.node()!);
// d3Selection.select<HTMLBodyElement, BodyDatum>(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.BaseType, any, HTMLElement, any> = d3Selection.selectAll('div');
const baseTypeElements: d3Selection.Selection<d3Selection.BaseType, any, HTMLElement, any> = 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<HTMLDivElement, DivDatum, HTMLElement, any> = d3Selection.selectAll<HTMLDivElement, DivDatum>('div');
const divElements: d3Selection.Selection<HTMLDivElement, DivDatum, HTMLElement, any> = d3Selection.selectAll<HTMLDivElement, DivDatum>('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.BaseType, any, null, undefined> = d3Selection.selectAll(baseTypeElements.nodes());
const baseTypeElements2: d3Selection.Selection<d3Selection.BaseType, any, null, undefined> = d3Selection.selectAll(baseTypeElements.nodes());
// let divElements2: d3Selection.Selection<HTMLDivElement, any, null, undefined> = d3Selection.selectAll(baseTypeElements.nodes()); // fails, group elements types not of compatible for baseTypeElements
let divElements3: d3Selection.Selection<HTMLDivElement, any, null, undefined> = d3Selection.selectAll(divElements.nodes()); // element types match, but datum is of type 'any' as it cannot be inferred from .nodes()
const divElements3: d3Selection.Selection<HTMLDivElement, any, null, undefined> = 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<HTMLDivElement, DivDatum, null, undefined> = d3Selection.selectAll<HTMLDivElement, DivDatum>(divElements.nodes());
const divElements4: d3Selection.Selection<HTMLDivElement, DivDatum, null, undefined> = d3Selection.selectAll<HTMLDivElement, DivDatum>(divElements.nodes());
// d3Selection.selectAll<HTMLDivElement, DivDatum>(baseTypeElements.nodes()); // fails as baseTypeEl.node() is not of type HTMLBodyElement
@@ -146,12 +146,12 @@ let divElements4: d3Selection.Selection<HTMLDivElement, DivDatum, null, undefine
// selectAll(...) accepts NodeListOf<...> argument
let xSVGCircleElementList: NodeListOf<SVGCircleElement> = document.querySelectorAll('circle');
let circleSelection: d3Selection.Selection<SVGCircleElement, any, null, undefined> = d3Selection.selectAll(xSVGCircleElementList);
const xSVGCircleElementList: NodeListOf<SVGCircleElement> = document.querySelectorAll('circle');
const circleSelection: d3Selection.Selection<SVGCircleElement, any, null, undefined> = d3Selection.selectAll(xSVGCircleElementList);
// selectAll(...) accepts HTMLCollection, HTMLCollectionOf<...> argument
let documentLinks: d3Selection.Selection<HTMLAnchorElement | HTMLAreaElement, any, null, undefined> = d3Selection.selectAll(document.links);
const documentLinks: d3Selection.Selection<HTMLAnchorElement | HTMLAreaElement, any, null, undefined> = d3Selection.selectAll(document.links);
@@ -168,7 +168,7 @@ let documentLinks: d3Selection.Selection<HTMLAnchorElement | HTMLAreaElement, an
// Using select(...) sub-selection with a string argument.
let svgEl: d3Selection.Selection<SVGSVGElement, SVGDatum, HTMLElement, any> = d3Selection.select<SVGSVGElement, SVGDatum>('svg');
const svgEl: d3Selection.Selection<SVGSVGElement, SVGDatum, HTMLElement, any> = d3Selection.select<SVGSVGElement, SVGDatum>('svg');
let firstG: d3Selection.Selection<SVGGElement, SVGDatum, HTMLElement, any> = svgEl.select<SVGGElement>('g');
// let firstG_2: d3Selection.Selection<SVGGElement, SVGDatum, SVGSVGElement, any> = svgEl.select<SVGGElement>('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 <svg> 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<SVGSVGElement> = 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<SVGSVGElement> = g;
console.log('Get <svg> 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<SVGGElement, CircleDatum>(wrongSvgGroupSelectorAll); // fails, wrong this context
gElementsOldData = svgEl.selectAll<SVGGElement, CircleDatum>(function () {
let that: SVGSVGElement = this;
// let that2: HTMLElement = this; // fails, type mismatch
gElementsOldData = svgEl.selectAll<SVGGElement, CircleDatum>(function() {
const that: SVGSVGElement = this;
// const that2: HTMLElement = this; // fails, type mismatch
console.log('Get <svg> 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<SVGGElement, CircleDatum>(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<SVGSVGElement> = g;
gElementsOldData = svgEl.selectAll<SVGGElement, CircleDatum>(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<SVGSVGElement> = g;
console.log('Get <svg> 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<SVGGElement, CircleDatum>(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 <svg> 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<SVGGElement | null> | d3Selection.ArrayLike<SVGGElement | null> = 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<SVGGElement | null> | d3Selection.ArrayLike<SVGGElement | null> = g;
return that ? that.querySelectorAll('circle') : [];
});
@@ -319,12 +319,12 @@ let filterdGElements: d3Selection.Selection<SVGGElement, CircleDatum, SVGSVGElem
filterdGElements = gElementsOldData.filter('.top-level');
filterdGElements = gElementsOldData.filter(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<SVGGElement> = 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<SVGGElement> = g;
console.log('Element Id of <g> DOM element: ', this.id); // this context SVGGElement
if (g.length > 0) {
console.log('Element Id of first <g> DOM element in group: ', g[0].id); // group: Array<SVGGElement>
@@ -341,11 +341,11 @@ filterdGElements2 = d3Selection.selectAll<SVGElement, any>('.any-svg-type').filt
// filterdGElements2 = d3Selection.selectAll('.any-type').filter('g'); // fails without using narrowing generic on filter method
filterdGElements2 = d3Selection.selectAll<SVGElement, any>('.any-svg-type').filter<SVGGElement>(function(){
let that: SVGElement = this;
const that: SVGElement = this;
return that.tagName === 'g' || that.tagName === 'G';
});
// filterdGElements2 = d3Selection.selectAll<SVGElement, any>('.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<SVGCircleElement, CircleDatumAlternative>('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<SVGGElement> = 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<SVGGElement> = 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<SVGCircleElement>
}
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<HTMLDivElement, DivDatum>('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<HTMLDivElement> = 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<HTMLDivElement> = 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<HTMLDivElement>
@@ -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<HTMLDivElement> = 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<HTMLDivElement> = 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<HTMLDivElement>
}
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<SVGCircleElement> = 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<SVGCircleElement> = 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<SVGCircleElement>
@@ -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<HTMLBodyElement> = 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<HTMLBodyElement> = 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('<div> 42 </div>');
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<HTMLBodyElement> = 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<HTMLBodyElement> = g;
return '<div> Body Background Color: ' + this.bgColor + ', Foo Datum: ' + d.foo + '</div>'; // 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<HTMLBodyElement> = 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<HTMLBodyElement> = 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<BodyDatum>(function (d) { // fails, data type incompatible with return value type
// newBodyDatum = body.datum<BodyDatum>(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<SVGSVGElement, SVGDatum>('#svg-1')
.select<SVGGElement>('g.circles-group') // first matching element only
.datum<CircleDatumAlternative[]>(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<SVGSVGElement, SVGDatum>('#svg-1')
d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain
.select<SVGGElement>('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<SVGGElement> = 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<SVGGElement> = 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<d3Selection.BaseType> = 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<d3Selection.BaseType> = 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<SVGCircleElement, CircleDatumAlternative, SV
circles2 = d3Selection.select<SVGSVGElement, any>('#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<SVGSVGElement, any>('#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<CircleDatumAlternative>(endCircleData, function (d) { return d.nodeId; });
.data<CircleDatumAlternative>(endCircleData, d => d.nodeId);
// circles2.data<DivDatum>(endCircleData, function (d) { return d.nodeId; }); // fails, forced data type parameter and data argument mismatch
// circles2.data<DivDatum>(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<d3Selection.EnterElement, CircleDatumAl
enterElements = circles2.enter(); // enter selection
let enterCircles = enterElements
const enterCircles = enterElements
.append<SVGCircleElement>('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<CircleDatumAlternative>(); // Note: need to re-type datum type, as the exit selection elements have the 'old data'
const exitCircles = circles2.exit<CircleDatumAlternative>(); // 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<SVGCircleElement> = 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<SVGCircleElement> = 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<HTMLTableDataCellElement, number, HTMLTableRowElement, number[]>;
td = tr.selectAll()
.data(function (d) { return d; }) // d : Array<number> inferred (Array[4] of number per parent <tr>)
.data(d => d) // d : Array<number> inferred (Array[4] of number per parent <tr>)
.enter().append<HTMLTableDataCellElement>('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<HTMLTableDataCellElement> = 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<HTMLTableDataCellElement> = 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<number> inferred (Array[4] of number per parent <tr>)
const td2 = tr2.selectAll('td')
.data(d => d) // d : Array<number> inferred (Array[4] of number per parent <tr>)
.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<HTMLDivElement>('div');
newDiv2 = body.append(d3Selection.creator<HTMLDivElement>('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<HTMLBodyElement> = 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<HTMLBodyElement> = 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<SVGCircleElement> = 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<SVGCircleElement> = 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<SVGCircleElement, CircleDatumAlternative, any, any>, 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<SVGCircleElement, Cir
// returns 'this' selection
circles = circles.call(enforceMinRadius, 40); // check chaining return type by re-assigning
// circles.call(function (selection: d3Selection.Selection<HTMLDivElement, CircleDatum, any, any>):void {
// circles.call(function(selection: d3Selection.Selection<HTMLDivElement, CircleDatum, any, any>):void {
// // fails, group element types of selection not compatible: SVGCircleElement v HTMLDivElement
// });
// circles.call(function (selection: d3Selection.Selection<SVGCircleElement, DivDatum, any, any>):void {
// circles.call(function(selection: d3Selection.Selection<SVGCircleElement, DivDatum, any, any>):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<HTMLBodyElement>) => 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<HTMLBodyElement> = 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<HTMLBodyElement> = 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<HTMLBodyElement> = 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<HTMLBodyElement> = 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 = <SuccessEvent> d3Selection.event;
customListener = finalOpponent => {
const e = <SuccessEvent> 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<SVGSVGElement, any>('svg').node()!;
let g: SVGGElement = d3Selection.select<SVGGElement, any>('g').node()!;
let h: HTMLElement = d3Selection.select<HTMLElement, any>('div').node()!;
let changedTouches: TouchList = new TouchList(); // dummy
const svg: SVGSVGElement = d3Selection.select<SVGSVGElement, any>('svg').node()!;
const g: SVGGElement = d3Selection.select<SVGGElement, any>('g').node()!;
const h: HTMLElement = d3Selection.select<HTMLElement, any>('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<Element, any>('foo').node()!;
let foo: d3Selection.Local<number[]> = d3Selection.local<number[]>();
let propName: string = foo.toString();
let xElement: Element = d3Selection.select<Element, any>('foo').node()!;
const foo: d3Selection.Local<number[]> = d3Selection.local<number[]>();
const propName: string = foo.toString();
// direct set & get on Local<T> 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'];
+1 -2
View File
@@ -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,
+1 -1
View File
@@ -7,6 +7,6 @@ import * as d3 from 'd3';
// Ability to access d3-select related properties
let d: d3.Selection<HTMLElement, any, null, undefined> = d3.selection();
const d: d3.Selection<HTMLElement, any, null, undefined> = d3.selection();
+2 -2
View File
@@ -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 => {
+15 -15
View File
@@ -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;
+3 -3
View File
@@ -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']);
+3 -3
View File
@@ -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<any, any> = (source, args, context, info) => {
const resolve: GraphQLFieldResolver<any, any> = (source, args, context, info) => {
info.fieldName = "f";
};
const fields: GraphQLFieldConfigMap<any, any> = {};
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: {},
});
+32 -32
View File
@@ -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 = '<html> hey </html>';
let escapedString = Hoek.escapeHtml(string); // returns &lt;html&gt; hey &lt;/html&gt;
const string = '<html> hey </html>';
const escapedString = Hoek.escapeHtml(string); // returns &lt;html&gt; hey &lt;/html&gt;
// 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)
+1 -1
View File
@@ -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((<HttpError> err).status);
console.log((<HttpError> err).message);
console.log((<HttpError> err).expose);
+4 -4
View File
@@ -1,9 +1,9 @@
import indentString = require('indent-string');
indentString('Unicorns\nRainbows', 4);
//=> ' Unicorns'
//=> ' Rainbows'
// => ' Unicorns'
// => ' Rainbows'
indentString('Unicorns\nRainbows', 4, '♥');
//=> '♥♥♥♥Unicorns'
//=> '♥♥♥♥Rainbows'
// => '♥♥♥♥Unicorns'
// => '♥♥♥♥Rainbows'
+3 -3
View File
@@ -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
// => false
+2 -2
View File
@@ -1,7 +1,7 @@
import isArchive = require('is-archive');
isArchive('src/unicorn.zip');
//=> true
// => true
isArchive('src/unicorn.txt');
//=> false
// => false
+2 -2
View File
@@ -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");
const b: boolean = isBinaryPath("src/unicorn.txt");
+2 -2
View File
@@ -1,7 +1,7 @@
import isCompressed = require('is-compressed');
isCompressed('src/unicorn.zip');
//=> true
// => true
isCompressed('src/unicorn.txt');
//=> false
// => false
+3 -3
View File
@@ -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
// => true
+2 -2
View File
@@ -1,7 +1,7 @@
import isRootPath = require('is-root-path');
isRootPath('/');
//=> true
// => true
isRootPath('/Users');
//=> false
// => false
+1 -1
View File
@@ -2,4 +2,4 @@
import isRoot = require('is-root');
isRoot();
//=> true
// => true
+2 -2
View File
@@ -1,7 +1,7 @@
import isTextPath = require('is-text-path');
isTextPath('src/unicorn.txt');
//=> true
// => true
isTextPath('src/unicorn.png');
//=> false
// => false
+3 -2
View File
@@ -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 <https://github.com/lgrignon>
// 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;
File diff suppressed because it is too large Load Diff
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../tslint.json",
"rules": {
"forbidden-types": false,
"unified-signatures": false
}
}
+1 -1
View File
@@ -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 <https://github.com/AnthonyMacKinnon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+1 -1
View File
@@ -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 <https://github.com/craigbrett17/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+1
View File
@@ -2,6 +2,7 @@
"extends": "../tslint.json",
"rules": {
"callable-types": false,
"prefer-const": false,
"void-return": false
}
}
+3 -7
View File
@@ -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 <https://github.com/mhfrantz/>
// 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;
@@ -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));
+1
View File
@@ -1,6 +1,7 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": [
"es6",
"dom"
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+3 -3
View File
@@ -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));
+18 -18
View File
@@ -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("<i class='icon-right'></i>");
@@ -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);
+12 -12
View File
@@ -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 : '<div>test</div>', selected : true },
{ type : 'divider' }
+2 -2
View File
@@ -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);
+2 -2
View File
@@ -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');
+5 -5
View File
@@ -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 <https://github.com/mudkipme>
// 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;
+1 -2
View File
@@ -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)
}));
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tslint.json" }
+11 -10
View File
@@ -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<T>(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();
});
+2
View File
@@ -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,
+1 -1
View File
@@ -8,7 +8,7 @@ const generator: Mailgen = new Mailgen({
}
});
let content: Mailgen.Content = {
const content: Mailgen.Content = {
body: {
name: "Hi",
intro: "test",
+1 -1
View File
@@ -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);
}
+2 -7
View File
@@ -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 <https://github.com/danny8002/>
// 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;
+4 -4
View File
@@ -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");
+1
View File
@@ -1,6 +1,7 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": [
"es6",
"dom"
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "../tslint.json",
"rules": {
"forbidden-types": false
}
}
+21 -21
View File
@@ -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");
+134 -134
View File
@@ -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");
+8 -8
View File
@@ -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
// => false
+1 -1
View File
@@ -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({
+1 -1
View File
@@ -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;
+23 -23
View File
@@ -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();
}
+21 -21
View File
@@ -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;
+52 -73
View File
@@ -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;
}
+2 -2
View File
@@ -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);
+1 -1
View File
@@ -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;
+15 -15
View File
@@ -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: '$<a-z>#$@%'});
const result6: string = readlineSync.questionNewPassword('PASSWORD: ', {charlist: '$<a-z>#$@%'});
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); });
+40 -43
View File
@@ -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 <https://github.com/andyshuxin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "redux-ui" {
import * as Redux from 'redux';
import * as Redux from 'redux';
export interface uiParams<UIStateShape> {
// 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<UIStateShape> {
// 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<UIStateShape> {
// 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<any>;
export default function ui<UIStateShape>(params?: uiParams<UIStateShape>): <T>(component: T) => T;
// optional `options` passed to react-redux @connect
options?: {
pure?: boolean;
withRef?: boolean;
};
}
export interface ReduxUIProps<UIStateShape> {
// 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<any>;
export default function ui<UIStateShape>(params?: uiParams<UIStateShape>): <T>(component: T) => T;
+5 -5
View File
@@ -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<UIShape>({
key: 'Root',

Some files were not shown because too many files have changed in this diff Show More