Monthly Archives: May 2013

AngularJS – Deferred & Promise

Playing around AngularJS. I didn’t know that AngularJS has deferred/promise functionality, which may be mostly known as jQuery feature.

The following is a simple example to wait for the completion of multiple tasks which takes random time.

http://jsfiddle.net/7svNT/

<!doctype html>
<html ng-app="Promise">
<head>
  <meta charset="UTF-8">
  <script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
  <script src="http://code.angularjs.org/1.1.5/angular-resource.min.js"></script>

  <title>Promise Test</title>
  <script>
    var app = angular.module('Promise', []);

    function PromiseCtrl($scope, $q) {
      $scope.run = function() {
        $scope.items = [];
        var promises = [];

        for(var i = 0; i < 5; i++) {
          var time = Math.floor(Math.random() * 10 + 5) * 500;
          $scope.items.push({time: time, css: ""});

          var promise = waitTask(time, i);
          promise.then(function(index) {
            $scope.items[index].css = "completed";
          });
          promises.push(promise);
        };

        $q.all(promises).then(function(messages) {
          $scope.message = "All " + messages.length + " tasks completed.";
        });
      }

      function waitTask(time, index) {
        var deferred = $q.defer();

        setTimeout(function() {
          $scope.$apply(function() {
            deferred.resolve(index);
          });
        }, time);

        return deferred.promise;
      }
    }

  </script>

  <style>
    .box {
      border: solid 1px;
      width: 100px;
      padding: 10px;
      margin: 10px;
    }

    .completed {
      background: #88dd88;
    }
  </style>
</head>
<body>
  <div ng-controller="PromiseCtrl">
    <a href="#" ng-click="run()">Start</a><br/>

    <div ng-repeat="item in items track by $index" ng-class="item.css" class="box">
      {{item.time}} msec
    </div>

    <div>{{message}}</div>
  </div>
</body>
</html>

Google I/O 2013 – Android Protips 3

Google I/O 2013 – Android Protips 3: Making Apps Work Like Magic

A topic about “Delight” was interesting (it starts around 26:00). It was like the following in a summary (not exact excerpt though).

People are willing to spend 5 bucks multiple times for a flavored hot water, but they can get angry for an app that charges $1.49 instead of $0.99. This is because the emotional experience that a cup of coffee provides the value, and it’s what people are paying for.

It’s an interesting topic. As more apps are flooded in the market, an additional satisfaction would be required for standing out. It’s very difficult to make a difference just with standard functionality, and some sort of essence is required.

Then, this topic made me think about the following.

Around 1.5 years ago, I’ve switched from Windows to Mac. Recently, I was asked about its impression from one of my colleagues. At that time, I just answered several functional reasons (smooth integration with shell, nice trackpad control, etc.). But after that, I was thinking about this topic, and realized that they’re not so important, as most of these functionalities can be achieved on Windows, too. Maybe the major difference is an computing experience around that. Slick hardware design and software interaction provides an comfortable experience, and it makes me bring the Mac anywhere around. That kind of though was not there for me before.

Another video I was watching is Google I/O 2013 – Instant Mobile Websites: Techniques and Best Practices. It talks about performance, and one topic was 1 second latency can cause reductions in page views, increases in bounce rate and drops in conversion rate. It’s interesting too. Maybe the performance could be defined as functionality. But, it would be more effect on the experiences on visiting the site.

Angular Resource with Rails Backend

Finally, I’m able to come back to AngularJS for playing around a little more.

https://parroty00.wordpress.com/2013/03/09/angularjs-routing/

Previously, I’ve tried some simple scaffold behavior using Angular’s routing and templates as above. This one just temporarily stores data in memory, so I’ve modified it to store them persistently on rails. It took more time than I initially expected, so I’m taking some notes here for reminding purpose.

Source

I’ve put the code in the following github repo. Readme contains some instructions.

https://github.com/parroty/anglarjssamplerails

Notes

Resources

The followings are some resources I’ve referred related to this topic.

Google I/O 2013 – Android Design for UI Developers

Google I/O 2013 – Android Design for UI Developers

Android Design in Action: Responsive Design

A little more on Google I/O session surfing. This one talks about practical design patterns for “responsive design”, and the 2nd one is about similar topic from the same presenters.

The followings are some of the tips talked in the session, and how to utilize the horizontal spaces would be the key.

  • Alternate Layout
    • Divide the set of components into a fragment, and combine them appropriately, based on screen size.
    • Master Detail Flow Template helps designing the layout for larger device screens.
  • List to Grids
    • Change number of columns based on screen size works well.
    • List and grids have similar interface and can be combined.
  • SlidePaneLayout
    • Newly released SlidingPaneLayout can show/hide navigation panel based on screen width.

I think not so many apps are handling the screen size well yet. Even a orientation change, most of them just extend the width of the elements and leaves some blank spaces. Small set of them fully utilizes the screen size by tweaking the layout with additional information with menu, etc. (as shown in this video).

Surely a surge of tables are changing the world, but it would require more standard frameworks for applying them. It’s good to see the new libraries like SlidePaneLayout.

