Tuesday, February 4, 2014

GWT - UiBinder and CSS

The main problem with CSS is the lack of namespace, everything is mashed together into the same global namespace. This is handy for prototyping, however once more and more developers go into the same project, things starts to become tricky. If I want to have a class
.enabled {color:red;}
another developer working on some other component also writing
.enabled {color:blue;}
then we are in trouble

There are several techniques to help mitigate the problem. Learning from C (which has the similar problem). We can prefix everything, instead of
.enabled {color:red;}
we need to write
.myModule-enabled {color:red;}
or
.myModule .enabled {color:red;}
However I feel both of them are less than ideal, prefixing is just a hack around the deficiency of the language, the essence of the codes are about "enabled".

Here is how GWT solves this problem. We still write the naked "enabled" as it is, but the compiler will help us to generate a new class name and replaces the original one.

ComponentA.ui.xml
<ui:style>
    .enabled {color: red;}
</ui:style>

<g:HTML styleName='{style.enabled}'>
    content A
</g:HTML>

ComponentB.ui.xml
<ui:style>
    .enabled {color: blue;}
</ui:style>

<g:HTML styleName='{style.enabled}'>
    content B
</g:HTML>

Notice here, both A and B are using the same naked "enabled" css class name. After GWT compilation, the class names are changed to EI for ComponentA's enabled rule. Now we have two components running happily inside the same page with their preferred css class name.


Source codes are available from https://github.com/verydapeng/gwt-tutorials under /UiBinder-And-CSS/ folder