Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

June 29, 2011

Jasmine Guard for CoffeeScript rocks on Rails 3

CoffeeScript sure is interesting and I had a very positive experience trying it with Jasmine BDD testing kit. With Guard autocompiling the .js files, it becomes a charm on Rails 3.

Jasmine BDD in CoffeeScript on Vimeo.

This setup guide from pivotallabs.com coupled with this updated gist you will have the infrastructure set up in no time. Any change to the CoffeeScript source or spec files should trigger the Guard to recompile the JavaScript.

To compile "bare" js see this tip to add :bare => true to your Guardfile.

Start guard and jasmine servers and browse to localhost:8888 to run the test suite.
$ guard
$ rake jasmine

Here is a good example of writing a CoffeeScript spec. More spec examples will eventually sprout up, undeniably. And naturally, the Jasmine wiki is a good source of information.

Here's one example: timer.coffee
class Timer
  constructor: (@timer_json) ->
    @start_date = new Date(@timer_json.start_date)
    @end_date = new Date(@timer_json.end_date)
    [@start_hours, @start_minutes] = @timer_json.start_at.split(":")
    [@end_hours, @end_minutes] = @timer_json.end_at.split(":")
And the corresponding test: timer_spec.coffee
describe 'timer-parser', ->

  timer_data = {
    start_date: "2011/06/20", end_date: "2011/06/25",
    start_at: "12:00", end_at: "04:04"
  }

  it 'should parse properly', ->
    timer_json = JSON.parse JSON.stringify timer_data
    timer = new Timer(timer_json)
    expect(timer.start_date).toEqual new Date "2011/06/20"
    expect(timer.end_date).toEqual new Date "2011/06/25"
    expect(timer.start_hours).toEqual "12"
    expect(timer.start_minutes).toEqual "00"
    expect(timer.end_hours).toEqual "04"
    expect(timer.end_minutes).toEqual "04"

June 1, 2011

Writing JavaScript in 2011 - catching up with the latest trends

JavaScript has definitely bloomed during the last few years. I do remember the first time I heard of JavaScript in the late 90s - I wrote a small script that showed a random image (out of a static array) on a static HTML page that I tested in Netscape and IE5-or-so. Today people run JavaScript in top- and mid-range mobile devices, on their web browsers, on servers, on the Gnome3 desktop.

JavaScript is the only language for building an application for all major "smart" mobile devices from within a singular codebase. That, already, interests me enough to give a closer look on some modern JavaScript tools - and write my observations about them.

Foremost, testing JavaScript was something I had completely neglected before. If I was to write serious applications using JavaScript, I'd absolutely needed a way to write unit tests. Secondly, I wanted to have a look at CoffeeScript, which has had a lot of positive attention lately.

I started out by digging into the recent archives of JavaScriptWeekly newsletter. Out of a good number of testing tools, I selected to try out JsTestDriver. It is compact, requiring only a single jar file and a configuration file. The jar contains a small web server that is ran on the source code directory, and exposes a specific url that should be opened in the browsers that will run the JavaScript code to be tested. Cool! If you consider to try out JsTestDriver yourself, I recommend you checkout their SVN repository and compile the jar yourself - the jar file given in the example is outdated and does not contain all the features that the guides may refer to - for example, mocking a piece of HTML that the JavaScript modifies.

Mocking AJAX was out of my scope at this stage, for that you may find this article to be helpful.

For learning to use JsTestDriver, I chose to write a simple slideshow application that uses CSS3 transformations to change the pictures. The required JavaScript for this seemed simple enough, and I wanted to learn some new CSS tricks as well. ;) So, this is "bébé", written in a few days using jQuery-powered CoffeeScript. I started out by getting the basics of CoffeeScript, having it to load the images onto the page, and then wrote tests to see the pictures were actually loaded. Testing the user interface seems to be very difficult, due to differences in how different browsers behave under JsTestDriver. I set the picture position to absolute, since elsehow I could not get the CSS transition to appear smooth (and have the image to disappear without hiding it with JavaScript). CoffeeScript is pretty amazing, and works really well with jQuery. :)

The code for this, along with the JsTestDriver tests, can be found on Github. This seems to work reasonably well in Firefox 4, Chrome, Opera 11, Safari (and Mobile Safari on iOS) and Android browsers. Firefox 3 behaves correctly, it just doesn't show the transition effect. IE fails miserably, never showing anything except the first image. :/

