I have been using coffeescript for a while, on my last project (a personal project), I encountered an issue that first freaked me out, but now I calmed down…

Take the following class:

1
2
3
4
5
6
class Animal
  name: ""
  power: []
  constructor: (n, p) ->
    @name = n
    @power.push(p) if p

Now take the following instances

1
2
monkey = new Animal("super monkey", "lightning")
mydog = new Animal("dog")

Well, now guess what? My dog has the lightning super power!
This is because it shares the same initialized value for the power instance variable: [], which is short for new Array[]. So, to avoid this issues, we should avoid initializing object at the class level, this should be done in the constructor:

1
2
3
4
5
6
7
class Animal
  name: ""
  power: null
  constructor: (n, p) ->
    @power = []
    @name = n
    @power.push(p) if p

Here you go, now mydog does not have any super power anymore!

theBeast.js

June 30, 2012

I have been working at Huge as a lead front end developer for almost a year now. From the first project I started, I have tried to find a way to organize code that gives a maximum freedom to the developer and which can be adopted fairly easily. It is somewhere between a full fledged MVC front-end, and plain old procedural JS coding.

I used this on 4 project, 3 of which or live and on production. This mini-framework has evolved it now has unit test and all the features that are required to be used as is, that is why it is now a V1.0. Since I coded this framework while working on real projects, the features are there to solve real life problems of mid-size projects. Bigger projects would probably need something more advanced like spine.js or backbone.js.

But enough said, There is a well documented tutorial: http://theBeast.heroku.com. And you can find the source code with the unit tests at https://github.com/hugeinc/theBeast.js

JS PubSub enhanced

October 14, 2011

This is not exactly HTML5 related, but it’s what I call the bof (backend of the frontend), and helped me a lot getting things clean and organized.

I was working on a project which had a very heavy front-end. It was relying on several back-ends I was taking information from and consolidating on the front-end. The front-end has several modules, and one or more needed to be updated every time I receive data. I can imagine a HTML5 game having the same kind of problematic where modules need to communicate but stay independent

Here is my (jQuery) solution, a small piece of js that I call eventer

Let’s take an example.



The game is handled in game.js which has a function that scores points:

1
2
3
4
5
6
7
8
var game = game || Eventer.extend({
scorePoints: function(score) {
$.publish("SCORE_UPDATED", score);
},
init: function() {
// the game here
}
});

You add the Event at the beginning of eventer.js

1
var customEventList = ["SCORE_UPDATED"];

now you can just create a function onScoreUpdated in a class called (for example) userInfo:

1
2
3
4
5
6
7
8
9
var userInfo = userInfo || Eventer.extend({
onScoreUpdated: function(score) {
  // code to update the DOM with the new score like:
  $("#score").text(score);
},
init: function() {
// the user info module here
}
});

So you don’t need to explicitly link the event with the onScoreUpdated function, eventer is doing that for you, camelize the name of the event, add on, and look for a function with that name

Your modules become very independant and easy to handle

Hope that can help

Upload images and resize

November 5, 2010

I am looking into ways to upload images and resize them. I had a straightforward php implementation, everything is done on the server by a script, it is using the cache and works fine. But we are afraid we are going to quickly run into a bottleneck, you need a good size server for only a couple of pictures/sec. So I looked on the internet and I found 2 services that offer resizing and transfer to a S3 bucket. These services are transloadit.com and uploadjuicer.com. Both offer a free test account, so far I have tried only transloadit, because it has more documentation and the concept of assembly is really easy to grasp. Uploadjuicer only has a getting started guide based on examples, no further reference documentation or support homepage. Plus, unless you are uploading very heavy pictures, it seems to me that transloadit is cheaper and the test account (5GB) allows more testing than uploadjuicer (100 images). Well, both services are in beta, but uploadjuicer is VERY recent, so let’s hope they will give us more documentation to let us try their services without wasting time. On the up side, uploadjuicer has a nice integration with rails, which is my favorite server side framework. Anyway, I tried only transloadit for now and I found out that their support team is very responsive, even proactive. You can have your system up and running in a matter of a couple of hours. Just the time you need to understand their system of “assemblies”.

So, I started by opening m amazon S3 account, create a bucket, and retrieve my API key and secret from my amazon account setting. Then I opened a test account at transloadit and started writing a test script.

