Monday, February 18, 2019

Music Theory for Programmers


For this post I wanted to do something a little different. Although my profession is software engineering, I would also call myself an amateur musician. Maybe even a singer/songwriter. I play the guitar, keyboards and a handful of other instruments and also like to write and record music.

For a while now I've been thinking about how much writing code and writing music were similar. And maybe that's why I like doing both things so much. Just like programming I can get lost for hours making a song sound just right. So I decided to enumerate the ways that writing music and writing code are similar. No knowledge of musical notation or theory is required to enjoy this post!

Music Theory for Programmers

You might think that writing code and writing music have nothing in common, but they actually share a lot of similarities. Besides both being creative endeavors that build something from pure thought, the underlying processes are also very similar. For example both are made up of loops and modules, both have varying input and output, and both compile down to binary.

As a programmer I assume you already know a lot about programming. So let me talk a little about how music works. As a human being who listens to music you probably already know a great deal about music whether you realize it or not.
  • Songs are made up of sections such as verse, chorus and bridge
  • Those sections are usually repeated multiple times
  • Songs have a key that dictate which notes are played
  • Songs have an underlying structure or motif
Let's delve into some of the similarities between music and code.

Loops

There are lots of loops in code; we have for loops, while loops, recursive loops. Loops are everywhere in our code. They allow us to iterate over an array or do something over and over until a certain condition exists, or even find the factorial of a number.

Music has a lot of loops too. The drum beat, the bass line, verses and choruses. Without loops music would just be a long string of notes without structure, and pretty dang hard to follow and listen to. The human mind craves patterns. If the listener can't discern any patterns she will write the music off as noise.

Here's what a loop looks like in music notation, called a repeat sign. Here the second note is repeated.


Modules

Code is made up of modules within modules within modules. Programs contain classes, classes contain methods, methods contain code blocks. Modularity is the cornerstone of programming. It's what makes it possible for us to read and understand code and keeps our code DRY (don't repeat yourself).

Music contain modules too. A song contains sections, those sections contain measures, those measures contain notes. Without modules written music would be hard to read too. Imagine pages and pages of musical notes with no delineation. You would get lost pretty quickly.


Which is equivalent to something like this minimized code.


Input/Output

Just as code modules can accept parameters as input to produce different output, so can music. Think of the verse of your favorite song; there probably isn't just one. There are usually at least two or three different verses. But the verses sound pretty much the same, just the words are different. The verse module takes words as an input and applies the structure of the verse's melody to it to produce different output.

Here's the structure of a song represented as if it were a set of code modules.

intro()
verse(A)
$chorus()
verse(B)
$chorus()
bridge()
verse(C)
$chorus()
outro()

Here's an example of a module with varying input. There are two lines of lyrics both set to the same melody.



Development Lifecycle

In code we have a development lifecycle. First we come up with an idea for an application. Then we write some specifications. Next we do the development by writing our code. Finally we debug and refactor our code until it's ready to be released into the wild.

Creating music isn't much different. First you come up with an idea for a song, play around with some chords until it sounds good and then write it down. Next you fire up your DAW and start recording the instruments and vocals then mix and apply effects. Then you find every thing that doesn't sound right and refactoring it until it does sound right. Finally after you have everything sounding right you release it into the wild.

Design Patterns

In programming we have design patterns that describe general, reusable solutions to a commonly occurring problems. There are also common reusable patterns in music that help us build songs. They are known as chord progressions. Chord progressions are a series of chords that are played in a specific order. Certain chord progressions sound very good to the human ear.

Probably one of the most common is the four chord progression I-V-vi-IV. There are countless popular songs using it. The numbers 1, 5, 6, and 4 are chord numbers in a key. In music theory there are seven primary chords in each key, each of which has a number associated with it. In the key of C, I-V-vi-IV translates to the chords C-G-Am-F. The reason numbers are used is so that you can easily move to a different key and have the exact same progression, just higher or lower in pitch.

Check out this mash up of songs all with that same I-V-vi-IV chord progression to see just how pervasive it is:
https://www.youtube.com/watch?v=oOlDewpCfZQ

Software Tools

In programming we have IDEs (integrated development environments) to help us write code. In music we have DAWs (digital audio workstations) to help us record and mix songs. Both make our lives so much easier. Writing code in notepad sucks. And having to record an entire song perfectly  is nearly impossible, at least for me. A DAW allows you to record sounds, add effects to them, cut and paste them and manipulate them in all sorts of ways.

Asynchronous

Plenty of languages support asynchronous coding so we can have multiple things going on at once without blocking. Music is massively asynchronous. You have a number of instruments or vocals all executing at the same time. Here's what playing a section of music might look like in C#.

async Task PlayVerseAsync(string lyrics)
{
    var tasks = new Task[] {
        PlayVocalsAsync(lyrics),
        PlayDrumsAsync(),
        PlayBassAsync(),
        PlayPianoAsync()
    };
    await Task.WhenAll(tasks);
}

Compilers

Music and code both compile down to binary. Your code compiles down to machine executable codes. Music compiles down to digital audio files such as WAV and MP3.

Input Devices

They both use keyboards ;)

Complex Notation

They both have strange and complex notation. If a musician were to look at some source code they would probably have no idea what it means.

function reduce(a: int[], reducer: (int, int)=>int): void {
  let sum: int = 0;
  for (let i = 0; i < a.length; i++) {
sum += reducer(sum, a[i]);
}
return sum;
}