Here are some nice pointers to related articles:

..and now for something different ..
PC emulator in the browser running Linux on JavaScript

April 15, 2010

Testing JavaScript & XHR with Python

I am working on a library for Django - which I'll describe later - and for building this project I need to test the behavior of XHR on the HTML page. That is, I have a page, inject some JavaScript (that may do a request on the server), and see how it changes the document. The Django application the library is designed for creates some parts of the original page and processes some parts of the server-side XHR.

Python is great for this. I've mentioned already in this blog how I like Qt4, and it proves to be very useful again. I could not get PySide running on OS X just yet, so I opted for PyQt4.

Four tests; four evenings working with them – each having an intricate problem to solve ;) Two tests work on the local document, the other two connect to the Portlet test bench, running on localhost. These tests trigger onclick submit actions from the XHR test page, simulating a user clicking a button.

This way it is possible to test the effect of JavaScript injection onto any web page in the wild. At least the WebKit response.. Firefox could be tested by using python-gtkmozembed. QWebKit also has methods for binding Python variables to the page (it is possible for JavaScript to trigger a Python callback function) and render an image snapshot of the page.

If you wish to run the tests, download the file, start up the Rails server with the test bench and run

$ python xhr_tests.py

January 23, 2010

Mathematical discourse on the web

Consider explaining mathematics on the web for someone. The tools to use are quite nifty. Algebra needs distinguishable symbols, geometry some other control methods. Even simple formulas are not so simple: I have a friend who recommended I should try to mix MathFlow with webMathematica and offered me a developer platform. This post is not so much as on the display of formulas as it is about my personal experience of mathematical expression on the web. Mathematica feels like a nice language. I had help for learning it from an experienced notebook / jsp writer, another friend. With his teaching I could quickly learn the essentials constructs of Mathematica's functional style to do simple experimentation and mix it in jsp. WebMathematica3 is a Java servlet package with the necessary backend kernel connectivity and a taglib for the developer. Worked out-of-the-box on OSX – Linux server requires 1 extra step for Xvnc. The taglib is quite usable, with three basic types of components: Manipulate is not quite as swift as it is in native Mathematica. The image does not follow the slider before the click is released. The network and server would be stressed for serving many concurrent users..

MathFlow is an input mechanism to essentially decrease the learning curve to input mathematical notation into the web. It is a Java applet that seems to work on all major OSes given that the moon is in correct orientation and system Java has not crucially changed. Icedtea6 Java plugin on Ubuntu worked too. MathFlow is proprietary software, this was an evaluation license. To be able to test it on a private server so that clients other than localhost can see it, was possible by recompiling the jar with a custom evaluation license. I could not find any open source alternatives, and this software seems capable of doing the job right now. Ideally, modern-day alternative could be written in JavaScript.. maybe compatible with MathJax..

The output formula is in MathML, and it can be captured to webMathematica input, in JavaScript, using for example the MooTools toolkit to do an XHR and update the page:

var mml = document.SampleSimpleEditorApplet.getMathML();
   params = 'fun='+URLescape(mml);
   var req = new Request.HTML({
     method: 'post',
     url: '_action.jsp?'+params,
     encoding: 'iso8859-15',
     onRequest: function() {},
     update: $('div.output'),
     onComplete: function(response) {}
   }).send();


This would send the contents of the editor applet to _action.jsp in request parameter fun, and the XHR would update the page. This _action.jsp in webMathematica could..
<%@ page contentType="text/xml"%>
<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>

<msp:evaluate>
  MSPFormat[
    MSPToExpression[$$fun],
    TraditionalForm
    ]
</msp:evaluate>
.. generate an image of the formula in traditional mathematical notation. Notice the $$fun variable, which is parsed by the webMathematica backend. In case where the formula has variables, it is possible to parse it in the "delayed" form:
SetDelayed[
    f[x_],
    Evaluate[
      MSPToExpression[
        $$fun,
        MathMLForm
      ]
    ]
  ];
Or plot it, notice the use of MSPBlock ..
MSPBlock[
    {$fun},
    MSPShow[
      Plot[
  
        $fun,
        {x, -2*Pi, 2*Pi},
        ImageSize->{600,500}

      ]]]

So you can build all sorts of elaborate user interfaces on top of these building blocks. This is just an example of plotting the user input formula. He shouldn't need to learn LaTeX or any other new notation to input the mathematics into the computer.