The assembly is a JSON object you are putting in the value of a hidden input field of the upload form. This is where you are defining the different resize operations before sending the images into your S3 bucket. Here is the assembly example I worked on:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
    auth:{key:"4cd1d373da5044cdb5822afc72ec3211"}
  , steps:
      { thumb1:
        { robot: "/image/resize"
        , width: 320
        }
      , thumb2:
        { use: ":original"
        , robot: "/image/resize"
        , width: 160
        }
      , store:
        { use: [":original", "thumb1", "thumb2"]
        , robot: "/s3/store"
        , bucket: "your_bucket"
        , key: "your_s3_key"
        , secret: "your_s3_secret"
        }
      }
  , redirect_url:"http://localhost:3000/uploading"
  , notify_url:"http://standupweb.net/uploaded.php?user=stan"
  };

The notify URL is key.

1
notify_url:"http://standupweb.net/uploaded.php?user=stan"

That is where I will save the image filename in the database and link it to the user (or other data like location, date…) so that I can easily reuse/browse the images from my server. This assembly needs to be HTML entitized and put inside the value attribute of the hidden input field, thus becomes pretty unreadable. I have written a short javascript to not worry about that, here is my complete example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
    <form id="MyForm" action="http://api2.transloadit.com/assemblies" enctype="multipart/form-data" method="POST">
      <input id="transloaditMsg" type="hidden" name="params" />
      <input type="file" name="my_file" multiple="multiple" />
      <input type="submit" value="Upload">
    </form>
<script>
  // from http://www.davidpirek.com/blog/object-to-string-how-to-deserialize-json
  function objectToString(o){
      var parse = function(_o){
          var a = [], t;
          for(var p in _o){
              if(_o.hasOwnProperty(p)){
                  t = _o[p];
                  if(t && typeof t == "object"){
                      if (t.constructor.toString().indexOf("Array") != -1) {
                        var arrayString = "\"" + p + "\":[", nbEls = t.length;
                        for (var i=0; i<nbEls; i++) {
                          arrayString += "\"" + t[i] + "\"";
                          if (i+1<nbEls) arrayString += ", ";
                        }
                        a[a.length]=arrayString+"]";
                      } else {
                        a[a.length]= "\"" + p + "\":{ " + arguments.callee(t).join(", ") + "}";
                      }
                  } else {
                      if(typeof t == "string"){
                          a[a.length] = [ "\""+p+ "\": \"" + t.toString() + "\"" ];
                      } else {
                          a[a.length] = [ "\""+p+ "\": " + t.toString()];
                      }
                  }
              }
          }
          return a;
      }
      return "{" + parse(o).join(", ") + "}";
  }

  var transloaditMsg = {
    auth:{key:"4cd1d373da5044cdb5822afc72ec3211"}
  , steps:
      { thumb1:
        { robot: "/image/resize"
        , width: 320
        }
      , thumb2:
        { use: ":original"
        , robot: "/image/resize"
        , width: 160
        }
      , store:
        { use: [":original", "thumb1", "thumb2"]
        , robot: "/s3/store"
        , bucket: "PhotoSafari"
        , key: "AKIAILQMUSNT3WCINDKQ"
        , secret: "jEOCPkE8srj5RcK7G4PrtP0sHmncsHUM5Dz9qgZn"
        }
      }
  , redirect_url:"http://localhost:3000/uploading"
  , notify:"http://standupweb.net/uploaded.php&user=stan"
  };
  document.getElementById("transloaditMsg").setAttribute("value", objectToString(transloaditMsg));
</script>

The only HTML5 part of this blog post is the fact that I am using the multiple attribute on the file input field that is supported by transloadit.

My need is a service to upload and resize images, but transloadit can also help out encoding, extracting thumbnails from video, it’s just another assembly rule using another robot.

Here is my PHP/mootools HTML5 tutorial to save your canvas on your web server. Click here to view the demo.
On a side note, for the people who read this post, since this demo is using Canvas, this is a level 3 HTML5 implementation, but since we are also using todataurl, and xhr.send, this is a level 4 HTML5 implementation

http://standupweb.net/canvas/swSaveCanvas.php

integration

First let’s prepare everything to make the plugin work, then I’ll explain how the plugin is working.
Note that all the files can be found in this package: download

1.HTML/CSS

As you can see in the file swSaveCanvas.php, we need 3 elements in the HTML for the mootools class swSaveCanvas to work:

  • 1
    <div id='ajax-action'></div>

    Element where the progress/status of the upload will be displayed.

  • 1
    <button id='save' >save it!</button>

    Button to save (i.e. upload) the canvas

  • 1
    <canvas id="swCanvas" width=320 height=240></canvas>

    The Canvas element

2.Javascript

you need to include mootools, swSaveCanvas.js and instantiate a swSaveCanvas object:

