SOS

Shane O'Sullivan's technical blog… really ties the room together

Archive for the ‘open source’ Category

Cool Portlets added to Dojo!

Posted by Shane O'Sullivan on June 1, 2009

Last week I put the finishing touches my Portlets for the Dojo Ajax Toolkit.  You can see them now on the test page at http://archive.dojotoolkit.org/nightly/dojotoolkit/dojox/widget/tests/test_PortletInGridContainer.html (it can take a while to load since it loads a hell of a lot of widgets and the code is not optimized with a build).

To see a description of what they can do, see my original post announcing them at https://shaneosullivan.wordpress.com/2009/03/11/cool-portlets-in-dojo

As a brief description, Portlets are widgets that represent individual applications used in a web portal.  They can be rearranged by dragging and dropping them around the page, and can often be customised with a number of settings.

The Dojo Portlets, in the dojox.widget project, support some useful features like:

  • Customisable settings widgets, for setting user defined options.
  • Loading Atom and RSS feeds to display as a list

and a good bit more.  See my previous post for a full description, or check out the test page.

Below you can see the Portlets using the blue Soria theme from Dojo.  There will probably be some small changes to the look and feel before v1.4 is released, but nothing major.  Note the different types of Portlets, from the Atom & RSS feed portlets on the left that can show more detail using tooltips or expandable secrions, to portlets containing generic widgets like a slideshow on the right.

Have fun!

Portlets

Posted in Ajax, Atom, dojo.data, dojo.image, dojox, dojox.image, Javascript, open source, tab | Tagged: | 16 Comments »

Code style checker for Dojo

Posted by Shane O'Sullivan on May 23, 2009

I’ve added a code style tool to the Dojo Util project that developers can use to ensure that their code is following the syle guidelines published here –http://www.dojotoolkit.org/developer/StyleGuide .

You can see the current report, as of May 23rd 2009 at http://skynet.ie/~sos/misc/dojoCheckstyle/util/checkstyle/checkstyleReport.html

It can be very difficult to police your own code for tabs and spaces, and developers have much better things to be doing with their time than visually scanning over their code making sure that it is formatted correctly.

This tool identifies style guide violations, and gives developers a HTML file that displays them, and automatically fixes many of the common mistakes for you.  (This works best in Firefox right now, so you that if you have it)

The style checker is primarily aimed at Dojo contributors, but can also be used by normal users of the toolkit.  To override the standard folders that are examined, you can simply set the ‘dir‘ parameter relative to the Dojo base folder, and a checkstyle report will be generated for you custom code.

To see how to use the tool, get the latest vode from svn, the go to util/checkstyle and type

checkstyle.bat help

To run the checkstyle tool on the entire Dojo tree, simply type

checkstyle.bat

then open the checkstyleReport.html file, which you can see below.

If you want to be able to save files from the web interface, you’ll have to renamve the file checkstyle.php.rename.html to checkstyle.php, then click the Save or Save All buttons in the UI.

There is a ticket to track all checkstyle fixes at http://bugs.dojotoolkit.org/ticket/7390 , so can developers please reference this when checking in style fixes?

Checkstyle UI

Posted in Ajax, Dojo, open source | 6 Comments »

EasyCheckboxes: dojo.query and Greasemonkey

Posted by Shane O'Sullivan on May 2, 2009

I’ve written a useful script for Firefox and Greasemonkey called EasyCheckboxes.  It makes it more convenient to work with multiple checkboxes on a page, enabling you to select, deselect or toggle groups of checkboxes. It will also work with all web pages.

See the video below for more info, or you can install it right now by clicking here, or by visiting the script homepage at http://chofter.com/apps/?n=easycheckboxes

Context Aware Selections

One of the most useful features of EasyCheckboxes is that it is context aware.  It figures out what checkboxes are related to the one you chose, and only changes the state of those. This is useful if you have multiple columns of checkboxes, and you only want to check all inputs in one column.

Of course you can also change the values of all checkboxes on the page.

Using Dojo’s query engine, Acme, in Greasemonkey

If you’re not interested in the techie details, you can stop reading now.

