Electron and Angular2: simple App example

In our first post about Electron, we were covering the main topics about what is and how it works. This time we will cover how to create a dummy application using Electron and Angular2 as a front-end framework.

The application tree should be something like this picture:

tree

we can observe:

  • gulpfile and package.json: we will talk later about this 2 files, by now we can just say that are needed to build the application.
  • assets: The package.json is a file useful to give directives to Electron, with this method we can order show/hide the window borders, icon, maximized/minimized, etc.
  • frontend: here we got the content relative to the front end, more especifically all the Angular2 stuffs.
  • main: contains the index.js referenced by assets/package.json and is the start point of our electron application.
  • Tsconfig and typescript files are needed to transcode the typeScript code into javascript.

The main gulp tasks needed to build and “deploy” the application sources:

gulp_file_main_tasks

from this file, the most important tasks are frontend and electron. The first one copy all the content from the source path.

The principal Electron tasks to run the application:

main_electron_gulp_tasks

 

The  second task begins the transcoding and building of the application.

   The electron package.js, it is useful to pass directives at start time, the format of  is exactly the same as that of Node’s modules, and the script specified by the main field is the startup script of your app, which will run the main process. An example of your package.json might look like this:

package_electron

   We need to remember, if the main field is not present in, Electron will attempt to load an “index.js”.

The main index file loaded by electron at first time looks like a common js file:

main_electron

Then, the final product, the application up and running:

app_running

    we realize that is a common web application, the tick here is to work in the look & feel to “hide” that common details (relative to the chromium browser) and make an effort in order to show the appplication like a elaborated desktop app. It is possible to change icon, task bar, menus, system buttons etc. Even if you don’t like the squared and classical window you can hide the background and create a “floating” app with alpha and the shape you want.

   In the sample app we’ve created a minimal environment with an image background and a button in the middle. If you press the button, you will get as result a notification at the notification area, that position will be according to the SO where the app is running, in my case Im running ElementaryOs so the notification area is in the upper-right conner:

notification_electron

The cool part here is, that notification is executing in real native code. The Electron API does the hard work to communicate to the SO what we are trying to do, in our case, show a notification with a text and image.

That’s all for this second part of Electron, you can download the code from here thanks for reading!

 

Electron and cross-platform applications

These days with the latest new technologies applied to apps we want everything faster, accessible and lightweight. To accomplish these goals, companies find that the developers do their job with tools that  require  low effort and can be used in many places.

Then, developers went to work and improve a kind of automatic programming with open source. For this reason, developers at Github started to work on developing something quick and comfortable without the need to learn another programing language. They wanted a framework to get a piece of product without reworking the same application on multiple platforms.

Chromium and the open source

Cheng Zhao, Electron’s director, realized the advantages of Google Chromium and their open source, at the beginning developed by Google Inc. to the community of developers who needed their own browser, without realizing about the potential which was delivering to Github’s developers. Later on, they started working on that for long weeks to get the Chromium core.

Finally, with the job done and successfully tested, it was launched in April of 2015. A few months later, Microsoft launched Windows10 with the possibility of installing applications from the Windows store (web based) then. For that reason, they believed in the great potential of this project.

But, what is Electron?

Electron is an open source project (GNU) written by  Cheng Zhao, an engineer working at GitHub  in Beijing  for the Atom text editor team. Its combines Google Chromium and NodeJS´s features in one codebase. Because of that, Electron updates with their releases. Under the hood, together they share the same Javascript engine V8, and it means that we, as developers, could use both context at the same time (something that, with a regular web app would be impossible)

NodeJS has supported Mac, Windows and Linux equally from the version 0.6 and Google Chromium is also cross-platform. The Electron’s API philosophy is that it only adds features supported by all platforms.  For example, on Windows, applications can put shortcuts in the JumpList of task bar, and on Mac, applications can put a custom menu in the dock menu. Electron conveniently allows developers to send notifications with the HTML5 Notification API, using the currently running operating system’s native notification APIs to display it.

Forget to develop one web application written in asp.NET and another one in C# for desktop, now with Electron you can develop only one NodeJS application and rebuild for desktop platform. Besides, it is an open source and you can improve some aspects such as performance or your custom features.

The project at present.