Web Languages and VMs – Dart and JavaScript

Google I/O 2013 – Web Languages and VMs: Fast Code is Always in Fashion

Just completed the above Google I/O 2013 session video. It nicely covers the history of V8 optimization with technical description of JavaScript VM implementations (garbage collection, etc), though it’s a kind of prelude to the last part of the Dart topics.

As indicated in this video, JavaScript performance were impressively improved (100x times faster during 2006->2013 time-frame). Then, the Dart is aiming to push the performance further with its simplified grammar. The following official page provides the latest performance graph.

http://www.dartlang.org/performance/

Native dart code (Dart VM) is 2x faster than JavaScript on V8, though “dart2js” code is yet slower than the native JavaScript at the moment. But the graph is progressing well faster than V8. Considering the expanding performance needs for web apps, providing a new language and VM would be an interesting approach.

Aside from the performance, language itself is interesting too. After working on JavaScripts recently, I’m getting to understand some difficulties that JavaScript imposes. At the moment, first alternative would be CoffeeScript, but the grammar doesn’t feel right for me, yet (mostly a little too simplified grammar and python essence part). Therefore, I’m looking around Dart and other related languages. Dart seems more easier to write, due to the grammatical closeness to statically typed languages, like Java. Java may not be the ideal language, but it’s “easier” to write for normal programmers, compared with JavaScript which requires relatively high-skill to write decent code. JavaScript is a little too powerful to control.

Then, one concern for Dart would be that there seems no specific progress on Dart VM on other browsers. Even though it’s open sourced, other browser vendors may not have strong reasons to support Google-controlled language at the moment. Also, as per the Q&A, there seems no translation support from JavaScript to Dart yet. CoffeeScript has “js2coffee”, and there was a news like [Dropbox Rewrote Its Entire Browser-Side Codebase In 1 Week] that indicates it’s getting accepted. Considering the situation that JavaScript ecosystem has already been hugely developed, interoperability with existing libraries would be an important factor.

As mentioned (joked) in this session, programmers have strong opinion in the programming language. Also, normal engineers requires certain efforts to learn new language (I’m pretty much taking time to learn basics of JavaScript). I would like to a little more keep watching that how the ecosystem will be setting up around Dart, as Google seems committed to it along with Blink and Chromium.

Google I/O 2012 – Making Good Apps Great: More Advanced Topics for Expert Android Developers

As I couldn’t wait for the Google I/O this year, I was viewing around the last year’s session videos. The following is one of the good one.

Session Video [Google I/O 2012 – Making Good Apps Great: More Advanced Topics for Expert Android Developers]

Session Presentation [Android Protips]

The topics were the following. Nice information.

Invisibility

  • Your apps should work just fine and let the users to focus on the services.
  • There are various devices (different features and capabilities). The app should detect the available device features and work within the capability.
  • There are various conditions (it can be offline or online). The app should detect the working environment (network, etc.) and work appropriately.

Efficiency

  • Network usage pattern affects the battery a lot. Knowing the characteristics of the wireless “radio” helps improving the battery life.
  • For example, every time the device hits the network, it keeps draining battery for around 1 minute. Therefore, it’s better to consolidate the access through perfecting and batching.
  • You can consolidate periodical request by using the queue. Or, a pre-fetch can be performed when users on-demand request is triggered. These kinds of technique should combined.
  • One useful tool for analyzing network access is DDMS. It provides network statistic analysis.
  • “TrafficStats” class provides stat tracking. “TelephonyManager” class allows to identify the connection type. It can be used to adjust the batch size of the pre-fetching.
  • http://developer.android.com/training/efficient-downloads/efficient-network-access.html has detailed information.

Reliability

  • Testing is important, but there are too many different devices to test. One approach is “Bucket Testing”. Classify the type of the devices into buckets, and focus the on testing for the majority of them.

Asm.js and Emscripten

http://ejohn.org/blog/asmjs-javascript-compile-target/

Maybe it’s a little late, but I just read the above article about Asm.js. Then, I was looking around the related information.

After some previous experiments on Three.js, I’m gaining interests on WebGL, and one major topic around this area seems like this Unreal Engine one. This working demo is compelling.

I tried to find how it’s interacted with browser and WebGL APIs, but couldn’t find one. If original code is OpenGL-based, it’s easy to migrate (or wrap) to WebGL? Anyway, I assume it may be the part of the four days work which is noted in the release statement.

http://www.unrealengine.com/news/epicgamesreleasesepiccitadelonthe_web/

Engineering teams at Mozilla and Epic ported the award-winning Unreal Engine 3 (UE3) to the Web in just four days using the powerful combination of Asm.js and Emscripten, which enables developers to compile C++ code into JavaScript.

The followings are some notes.

Notes

  • It’s JavaScript subset: Asm.js utilizes the subset grammar of JavaScript, instead of using bytecode syntax which normal VMs are applying.
    • It seems like the current focus is providing a fast low-level API, which is specifically intended for the conversion from the LLVM. But, there seems a plan to support garbage collections and JavaScript interfaces (ES6 structured binary data API).
    • http://asmjs.org/ has good FAQ information.
  • It uses Emscripten: Asm.js utilizes Emscripten is a LLVM to JavaScript compiler. It converts the LLVM bytecode generated by the result of C/C++ compiling through Clang.