1
2
3
4
5
6
7
<script src="lib/mootools/mootools-1.2.4-core-jm.js" type="text/javascript"></script>
<script src="js/swSaveCanvas.js" type="text/javascript"></script>
<script type='text/javascript'>
   window.addEvent('domready',function() {
      var scObj = new SwSaveCanvas('swCanvas', 'save');
   });
</script>

3. PHP

On the server side we need to catch the file, decode it and save it. The decode part is because the js is generating a base64 encoded string and PHP will need to retrieve the binary content of it, here is how you can achieve within a few lines of script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
   function decode($tmpname, $filename) {
      $tmpFile = fopen($tmpname, 'r');
      $file = fopen($filename, 'w');
      while (!feof($tmpFile)) {
         fwrite($file, base64_decode(fread($tmpFile, 8192)));
      }
      fclose($file);
      fclose($tmpFile);
   }

   $arrfile=$_FILES[0];
   $tmpname = $arrfile['tmp_name'];
   $upload_file = "path/of/the/file.jpg";
   if (is_uploaded_file($tmpname)) {
      decode($tmpname, $upload_file);
   }
?>

explanations

How does that work? We are using 2 key mechanism available in HTML5:

  • get the data from the canvas: The key part of the swSaveCanvas class is here:

    1
    self.canvasEl.toDataURL('image/'+type)

    , that is where we encode the canvas in base64. Once we have this we can build a multipart request according to RFC2388

  • send binary content in an ajax request: Now that we have our request we send it using
    1
    XMLHttpRequest.send()

    . It works on Firefox 3.6 using send() or sendAsBinary(), but sendAsBinary does not work on Safari. Send works fine with Safari. Chrome does not send the correct data, it sends ASCII instead of binary I guess, and does not understand sendAsBinary. Part from that I also could not have this working on IE (with exCanvas), nor on opera. If anyone has an idea, it is more than welcome!

Canvas or SVG?

May 18, 2010

This is our HTML5 alternative to flash for the visual components on our websites. First, one good news, although the first previews of IE9 only show implementation of SVG, Microsoft does want to implement Canvas as well, and is doing some proofs of concept for the moment (see IEBlog ).

So, for the readers who want a quick and straight forward answer:

- If you are doing graphs, maps, simple animations based on vectors or anything that can be rendered with vectors: Use SVG, you will be able to import your vector graphics done with illustrator, and manipulate it the way you want

- If you are doing animations with effects, bitmap manipulation, games… use Canvas.

I think it is going to be obivous, but it’s still new technologies and it’s good to have a quick reference as to when to use what. If you want a more in depth comparison go here


Good resources to start with canvas I, personally followed the Mozilla Canvas (here) and found also this article being very useful.

Good resources to start with SVG Find a good tutorial at W3Schools.com, and the reference library from mozilla (here)

Level 2 HTML5 website

May 13, 2010

So in my last post I showed how to distinguish 4 level of HTML5 integration.

I am now taking an example to show how to build a level 2 HTML5 website (i.e. integrate doctype + HTML5 markup).

lostfinale.com

http://thelostfinale.com



Background story of the website:

You may know that the show “lost” is ending soon, everybody following the show has his own version of what should happen during the finale. So I have had the idea of building this website: http://thelostfinal.com just to gather funny and serious scenario that people made up for the end of the show. I like this speculations, it is a good exercise to try to gather all information you have from the show (during 6 years!) and figure out what could be a logical ending. The actual end might be disappointing, but looking at what people make up is never disappointing. Anyway, not the purpose of this article, just sharing…

Website skeleton:

1. Doctype

1
<!DOCTYPE html>



2. Header

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
       <title>Lost Finale suggestions</title>
       <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
       <meta name="description" content="suggestions and theory for the last episode of Lost"/>
       <meta name="keywords" content="lost theory finale episode suggestions"/>
       <link rel="stylesheet" href="css/standupwebcms.css" type="text/css" media="all" />
       <link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
       <link rel="stylesheet" href="css/roar.css" type="text/css" media="all" />
       <link rel="shortcut icon" href="images/favicon.ico" />
       <!--[if IE]>
         <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
      <![endif]-->
   </head>

Nothing special here, except the IE rule to include a little piece of javascript that would make the HTML5 markup also recognized by IE


3.Body part of the HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
   <body>
      <div id='wrapper'>
         <header>
         </header>
         <nav>
         </nav>
         <section id='content'>
            <article>
            </article>
         </section>
         <footer>
         </footer>
      </div>
   </body>