The team released Electron when they launched Atom two years ago, known as Atom Shell, the framework they’d built Atom on top of. In those days was the ‘driving force’ behind the features and functionalities that Electron provided as they pushed to get the initial Atom release out.

Today as a dedicate project, Electron is a growing community of developers and companies building a lot of apps (just in the past year it has been downloaded over 1.2 million times) and releasing the mature 1.0 version.

electron-downloads

In the last times Electron has since been used to create applications by companies as Microsoft, Slack, Docker etc. we can inspect a few of them here.

Angular2 and the future of HTML5 on desktop

  • The main process  provides platform specific API’s and taking care about the application lifecycle
  • Meanwhile the render process  provides functionality for the user interface, in this case Chromium with all it’s advantages such as Chrome Developer Tools available right inside of your desktop app.
  • Angular2 currently has become one the most popular open source javascript frameworks in the world:
    – Its modular so we can choice what part of Angular use
    – its modern, is targeted on ES6 and “evergreen” modern browsers, no hacks or workarounds are needed, allowing developers to focus on the code related to their business domain.
    – its focused on mobile devices which means that we can port a current mobile applications to desktop just wrapping up in Electron.

Looks like Electron + Angular2 is a pretty good combination.

In the next post about Electron we will make a real code basic application to demonstrate the use of this nice stack.

My two cents

There are a lot of good features but here are some collected pros and cons:

Pros:

  • No cross-browser compatibility issues
  • No loading of remote assets (then no latency)
  • Reuse of npm modules, out of the box
  • hardware access
  • Native-ish features (system dialogs, file selection dialogs, notifications, printer, etc)

Cons:

  • The size, the Electron API Demos for linux compress takes 41MB (it could be worst, giving account that is a complete and customizable browser).

TypeScript

Intro

TypeScript is an open source compiled superset language of Javascript maintained by Microsoft. Introduced in 2012 after several internal iterations, the project was born out of the desire to add some variable typing to Javascript. Hence, TypeScript.
While you may first recoil at the idea of another transpiled javascript library, let me explain some of the great features and speed increases you can get by including it in your workflow and you might change your mind.

How it Works

TypeScript is just a superset of JS that compiles to ES3, ES5 or ES6. Think of this as a higher level language that normalizes the features of ES5 & ES6 into a version compatible with your target language and polyfills missing features.
This means, if you are compiling to ES3, TS will turn your fancy ES6 class into the syntactic sugar required to replicate it in ES3. Also, it will do it better than you.

Why TypeScript is a good thing: you can have ES6 features, now

ES6 compatibility is woefully lacking for most browsers found in the wild, which is definitely appealing if you want to use some of those cool features you hear about… especially the ones that most people gripe about the lack of in JS (classes and inheritance) when compared to most other OOP languages.
Classes and Modules are now available to you, and down compiled . You can use the super cool (and often confusing on your first encounter) “arrow” functions notation for your Anonymous Functions. Rest functions where you can finally make your functions as flexible as you want them.
When you let TypeScript transpile your code you can have all of those amazing ES6 features with your current user base’s browsers! Yes, even Safari!

Why TypeScript is a good thing: You get type hints, type checking at compile time

Loose typing has always been a gripe of higher level languages like PHP and Javascript. At its core, the argument really comes down to keeping your code clean and safe by asserting you pass and ask for the correct types of variables. If your reading this, and enjoying it, I’m sure you have encountered the terrible spiral of type juggling and the concept of ‘falsy’ when looking for an optional variable input in a function.
Type annotations allow you to specify the exact type of input and output you are passing around your functions. This not only leads to implicit assertions of your types, but also allows for great real-time syntax checking if you are using an editor that supports it.
Also, the next time you try and pass a boolean variable to a function expecting a string, your compiler will complain “LOUDLY” and refuse to compile your crap code. Using explicit variable types is the best documentation you can provide and its built into the code you are writing.

How to Install / Use It

Install TSC via NPM
npm install -g typescript
Then follow along in the easy to understand QuickStart / HelloWorld from the TS team: http://www.typescriptlang.org/docs/tutorial.html
If you cannot install it, you can also try the TS playground: http://www.typescriptlang.org/docs/tutorial.html

Who is really using TypeScript?