The mathematica magician can work with the Wolfram Workbench to write Mathematica code, and still work in a familiar notebook environment.

The web developer has a similar view to produce the 3D applet, where the MSPLive3D module creates the HTML code for the Java applet.
Needs["Talo3D`"];

...

  MSPLive3D[
    Graphics3D[
     {
      RGBColor[0, 0, 1],
      Thickness[0.005],
      Map[Line, house]
     },
     Boxed -> False
    ]
  ]

This is LiveGraphics3D generated by webMathematica3 on Safari. The house is rotatible. =) The original .nb was cc'd to me by Jyrki Kajala a few years ago. Quite recently he taught me about Mathematica packages, and .m files, and how the notebook can load the package. The package can now be subjected to functional testing and also included to webMathematica JSP. The tools have a certain good feel of dynamicity. Some issues, here and there, but it would be very interesting to build various use scenarios ..

November 17, 2009

Recent advances in WWW technologies and the new generation of user interfaces

Many new technologies for the web have emerged during the year 2009. Google Wave, HTML5 and the increasing importance of JavaScript are the driving on the internet, but the mobile device is a growing market where Qt and Android look to provide the best SDKs for iPhone competition. JavaScript engines have been making significant improvements in performance, and V8 makes the Chrome browser a playground of innovation.

I have been silently learning Python with PyQt4 that along with QtDesigner make a good combination of tools for cross-platform GUI development. PyQt4 on the other hand did not agree on new licensing with Nokia, and now there is a new Python Qt4 library emerging: PySide. PySide is an important effort and Python -the language- is looking very promising for a number of reasons.

This exciting iframe below presents Your World of Text, a co-editor which is a prime example of what is possible with modern technology, but this is just a sneak preview of the possibilities that are opening up for developers. Not just on the web but also on the desktop. This demo is produced by Andrew Badr using jQuery, a few lines of custom JavaScript and Django, the Python framework.

In 10 years we may have an Ajax X-server.

The Google Wave videos (check also the playlist) are also inspiring. Google Wave provides a same kind of technology as the demo above, but the codebase is not the same.

The "Wave" that Google presented is under the hood essentially an XML document. The Google Wave Federation Protocol defines the operational transformation layer for sharing the document and mitigating live updates between all wave providers. This works not unlike Git, and all geeks agree how fabulous Git is. As an analogue, Wave provides to non-techie fellow humans (communicate, share) what Git does for code hackers (code, share). Just in a very cool way that code hackers too can appreciate. The protocol is open to contributions by the broader community with the goal to continue to improve how humans share information, together. Even across language barriers!

So in the very near future, we can have live co-editing in multimedia documents with indesign publication / forking / remixing mechanism. The environment, then .. will it be only the web?

The trio: HTML5, CSS3 and JavaScript, has matured and provides a solid base for new generation of dynamic user interfaces. The Amiga Workbench Emulator is a showcase of JavaScript UI and Qt Labs demonstrates the power of HTML5+CSS3 that only works on WebKit browsers (Safari, Konqueror, Chrome). There is no particular Javascript code that switches the items, everything is done by CSS.

Any defences for the plain old desktop apps? Other than terminals, text/video/etc editors, games, mission-critical tasks, CPU/GPU-intensive 3D apps, ... Oh yes. I for one find it somehow silly to overload a web browser with all of this. One of the reasons why web apps got widly popular at some stage is that they are not locked into one physical computer and that the user can change from operating system to another. Reality hits back in the form of browser inconsistencies and especially by the well-known fact that the single most used browser is completely incapacitated by todays standards (IE6 - 23,4% of all browsers in October 2009).

When I started using QtDesigner and Python I was fairly delighted how well they work together. Nice IDE to design the GUI and the UI widgets can be imported and instantiated in my Python code. This is a win for the Qt app. Qt implements the concept of signals and slots, which provide a way to connect asynchronous events (signal) to call a method (slot). For a web app, this would be possible with JavaScript XHR, but there is no "API", since this concept is a bit foreign in the web world. This is a win for the Qt app. The layout of a QFrame is very rigid, unlike HTML+CSS which can be extremely fluid. This is a win for the web app. It also is quite sensible to use accessor objects for inserting data onto a table, but I have to say it feels a bit silly to write 10-20 lines of boilerblate code instead of just iterating over an array and setting a few CSS classes to ones liking? This is a win for the web app. Σ: Qt ≘ web = 2. Both have unique strengths.