Since version 1.3 of the Dojo Ajax Toolkit, it provides a standalone DOM query engine called Acme.  I compressed this down to a single line of code, and inserted it in my GreaseMonkey script.   I previously tried using the Sizzle query engine, but it had too many issues with Greasemonkey, the main being that it sometimes crashed the browser.

Using it is very simple.  Simply call:

acme.query(“.someClass”, unsafeWindow.document);

And it returns an array of the matching nodes.

Posted in Ajax, Dojo, dojo.query, greasemonkey, Javascript, open source, Technical | Leave a Comment »

Cool Portlets in Dojo

Posted by Shane O'Sullivan on March 11, 2009

I’ve been working on writing Portlets for the Dojo Ajax Toolkit for a while now, and they’re almost ready.

You can see a demo of it at http://www.skynet.ie/~sos/misc/dojo/dojox/widget/tests/test_PortletInGridContainer.html?theme=soria

A Portlet is similar to a dijit.TitlePane, in that it has a title bar, a content area, and is collapsible.  However, it should also have the option of being configurable, perhaps using a dialog box or an expandable area.  A nice example is the BBC website at http://bbc.co.uk, or the Google Portal http://www.google.com/ig.

Portlets are generally presented in a draggable grid, and a very cool new addition to Dojo is the dojox.layout.GridContainer, which provides this framework.

A number of types of Portlets and Setting widgets will be provided, hopefully in v1.4 (1.3 is in final beta, so this is too late for that).

  • dojox.widget.Portlet – this is the basic Portlet, which provides a close button, a collapse button, and a settings button.  All of these are optional.
  • dojox.widget.FeedPortlet – this Portlet loads an external Atom or RSS feed and displays it as a list.  Hovering over an item shows a dijit.Tooltip with a summary of the news story.
  • dojox.widget.ExpandableFeedPortlet – similar to FeedPortlet, but instead of using tooltips, a toggle icon is used to show more or less of a news story.
  • dojox.widget.PortletSettings – a widget that can be placed inside a Portlet to provide customizable settings for that widget.
  • dojox.widget.PortletDialogSettings – like PortletSettings, but the configuration options are displayed in a dijit.Dialog.
  • dojox.widget.PortletFeedSettings – provides one or more URLs to Atom or RSS feeds for a FeedPortlet to load.

These widgets offer pretty large set of functionality, which should be sufficient for the majority of peoples needs.  However, this is still in active development, and if you have any ideas for cool additions or changes I could make, please let me know.

Posted in Ajax, Atom, Calendar, chart, charting, Date Picker, demo, dijit, Dojo, dojo.charting, dojo.data, dojox, open source, widget | 74 Comments »

Dojo & GreaseMonkey == DaftMonkey

Posted by Shane O'Sullivan on January 26, 2009

Given that I’m looking for a new apartment, and I live in Ireland, I use the property search website Daft.ie.  Everyone does.  However I wasn’t very happy with how slow it is to scan through the many results that match my meagre budget.  I realised that it could be readily fixed with GreaseMonkey, using the Dojo Ajax Toolkit to make life easier when it comes to parsing the page, adding effects etc.

The result is DaftMonkey.

I wasn’t even sure if Dojo could be used from within a GreaseMonkey script, as it sandboxes away the custom script code.  However, with a little hackery it was (more or less) possible.  The steps I took were:

  1. Set up the djConfig parameter in the host window to tell Dojo that the page had already loaded, using unsafeWindow.djConfig = {afterOnLoad: true};. unsafeWindow is what GreaseMonkey calls the normal, non-sandboxed window.
  2. Added the <script> tag for dojo.js to the head of the document.  In this case I used the dojo.js.file hosted on AOL’s CDN servers – see http://dev.aol.com/dojo .
  3. Now you have to wait for Dojo to load.  This can be done with a simple setInterval function call, checking if unsafeWindow.dojo exists or not.  (Update: thanks a comment from James, this has been changed to use the djConfig.addOnLoad function)
  4. Once Dojo is loaded, you can call a function kicking off whatever it is that you  script is supposed to do.  In this case, I wanted to add a bunch of DOM nodes to the page (which you can do without Dojo), and add some cool effects, so I also included the dojo.fx bundle.
  5. Copy the dojo variable back into the sandbox window using var dojo = unsafeWindow.dojo, otherwise you’ll have to refer to it as unsafeWindow.dojo all the time.