On the other hand if a programmer were to look at some sheet music they would be equally confused. Here's particularly perplexing piece of music.

Bugs

Music and code can both be very frustrating to work on. Sometimes there's a bug in your code and you can't figure it out. Sometimes there's a bug in your song and you can't work it out either. But when you finally do figure it out you feel that rush of greatness!

Conclusion

I hope I have convinced you that writing music and writing code share some similarities. I enjoy doing both. Each gives me the same feelings of starting a project, doing some creative things and getting a sense of accomplishment at the end. Both are a creative process that requires deep concentration and thought. I guess that is the main similarity between the two is the creative process. But as I've shown above it doesn't stop there.

Wednesday, February 13, 2019

Polymer LitElement is Here!



I've been using Polymer to help me write web components for a couple months now. During that time I've been using Polymer's base class PolymerElement which among other things provides DOM templating and data binding.

Just the other day the Polymer team announced the official release of their new base class called LitElement. It is provides a more lightweight and simpler way to create web components as compared to the PolymerElement.

I decided to give it a try and this is what I learned.

First of all I really like the simplicity of the LitElement programming model. It's very lightweight and easier to understand than the old PolymerElement way of doing things. If you've ever used React you will find that using LitElement is almost exactly like creating components in React. In fact I think the Polymer team borrowed heavily from React (or maybe ripped them off depending on your point of view).

The two-way data binding of PolymerElement is gone and replaced by one-way data binding, a la React. The old two-way data binding felt more Angular, while the new on-way feels, as I said, more like React. You can't rely on changes to propagate up anymore. Now you need to use events to notify parent elements that something has changed. This is a little more work, but in the long term probably more simple and reliable.

PolymerElement's two-way data binding was sometimes complex to understand and required you to use all sorts of extra configuration to make it work. LitElement's one-way data binding is just simple and easy to understand. I'm not sure I would even call it data binding, really. Your element has properties and when they change your element is re-rendered.

There is the big difference, I think. In PolymerElement you had a static accessor where you defined your HTML template with data binding embedded into it. With LitElement you now have a render() method that gets called any time a property of your element changes. The render() method completely rebuilds the DOM structure of your element. Instead of embedded data binding you build a string that represents your DOM using template literals accessing your properties directly.

For example, here's what a data binding looks like in PolymerElement where "name" is a property of the element.

1
2
3
4
5
    static get template() {
        return html`
            <div>Hello, <span>[[name]]!</span></div>
        `;
    }

And here's what it looks like in LitElement.

1
2
3
4
5
    render() {
        return html`
            <div>Hello, <span>${this.name}!</span></div>
        `;
    }

Notice how we are building a string inserting "this.name" property as an embedded expression in the template literal rather than using a static binding "[[name]]".

This works because behind the scenes the LitElement creates get and set accessor methods for the properties of your element. Whenever a property changes it calls the render method so that the template string gets rebuilt. Then it figures out what changed and updates that portion of the light DOM on the page.

The great thing about using template literals is that you can now use any kind of JavaScript expression to build your DOM template, giving you a lot more power.

The consequence of this is that element properties must now be immutable. If you use React you are probably used to this. If one of your properties is an object or array you can't change an element in it and expect LitElement to notice that change and call render(). You will need to make a new copy of the object or array and change the value you want. If you want to know why this is better in the long run I suggest going through the React tutorial. They explain it in detail.

This also means that changes to properties in child elements will not automagically propagate up to the parent's properties. If you want to notify the parent of a change you will need to use custom events. Again, I suggest going through the React tutorial if you are not familiar with this way of doing things. (I told you they ripped off React :-p)

There is also a new way to bind properties to DOM element. For event handlers you use an @ before the event name and then an embedded expression using the name of the handler function. To define boolean attributes use a question mark. To bind to properties use a dot.


`<input type="text"
    @keyup="${this.keyPressed}"
    .value="${this.name}"
    ?hidden="${!this.isVisible}">`

In all cases you use embedded expressions for all of these bindings, even event handlers.

Using TypeScript

If you're like me and prefer using type annotations in your code, LitElement has support for TypeScript. It also allow you to use decorators to define your custom element and its properties. Use the customElement() decorator on your class and the property() decorator on properties. This will set up your element and properties for you making your code more terse.

1
2
3
@customElement('my-element')
export class MyElement extends LitElement {
  @property({type : String})  prop1 = 'Hello World';

I tried this but was having trouble getting it to work. In general I was having trouble getting the LitElement npm package to work nicely with TypeScript. The TS files in the npm package would not compile correctly because there was something missing that it relies on. This also affected the code completion in VS Code. [Edit] I did get type definitions and decorators to work correctly. Problem was that my compiler was not up to the version required for LitElement, which I think is 3.2. After installing latest everything worked fine. Also, you will need to set experimentalDecorators to true in your tsconfig file if you want to use decorators.

I'm really hoping TS support gets better over time. I didn't have these issues using PolymerElement.

Conclusion

In some ways LitElement feels like a step back because it's so much more primitive than PolymerElement was. But I feel like this is a good thing because it makes everything a whole lot simpler to understand and reduces complexity in your apps. I suggest you go ahead and start using LitElement now and hopefully TypeScript support will get better (or I will figure out what I'm doing wrong) in time.

Start learning LitElement here: https://lit-element.polymer-project.org/guide