Indeed, the web hosts many exotic UIs without overall consistency, whereas the desktop look and feel is pretty much standard with a limited set of widgets, uniform in appearance and function across all applications. That is user-friendly. In some sense it is nice to provide the administrator a single install file and the user an icon on the desktop (or Dock) to click on to access the application. A desktop application may also have access to the hardware and external devices such as USB cameras. An everyday internet browser, enhanced for secure anonymous browsing, should never have these privileges.

Mozilla Prism is a small independent browser window and it already is my favourite way to read GMail and Facebook, but the full potential of desktop integration is not used. Prism uses the Gecko engine, whereas Qt4 provides a QtWebKit module that is capable of loading and rendering web pages with the help of the WebKit browser engine.

I will continue in part #2 on my ideas how desktop and web technologies could build on top of each other's strengths.

November 15, 2009

Chrome Experiments paint the canvas with the future

This is one of my favourites from the Chrome Experiments. Colorscube by Dean McNamee. Best run on the Chrome browser.

It reminds me of the movie Cube. In this demo you can't actually zoom into the cube, but the controls make possible to rotate the cube on the canvas element.

The user interface on this demo, for example, show the power of HTML5 and modern JavaScript technologies. The user experience in the Chrome Experiments is good also on modern touchpads.

This will open up new technologies for developers also on the desktop - and today the most promising tech looks to be Qt. The desktop is a tremendous playground, not just the browser where the drag is one de-facto breed of browsers.

December 30, 2008

ARTS

ARTS has branched, as the original author has not updated the project. The new branch at github.

September 13, 2008

RJS testing

Last week I spent two very full days in creating an RJS-enhanced admin GUI on Rails. As RJS is extremely brittle ( it takes some time to tie the Ajax and css together and still it's easy to break an aspect of functionality without realizing it ), testing is important to later add new functionality, and a necessity for another developer to write new code without regressions. In the GUI there is a list of users and a list of groups. On the page there is an XHR call to the AjaxController, which responds by updating a div on the page.
def select_group
raise unless request.xhr?
render :update do |page|
  page.replace_html :zcore_inspector,   :partial => 'admin/ajax/group'
  page.replace_html :zcore_group_users, :partial => 'admin/ajax/groups_users'
end
end
Kevin Clark has written an RJS testing plugin (ARTS) and the guide gives a good head start. As RJS returns a chunk of JSON-encoded JavaScript, it's simple to regexp for an item that is expected to be rendered from the partial. As can be seen below, this is a powerful testing utility.
xhr :get, :select_group, :groupid => group.id, :uid => @admin.id
  assert_response :success
  assert_not_nil assigns(:admin)
  assert_not_nil assigns(:company)
  assert_equal assigns(:company),@company
  assert_not_nil assigns(:group)
  assert_equal assigns(:group),group

  # group.name should be in the returned JavaScript
  assert_rjs :replace_html, 'zcore_group_users', /#{to_json(group.name)}/

  # all groups users should be listed, as they are draggable the id is fixed.
  group.users.each do |u|
    assert_rjs :replace_html, 'zcore_group_users', /id=\\\"uid_#{u.id}\\\"/
  end

  # closer inspection of the group
  assert_rjs :replace_html, 'zcore_inspector', /span id=\\\"groupid.*>#{group.id}<\/span>/

  # if the group does not have forums, offer a link to create them
  unless group.has_zcategories?
    assert_rjs :replace_html, 'zcore_inspector', /create_message_board/

  else
    root = group.private_councelling_category
    assert_rjs :replace_html, 'zcore_inspector', /#{to_json(root.description)}/

    # groups members have their private category, assert their names are mentioned
    root.subcategories.each do |c|
      assert_rjs :replace_html, 'zcore_inspector', /#{to_json(c.user.fullname)}/
    end
  end
The assertion doesn't match if the string has non-ascii characters that are encoded by the String.to_json() method. I got around this by creating a json wrapper method to_json(), with the 'falling matchsticks' and whatnot so the string properly evalutes in the regular expression.
def to_json(s)
s.to_json.gsub(/^\"|\"$/,'').gsub(/\\/,'\\\\\\\\').gsub(/\(/,'\(').gsub(/\)/,'\)')
end