This is really the basics, I have put a div, just to center the content on the page, but otherwise, it is pure HTML5 markup. If you view the source on the page (http://thelostfinale.com) you will see this markup. I have put the left navigation inside the <nav> tag and the form inside the <article> tag. The rest should be obvious.

And that’s it! Well almost, just close the html tag…

I did this site in less than 4 hours, so it does not take more time to do a HTML5 website than a HTML4 website, just need to get used to the markup. Not that this website also has some CSS3 features (see the form, it does not look as on IE…)

How does a HTML5 website look like? What makes it HTML5 specific? How can I start with HTML5?


I like to hear what HTML5 means for most people. It’s basically the new way to do animations on the web. A replacement of Flash. Of course this is not very accurate technically, but I like that there is a keyword for a new trend. HTML5 can do great things that will make the website look closer to a flash experience: Video, Audio, Canvas, SVG. Not mentioning things that are impossible to do with flash (like Geo-location) And what is also really appealing for website owners is the semantic aspect and how easy it is to update, integrate with a CMS…


HTML5 on google trends




I think there is confusion as to what is done with HTML5, what is done with CSS3 and what is done with Javascript. What I mean is that a new modern website using a lot of CSS3 and Ajax, can already look very close to a flash experience and make people think it is HTML5. Only a look at the source code can confirm that. When you see games like this, not even using canvas, it is pretty amazing.


The confusion is there because there are different level of integration of HTML5. Here are 4 different levels of HTML5 integration

  1. Putting only a doctype: If you just replace your doctype in your HTML by <!DOCTYPE html>, you can already pretend “doing” HTML5. And I went to http://101besthtml5sites.com/ and the first 2 websites of this bestof only have the doctype changed! The rest of the code is full of <div>, I don’t see any video or anything else, I may have missed something, but this just adds up to the confusion
  2. Using the semantic: A very good resource for that is surely http://html5doctor.com This is the second level of integration, and requires already some more HTML5 education. <header><content><footer><figure> and other <aside> tags need to be used where HTML4 only had <div> and <span>
  3. Graphics and animations: Canvas, SVG, This is the real potential replacement of flash. SVG is the oldest one and is slower (see here), but canvas has a real potential. You can play with it on every browser (excanvas for IE is working great in most cases) and it’s really fun!
    Some simple examples:
    http://reas.com/twitch/
    http://mrdoob.com/projects/harmony
    And the best resources I found to start with:
    http://diveintohtml5.org/canvas.html
    https://developer.mozilla.org/en/Canvas_tutorial
  4. Other specific features. I put it as last, because the browsers are supporting it very differently. I am talking about the Audio and Video tags (see youtube), geo-location and other HTML5 features (I’ve developed a dragndrop file upload using Firefox specific HTML5 feature, and include fallback upload for the other browser: click here)



It will never be obvious to recognize at first sight an HTML5 website on a browser with a flash plugin installed (except if the site uses geo-location?), and the different levels of integration make it even harder, but the trend is here and Steve Jobs making a big advertisement for HTML5, Microsoft saying they would support it in the next versions of IE confirm this, so start today using the doctype, integrate some elements, and play with canvas!

New mootools file upload

April 30, 2010

Everybody likes the way you can upload files in gmail. The only drawback is that it uses flash. I managed to do the same using only html/ajax. The only thing I did not manage to achieve is the progress bar. Since we don’t have any progress event… It does not work on IE6 and IE7 (i.e. < 20% of the market). There should be a better solution for these browser than no fallback at all but it did not interest me for the moment

On the other hand, if you are using Firefox 3.6 and above, this plugin will turn into a drag-and-drop file upload component. The main articles that helped me for this part are:
- http://www.thecssninja.com/javascript/drag-and-drop-upload
- http://www.appelsiini.net/2009/10/html5-drag-and-drop-multiple-file-upload

I am providing client (Mootools) and server scripts (PHP). The plugin is documented and available here:
http://mootools.standupweb.net/dragndrop.php

dragndrop file upload

dragndrop file upload

New mootools slideshow

April 26, 2010

I spent some time lately reshaping my picture site: http://pics.standupweb.net

This led me to develop a couple of new mootools classes that can be easily reused. I provide instructions, callback functions and options:

pics.standupweb.net


- SwSlideshow: A ajax-based slideshow with a nice thumbnail tape: see http://mootools.standupweb.net/slideshow.php


- SwFolder: A ajax-based menu based on a folder hierarchy on the server. Have a look on http://mootools.standupweb.net/folderMenu.php


And because my roommate likes shooting a lot of pictures, I derived this classes to build a flipbook, the result is pretty funny: http://flipbook.standupweb.net