Well, for one, Microsoft is using it on quite a few internal projects. The Angular 2 team actually wrote the majority of the new framework using TypeScript. Also, the popular project management tool Asana’s team made a rather well publicized switch to TypeScript recently.

Should I use TypeScript?

The simple answer is, sure. Why not. I would give it a shot and try and work it into your workflow and see how it goes. Thankfully it plays nice with vanilla JS as well.
Leave us a note in the comments if you actually use TypeScript, or have a good reason not to use TypeScript, in your work.

AngularJS 2 & AJAX

Intro

The AJAX paradigm really launched the web into primetime some 10+ years ago, but now its almost expected. Now it’s a ubiquitous part of the web landscape. Most web apps now resemble an ‘app’ in regards to their UX and users ‘expect’ content to dynamically update without a page refresh. In the past, we have used some great tools like jQuery to cobble together a basic app to interact with our page and an AJAX backend, but a framework like AngularJS adds some sanity and structure to what could have been a mess of spaghetti code.

The most common use cases for AJAX are dynamic content and form interactions. For example, if you have a large list of tabular data, you can load it via AJAX to show your basic page to a user without having to render the table on the server. Forms can be validated with JS and sent to the server in the ‘background’ so the user doesn’t have to leave the page. There are MANY other use cases for AJAX, but I think this covers the majority you will encounter when developing a web app.

HTTP / XHR

Most browsers you will encounter, or your clients will use, will have access to the HTTP API known as XHR (it’s safe to assume that anything above IE 5.6 will allow you access to this API). While some browsers offer Fetch support, I will skip that for the purposes of this blog post.

AngularJS Services

In general, you will provide AJAX access via a service. Services are a part of the Dependency Injection patten that makes AngularJS so modular. Creating a piece of code that allows you to encapsulate all actions that make AJAX calls allows for better re-use and easier testing.

Observables vs Promises

Too often used tools/patters for working with asynchronous data structures are Observables and Promises. While you may be familiar with Promises as a pattern, and most likely have used something like promises in the past, Observables are a pretty new concept to me.

In short, Observables are “a push based collection” using the observer pattern. Put simply, this is a queue of objects with some amazing manipulation methods and hooks to allow you to detect when something occurs within the queue. It’s pretty great for dealing with a dataset that needs to be lazy loaded or can possibly get updated in the life cycle of the application.

Here is a simple example based on the angular.io Hall of Heros example showing an observable request:

image

A promise is “a way to define actions or computations once an async event completes”; an observable is “way to define computations or actions that happen when one or more events in a stream occur”.

Here is a simple example based on the angular.io Hall of Heros example showing an promise based request:

image

The key take away from comparing these two tools: observables and promises are both great tools for async programming like AJAX, but observables are more like a stream of data than a ‘one time request of data’. We’ll touch more on this in future blog posts.

Here are some code examples that borrow very heavily from the HTTP Client example found on the Angular.io site.

Code Example: Promise

http://plnkr.co/edit/aB69cfM5soJzz9SPf1e7

Code Example: Observable

http://plnkr.co/edit/t6zDqSAjGNvSKNzIQJtR

Understanding AngularJS 2 vs AngularJS 1: Part 2

Components instead of Controllers

While Components have been around in some shape or form around the web, Angular 2 is based around these amazingly flexible elements.

Components in AngularJS 2 will entirely replace controllers. In fact, they will also replace the concept of a module. They look like a directive, but actually act like a controller.

A component is essentially an HTML element that uses Shadow DOM to encapsulate its own scope and behavior. What this really means: your component has its own variable scope. What happens in your component, stays in your component. You can however inject your components into other components or decorate them to add functionality.

Here is an example of the previous burrito example above implemented in AngularJS 2 showing a component in action:

Decorators via Annotations

Decorators are a simple design pattern that we can now use to update the values and context of a component without introducing new behavior.

Seriously, this is great. You can just apply a decorator to your directive and change its variable values without actually tearing into its guts. Change your components color from ‘Red’ to ‘Blue’ at runtime externally without hacking away at its internal functionality or exposing some getter after the fact.

Currently, this is available in the upis provided by TypeScript, but is

A Focus on Dependency Injection

