Showing posts with label YUI. Show all posts
Showing posts with label YUI. Show all posts

Friday, 20 March 2009

Dynamically load YUI dependencies

I've been using YUI Grids and LayoutManager for the backbone of my app's interface since the end of last year. It's been a steep learning curve and I still consider myself very much novice and, indeed, only noticed this week the 'dynamic loading' tab on the YUI Configurator. Rather than statically including the required YUI CSS and JavaScript resources, it is possible to use YUILoader to dynamically import them on load. While I appreciate that YUI-experts will not be impressed by my YUILoader-epiphany, this approach has helped me to slim down my app's JS files while decreasing maintenance concerns and so I feel is worth mentioning for the benefit of other noobs.

As described on the Configurator page, it is possible to define the required resources in YUILoader's constructor and to tweak YUILoader's behaviour to suit your application. I found two constructor arguments particularly useful, 'base' and 'onSuccess':


var loader = new YAHOO.util.YUILoader({
base: "//YUI build dir",
require: ["dom","element","event","fonts","grids","layout","reset","selector"],
loadOptional: false,
combine: true,
filter: "MIN",
allowRollup: true,
onSuccess: function() {
//Stuff that needs doing on load, e.g. running LayoutManager
}

});


YUILoader API documentation claims that the String value of base is the directory used by YUILoader when loading dependencies. However, I have noticed that no matter what directory location I pass as base, YUILoader fetches resources using the directory used to import YUILoader. That is, if I've imported src="http://yui.yahooapis.com/2.7.0/build/yuiloader/yuiloader-min.js" and set base to "http://yui.yahooapis.com/2.6.0/build/", YUILoader sucks down 2.7.0 versions of my required resources, whereas if I change the directory of the YUILoader import to 2.6.0 I get resources corresponding to this version. Perhaps I am missing something in how this all works, but I would expect to be able to override the YUILoader's build version by passing a value to base. On the upside, it is possible to control the resources gathered by YUILoader so, once you've gone to production, your app doesn't spontaneously upgrade with potentially dire consequences.

In contrast, I've found the onSuccess argument reliable for running the JavaScript used to render my app's display, i.e. to instantiate and run a LayoutManager. Previously I had included a script on every page to run LayoutManager, and have now been able to reduce the page-weight of my app by one file (before I've even started really polishing my frontend optimisation).

Finally, I've used YUILoader's insert() function to demand that only the JS, and not the CSS, dependencies are fetched:

var options = [];
loader.insert(options, "js");


I've overridden some of YUI's skin-sam CSS in my own CSS file which is imported after my third party resources. However, because the YUILoader inserts dependencies at the end of the page, my customisation of YUI's CSS was negated by a second and freshly imported batch of CSS dependencies. So, I've told YUILoader to just bring me the JS and I'll have to update the CSS version manually (unless of course some wise reader can suggest a more optimal solution).

Happy ui-coding.

Thursday, 12 February 2009

Dav Glass to the rescue or the curious case of the hidden border-right

The YUI Grids and LayoutManager issue described in a previous post has been fully resolved with the kind assistance of Dav Glass, LayoutManager developer and Twitter buddy. Thanks brother!

As suspected, the issue was rooted in my noob-i-licious implementation rather than in the YUI tools themselves. Early-stage work-arounds came back to haunt me, and Dav kindly made the necessary adjustments to my code. There were two main flaws with my implementation: 1) manually added wrapper divs and classes (these are applied automagically onload); 2) missing override to YUI class. So, the mark-up ends up as:

div id="custom-doc" class="yui-layout"

div id="hd" class="myHd"

div id="bd"
div id="yui-main"
div class="yui-b"
div class="yui-gc"
div class="yui-u first"Lorem ipsum dolor lacus feugiat.
div class="yui-u"Lorem ipsum dolor sit amet, acus feugiat.

div id="ft"


How tidy, clean and sexy is that?! Marvellous. Now, just to add a bit of CSS to customise the YUI resources to my app's look and feel:

.yui-layout-unit-center .yui-layout-wrap {background-color: #ffffff; border: 3px solid yellow;}

Score! Is great to get the code tighter and, of course, behaving as expected. Feeling evermore pumped for London Twestival this evening, as once again, in spite of what the nay-sayers and sceptics may say about social networking on the inter-web, the gloriousness of the enlightened telecomms age we live in has saved my proverbial bacon.

Wednesday, 11 February 2009

YUI Grids and LayoutManager: border-right of .yui-layout-unit-center doesn't render

In the process of developing my app I realised that my layout needed a slight overhaul. My goal is to increase the width of my main content area and to dispense with the right-hand nav bar in favour of tabs above the main content area (to be implemented using jQuery UI). I've created a template UI using YUI Grids with LayoutManager and I'd like to define a custom width for my content pane and give the main content area a white background and yellow border. I believe that I've faithfully followed the directions given with the YUI Grids + LayoutManager example, but I am unable to get the border-right to render in either FF3 or IE7. I've stripped the page right back to first principles, hoping to resolve the error with a simplified page, but have only succeeded in reproducing the error. Here she is:

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"

html

head
title YUI Base Page /title

link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?2.6.0/build/reset-fonts-grids/reset-fonts-grids.css
&2.6.0/build/layout/assets/skins/sam/layout.css"

style type="text/css"

body {margin: 0; padding: 0; font-family: Arial, sans-serif; font-size: small; color: #33333; background-color: #6699cc;}

#custom-doc {margin: auto; text-align: left; width: 88.46em;}

#hd, .yui-layout-unit-top {background-color: #6699cc;}

.myHd {background-color: #6699cc; margin-left: 1.92em;}

#bd, .yui-layout-unit-center {background-color: #ffffff;}

.yui-layout-unit-center {border: 3px solid yellow;}
/style

/head

body

div id="custom-doc" class="yui-layout"
div class="yui-layout-doc"

div class="yui-layout-unit yui-layout-unit-top yui-layout-noscroll"
div class="yui-layout-wrap"
div class="yui-layout-bd yui-layout-bd-nohd yui-layout-bd-noft"
div id="hd" class="myHd" /div
/div
/div
/div

//This the main content area
div class="yui-layout-unit yui-layout-unit-center"
div class="yui-layout-wrap"
div class="yui-layout-bd yui-layout-bd-nohd yui-layout-bd-noft"
div id="bd"
div id="yui-main"
div class="yui-b"
div class="yui-gc"
div class="yui-u first" Lorem ipsum dolor lacus feugiat./div
div class="yui-u" Lorem ipsum dolor sit amet, acus feugiat./div
/div
/div
/div
/div
/div
/div
/div

div class="yui-layout-unit yui-layout-unit-bottom yui-layout-noscroll"
div class="yui-layout-wrap"
div class="yui-layout-bd yui-layout-bd-nohd yui-layout-bd-noft"
div id="ft" /div
/div
/div
/div

/div
/div

type="text/javascript" src="http://yui.yahooapis.com/combo?2.6.0/build/yahoo-dom-event/yahoo-dom-event.js
&2.6.0/build/element/element-beta-min.js
&2.6.0/build/selector/selector-beta-min.js
&2.6.0/build/layout/layout-min.js"

(function(){
var Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event;

Event.onDOMReady(function() {
var layout = new YAHOO.widget.Layout('custom-doc', {
height: Dom.getClientHeight(), //Height of the viewport
width: Dom.get('custom-doc').offsetWidth, //Width of the outer element
minHeight: 150, //So it doesn't get too small
units: [
{ position: 'top', height: 70, body: 'hd' },
{ position: 'bottom', height: 25, body: 'ft' },
{ position: 'center', body: 'bd', grids: true }
]
});
layout.on('beforeResize', function() {
Dom.setStyle('custom-doc', 'height', Dom.getClientHeight() + 'px');
});

layout.render();

//Handle the resizing of the window
Event.on(window, 'resize', layout.resize, layout, true);
});
})();

/body
/html

I suppose I am missing some very fundamental point, but I've nearly exhausted the tricks up my sleeve to get this baby rendering as I'd expect and would be grateful for any insight from more expert UI developers. If and when, dear reader, I crack this nut I'll be sure to post my solution.

Monday, 19 January 2009

jQuery UI Dialog v. YUI Dialog

Background

I've recently been seeking to implement dialog boxes in the online learning application I am building (perhaps for launch by March '09 – watch this space). Having learned some hard lessons about getting these seemingly straightforward bits of display to render correctly while working for the start up www.bview.co.uk, I was determined to harness the collective intelligence embedded in one of the great UI frameworks of the enlightened times we live in. A fortnight later, after much pain, frustration and incandescant programming-induced rage, I've settled for a slightly 'hacked' implementation of jQuery UI's Dialog.

In the past 6 months I've morphed from a Java/Spring MVC/Hibernate web application developer into a Google App Engine/Python developer with sole responsibility for the design and implementation of my application's user interface. So, I am a bit novice when it comes to more advanced UI-coding and best practices, but I do have a good appreciation for JavaScript APIs, such as jQuery, and I have sought to take advantage of robust UI APIs in building my app. With the understanding that there are gargantuan gaps in my knowledge and skill set, I'd like to share with readers my experiences with YUI's and jQuery's Dialogs. On the one hand, I might get some guidance from more capable readers, and on the other I might help other noobs avoid some of the intense pain I suffered especially as regards the freshly born (and slightly flakey) jQuery Dialog.

I built my initial UI using YUI Grids and LayoutManager. I found this process to be pretty straightforward and have been really impressed with these products' reliability and performance cross-browser (resizing is weird in Chrome, but that seems to be a more general issue). When it came time to add buttons to the site, I naturally opted for YUI Button, a basic implementation of which I was able to get running super fast. However, customising the look and feel seemed to require more effort than I was willing to put in at this early stage of development, and I left that to one side. The complexity of YUI and the steepness of the learning curve really hit home, however, when I sought to implement YUI Dialog.

The Use Case

I've got a list of items. Next to each item is a cross icon the user may click to delete. The goal is to display a Yes/No dialog to confirm a user's intent to delete a given item before initiating an AJAX call to delete the item.

Attempt 1: YUI Dialog

Having had a reasonably carefree relationship with YUI up to this point, I initially sought to use YUI's Dialog. I was able to get a basic example from YUI's site running in short order:

YAHOO.namespace("example.container");
function init() {
YAHOO.example.container.simpledialog1 = new YAHOO.widget.SimpleDialog("simpledialog1",{
width: "20em",
fixedcenter: false,
visible: false,
draggable:false,
close: true,
text: "Delete this",
icon: YAHOO.widget.SimpleDialog.ICON_WARN,
constraintoviewport: true,
buttons: [ { text:"Yes", handler:handleYes, isDefault:true },
{ text:"No", handler:handleNo } ],
context: ["show", "bl", "bl"]
} );

YAHOO.example.container.simpledialog1.setHeader("Are you sure?");
YAHOO.example.container.simpledialog1.render("container");

YAHOO.util.Event.addListener("show", "click",
YAHOO.example.container.simpledialog1.show,
YAHOO.example.container.simpledialog1, true);
YAHOO.util.Event.addListener("hide", "click",
YAHOO.example.container.simpledialog1.hide,
YAHOO.example.container.simpledialog1, true);
}
YAHOO.util.Event.addListener(window, "load", init);

In my markup I added:

div class="yui-skin-sam"
div id="container"
button id="show"Show simpledialog1/button
button id="hide"Hide simpledialog1/button
/div
/div

This worked like a dream. Problems came thick and fast, however, when I sought to extend this simple use case to fit the needs of my app. Essentially I could not figure out how to dymanically instantiate multiple dialogs, each one associated with a particular delete cross. For instance, where I retrieved all elements with a particular class (e.g. all elements with .delete-cross) I was unable to loop the returned array and create a new YAHOO.widget.SimpleDialog with a variable name and etc dynamically generated from the element's id attribute. Ultimately I was only able to create one YAHOO.widget.SimpleDialog which was associated with the last element in the collection. It was around this time that Twitter lit up with news of jQuery's 1.3 release and I thought, 'I wonder if my beloved jQuery's UI API is as kick ass as its JavaScript API?'

Attempt 2 : jQuery Dialog

I went to the jQuery UI site and hit the Gallery / Themeroller, which had me very excited as it looked like I could get something much more inline with my app's look and feel 'out of the box' than with YUI and perhaps roll it out for my buttons and etc. I got the resources downloaded and into my project, no drama. I got the basic use case running in a snap, i.e. ("#dialog").dialog("open"). I was feeling full of hope and optimism and generally love for my old pal jQuery. These rosy feelings soured as, again, going beyond the basic use case was exceptionally problematic.

Once I started to customise the dialog that was instantiated in the JavaScript, things went haywire. In particular setting autoOpen to false (it defaults to true) caused me no end of hassle. The documentation claims: "When autoOpen is true the dialog will open automatically when dialog is called. If false it will stay hidden until .dialog("open") is called on it." Indeed, setting autoOpen did not hide the dialog div on page load. I attempted to hide the dialog div on page load by: a) setting style="display: none"; b) adding .ui-helper-hidden to the markup. Both of these approaches did hide the dialog div on page load, but when .dialog("open")was invoked, the dialog did not render correctly; the content area of the div was obscured because it was not clearing between the title and content areas of the dialog.