Fun and Flair with CSS3 Animations

Fun and Flair with CSS3 Animations from Alexis Goldstein at HTML5DevConf

github – alexisgo / html5devconf-slides

Just watched the above video. It was a nice CSS3-animation presentation with nice and concise examples.

I haven’t tried writing complex CSS before, but after playing around with it some time, I’m now getting to understand the power of CSS animation. It’s nice. Though there’re plenty of JavaScript libraries that supports animation, native CSS expression is concise and easy to use. As indicated in the above presentation, simple animation trick would make the difference on the site.

Along with that, I’m also getting to understand the issues of vendor prefixes and redundancy in CSS description, and next step would be surely SCSS/LESS types of things…

There’re a lot of buzzing around HTML5 recently, but it seems still a long ways to go establish a solid and standard ways of developing web sites. Too many options, and too many things to learn.

The following is some jsfiddle, as the result of my struggling.

http://jsfiddle.net/MXgbM/3/

Three.js – Location Selector

Three.js again. But, this time, I’ve tried on some interactions with standard HTML DOM elements by slightly changing the direction.

The following is the working example and screenshots.

Three.js – Location Selector

blog_location_selector1

blog_location_selector2

This is intended to provide a location (country) selector using Three.js sphere object. You can select a country on the sphere, and then, it can open the corresponding google web site based on the selection.

It’s just a UI Testing with Three.js and may not be practical one. But, I found interesting is that it’s not so difficult to interact with HTML elements and Three.js objects. When I search around the Three.js (WebGL), it’s mostly about the graphical demos and gaming. However, one good aspect of WebGL would be the seamless development/interaction with HTML/JavaScript features. It may be good to look for a way to pursue more integration with it.

The following is the notes during my trial (struggle) so far.

Mouse Interaction

It’s about rotation of the sphere based on the mouse dragging. One way is to track the mouse position and move camera, but “TrackballControls.js” in the Three.js example handles the scenario very easily. It’s basically just creating a “THREE.TrackballControls” object with some parameters, and call “update” method of the object for each animation frame. It works nicely.

https://github.com/mrdoob/three.js/blob/master/examples/js/controls/TrackballControls.js

[initialize]

controls = new THREE.TrackballControls(camera);
controls.target.set(0, 0, 0);
controls.rotateSpeed = 1.0;
controls.zoomSpeed   = 1.2;
controls.panSpeed    = 0.3;
controls.noRotate    = false;
controls.noZoom      = true;
controls.noPan       = true;

[update]

controls.update();

DIV Tag Overlay

It’s about showing the country name on the sphere. It’s a div tag shown over the canvas for Three.js. The following GitHub issue covers an example to map the 3D location into 2D canvas location, which allows to identify where to locate the DOM element.

https://github.com/mrdoob/three.js/issues/1321

In my example, this method is used to identify the x/y location of the element (left/top), and using z location to show/hide the element.

Loading Texture

It seems like texture loading using “THREE.ImageUtils.loadTexture” is executed asynchronously. 3rd argument of the function takes “onLoad” callback to handle the completion scenario. The following sites have related information.

http://stackoverflow.com/questions/7919516/using-textures-in-three-js
http://stackoverflow.com/questions/6911815/how-do-i-use-texture-on-a-sphere-in-three-js

High Performance HTML5

Google I/O 2012 – High Performance HTML5

As part of my learning on HTML/JavaScript, I just watched the above Google I/O session, and taking notes here as it was a nice one.

  • Performance and business
    • There’s correlation between good performance and business success. There are some studies that indicates about the improvement (better conversion rate or longer user session) by cutting the load time, since it improves the user experience.
    • Simple setting change (concatenating scripts, turning on GZIP, adding expire header, etc.) can improve performance metrics.
  • window.performance metrics
    • Browser provides performance metrics through window.performance properties. For example, [window.performance.timing.loadEventEnd – window.performance.timing.navigationStart] indicates the loading time, and it can be confirmed on JavaScripts or browser console. Also, showing the [window.performance.timing] object in the browser indicates a lot more supported metrics.
    • [Google Analytics] measures them and show some charts based on the sampling on the site visitors.
  • Script Loading
    • Loading JavaScripts block the execution HTML manipulation.
    • ControlJS has a lazy loading functionality. There are other libraries LABjs, YUILoader, etc. (Based on my brief search, “requirejs” seems like the popular one).
  • Caching
    • Caching is important on mobile browser, as network is relatively slow. AppCache and LocalStorage can be utilized.
    • However, about 50% users can come with empty cache (analysis based on the If-Modified-Since header). It needs to be kept in mind.
  • Others
    • CSS instead of images helps on performance. Or, SVG, canvas, etc. can be used too.
    • For animation purpose, use “requestAnimationFrame” instead of “setTimeout”, which is faster.