Archive | November, 2016

React with Javascript package managers

13 Nov

React with Javascript package managers

One of the best ways to learn new software is to take on a commercial project and force yourself to use it. I do this all the time and with all the cool kids ranting about React, I felt that it was time to do a project based on it. It's been a bit painful, but I've come to enjoy the way React works. It's actually quite beautiful!

I've used Angular before and React feels much more solid and natural. It does require that you learn how React thinks (or want you to think), and that part might take a little time. Here's some of what I've learned while using React.

Javascript - the new frontend AND backend favorite

To create a HelloWorld on the web, all you need is a HTML page with a few lines of inline JS. How can a 200+ file download possibly be an upgrade from that? It just does not make sense that a simple HelloWorld-project should become a folder with 139Mb of Javascript based libraries, right? Like it or not - Javascript is the language that takes over both frontend and backend development these days.

You can use it old-style (and write it all by hand) or use one of the many hundred frameworks that are out there to make your life easier. So while the initial download may be large when using frameworks, the files will normally be cached by the browser. If you use a CDN for your framework, odds are that it's already cached.

I've always known JS and it's very close to Actionscript. Learning React has not only been yet another nail in the Flash coffin (it's really completely dead). Learning React has also taught me several new programming concepts that I'll keep using for other projects.

How React is different

I've had to do lots of refactoring every time I've understood how a new thing worked in React and that’s been a bit painful. Initially I tried to fight against how React worked since I wanted to be in control. The React way of doing things is to not do things directly, but to always do things based on state. The data model controls the GUI in reactive programming. React only re-renders if an object has changed, so to change something on screen, you need to implement a visual change in response to an object/variable changing. This happens asyncronously since the React DOM and the browser DOM are two different things. With React, you never manipulate the DOM directly. It always happens because of a change in the data model of the app.

Changing an object/variable to change the GUI sounds cumbersome until you've used it. The super-neat thing about this is that if you do things correctly, you'll be able to start your app from ANY state and also to change it while it's running! You just set the variables and the app will render straight to this state! No more clicking 20 times to get to a certains state for debugging. Now you just set the data of that state and you're there? Understanding how to solve things "the React way" is what really takes time, but once you get the hang of it you'll wonder why not all software is based on this principle.

A React application starts at a root component, that then renders sub-components that renders sub-components. It takes time to understand where in such a hierarchy certain data should be, how it's passed most effectively and how to implement the visual changes in response. I won't say I'm completely on top of this yet, but I really feel that I'm getting a lot back from this approach of working. The very clean separation of responsibilities between each component makes you much less afraid of breaking stuff than with other ways of working with code. You basically jump straight to the module you want to work on and do your thing, knowing that it won't break stuff. I really recommend trying out this way of developing web apps if you haven't!

Getting up to speed

When you start out with React, you'll most likely start like me using the in-browser JSX transformer to convert JSX to pure javascript at runtime. This process is called "transpiling", since you're not really compiling but rather converting the React's custom JS format (JSX) to plain ECMAScript JS. Following the official docs from Facebook, you'll get your project started but to really grasp the full power of React, you should go through setting up the NPM and JSPM package managers.

Why? For one thing - most of the example code you'll find online will require it. Package managers are great tools since they keep track of all the dependencies used in your project and they download all dependencies from CDN's. The most important is however that they can convert your app to a pure JS class that is much faster than the runtime-compiled JSX script.

So how do you get started with Package Managers? There's several to choose from, but if you've played with Node.js you probably already have "npm" installed? If not, click here to learn how to install it. Once you have npm installed, open a terminal window (or CMD command line on Windows) and type:

  sudo npm install jspm -g

This will install JavaScript Package Manager (JSPM) on your system and make it easy to install any library you want to use. JSPM seems like a solid choice among a flurry of others that pop up and then disappear and it can pull in code-packages from both npm and github.

To create a new project from scratch, you'll make a new folder, go into it and type the following:

  npm init
  jspm init

This will create a couple basic files that the package manager needs to keep track of what libraries your project is using. It will also download some base packages you need to start developing: Systemjs makes it easy to include libraries on your app. Babel compiles JSX to a variety of JS (including ECMAScript 6 / ES2015), makes sense out of error messages and adds support for missing features in some browsers. You'll find these and some others in a folder called "jspm_packages". With these files in place, you'll want to get ready for React programming by installing React itself:

  jspm install npm:react

These are now added as dependencies in the package.json file in your folder and you can start using React with a package manager to ease your development.

JS and it's blazing speed of development

This talk from Jack Franklin was of great help to me in learning JSPM, but it's also quite typical in the JS-world that the talk from May (6 months ago) is already full of "bugs". JS libs are rarely consistent over time, and if you try to run his code, you'll get errors like:

  Warning: React.render is deprecated. Please use ReactDOM.render from require('react-dom') instead

If you then try to use that code, you'll realise that you didn't install the package "react-dom" since that wasn't needed 6 months ago. Looking at the official documentation from Facebook you'll see that you should not use the import-statement as Jack does, but rather use "require" like this:

var React = require('react');
var ReactDOM = require('react-dom');

Running that will give you the error:

  Error: require is not defined

Facebook just takes it for granted that you've installed the "browserify" package. This is what give you the require-statement and other goodness since there's no such thing in JS. They take this for granted in all their doumentation, so be aware that you'll need that to have browserify or webpack installed if you want to just cut and paste their examples. They do actually mention it on their Getting Started page, but if you're new to Javascript package managers, it's quick to skip that single mention.

But - armed with your new knowledge about JSPM, you could just pull it down

  jspm install npm:browserify

The problem is that this requires that you reconfigure your app from scratch, and since you're now following Jack's great tutorial, you should rather do the following:

  jspm install npm:react-dom

Once that is in place, you can use "import" rather than "require" like this:

  import React from 'react';
  import ReactDOM from 'react-dom';

I don't find these error messages intuitive at all, so I thought I'd better jot this down for Google to find, so others can skip some frustration smile

Using "import" or "require" syntax is just a matter of preference. You can use both, but since none of them actually exists in JS they're implemented as Polyfills - placeholder syntax for methods that may or may not end up in the ECMA language.

Why Javascript should become what students learn first

When I started using Node.js on both the server & client some years ago, I never thought it'd become as popular as it is today. Now that I'm teaching a bit, I keep thinking that it's crazy that students don't learn JS in school. Think about it - why should students not learn a language that can cover both the client and the server? It is after all the programming concepts you should be tought at school, not the syntax. The Syntax is bound to change and keep changing, but the general concepts of programming is something that you'll carry with you from one language to the next.

If I could affect the students carriculum at University and higher education, I'd use Javascript as the first programming language to learn. Once students know the basics of the language, I'd make a frontend and a backend track. Having one language for both makes it quicker to get past the syntax and tooling stage, and get into the concepts and useful stuff. The frontend track would be focused on using React, Angular and other frameworks. It would be more about how to learn frameworks than creating big projects. Knowing how to learn a new framework is much more useful than focusing on the fine details of a language.

The backend track would be foused on Node.js making multiuser apps and games, controlling hardware and persisting data. Compared to starting with Java, C,C++ or PHP, this would be much more useful to the students. They'd get results faster, they'd learn skills that are instantly useful in a job situation and they'd have a huge and great community to learn from. Once they've learned JS, they'll easier pick up the more advanced features in more mature languages. JS is basically a much better starting language.

Unexplainable errors in Flash Builder 4.7

11 Feb

For reference: if you have unexplainable errors in Flash Builder 4.7 (and other versions) make sure you turn off "Marc Occurences" in the IDE. Turning this feature off holds the key to removing errors such as:

"com.google.common.collect.ComputationException: java.lang.NullPointerException" and several more.

Installation Error: ApplicationVerificationFailed

04 Dec

For future reference: if you're compiling a mobile app for Adobe AIR and you get this error, it basically means that there's something wrong with the certificate that you're compiling with. The app I'm working on at the moment is using TestFlight for distribution and after pushing a build, I was unable to install to any of my devices. The installation on both iPad and iPhone went as normal until after the install, where it just said that it "Failed to install".

Turns out I had mixed up release and development versions of the certificates. Duhh... Posting it here to help others doing the same and not finding a solution.

Feb 11 2013 update: so got this error again and my own explanation showed up in Google - but - it didn't help me. So some more detail on the problem I had today. I have several identities on some of my accounts. Some are for companies I work for and for some reason - I have two developer identities with Apple.  Let's hope I don't pay for both hmmm

This time, I got the error for trying to export the app, or rather the provisioning file with a company certificate for wich i didn't have the Key (.p12/.cer). As soon as I connected the right certificate to the provisioning file, I was able to install the app on my phone. What made me solve it eventually was to open the Organizer app in XCode. This will actually tell you if the Provisioning profile is valid, whereas Flash Builder will not. It was a bit of a facepalm when i realized it, but I'm posting it here so it can help others.

Here's Organizer showing me what Flash builder should have told me half a day ago...

Update May 2014: another way to get this error -> if you're toggling between release and development versions of the app, you must be sure that the "aps-environment" are set to "development" and not "production" when testing.

The slow climb of HTML5

27 Nov

The slow climb of HTML5

Many people I meet these days ask why I still use Flash as a base for development of applications and games. It is downright scary to hear that virtually all these people still don't know that you can author your apps in Actionscript and then easily cross-compile to very performant native code for iOS and Android. Targeting the desktop with Flash has been around for more than 10 years. Using AS3 as the language and Adobe AIR to export gives you great performance and access to really advanced tools that allows for proper debugging, even directly on the GPU.

Using this stack comes with an overhead, but I would say that it's only 5-15% slower than pure native code. Perception of speed is of course subjective, but my Arduino Companion app have now been installed on more than 60.000 devices and both major app stores show a 4.5 of 5 rating. This app is currently not using any form of GPU acceleration, but the users still love it. I am currently in the middle of a cross-platform game that IS using acceleration and I'm really happy with what I'm seeing this far.

When it comes to HTML5, I see lots of good stuff happening on the desktop. HTML5 has replaced Flash for many purposes on the desktop and I don't mind this. In fact, I encourage it. I've always been a huge fan of using the right tool for the job. That's why I switched Flashmagazine to HTML more than ten (!) years ago. Flash became big because there were no good alternatives and it's only natural that it's role should change.

HTML/JS/CSS is part of my toolset and it has always been that along with PHP for the serverside. However, if you are one of those that think that HTML5 is a good solution today, you should read this great article by Ben Savage of Spaceport.io. It summarises most of my experience from the mobile HTML5-game I made for NASA recently. My biggest problem with HTML-based apps is that they're slow and have little contact with the device they run on. I absolutely hate going to a website that asks me to install it "as an app". All this does is add a desktop shortcut and the poor developers can't even know if I already did install the shortcut. Due to the lack of this they keep nagging me with their stupid "install-me" dialogue every time I visit their site (yes - I'm looking at you Google Calendar).

I'm sure that omissions like this eventually will annoy enough mobile vendors so they create a way to reliably detect if a shortcut has already been installed. The problem is just that this is but one of many things that need to fall in place before HTML5 is really useful. I also got a shock recently when a friend bought a brand new MacBook Pro and Safari couldn't show the default HTML5 video. All he got was green flickering squares. The fix was simply to install Chrome, but this highlights a core point in Ben's article - browser vendors have no interest in making Browser apps really good.

My other experience is that doing an app as HTML5 adds development time. I've discussed this with others and their ballpark is about the same as mine. 30-50% extra time is required to make a good cross-platform HTML5-app. Most developers ignore mobile for this very reason, but come on... Isn't the whole point of HTML5 to get that extra reach? To actually make it work Mobile first and fully responsive?

So why do I still use the Flash Platform for apps and games? I use it to deliver on my promise of real crossplatform apps. I can use the very same code-base to make a game for iPhone, iPad, iPod, desktop, Facebook-apps, Web as well as all the funky flavors of Android. All I would want extra at the moment is Windows 8 support. That would make my toolkit complete.

Now if only Adobe could start telling the world how good this stack really is...

SafeFrames for mobile apps

25 Oct

SafeFrames for mobile apps

When designing a mobile app for multiple devices and resolutions, it's important to know how the different aspects can limit the positioning of design elements. For a recent project, I made some SafeFrame images that the designer can overlay to make sure all important elements are within the limits of typical iOS devices and a popular Android tablet that we target. I guess this can be useful to others so here's the image for centered designs and here's the image for Left-adjusted designs (transparent PNGs).

Flash Builder fails to start

25 Oct

Flash Builder fails to start

After upgrading my Mac to Mountain Lion, I keep having problems with the machine not going to sleep as it should. Instead, some process (that I never started) hangs the machine at full load. I usually find my machine with the fans blowing hot air and in an unrecoverable crash state. Many of my friends have the same problems with Mountain Lion, but I've found that the problem disappears if I unplug my external screen before putting it to sleep? I dunno why, but this works.

Anyway - yesterday I for got to unplug the screen and upon rebooting I could no longer start Flash Builder. It took a while to Google the correct result so here's the quickfix and link. If Flash Builder 4.5, 4.6, 4.7 or any other version fails to restart, it's usually your workspace that have become corrupted. The fix is simple. Open a terminal window and navigate to your workspace directory. In this folder, there is a hidden directory called .metadata. This is what is corrupt. Solve the issue by changing the name like this:

mv .metadata .metadata.old

On next restart, Flash Builder (or rather Eclipse) will recreate this file. Unfortunately it won't restore your projects so you'll have to manually import these again. There's also a more complex option for the command-line savvy. 

Arduino Companion - my first app for devices is out

10 Feb

Arduino Companion - my first app for devices is out

Tonight I finally pushed the app out to Android Market and Apple's AppStore. It's already live on Market, but I guess it can take both days and weeks for it to hit the App-store? I hope others will find it as useful as I do. The idea of an offline Reference came about when arduino.cc experienced some server issues in January 2012. When I looked around for a way to browse the Arduino reference, I figured I could make something better than what was already available. I also had need for a Resitor calculator, so I've added that as well. That one I use many times a day thanks to my newfound hobby.

Making the app

I have lots of plans for new features I want in the app, but feel free to suggest improvements or new features in the comments. All sorts of feedback is very welcome! The app is pure Actionscript. I made parts of the app using Flex initially and the speed/responsiveness was nowhere near what I wanted. The data for the reference is structured using Expressionengine for easy editing/export. It took about 1,5 weeks to take the app to it's current state and more than half the time was spent on testing. Getting one app to work well across multiple screens is really quite a mess, so I hope I've tested enough?

The only known bug is that my Asus Transformer will report incorrect sizes when the app is rotated. It actually swaps the values for rotated and default orientation around? I only have this Android tablet to test on, so if you have an Android tablet and a few minutes to test - please do so and leave a message here. Apart from that bug, it works like a charm on iOS and Android. I haven't tested it on Playbook as I'm yet to receive from RIM the one I won just before GotoAndSki.

I'll probably spend some time getting it published to the other app stores as well such as Amazon, Nook and maybe also smaller ones like Samsung Apps. Any other suggestions?

Other apps?

While this is the first one that has been  published, I've also worked other AIR-based apps for devices. Next out will be my game project MineGunner and start to play with Genome2D. I had to take a break from that when I discovered that I needed hardware to get it where I wanted. The demos I saw of Stage3D / Genome2D at GotoAndSki totally blew me away! Who will need more than 6000 sprites running at 60fps on an iPad? Not me! :-D

Getting an extra item in your list control?

07 Sep

Had a stupid bug that cost me a lot of time so I figured I’d post the solution here in case others stumble onto the same problem.

I had an app with a Horizontal List control and for some reason, Flex insisted on adding an extra item to my list whenever I added a new item to it? Strange. This only happened after I converted the project to Flex 4 and when I went back to Flex 3, it worked as it should. I debugged and confirmed that it was getting the correct dataprovider and despite there being only two items in the dataprovider, three items were rendered.

I looked and looked in all the wrong places until I noticed that I was setting “horizontalScrollPosition” to -1? Why on earth was I doing that? Turns out that if you do this, Flex 4 will create the missing item in your list rather than throwing an “out of bounds” error. Hope this helps someone else with a similar problem!

Nordic Rich Internet Experience Tour

23 Mar

In about a week, Adobe starts a small Nordic RIA Tour in Oslo. They’ll be presenting the Adobe RIA tools as well as a series of client case stories. The day is divided in two with the first half for Designers and the second half for Developers. I’m really looking forward to seeing my friends Peter (Hello Group) and Johan (Swiff) as well Adobe’s evangelist team here in Oslo. Hopefully they’ll have time for a trip to the Dub the evening before the event? FUGN is also planning to have a small stand there as well, offering some free consulting advice to those that have questions about the Flash Platform.

The event is open to all, but registration is required. Seating is limited, so if you want to learn more about AIR 1.5, Flash Catalyst, Pixel Bender, Flex 4 (Gumbo) and LiveCycle, register at the proper link below.

- 31 Mars at Oslo Konserthus, Lille Sal, Oslo
- 1 April at Skandia in Stockholm
- 21 April at Finnkino, Tennispalatsi 2, Helsinki
- 22 April at CinemaxX in Copenhagen

A Graphic is a MovieClip is a Sprite

07 Jan

Spent some hours figuring out a bug that others may want to know of if they get Flex assets as SWFs generated with the Flash IDE. If you create a “Graphic symbol” in Flash and later change it to a MovieClip in the library of the IDE, it will look like a MovieClip but it is still considered a Sprite by the Flex 3 compiler. It doesn’t matter if the symbol has one or more frames, Flex will insist it’s a Sprite since it came from a Graphic symbol.

The error I got was this:

TypeError: Error #2007: Parameter child must be non-null.
	at flash.display::DisplayObjectContainer/addChild()

I this case, it was me that had changed the Graphic symbol to a MovieClip, so I was able to figure out what caused the problem. If the change was done by the designer I got the FLA from, I’d have no clue at all. So, if you run into that error message for no reasonable reason, try copying the contents of the problematic symbol into an empty MovieClip, export the SWF, clean your Flex project and then re-export.

Updated: I did a little more testing yesterday and it appears that it’s Flash CS3 that is the culprit. As soon as you add more than one keyframe, the symbol will change from graphic to MovieClip in the SWF. Extending the timeline will not trigger the update since it can still be considered a Sprite.