Since LitElement is so much like React, and the documentation is limited for LitElement, I also suggest reading the React tutorial. https://reactjs.org/docs/hello-world.html

Thursday, November 15, 2018

Polymer Computed Properties

Polymer supports the concept of computed properties which allows you to create virtual properties whose values are calculated from other properties. If those properties that it depends on change the computed property will get recomputed.

However, there are a few gotchas when creating computed properties that you  need to know in order to successfully write your own. So let's do a simple example to explain.

Let's say we have a component with a name property and we want to change the layout depending on if the name is defined. So what we need is a computed property called hasName that returns true if the name is defined.

class MyElement extends PolymerElement {
  static get properties() {
    return {
      name: String,
      computedName: {
        type: String,
        computed: "_computeName(name)"
      }
    }
  }
  static get template() {
    return html`
      <span>[[computedName]]<span>`;
  }

To make a computed property you need to tell the property how to compute the value by specifyingit a function call, _computeName. Any parameters to the function will become dependencies of the computed property. In this case "name". So whenever name changes the _computeName() function will be called to recompute the value of computedName.

Here's the _computeName() function. It takes the name as a parameter and simply returns the name or "unknown" if it's not defined.

  _computeName(name) {
    return name || "Unknown";
  }

You might think we're done at this point, but if you were to run it now all you would ever get is "Unknown" for computedName, even if the name property changed. You would be pulling your hair out trying to determine why it doesn't work (not that I'm speaking from experience or anything ;-)).

The problem is that if the name property is undefined the first time the component gets created it will cause computedName to never get recomputed. Therefore we must give name a default value in the constructor. We'll just set it to empty string.


  constructor() {
    super();
    this.name = "";
  }

There! Now it should work properly.

Code hard!

Wednesday, November 14, 2018

Polymer Component Visibility Change Handling

I was working on a web app using Polymer's routing and I needed to know when the view changed to my component so that I could do certain things, like set the focus on a particular control.

There's a ready() method in the PolymerElement base class that you can override, but it only gets called the first time the component is shown. I needed it to get called every time the component is shown. So that doesn't work.

The key is to set selected-attribute on the iron-pages element. I set it to "visible". This will cause it to set a visible property on your view's component to true or false, depending on if the component is visible.


<iron-pages selected="[[page]]"
  attr-for-selected="name"
  selected-attribute="visible"
  role="main">
  <my-view name="my-view"></my-view>
</iron-pages>

Note that we don't need to set a visible attribute on the <my-view> component because it automatically gets passed into it.

Next thing to do is go into the view component and add a visible property definition whose type is Boolean. We also need to make it an observed property so we get notified when it changes.

class MyView extends PolymerElement {
  static get properties() {
    return {
      visible: {
        type: Boolean,
        observer: '_visibleChanged'
      }
    }
  }

Now whenever the visibility of the component changes it will call the _visibleChanged() method passing in true or false as the first parameter.

  _visibleChanged(visible) {
    if (visible) {
      // do something...
    }
  }

That's all there is to it. I figured it out from this article, which is (relatively) old and I think out of date for Polymer 3. It didn't quite work the way that article explained and this way seems a lot simpler.

Code hard!

Friday, November 9, 2018

A Simple TypeScript IOC Container

Motivation

When accessing external services from my web apps I like to use interfaces so I'm not tightly coupling a service implementation to where it's used. This has the benefit of making it easy to swap out the service implementation when writing unit tests. It's also very handy early on in the development process before you've implemented your service. You can create an implementation that just returns mock data and not get blocked waiting for the service.

To make this work you need a way to tell your application which implementation of the interface to use at run time. That's where an Inversion of Control (IOC) Container comes in. An IOC container allows you to use a technique known as dependency injection to get an instance of an interface without tightly coupling your code to a particular implementation.

If you've used Angular you know that it has dependency injection built in. But what if you're not using Angular? There are DI libraries out there for TypeScript, like InversifyJS. That's a pretty comprehensive library that even lets you use annotations to inject into constructors. This is great if you have deep objects with a lot of dependencies.

However, for most of my TypeScript apps all I need is a simple IOC container where I can ask it to give me an object for an interface. This is called a Dynamic Service Locator by Martin Fowler. So I created my own IOC container module for TypeScript based on this pattern.

Implementation

To start with we need a way to register interface implementations. For this we need a hash map to associate interface names to object constructors. Then we need a method to add them, which I will call bind(). Let's start by creating a module in its own file with a class called IocContainer.

class IocContainer
{
    private bindings = {};

    /** Binds an interface to an object
     * @param interfaceName Name of the interface
     * @param type Type to bind the interface to
     */
    public bind<T>(interfaceName: string, type: new () => T): IocContainer
    {
        this.bindings[interfaceName] = type;
        return this;
    }

The bind() method takes two parameters; the name of the interface and a constructor function of the class that implements that interface. Unfortunately there's no way to get the name of an interface from a generic definition in TypeScript so we must pass in the name of the interface as a string. All we do is add the mapping into the bindings object and we're done.

Next we need a way to get a concrete instance of an interface from the container. For this we need a get() method.

    /** Gets an instance for an interface as defined by bind() */
    public get<T>(interfaceName: string): T
    {
        let c = this.bindings[interfaceName];
        if (c)
        {
            return new c();
        }
        console.error(`There is no class bound to ${interfaceName}.`);
        return undefined;
    } 
}

The method takes one parameter; the name of the interface. We make it generic so it will automatically be cast to the correct type when we get it. All we do here is look up the constructor function for the interface name in the bindings object. Since it's a constructor function we can call "new" on it to create an instance of the object.

Note one limitation of this is that we can't pass parameters to the constructor. This is necessary because we don't know anything about the implementation! If the mapped object has its own dependencies on interfaces it too can use the container to get them.

The final thing we need to do is to export the container instance from our module. This makes the IOC container a singleton, which means there will be only one instance of it used everywhere.

var container = new IocContainer();
export default container;

Now for an example. Let's say we have an interface called ICustomerService and an implementation called MockCustomerService. Then we could register it like so.

import container from './services/IocContainer.js';
interface ICustomerService {
    getCustomer(id: number): Customer;
}
class MockCustomerService implements ICustomerService {
    getCustomer(id: number): Customer {
        return {...};
    }
}
container.bind("ICustomerService", MockCustomerService);

Finally, we get an instance of the interface from the container.

let service = container.get<ICustomerService>("ICustomerService");

Note that the get should be in a different file from where we did the binding. It would defeat the purpose to put the binding and get in the same file! Put the binding somewhere in your startup code. In this example, once we get our real customer service working all we need to do is change the binding and we're good to go.

Now let's say we wanted to write a unit test for the module that uses ICustomerService. All we would need to do is set up our binding differently in the unit test before testing the module.

class TestCustomerService implements ICustomerService {
    getCustomer(id: number): Customer {
        return {...};
    }
}
container.bind("ICustomerService", TestCustomerService);

Conclusion

Using an IOC container helps you avoid tight coupling to external services in your application by removing the construction of interface implementations from your code. This allows you to easily change the implementation later and provide different implementations in your unit tests.

Code hard!

Thursday, November 8, 2018

Web Components and Polymer

Web Components

I recently started working on a new web app and so started the process of trying to figure out what framework to use. Angular, Vue, React, something else? I remembered reading about web components so I thought I would take a look at that. I was pleasantly surprised by what I found.

I had thought that web components were another one of those things that was far off on the horizon, but it's actually implemented by most browsers at this point. And for the ones that haven't implemented it there are shims.

Web components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps.

  • Custom elements
  • Shadow DOM
  • ES Modules
  • HTML Template
Custom elements allow you to create new elements and add them to the browser.

Shadow DOM allows you to encapsulated style and markup in web components.

ES modules allow you to load and reuse JavaScript components.

HTML Template allows you to create unused HTML fragments that can be instantiated at runtime.

See this page for more details: https://www.webcomponents.org/introduction

Polymer

Web components sounded great to me. I love the idea of creating small reusable components that can all be linked together to create an application. As I started to do more research on how to get started I discovered Polymer. This was another thing I've heard of before but never paid much attention to.

Polymer is a set of tools created by Google that helps you build web components. It also has a library of web components you can use in your own apps. I don't want to call it a framework. It aims to be very lightweight and allow for progressive loading of apps so they start up quickly. This is in contrast to the big frameworks that are large and take a lot of resources to run. Polymer's philosophy is to let the browser do what it does best.

See the Polymer site for more information: https://www.polymer-project.org/

So I decided to give it a try and use it my new app. What I like about Polymer:

  • It gives you components to help you do routing and interacting with external services even when the user is offline
  • Allows you to define your component's style and HTML markup as a string in your component rather than having to build a shadow DOM by hand
  • Gives you two-way data binding to bind elements on the page to your data model
  • It's not that hard to learn
  • It's modular, use the pieces you want; it doesn't lock you into a opinionated framework
  • It's lightweight compared to some of those frameworks out there (yeah, I'm taking about you Angular)
  • Quick and easy to get up and running and create an app skeleton
Things I didn't like about it:
  • The documentation isn't that great; It's hard for me to find all of the properties and values for polymer components. I spend a lot of time trying to figure out how things work. There aren't that many examples out there either. Luckily it's not too complex and I can figure most things out.
  • I haven't found a way to extract the HTML markup and styles out of the JavaScript file. This makes it hard to get syntax highlighting and code completion. On the other hand I almost feel like this is also a good thing because it forces you to keep your components small.
  • Two-way data binding is not intuitive at all. There are all kinds of little gotchas that require "hacky" workarounds to get changes to propagate to the same object in other components.

Conclusion

So far I really like using web components. I'm getting the same feeling I had when I first heard about HTML 5, like this is the future of web development. Polymer has some things that I don't like but it really helps you build apps from web components quickly. But doesn't every web dev tool have things you don't like? The question is, are those things bad enough for you to move on to something else. We shall see.

I'm really excited about this new technology. I'll be using it as much as possible in the near future so I will keep you posted on my progress. Look for more posts as I learn more about web components and Polymer.

Code hard!


Tuesday, May 29, 2018

Fixing NPM Global Packages

I recently got a new Windows computer and when I opened up an old Angular project I realized that I hadn't installed Angular CLI yet. So I installed it globally and tried it again. It still wouldn't work. When I typed "ng" on the command line it said it was not recognized as a command. I tried some other packages I know I had installed globally, like TypeScript. That didn't work either. WTF man!

Finally I discovered that there was a nodejs command prompt installed so I opened that and it worked from there. However that only fixed it for running from that particular command prompt. If I tried to run it in VS Code it still wasn't working.

So I opened up the batch file for the nodejs command prompt (C:\Program Files\nodejs\nodevars.bat) and noticed that it was adding npm to the path system variable. I looked at my path and I only had the nodejs path. So I added the path to npm, which I copied from nodevars.bat, and that fixed it.

Now that I think about it, this also solves a problem I had a few weeks ago when I created my own node app and installed it, but it wouldn't run from the command line. I figured I was just doing something wrong when configuring my app, but now I know I was right all along. Vindication!

Code Hard!

Tuesday, April 17, 2018

Node.js + TypeScript = Awesome

Node.js + TypeScript = Awesome

You can use TypeScript to write maintainable Node.js apps. Here's how to set up a project in VS Code.

Create the Project

First create a project folder. Next I like to use "npm init" to set up the package.json file for the project. This will make it easy to track your npm dependencies.

Now you can open the project folder in VS Code.

Set up TypeScript Compiler

To set up the compiler create a file called tsconfig.json and add the following into it.


{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "sourceMap": true
    }
}

The important bit is to set the module to "commonjs" because this is the module loading system used by Node.js.

Start Programming

Create your main entry point TypeScript file. I usually call mine "main.ts".

Now you can add any supporting TypeScript files. To turn on the TS compiler to watch for changes and automatically compile go to the Tasks menu, select Run Build Task and select "tsc: watch" from the menu.

Although you can use the require keyword in your TypeScript files to import npm packages, you should use a TS import statement instead. Otherwise you will not get code hints.

import * as fs from "fs";

JavaScript Main File

You may want your main file to be a JavaScript file (don't ask me why). In that case you can import files generated by TypeScript using require. For example, if you have a TS file named myModule.ts then you would import it like so. Note that it must start with "./" so it knows it's a local module not an npm module.

let myModule = require("./myModule");

Note also that you probably don't want to use "export default" in your TypeScript file or you will have to reference the default item using the default keyword, which is a little awkward...

let something = myModule.default();

Code hard!

Thursday, July 27, 2017

Creating a New TypeScript Project in VSCode

I recently switched to using VSCode when writing TypeScript apps because I like the lightweight nature of it. However, this means setting up a lot of things yourself when compared to using an IDE like Visual Studio that does everything for you. Here is a quick outline of the steps I use to set up a new project. There aren't many explanations here, this is just a quick reference.

Create the app

First thing you need to do is create a place to put your app and initialize it. So create a folder with your app name, then inside that folder run from the command line: npm init

This will guide you through creating a package.json file by asking a number of questions. Now you can open the folder in VSCode and start working on your app.

Set up the compiler

Next you'll want to get the TS compiler set up for your project. There is a long article here about how to do it, but here's the gist (I'm assuming you already have the TS compiler installed).

In VSCode create a tsconfig.json file and put the following in it:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true
    },
        "include": [
        "src/**/*", "unittests/**/*"
    ]
}

You'll probably want to put all your TS source files in a separate folder in your project. If you want to configure the compiler to only compile files within certain folders use the include option. In this example I'm only compiling files in the src and unittests folders.

Now configure VSCode's default build task to TS. Select menu item: Tasks => Configure Default Build Task then select the tsc:build option in the dropdown list. This creates a tasks.json file already configured to use TS so there's nothing else to do.

Now you can start writing TS. To compile press Ctrl+Shift+B.

At this point you probably don't want to see all the generated JS files. You can hide them by selecting menu item: File => Preferences => Settings and adding the following.

"files.exclude": {
  "**/*.js": { "when": "$(basename).ts"},
  "**/*.js.map": true,
},

Import JS libraries

If you're using JS libraries like JQuery, Knockout, etc., you can add them to your project using npm. You can use the terminal window inside VSCode to do this. For example, to get knockout.js type the following: npm install --save knockout

This will get the knockout file and put it in the node_modules folder. It also saves the reference to your package.json file as a dependency.

If you want type definition files for your libraries it's also very easy to get using npm. npm install --save @types/knockout

Running your app

A great tool for running web apps is live-server, which you can install from npm. If you name your HTML file index.html it will open it in the browser automatically and any time you make changes it will reload the page.




Friday, February 10, 2017

live-server

A quick post today to talk about a nice Node.js tool called live-server. This app starts up a simple development http server to serve your web apps on your local computer. It also watches for changes to your pages and tells the browser to reload them automatically.

There was a time when you used to be able to just run your web apps straight from the file system. Those days are gone due to increased security with browsers. Also, if you want your page to make ajax calls that won't happen over the file protocol either, again due to security restrictions. So this is a really simple way to start up a server without having to configure something like IIS.

All you have to do is go to the folder in your file system where you want to serve files from and fire it up from a node command line. And just like that you're in business, it couldn't be any easier.

Monday, October 3, 2016

Debugging Touch Events on the Desktop

It can be a pain in the behind to debug touch events when developing your web application on the desktop. But I found this great setting in Chrome that makes it a whole lot easier. Just put this into the browser:

chrome://flags/#touch-events

If you set the value to "enabled" it will then emulate touch events whenever you are emulating a touch device. How do you emulate a touch device, you ask?

To emulate a touch device open up developer tool (F12) and click on the "Toggle Device Toolbar" button. At the time of this writing it's in the upper left corner of the window (it seems to move around with each new release so you may have to hunt for it).


When you turn this feature on it shows how the web page would look on that device, allows you to rotate the device, and allows you to choose from multiple devices including iPhone and Nexus or even define your own device.



When you have both of these features enabled you will start getting touch events instead of mouse events. To switch back to mouse events just turn device emulation off. You can leave the touch-events flag on, it won't hurt anything.

Code hard!

Thursday, August 25, 2016

HTML5 Canvas DrawImage Artifacts

I'm working on an HTML5 canvas game that requires smooth scrolling of images across the screen. The coordinates of the images are real numbers, not integers. The canvas can handle real number coordinates just fine and antialiases everything to make it look smooth. The problem is that it also sometimes produces some weird artifacts to be drawn.

What do I mean by artifacts? Artifacts are pixels that are drawn that you don't expect. In my case, for example, I have an image that has a significant amount of transparent pixels. When it's drawn at particular locations thin gray lines get drawn in some of the space where it should be transparent. It's not a lot, but it's noticeable.

So what can you do about it? There are a couple things, but they have their disadvantages. For one thing you can convert all of your coordinates to integers. One way to do this is with a little JavaScript trick; binary "or" the value with 0.

var x = 1.67;
x = x | 0; // x is now 1

That eliminates the artifacts because the images are drawn on whole pixel boundaries, so there's no need for the canvas to smooth out the image. The problem is that it makes your animations really choppy, especially if you have a lot of images scrolling next to each other.

Another thing I tried was to use Math.round() instead of just lopping off the fraction. I figured that would reduce the amount of choppiness. Unfortunately it didn't make much of a difference.

var x = 1.67;
x = Math.round(x); // x is now 2

But wait, there's one more. The canvas context has an imageSmoothingEnabled property you can set to true or false. By default it's true. I found that when you set it to false it's basically the same as using Math.round() above. It forces your images to be drawn on whole pixel boundaries. Which also produces choppiness.

context.imageSmoothingEnabled = false;
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;

So now we're right back where we started. In the end I decided not to use any of these methods and just stick with the occasional artifact being drawn. It looks crappy, but it only seems to happen at certain screen locations. In my case having smooth animations was far more important than the occasional artifact.

I think in most cases the choppiness wouldn't be such an issue and one of these techniques would work. It's up to you to determine what looks best. I would go with using imageSmoothingEnabled property because then you don't have to add any extra code to convert to an integer. Let the system do the work for you.

Code hard!

Saturday, May 7, 2016

Testing TypeScript Modules with Jasmine

In my previous post I talked about using TypeScript/ES6 modules. I have been thinking about making the transition from namespaces to modules, but there were a few things I needed to work out first. First of all how to load them (native ES6 support isn't widely available at the time of this writing). In the previous post I talked about using a library called Require1k (http://requirejs.org/) as the module loader. As the name suggests it is only 1kb in size yet provides the basics you need for CommonJS module loading. So far it does everything I need.

The next thing I needed to work out was how to package up my application when it was ready for release. In that post I also talked about using WebPack in Node.js to combine and minify the application modules.

The final thing I needed to work out was how to get my Jasmine (http://jasmine.github.io/) unit tests to run against modules. This was giving me a lot of trouble; it's not as easy as you might think. Jasmine was built in such a way that it expects all of your files to be loaded using script tags, then it runs when the page onload event fires. Unfortunately when using a module loader things don't happen that way. The module loader doesn't load your modules until after the page is loaded.

So for the remainder of this post I'll show how I got my Jasmine tests to run using the Require1k module loader. Although I'm using a specific module loader there shouldn't be any problem using the same principles for any other CommonJS module loader library as they most all work the same way.

Creating the Unit Tests


The first thing we need to do is create unit tests. I won't go into how to write Jasmine tests. There are plenty of good examples on their web site. The only difference is that you will need to use import statements to reference the modules you want to test.

For example, say you want to test module1.ts. Then your unit tests might look something like this.

/// <reference path="../scripts/typings/jasmine/jasmine.d.ts" />
import * as Module1 from "./module1";
describe("When testing module1", () =>
{
    it("should be true when something happens", () =>
        expect(Module1.something()).toBeTruthy());
});

First we have a reference to the Jasmine type definition file (because as TS programmers we like to have better tooling and autocompletion). Then we import everything from module1. Then we define the Jasmine specs for the unit tests. It's that simple ;-).

One important thing to point out here: your unit tests are modules too. Once you decide to use modules everything needs to be a module. Our unit tests need to load the modules they test, therefore they have to be modules for the module loader to pick up the imports and load them.

The Bootstrap File


Now we need a bootstrap file. This is the main file that gets things going. We will call this file unit-tests.ts.

declare function require(s: string): void;
 
require("./module1.spec");
require("./module2.spec");
 
jasmine.getEnv().execute();

The first thing we did was to declare the require function. This is the function defined by the Require1k library (or any other library for loading CommonJS modules) to load a module file. Without this we would get errors from the compiler because it doesn't know what "require" is.

Next we use require to load all of the unit test modules. In this case we have unit tests for two different modules.

I like to name my unit test files with the name of the module it's testing and a ".spec.ts" extension. This way you know exactly which module it's for and you know it's a Jasmine test file (Note: unit tests are known as specs in Jasmine).

The last line is necessary to tell Jasmine to start running the tests. As I stated above, Jasmine will look for any unit tests and run them on page load. But since this is all happening after page load we have to explicitly tell it to run again.

You might be asking yourself: why not use import statements to load all of the unit test files? That's a valid question. The unit tests are modules, I said so previously. The answer is: because nothing is being exported from the unit test modules. All they do is define Jasmine specs. Therefore if you tried to import them the TypeScript compiler would see there's nothing being exported and just skip it. Then your unit tests wouldn't load and you would be wondering what's going on (not that I'm speaking from experience or anything like that).

The Host File


The final thing we need to do is set up the host HTML file to run the unit tests. It will have all of the files for jasmine, of course. Then it will need the script tag for Require1k.

<link href="../Content/jasmine/jasmine.css" rel="stylesheet" />
<script src="../Scripts/jasmine/jasmine.js"></script>
<script src="../Scripts/jasmine/jasmine-html.js"></script>
<script src="../Scripts/jasmine/boot.js"></script>
 
<script src="require1k.js" data-main="./unit-tests"></script>

The "data-main" attribute tells Require1k what the main or start file is. In this case unit-tests.js which we created above. This will define the starting point of the module loader. From there it will load the unit test modules which will in turn load the modules they are testing.

Conclusion


The trick to testing external modules with Jasmine is to have a single bootstrap file that loads all of the unit test files and to tell the module loader where to find it. Then the key to making it work is to tell Jasmine to run again after all of the tests and modules have been loaded.

Switching from internal namespaces to external modules in TypeScript requires a whole new way of looking at things and some new ways of doing things that you're not used to. You just have to learn a few new tricks to get it to work across the board from your source code to your unit tests.

I think in the end using modules is the way of the future for TypeScript, and JavaScript. Once ES6 is fully supported by all browsers and able to provide native module loading things will be a lot easier and modular JS will become more popular.

<jmg/>

Wednesday, April 6, 2016

Packaging Web Apps with Node.js

There comes a time when you're at the end of developing your awesome TypeScript/JavaScript web app that you need to think about releasing it into the wild. If you've been using good programming practices you should have split your app into multiple files to make it easier to manage and maintain. Only problem is, it's not a good practice to serve up a ton of files when the user runs your app. The best practice in this scenario is to package up your JavaScript files into one file and only serve that one file.

In this post I will show you how to use TypeScript/ES6's module loading system and Node.js to make it easy to package your web app's files into one file for release while allowing you to develop without packaging. We will use TypeScript's module system to set up file dependencies. Then we will use Require.js to load those modules in the browser. Finally we will use Webpack to package up all of the files into a single JS file and compress it for release.

Prerequisites: I'm assuming you know TypeScript and Node.js basics, but even if you don't you should be able to understand the concepts and use them as a jumping off point to learn more.

The Modules


First of all lets look at how external modules work in TypeScript/ES6. For this example we are going to create three separate TS files, each of which depends on the next one. Two of the files will be modules and the other will be the main application file.

The first file module2.ts exports a class named MyClass2 with a public method getText().

export class MyClass2
{
    public getText(): string
    {
        return "Hello from module 2";
    }
}

Nothing special yet. We just have a class with a method.

The next file is module1.ts. It is a bit more interesting.

import * as module2 from "./module2";
 
export class MyClass1
{
    public getText(): string
    {
        let c = new module2.MyClass2();
        return "Hello from module 1 " + c.getText();
    }
}

At the top of the file we import our module2 module that was defined in module2.ts. Now this file depends on module2.ts. This allows us to use the exported members of module2.ts in module1.ts. This syntax follows the ES6 standard for importing modules.

Next we define the contents of module1. We export a class called MyClass1. In the getText() of this class it creates and instance of MyClass2 from module2 then calls its getText() method and concatenates the messages together.

That's how we do external modules in TypeScript and ES6. Pretty simple, right?

Now we need a main app file for our starting point, which in this case is app.ts.

import {MyClass1} from "./module1";
 
namespace WebpackModules
{
    export class MyApp
    {
        constructor()
        {
            let c1 = new MyClass1();
            var el = document.getElementById('content');
            el.innerText = "MyApp started " + c1.getText();
 
        }
    }
}
 
var app = new WebpackModules.MyApp();

We begin with an import of module1.ts. Now this file depends on module1.ts and by association module2.ts. Notice that the import is a little different from the previous one. Instead of importing everything from module1.ts and assigning a name for the module, we are only importing the MyClass1 class.

Next we wrap the MyApp class in a namespace just because this is what I would do in a real app to keep the global scope clean. If you're not familiar with it, namespace is the new keyword to create internal modules in TypeScript and is equivalent to the old keyword of module.

Inside the namespace we export the main application class, MyApp, so we can use it outside of the namespace. Inside the constructor is where we use the MyClass1 that we imported. We create a new instance of MyClass1, then call getText() on that object and output it to the web page.

The Script Tag


Now we need to set up our web page and get a module loader that can load the modules for us. At this time most browsers don't support the loading of modules using the ES6 specification. Therefore we are going to have to use something else. A well known module loading framework is RequireJS (http://requirejs.org/). So let's use that.

In order to use RequireJS we need to tell the TypeScript compiler which kind of package manager we are using. RequireJS implements the AMD standard so we must tell the TS compiler to use AMD. If you're in Visual Studio you can change it in the project properties. Otherwise change it in the tsconfig.json file ("module": "amd"). The TypeScript compiler will output the correct code that works with the package manager of your choice.

In the html file we only need one script tag that references the require.js file.

<script src="../Scripts/require.js" data-main="app"></script>


Notice that it has a data attribute called data-main. This is where you tell it what file is your entry point. In this case it's app.js, or just app (you don't need to specify the file extension). When the web page is loaded Require will load app.js first, then fulfill all of the imports specified inside the application's modules (module1.js and module2.js).

At this point the application is running and it is loading all the files separately. This great for our development environment. If all our files were packaged up in development it would make it a lot harder to debug.

Packaging the App


When it's time to release the app we need to package it up. For this we will be using a Node package called Webpack. You can easily install it using "npm install webpack -g". Then you can execute it from the command line telling it where your entry point file is and where to save the packaged file.

$ webpack ./src/app.js ./app.package.js


Here we tell it to start with app.js and save the result to app.package.js. Webpack will go through all of the imports just like Require did and load all the dependencies then save all of the code in the correct order in the output file along with any code it needs to bootstrap the app.

At this point you can change the require.js script tag to set data-main="app.package.js" and the application should run. Congrats, you now have a packaged up web application.

One thing to note about using Require, it's a very comprehensive library and therefore not a small file. The minified version is about 85kb. So you're making the user download 85kb just to run your app. If you don't need all of that functionality there is another, much smaller option, Require1k.

Require1k is a minimal library for loading CommonJS modules. If all you want to do is use modules in a web application it's perfect. And, as you can tell from the name, the file is only 1kb. That is a BIG difference. If you can use it instead you probably should.

To use Require1k we will need to change the TS compiler module type option to CommonJS ("module": "commonjs"). Other than that it works exactly the same. The script tag would look like this now:

<script src="require1k.js" data-main="./app"></script>


The only thing that changed was the name of the source file. From here we can use webpack just as we did before and everything should run, but with only 1k of bootstrap code.

Bonus Points: Minification


OK, all of our JS files are packaged up into one file. That's great but it could be better. We could minify the file to make it as small as possible. To do that we can use a Node package called Uglify. Install it using "npm install uglify-js -g".

It's very simple to use. Just point it at the file you want to minify.

$ uglifyjs ./app.package.js -o ./release/app.js -c -m


Use the -o option to specify where to save the minified file to. The -c option tells it to compress. The -m option tells it to mangle names which will rename everything it can to single letter names for more space savings.

Conclusion


Here we have seen how to use external modules in TypeScript/ES6 and how to use Require to load modules in the browser. Then we learned how to use the Node webpack tool to help us package up our TypeScript app for release while keeping them unpackaged for development. Then we seen how to use uglify to compress our application's code.

Knockout in Chrome Web Apps (Yes!)

In a previous post I lamented on the fact that you can't use Knockout when creating a Chrome web app. The problem is that Knockout doesn't play well with Chrome's content security policy (CSP) because its binding engine uses "new Function" to parse bindings. This could allow someone to inject malicious code into the Chrome app which has access to low level resources that normal HTML5 apps don't.

After looking around though I came upon a solution to the CSP problem in Knockout. It seems I wasn't the only one with the problem. I found that Brian Hunt created a binding provider for Knockout that is CSP compliant. The project, called Knockout Secure Binding (KSB) can be found on GitHub. It is a replacement for Knockout's built in binding provider.

KSB is not a complete replacement though. It is limited in the kind of bindings you can create. Since it can't use "new Function" to parse bindings you can't create more complex bindings such as passing parameters into functions, and only a subset of JS expressions are available. But these limitations can easily be resolved by being more mindful of your bindings.

For example, say you have a binding for a "like" button that sets a certain thing as being liked. It calls a function in your view model called "like" and passes in the thing to like and true or false.

<button data-bind="click: like("knockoutJS", true)">Like</button>
<button data-bind="click: like("knockoutJS", false)">Dislike</button>

This won't work when using KSB because it doesn't support passing parameters to functions. You will need to rewrite the binding so it doesn't have to pass parameters.

<button data-bind="click: likeKnockoutJS">Like</button>
<button data-bind="click: dislikeKnockoutJS">Dislike</button>

Now the expression is moved back into the view model into functions called likeKnockoutJS and dislikeKnockoutJS. The downside is that this is going to require your view model to have a lot more functions in it, but your bindings will probably be a lot cleaner in the end.

KSB supports most any logical expression including comparison and mathematical operators, so you can perform some basic binding expressions.

<button data-bind="visible: !knockoutJSLiked())">Like</button>
<button data-bind="visible: knockoutJSLikeCount() > 0">Dislike</button>

Here the like button is visible only when the knockoutJSLiked() function does not return true. The dislike button is only visible when the knockoutJSLikeCount() function returns a value greater than zero.

To use KSB you just need to tell Knockout to use it as your binding provider before applying your bindings. You create an instance of a ko.secureBindingsProvider passing in the options you need and set that as the ko.bindingProvider.

let options = {
    attribute: "data-bind",        // default "data-sbind"
    globals: window,               // default {}
    bindings: ko.bindingHandlers,  // default ko.bindingHandlers
    noVirtualElements: false       // default true
};
ko.bindingProvider.instance = new ko.secureBindingsProvider(options);
ko.applyBindings(this.viewModel);

For more info on using KSB see the GitHub page.

In my app (PowerChord) I had to do some reworking to get my bindings to work with KSB. I also had to rewrite some components to make them work, which was probably a good thing because they were a bit convoluted. KSB forced me to write my components the way they should have been written instead of trying to use shortcuts with complicated bindings in my view.

Overall I'm very pleased with KSB and highly recommend it if you are writing a Chrome web app or need to implement the CSP and want to use Knockout as your binding framework (which I highly recommend).