Screen Scraping With dojo.query

A lot of the features of DaftMonkey rely on asynchronously fetching remote HTML pages and scraping the required data from them.  The approach I used for this was:

  1. Perform a remote request using GreaseMonkey’s native Ajax function GM_xmlhttpRequest.  This works more or less the same as dojo.xhrGet, and I saw no reason to not use it.
  2. When the text is returned, create a DIV, and absolutely position it far to the left.  Fix it’s size to just one pixel so it doesn’t mess with the scroll bars.
  3. Set the innerHTML of the DIV to the text you have retrieved.  Congratulations, you can now use dojo.query to find whatever nodes you need.  e.g. to find all images inside anchor tags, use dojo.query(“a img”, tempDiv).  Note the second parameter, this tells Dojo to only search inside the temporary DIV we created, and not the whole document.

Some other site-specific things were required as part of the screen scraping process.  Many of the sites had iframes included, and as soon as you add those to the temporary DIV, they start loading another page.  This was a nasty performance hit, so I had to remove them from the HTML string before setting the innerHTML of the temporary DIV.

Problems

One problem I found is that calling dojo.declare didn’t work from inside a GreaseMonkey script.  I don’t know why.  Therefore widgets had to be defined the old fashioned way.

A second problem was more related to the website I was writing the script for, Daft.ie.  The entire site is programmed using TABLES!  Seriously, there’s barely one or two DIVs on the page, with practically no CSS either.  This makes it quite difficult and brittle to screen scrape using dojo.query, as there’s really no classes to match.  Still it was possible, but could break relatively easily if the site layout is changed.

Get the Source

You can get the entire source for the script at http://userscripts.org/scripts/show/41105 .

To read a bit more about DaftMonkey, I’ve put up a page about it at http://www.chofter.com/apps?n=daftmonkey .

Posted in Ajax, Dojo, dojo.query, greasemonkey, Javascript, open source, search, widget | 8 Comments »

Deleting DOM nodes with Dojo

Posted by Shane O'Sullivan on January 2, 2009

This is a quick and simple tip for deleting multiple DOM nodes in JavaScript using the Dojo Ajax Toolkit.

A common pattern in non-trivial Ajax applications is the need to delete many nodes that may or may not have been created.  The code to do this without Dojo (or a similar library such as jQuery) would look something like the following code (assuming nodes are identified by ID):

var nodeIDs = ["node1", "node2", "node3"];
for (var i = 0; i < nodeIDs.length; i++) {
 var node = document.getElementById(nodeIDs[i]);
 // Verify that the node actually exists, otherwise an error occurs
 if (node) {
  node.parentNode.removeChild(node);
 }
}

This is of course a bit messy.   It would be infinitely messier if you needed to match nodes not by ID, but by another method such as by class name, relative position to it’s parent or sibiling nodes etc.

To achieve the same in Dojo, use this simple code.

var nodeIDs = ["#node1", "#node2", "#node3"];
dojo.query(nodeIDs.join(",")).orphan();

Update: There is a bug in Dojo that means that if the node with ID “node2” does not exist, “node3” will not be deleted.  (Thanks to Pete Higgins for letting me know). Instead use the following code:
dojo.forEach(arr, "dojo.query(item).orphan();");

Very simple, and much smaller and cleaner than the previous example.  It also scales very well to match nodes using CSS selectors, not just by ID.  For example, to delete nodes both by ID and class name, use the following code.

var nodeIDs = ["#node1", "#node2", ".className1", ".parentClass .childClass"];
dojo.query(nodeIDs.join(",")).orphan();

Update: as with the first example, replace the second line with:
dojo.forEach(arr, "dojo.query(item).orphan();");

For more info on the cool features of dojo.query, see the docs at http://docs.dojocampus.org/dojo/query .

Posted in Ajax, Dojo, dojo.query, Javascript, open source | 14 Comments »

dojox.gfx: Rotating in an elliptical line