AngularJS 1.x certainly used the concept of dependency injection and promoted it with the usage of services and factories. I don’t think I need to spend a lot of time stumping why and how this can make for better encapsulation and easier re-use of code.

AngularJS 2 will take this a step further and encourage you to use dependency injection with components. Write a login component and inject it into

Zones.js

Previously, we needed to let the Digest / Apply loop cycle through your variables, or use the oft-maligned scope.$apply to let your app know that something changed. ZoneJS will now be handling all of this.

Zones is able to encapsulate the entire scope of your component and is aware of when asynchronous events start and stop.

While getting away from $apply and not having to worry about your scope is great, here comes the best part: ZonesJS will speed up execution time as much as 5x compared to AngularJS 1.x code.

Here is a great talk about Zones by Brian Ford given at the 2015 ng-conf.

The bad news: Zones is only available for modern evergreen browsers. This means if you are using IE10 or below you will not get the to use this amazing toolset. Angular 2 will have fallbacks with dirty value checking and poly-fills to make sure this is all invisible for you, but you will not see the major speed increase you would get from actually using ZonesJS.

TypeScript

TypeScript is a superset of ES6 and gives us some amazing features.

AngularJS 2 will be written in TypeScript, but this doesn’t mean you have to use it. I can say that I plan on using it as I think this will be an area

Ok, this sounds great. How do I prepare to upgrade?

I won’t go too much in depth on this but there will be upgrade paths and plans if you dont want to just ‘start over’ with your existing angular app.

The Official AngularJS 1.x to 2 Upgrade Strategy Doc offers some insight on how to upgrade.

Understanding AngularJS 2 vs AngularJS 1: Part 1

As I’m sure you know if you are reading this, the AngularJS team is planning for a major version release “very soon” that will include some major paradigm shifts. A lot of the things you learned while teaching yourself AngularJS 1.x will just not be present in AngularJS 2.

AngularJS 1.x is stable and will definitely be around for a long while with long term support from the original team. But do you really want to pass up on some of those amazing features (3-5x Performance increases, the ability to use Server Side Rendering, bragging rights)? No, of course not.

Just to make sure we can explain the concepts of Angular 2, let’s briefly review the main concepts of Angular 1.

Modules & Controllers

Controllers are just Javascript objects that create scope (more on this later), setting up attributes and functions. It’s the connection point for all scopes, functions and data sources in the application. These are similar to traffic cops that direct the flow and send data back and forth between the parts of your application.

A module can be thought of as the container that holds all the different parts of your AngularJS application. These have the advantage of making your code declarative and well encapsulated.

Directives

Custom HTML elements used to enable and interact with AngularJS. This cool feature is how we instantiate your app (`ng-app`) or create custom elements that transform data and views with JS logic stored in your models and controllers.

Here is an example of a directive in AngularJS 1.3 that replaced a `<burrito />` directive with an image of a burrito:

HTML

   <div>
<burrito></burrito>
</div>

JS

var app = angular.module(‘plunker’, []);

app.controller(‘MainCtrl’, function($scope) { });

app.directive(‘burrito’, function(){
return {
restrict: ‘E’,
replace: true,
scope: true,
template: ’<img src=“[ASSET SOURCE]” />’
};
});

Scope

The Application model and context, defined by an angular element. Defined hierarchically, scopes can be passed between elements

It’s important to note that Controllers, Services and Directives all have their own nested scopes. This can get messy when you are passing around data and need to make sure you aren’t polluting your own scope.

image

 

Databinding

 

While this is a great feature, it’s incredibly slow. Every digest cycle has to check ALL of these variables and update them appropriately.

Data binding is that magic that lets you sync data between your models and your view. In a sentence: your model’s data is bound to the view and your view is bound to your model’s data.

Here is a quick example:

HTML

<fieldset
<h1>Hello {{name}}!</h1>

<fieldset>

<label>an example of databinding:</label>

<br>

<input type=“text” ng-model=“name” />

JS

var app = angular.module(‘plunker’, []);app.controller(‘MainCtrl’, function($scope) {
$scope.name = ‘World’;
});

This is that awesome thing that does that sweet ‘live’ updating of values in your forms. Most likely, this was the huge selling point when you first started learning about AngularJS and the ‘reactive’ web.


We’ll explore where these things start to differ in Angular 2 in our next post