OK, back to the jQuery UI theming API where I discovered some utility classes, but things got especially hairy when, if I added .ui-helper-clearfix, the dialog div was displayed on page load, but when opened the dialog's content was rendered incorrectly. Calgon – take me away! I resolved these issues, but am not satisfied with my hack-around and I would like to be able to use the API in a more pure way.

I added an empty dialog div in the markup:

div id="dialog" title="Are you sure?" class="ui-helper-clearfix"
p
span id="icon"/span span id="message"/span
/p
/div

I then dynamically generate the spans' content in the JavaScript:

$("#message").html("Delete this?");
$("#icon").addClass("ui-icon").addClass("ui-icon-alert");

I then instantiate and open the dialog:

$("#dialog").dialog({
autoOpen: false,
bgiframe: true,
buttons: {
"Yes": function() {
delete();
},
"No": function() {
$(this).dialog("close");
}
},
minHeight: 0,
modal: true,
overlay: {
backgroundColor: '#000000',
opacity: 0.5
},
resizable: false
});
$("#dialog").dialog("open");

At this point, I thought I was good to go and could go in peace that'd I'd gotten this running in an acceptable, if less than optimal way. Oh, silly, silly me.

While I found tweaking the CSS used in the dialog to get it just right for my app much easier than with YUI, overriding the minHeight default of 47px by setting the minHeight option in the constructor caused IE7 to yelp in pain. So, bring on the browser sniffing:

if($.browser.msie){
$("#dialog").dialog({
autoOpen: false,
bgiframe: true,
buttons: {
"Yes":function() {
delete();
},
"No": function() {
$(this).dialog("close");
}
},
modal: true,
resizable: false
});
$("#dialog").dialog("open");
} else {
$("#dialog").dialog({
autoOpen: false,
bgiframe: true,
buttons: {
"Yes": function() {
delete();
},
"No": function() {
$(this).dialog("close");
}
},
minHeight: 0,
modal: true,
overlay: {
backgroundColor: '#000000',
opacity: 0.5
},
resizable: false
});
$("#dialog").dialog("open");
}

This solution is still being reworked as I hope to get overlay to play nice in IE7, but this is pretty much how I got where I needed to go. It is much less elegant than I'd like, and while it is acceptable in FF3 and IE7 it starts scrolling the content area in Chrome (but is anyone using it?).

Conclusion

While I believe that YUI might provide a more robust solution, I find building up the complexity of an implementation too difficult considering pressures in terms of releasing my app this quarter (already a quarter behind schedule, but then I made major tech shift to GAE in November so can live with that). If it was more clear how to dynamically instantiate the YUI widget, I might've stuck with it and struggled with customising the skin, but as the jQuery option allowed much faster take-up and customisation, it is much more practical for me at this time. I am hopeful that as the jQuery UI project matures it will become as resiliant and reliable as its JavaScript API.