Posted by Shane O'Sullivan on December 7, 2008

This post describes how to get a shape to rotate a central point following an elliptical path, using the Dojo Ajax Toolkits cross browser graphics engine, dojox.gfx. To see it in action, go to http://www.skynet.ie/~sos/misc/EllipseAnim.html

dojox.gfx is built in much the same way as SVG, with most of the same capabilities.  When it comes to moving shapes around a surface, it provides useful translations that move objects in straight lines, circles and more.

You can also combine different transformation matrices together to create more complex animations.  However, this is difficult in the extreme unless you have an really (and I mean REALLY) good grasp of matrix transformations and Cartesian coordinate manipulation.  Which I don’t.  And it is unlikely that you, the good reader, do either (if you do, I heartily apologise).

Anyhow, I had the requirement to rotate a small circle in an elliptical shape around a central point.  After much hacking, I gave in and asked Eugene, the dojox.gfx author, and one of the guys who DOES understand all this matrix stuff, and he solved it.

The trick is use two transformations simultaneously:

  • The first transformation rotates the shape around a point by 180 degrees.  This is not the central point of the ellipse.  For simplicitys sake, I start the animation with the shape at the leftmost point of the ellipse, level with the ellipse central Y point.  The point around which the shape should rotate has an X position equal to the central point of the shape plus the Y radius of the ellipse, and a Y point equal to the centre Y of the ellipse.
  • The second transformation moves the shape from left to right in a straight line.  This starts from the origin of the shape, and ends just short of the right hand median point of the ellipse.  The distance between the end of the lateral linear transformation and the rightmost point of the ellipse is twice the radius of the circle used for the rotation translation.  The reason for this is that the rotation transformation will, by the end of the linear transformation, have moved the shape twice the radius of the rotation circle in the X direction, so this must be subtracted from the lateral linear transformation.

The code I used for this is shown below.  Feel free to take it and play around.

<html>
<head>
<style type="text/css">
@import "../dojo/resources/dojo.css";
@import "../dijit/tests/css/dijitTests.css";
</style>
<script type="text/javascript" src="http://o.aolcdn.com/dojo/1.2.0/dojo/dojo.xd.js"
djConfig="isDebug: true"></script>

<script type="text/javascript">
dojo.require("dojox.gfx");
dojo.require("dojox.gfx.fx");
dojo.require("dojo.fx");
dojo.require("dojox.gfx.matrix");
dojo.require("dojo.fx.easing");

var circle, surface, cx = 50, cy = 200, rx = 40, ry = 20;
var ellipse;

dojo.addOnLoad(function(){

var domNode = dojo.byId("test");
// Create the surface, this contains all the graphics objects
surface = dojox.gfx.createSurface(domNode, 400, 400);

// Create the circle shape to be moved in a elliptical line
circle = surface.createEllipse({cx: 10, cy: cy, rx: 5, ry:5});
circle.setFill("blue");

// Create an elliptical line, just to show you the path it will take
ellipse = surface.createEllipse({cx: cx, cy: cy, rx: rx, ry: ry});
ellipse.setStroke("black");
});
// Define a function to create an animation.
//'isLTR' means 'Is Left To Right'

function getAnim(isLTR) {

var g = dojox.gfx, m = g.matrix;
var startAngle = isLTR ? 0 : 180;
var endAngle = isLTR ? 180: 360;
var startX = isLTR ? 0 : rx;
var endX = isLTR ? rx: 0;

return g.fx.animateTransform({
shape: circle,
duration: 1000,
transform: [
// The first transform just moves the shape either from
// left to right, or right to left

{name: "translate",
start: [startX, 0], end: [endX, 0]},
// The second transform rotates the shape in a circular
// path

{ name: "rotateAt",
start: [m._degToRad(startAngle), cx - ry, cy],
end: [m._degToRad(endAngle), cx - ry, cy]}
],
onEnd: function(){
// When the animation to make the circle go
// half way around the ellipse finishes,
// start it again in the opposite direction

getAnim(!isLTR).play();
},
easing: dojo.fx.easing.linear
});
}

function animate() {
var anim1 = getAnim(true);
anim1.play();
}

</script>
</head>
<body>
<button onclick="animate()">Animate!</button><br/>
<div id="test" style="border:1px solid black;margin-top:10px;"></div>

</body>
</html>

Posted in Ajax, Dojo, dojox, dojox.gfx, Javascript, open source, svg, Technical | 2 Comments »

Context Menus And Korean Added To Chofter, 한국어판 출시

Posted by Shane O'Sullivan on October 17, 2008

Today two features I’m very happy with were added to Chofter, the next-generation search engine.

오늘 두가지의 새로운 기능이 Chofter, 차세대 검색 엔진,에 업데이트 되었습니다.

The first feature is the Context Menu. A new orange icon is placed next to search results which, when clicked, gives you list of actions you can take on the link in the search result. For example, you can create a bookmark, send it to Digg, add it to your online bookmarks at del.icio.us, share it on Facebook, and more. The image below shows it in action.

첫번째 기능은 팝업 메뉴창입니다. 검색 결과 페이지에 오렌지색의 아이콘들이 새롭게 만들어 졌는데, 이 아이콘을 클릭시 검색 결과에 관련된 링크 리스트가 보여집니다. 예를 들면 특정한 결과 페이지를 북마크에 더한다거나, del.icio.us로부터의 개별적인 온라인 북마크, Digg 사이트에 더할수도 있으며, 또는 페이스북에 원하는 검색 결과를 공유하는 등의 여러가지 기능이 더욱 손쉬어 졌습니다. 아래 사진에서 확인할수 있구요:-)

The second feature is Chofter’s first Asian language, Korean (which is why this post is in both languages). The translation was done by the lovely Francesca Kim, otherwise known as my main distraction.

두번째 새로운 기능은 Chofter의 첫번째 아시안 언어, 한국어 사용이 가능해졌습니다. 번역은 Francesca Kim님이 도와주셨습니다.

Chofter Context Menu

Chofter Context Menu

Posted in Ajax, chofter, dijit, Dojo, dojo.data, dojox.data, Javascript, open source, Technical | 1 Comment »

More Offline Goodness With Dojo

Posted by Shane O'Sullivan on September 23, 2008

Kris Zyp from SitePen has posted an article about the Dojo Ajax Toolkit‘s latest addition to it’s Offline Web capabilities, OfflineRest. Check it out at http://www.sitepen.com/blog/2008/09/23/effortless-offline-with-offlinerest.

The idea is brilliant – if you send your data to the user using the JsonRestStore, you can now add an amazingly simple offline capabilty to your website with two lines of code (more or less).

This rocks.

There’s also an interview with Kris over at Ajaxian – http://ajaxian.com/archives/audible-ajax-episode-30-interview-with-kris-zyp

Posted in Ajax, Dojo, dojo.data, dojox.data, json, offline, open source | Leave a Comment »

Setting the default locale in Dojo using PHP

Posted by Shane O'Sullivan on September 13, 2008

When writing locale aware JavaScript for a browser environment,  you only have access to the locale that the browser used upon installation.  If the user changes their preferred locale, a JavaScript application has no way of detecting it.  See the Dojo documentation for more details on this at http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/i18n/specifying-locale

However, the list of accepted languages are sent to the web server in the request headers.  It is also possible to instruct Dojo as to which locale to use.  Below is an example of how to do this in PHP

<?php
 // Get the array of request headers
 $h = getallheaders();
 // Retrieve the 'Accept-Language' header, a comma separated list
 $langs  = $h['Accept-Language'];
 // Parse the first language
 $locale=strtok($langs,",");
 if(strlen($locale) < 1) {
  // Set a default language if you like
  $locale = "en";
 }else {
  // Make sure that the optional 'q' parameter is not included
  $locale = strtok($locale, ";");
 }
?>
<script type="text/javascript" src="dojo/dojo.js" djConfig="parseOnLoad:true,locale:'<?=$locale?>'"> </script>

Note the djConfig attribute when including the dojo.js file. It specifies the locale to be used.

Posted in Ajax, Dojo, i18n, Javascript, open source, Technical | Leave a Comment »

 
%d bloggers like this: