Archive

Archive for the ‘Web’ Category

Shift an array in O(n) in place

April 7, 2015 Leave a comment

Below I copied the code for shifting an array in place.

void shift(Object[] array, int startIndexInclusive, int endIndexExclusive, int offset) {
if (array == null) {
    return;
}
if (startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
    return;
}
if (startIndexInclusive = array.length) {
    endIndexExclusive = array.length;
}        
int n = endIndexExclusive - startIndexInclusive;
if (n  0) {
    int n_offset = n - offset;
    
    if (offset > n_offset) {
        swap(array, startIndexInclusive, startIndexInclusive + n - n_offset,  n_offset);
        n = offset;
        offset -= n_offset;
    } else if (offset < n_offset) {
        swap(array, startIndexInclusive, startIndexInclusive + n_offset,  offset);
        startIndexInclusive += offset;
        n = n_offset;
    } else {
        swap(array, startIndexInclusive, startIndexInclusive + n_offset, offset);
        break;
    }
}

The swap(array, index1, index2, len) method swaps in the given array the elements from [index1, index1 + len) with the ones [index2, index2 + len).

Even though it may seem complicated at first, the idea is pretty simple. If the offset is half of array length, or in other words if offset == (n – offset), where n is the total number of elements to be shifted, then the shift is equivalent of swapping the two halves of the array.
For the first two cases we swapped the portions at the ends and one of them will come in place and we will continue the iteration for the rest as shown in the below figure.

shift algorithm

Space complexity is clearly O(1), but what about time complexity. I’m gonna prove that it is O(n).

Let Sh(n, k) be the problem of shifting k positions in an array of size n and Sw(k) be the problem of swapping k elements in an array. For the sake of simplicity I left out the start and end indices.

It is obvious that O(Sw(k)) = O(k).

It is also obvious that O(Sh(1, k)) = O(1), with k < 1. Also O(Sh(x, 0)) = O(1).

Now let's assume that O(Sh(n, k)) = O(n), whatever n, with k < n. I'll try to prove that O(Sh(n + 1, k')) = O(n), with k' < n + 1.

Analyzing the algorithm we have

O (Sh(n + 1, k’)) = max(
O(Sw(n + 1 – k’)) + O(Sh(k’, 2k’ – n – 1)), if 2k’ > n + 1
O(Sw(k’)) + O(Sh(n + 1 – k’, k’)), if 2k’ < n + 1
O(Sw(k')), if 2k' == n + 1
)

  • First case 2k’ > n + 1

    O(Sh(n + 1, k’)) = O(Sw(n + 1 – k’)) + O(Sh(k’, 2k’ – n – 1)) = O(n) + O(Sh(k’, 2k’ – n – 1))

    Because (k’ < n +1) ⇒ (k' ≤ n) and (2k' ≤ 2n) ⇒ (2k' – n – 1 ≤ n – 1) ⇒ (2k' – n – 1 < n), then O (Sh(n + 1, k')) = O(n) + O(n) = O(n).

  • Second case 2k’ < n + 1

    O(Sh(n + 1, k')) = O(Sw(k')) + O(Sh(n + 1 – k', k')) = O(k') + O(Sh(n + 1 – k', k')) = O(n) + O(Sh(n + 1 – k', k'))

    Because (0 < k') ⇒ (n + 1 – k' < n + 1) ⇒ (n + 1 – k' ≤ n) and (k' < (n + 1)/2) ⇒ (k' ≤ n/2) ⇒ (k' < n), then O(Sh(n + 1, k')) = O(n) + O(n) = O(n).

  • Third case 2k’ == n + 1

    O(Sh(n + 1, k’)) = O(Sw(k’)) = O(n)

So O(Sh(n + 1, k’)) = O(n). As a consequence O(Sh(n, k)) = O(n), whatever n, with k < n.

The code will become part of commons-lang, ArrayUtils class, as of version 3.5.

Categories: Web

WebRTC saga

February 5, 2015 Leave a comment

Recently I started using WebRTC. Cool technology. You can build a web chat in just tens of lines of code, you can take pictures with your webcam and using canvas you can manipulate them. And these are just a few examples of what WebRTC can do for you and your web app.

Tens of lines of code indeed. But not easy lines at all. Even though WebRTC will enable peer-to-peer communication, you still need some server components. These server components are involved in the session initiation.

First there is a ICE/STUN/TURN server that it’s used for a client to discover its public IP address if it is located behind a NAT. Depending on your requirements could not be necessary to build/deploy your own server, but use an already public (and free) existing one – here‘s a list. You can also deploy an open source one like Stuntman.

Then it comes the signaling part, used by two clients to negotiate and start a WebRTC session. There is no standard here and you have a few options.

You can use an XMPP server with a Jingle extension. Developing your own XMPP server (or component) just for this will be an overkill, so you should definitely consider using an existing one. But even installing, configuring and integrating an existing one could be too much if you don’t use it for anything else. But if you already have one in your infrastructure, you could hook up into it. On the client side, you can use an existing XMPP JavaScript library.

You can also use SIP, a protocol much more encountered for VoIP. Like XMPP, SIP it is too much to be used just for WebRTC signaling. If you already have it in your infrastructure, then could be easy to use it. As for SIP, in Java you have two development options.

The high level one is SIP servlets with its most notable implementation, Mobicents. If you develop a non-GPL application, Mobicents commercial license could be quite expensive just for WebRTC signaling.Mobicents is developed on top of Tomcat or JBoss, so, depending on your environment, this could also be a drawback.

The lower level option for SIP is JAIN-SIP, on which even Mobicents is developed on. It is completely free. There you have different protocol options, like TCP, UDP or websockets. And for WebRTC the latter will be more appropriate.

With both options, you’ll still have to develop the server logic and SIP is a pretty cumbersome protocol so prepare yourself for a few headaches.

If you decide for SIP, on the client side, things could be a little bit brighter. There are already JavaScript SIP signaling solutions that you can easily integrate into your web applications. I looked into JsSIP and SIPJS and I ended up using the latter. SIPJS is actually forked from JsSIP, but it encapsulates the intricacies of the protocol better, which makes it a little bit easier to integrate.

Another option is to develop your own signaling protocol using something like websockets. Then you have to develop from scratch both the client and the server side part. Developing the server side part, in my opinion, will be easier than the previous options. You have to practically develop a messaging system, that forwards messages between users, without caring too much about the content. @ServerEndpoint abstracts development in an elegant manner and you can even use your existing authentication system as you can bind a websocket session with the HTTP one.

If you’re worried about websockets browser support, don’t. Wherever WebRTC is supported, Web Sockets are too.

In the client side, things will be a little bit more complicated, as you will have to develop the entire message flow, the server will just forward your messages to the appropriate peer. This entire flow should be asynchronous, something like a request-response paradigm.

The development difficulty arises here mainly from the different behavior on various browsers. And by various, I mean Firefox and Chrome, the main ones supporting WebRTC.

When it comes to WebRTC you don’t have to code anything for actually streaming, but only for initiating the session. Theoretically, WebRTC session initiation process is as follows. Let’s suppose A wants to talk B. And for the sake of simplicity we will use A signals B with the meaning that A sends a message to B through the signaling channel.
1. A will create and initialize an RTCPeerConnection. Few things involved here: a list of addresses of the ICE/TURN/STUN servers, a local stream to share with B.
The list of ICE servers is passed in the constructor, the local stream is obtained through navigator.getUserMedia() and added afterwards.
2. Using that connection A creates a SDP(session description protocol) offer.
3. A signals B the offer
3. When B receives the SDP offer from A (or even before) will create the RTCPeerConnection like in step 1.
4. B will set the remote session description like RTCPeerConnection.setRemoteDescription(new RTCSessionDescription(SDPOfferFromA)), where SDPOfferFromA is the JSON object received through the signaling channel.
5. B will create a SDP answer.
6. B signals A the answer
7. When A receives the answer, sets the remote description like in step 4, using SDPAnswerFromB.
8. Asynchronously, when a new ICE candidate is discovered and presented through the onicecandidate event of RTCPeerConnection, A (or B) should signal it to B (or A). When the other party receives it, B (or A) will add it using RTCPeerConnection.addIceCandidate(new RTCIceCandidate(candidateDescriptionReceived)).

Again, theoretically. In practice …

First of all, because WebRTC is not final, but in draft state, all the types are prefixed, like mozRTCPeerConnection (in Firefox) or webkitRTCPeerConnection (in Chrome and Opera). But this can be easily fixed.

window.RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;

.

Then it comes the ICE candidates part. In Firefox the ICE candidates must be gathered before creating an SDP offer or answer. So before creating an offer/answer, check RTCPeerConnection.iceGatheringState and do it only if it is "complete".

There are also few inconsistencies when it comes to the media constraints passed to navigator.getUserMedia().

In the end, I can conclude that WebRTC is really cool and you can build media application in matter of tens or hundreds of lines of code. I guess it could have been designed to be easier to use. Even though there are a lot of opinions stating that the signaling protocol is better left out of the standard, I still think that it will be better if an optional one is included. Or at least a minimal easy to implement API.

Categories: Web Tags: ,

Choosing an XMPP server

January 28, 2015 1 comment

I was working lately with WebRTC. One of the biggest issues there is the signaling part.

As an option you can choose XMPP with its Jingle extension. So, naturally I was looking into a few XMPP servers. What are the requirements that I was chasing for these?

My architecture is a Java based, so I was looking into solutions based on this technology. I know that I can integrate different technologies through things like LDAP or web services, but … If I needed something custom, it would have been much easier to develop something in Java. So as a nice to have, the final solution should be extensible through some kind of plugin system. Another requirement was to be open source or at least affordable.

Taking these into account I narrowed down the list to OpenFire, Tigase, Apache Vysper and Jerry Messenger.

Apache Vysper aims to be a modular, full featured XMPP (Jabber) server. Unfortunately, it is not out-of-the-box to feature an easy installation and integration procedure. It also seems to be in a beta stage, not production ready.

Jerry Messenger has an embedded Jetty server, it can be easily configurable and it features a plugin-able system.

OpenFire seemed the most complete solution in its field. It has a very rich web admin interface, a plugin system and extensive documentation. As a bonus, it is just a web application so you can install it in your favorite web application server along with your other web applications.

Tigase claims to be the most scalable XMPP server supporting hundreds of thousands of concurrent users. It is configurable, standalone and plugin-able. Unfortunately the documentation is not as extensive.

Clearly, my preference went towards OpenFire and Tigase. But I ended up not using XMPP at all for WebRTC signaling. Why? All about it in the next article.

Categories: Web

Building enterprise web sites

August 26, 2013 Leave a comment

Responsive design is one of the latest and hottest topics in web design and development. Creating a responsive site, a site that offers a decent to good user experience, a site that follows accessibility guidelines it’s not easy, but it’s not that hard after all. It could take few iterations, but you’ll get there. But doing it at an enterprise level, that’s a whole different game.
First of all, what’s enterprise bringing to the table that hardens things? I’ll clarify just to know where we stand and to clearly define the requirements.

To start, enterprise usually means big. So we have volume. In terms of pages, visitors, infrastructure, human resources. Let’s see how all they’re influencing.

Lots of pages. This is probably one of the most important aspects. If you’ll develop each page individually, on its own, then you’ll waste money and time. And by the time you develop the last page, the first one becomes obsolete and needs to be redone. Of course, I assumed that you’ll want the same user experience (look and feel) on your entire website, which is the smart thing to do anyway and I won’t enter here into details why. So, coming back, there is clearly the need to reuse code in order to reduce development and maintainance effort and easily update all pages at once.

Lots of visitors. And this brings with it the need for performance. At every level: network and server infrastructure, code and process. Infrastructure is the foundation of your site and it’s also the main reason for stability (or instability) or, in other words, uptime (or downtime). If infrastructure is alright, then performance comes down to code. And on the web, this translates into server side execution time, number of requests, response size and client side execution time.

Big infrastructure. When talking about huge infrastructure, we will definitely see a heterogenous environment: different server-side technologies and different ages. So we will have outdated environment, outdated code, we will need to deploy to multiple environments simultaneously.

Lots of human resources. As many people will be involved in the development, there should be clear process and extensive documentation. Clear process will reduce the mistakes and inconsistency, while increasing development efficiency. Extensive documentation will decrease the learning curve and the need of direct support from developers. Also you should take into account that people with different backgrounds and skills will all work together. If we’re able to make development easier we will be able to reduce costs, either by reducing the need for high level skills or reducing the development time.

Now that we’ve seen what an enterprise site means and what are the basic requirements, I will just go through a list of good practices. The list of requirements could actually be bigger than the ones above, depending on your business needs. Also the following best practices are focusing only on client side development.

Architecture: Use a modular architecture

Modularize as much as possible. Besides a core framework, everything should be described and implemented as a component. Components will be assembled together to create pages, microsites or web applications. This will lead to many advantages. Different teams can implement different components. The user experience can be changed in its entirity or partially, but the most important aspect is that it can be done globally. Updating a component will update all the pages using it.
Beside the component developer, we identify the role component user, which is the person that will assemble a page, microsite or web application from the existing components.

Architecture: Use a governance process

Even though the component development process can be easily descentralized, ensuring consistency and avoiding development overlaps should be done centrally through some kind of governance process. Representatives from all teams should be involved. By consistency, I mean using the same technologies and architectural patterns for the same purpose. Overlaps can mean implementing the same components twice or components very similar in nature. E.g. if you implement an autosuggestion input component for cities, while you have already an autosuggestion generic component, then you’re overlapping. It’s better to find a way to integrate a city suggestion service into the generic component.
Before starting to implement a component, check to see if you cannot use an existing one, even though it means some degree of customization.

Architecture: Reuse

As I told one of the main reasons of a governance is to reuse as much as possible. Either we’re talking about your code or third party libraries. Do not reinvent the wheel, it will always be round and, unfortunately, maybe not from the first tries.

Architecture: Adopt the new

As a rule of thumb, always prefer to use the new version, either we’re talking about a standard or a JavaScript library. This way your site will take better the test of time. Of course, the problem is the browser support (read IE support), but there are usually workarounds.
Use the new HTML tags instead of the deprecated ones. STRONG is preferable to B, as it is related to semantic instead of layout.
Use CSS transitions instead of JavaScript animations. CSS transitions gives better performance (as they could make use of GPU), but JavaScript animations could be used as a fallback, when browser don’t offer support.

Architecture: Create extensive documentation

Document the development process, patterns, choice of technologies. Heavily comment your code. Document all the components and create some kind of easy browsable index. Consistency should be a concern when it comes to documentation too, by using the same style and tools throughout all teams.
Extensive documentation will reduce the learning curve, especially for new resources. It will also reduce the developers involvement in the deployment and support for component users.

Architecture: Encapsulate JavaScript/CSS into easy to use components

I mentioned earlier about different roles in your organization. Could be that the users of your components don’t have a high degree of knowledge in JavaScript and/or CSS (Please keep in mind that JavaScript is the most misunderstood language). E.g. YahooUI is great library, but it requires JavaScript knowledge. Same goes for jQuery components. Instead of this approach, or actually over this approach, you should use a very simple principle: convention over code. Just to take out the JavaScript part out of the equation you could use CSS classes to annotate, by convention, your component. E.g. instead of $("TABLE.whatever").tablesorter() you can simply use .sorted CSS class and include $("TABLE.sorted").tablesorter() in your main JavaScript as an onload event. Of course, this will impact the initial load performance, but there are always trade-offs :).

Performance and maintanability: Reduce the number of global resources

Reducing the number of global resources will reduce the number of requests and improve performance. But performance is not the only concern, maintainability is there too. It’s easier to deploy one resource and it’s easier to update one reference. By resources I mean stylesheets, JavaScript files, images, fonts etc.

The number of stylesheets and JavaScript files can be easily reduced to one. In case of CSS, frameworks like Less or Sass will be of great help and in case of JavaScript, frameworks like AMD. These frameworks will help you modularize and organize your development environment, while you will still be able to deploy only one resource into production. It makes it easy to integrate even third party resources.

When it comes to images, icons more specifically, icon fonts is the key. These are supported on many browsers, reduces all icon requests to one, they’re scalable in size and color. The only disadvantage is that you cannot have multicolor icons. You can combine icons to obtain this, but this could become cumbersome.

Naming: Prefer short, but meaningful names

As for the naming try to use generic, but meaningful names for everything, from resources to CSS classes. E.g. for resources prefer using “global.css” instead of “global_v3_blue.css” as you should stick to them for a long time. This way moving to a new version you will still have a meaningful name. Also make use of server side processing if you want to personalize the experience for different users, geographies, browsers etc. E.g. if you want to have two different CSS, one for mobile devices and one for desktop browsers, then refer to both as “global.css”, but do a server side redirect based on device detection.
As for the CSS classes, I already wrote about this subject.

Naming: Use the semantic of HTML tags

Use the semantic of HTML tags instead of defining new CSS classes, where appropriate. It is preferable to use H1 instead of .title and H2/3 instead of .sectionTitle.

Naming: Use as few CSS classes as possible

This falls into the same reuse category. It will be harder to remember which class is for what if you have hundreds of them and when to use one over the other. Prefer using contextual references in CSS selectors or combining existing classes rather than creating new classes. E.g. do not create a new class .right-menu, but use two classes .menu.right. Of course a better naming will be .menu.contextual.
So reuse comes even to CSS class names.

These are simple rules, but following it’s not always easy. But they will help you get an easy maintainable website so you can easily react to industry changes.

Categories: Web

Innovation Summit 2013 in Bucharest

May 30, 2013 Leave a comment

Innovation Summit just happened in Bucharest this week. In a few words: some interesting presentations, given in a more or less attractive and engaging way. Most of the things were not new, but it’s nice to hear them again as a confirmation and most importantly presented in a different way. Also, a lot of study cases were presented which always brings confirmation to the speaker’s ideas and even yours if similar.

Petru Jucovschi, Technical Lead for Windows and Windows Phone – The next level of Digital Innovation This was a presentation about innovation in user interfaces with a strong focus on the so called Metro interface for Windows 8. You can read more about it here or here. Embedding HTML5/CSS3/JS into the OS and as a application platform was presented as an innovative approach. It isn’t. Palm had webOS years ago. Indeed, HP killed it, but this was on the market years ago.

Meldrum Duncan, Innovation Consultant, Founder ?What IF! US – Oh, the mistakes I’ve made: 13 years of running innovation projects. Clearly an engaging speaker and an attractive presentation. He focused on 10 simple principles of driving innovation. Among the principles were also the ones that engage collaboration outside the office, like “Drink beer!”. Yes, yes, to engage with other colleagues, stakeholders, clients in a friendlier environment, which will open new thinking.

Windahl Finnigan, Associate Partner, UX Innovation & Strategy Director for Smarter Commerce at IBM – Full Tilt Boogie of Disruption was a too corporate speech for my taste. Even though with some good and interesting examples, the presentation was less engaging and more like a flat line.

Matt Rosa, Innovations Director at BAT – An Iterative Consumer-Centric Approach to Product Innovation discussed about tobacco industry innovation with a focus, of course, on BAT. Innovation on this field was close to zero up until 1999, but it started to cover multiple topics since then. From a process standpoint he brought the idea of going outside the organization to external agencies for a fresh and different view. Personally, I’m just glad, that with all the innovation, the base of tobacco customers is shrinking each year.

Martin Hablesreiter, designer / artist / filmmaker at honey and bunny studio – Food Design is more important than politics. The innovative capacity of food design. I liked the presentation style, the content, the slides, but for me, food is just food and what it counts is its nutritional and health value. Martin discussed in an ironic way the many influences on food design: functionality, culture, transportation, economic feasibility etc. But imagine the visual impact of the photos on the slides right before lunch :).

Susan Choi, Director of Innovation at Mandalah – How the heart and pulse of culture can lead companies to culturally relevant and successful innovation? was an advocate for local research before jumping to conclusion or using any well known stereotypes. As a case study she used a campaign launched in Middle East, where, surprisingly, they acknowledge an entire youth movement towards the digital space and into innovative solutions.

Daniel Jurow from R/GA started his presentation with a bit of his company history and how they expanded.
I clearly remember one of the slides: “93% of executives say their long term success depends on their ability to innovate, but only 18% said that heir innovation strategy works.” The speaker said that is happening because they are not taking bold steps, but smaller safe ones. I would say that this is the result when you base your innovation and related decisions on spreadsheets.

Instead of the old formula for growth either through horizontal (line extension backed up by a serious mass-media campaign) or vertical integration, Daniel debated the concept of functional integration. Functional integration is the new idea to extract value of your existing ecosystem. In plain English, reach your existing customers and sell them additional products and services – maybe some they don’t even need, but they’re so cool :). Examples are clear: Apple, Google and at the summit I heard about BMW and Nike. Yes, Nike with Nike+ which allowed them to gain a huge market share. As a runner, I like minimalist shoes and trail running, and Nike don’t have options there, so I don’t use them. But it seems others really like to share their exercises on Facebook, so …

Of course, the only integration platform for end-user customers is the web.

In the end, the speaker was recommending to not restrict innovation to a single group, but encourage a culture of innovation in the company, an idea reiterated by almost all the speakers after.

Erez Tsalik
If I said in the beginning that most of the things presented. Not the case here, at least not by approach. Erez contradicted almost everything the other speakers said and he took a clear analytical approach to the process of thinking innovation. But he also reiterated that innovation needs commitment throughout the company, starting with the executive levels. Managers needs to know how innovation works and how to manage innovative people, because usually managers do not know to distinguish between a good innovative idea and a bad one. That’s the reason they should not validate innovative projects and ideas.

He discussed some of the classical approaches toward the process of innovation (if there is one). Brainstorming seems not to get the best results, because people being separated generate more ideas than together. Why? They don’t waste time listening to others. But I would think that brainstorming is good as a next step to validate the ideas and select the feasible one.

Think out-of-the-box! Or better NOT! Out-of-the-box means no rules, but with businesses constraints exists. Constraints enhance innovation, it is said that necessity is the mother of all inventions.

Another interesting topic was fixedness – symmetrical, structural, functional etc. Which is normally good. But if you want innovation you have to make an effort and break it.

Altogether, an interesting and intriguing presentation with lots of good examples. The kind of presentation that makes you think: “But what if I try?”

Alexandru Cernatescu, Co-Founder, CEO & Head of Strategy at Infinit Solutions Agency – Romanian Reality Innovation Update – What stands behind a Romanian story of success based on innovation?. Unlike the other speakers, Alex didn’t focused on innovation process, study cases or ideas. He presented, in a very dynamic way, how innovation was the basis of his entrepreneurship and how with will and abnegation can overcome obstacles and write yourself a success story.

As participants, we also had the opportunity to play with innovative products: transparent displays, latest laptops that double as a tablet, Windows phones. And we even took part in molecular food demo with Bernd Kirsch, Executive Chef of Radisson Blu, as an innovation in gastronomy. The opportunity to sample the end results was clearly a delight for all of us.

I would like to finish with a few recommendations that I liked and were shared by most of the speakers. Innovation is not limited to a small group in the company, but it should be encouraged as part of the internal culture. Managers (especially executives) should not be pose as innovation judges, as this is most probably their main focus and strength. The innovation process, if any, is ever changing and it should be part of the innovation itself.

Categories: Web

Icon fonts

April 24, 2013 1 comment

Icon fonts are a great way to enhance the performance of your website. I decided to put together a list of resources to help you understand, create and integrate icon font into your website.

Why use icon fonts?

First of all, what’s the big fuss about icon fonts? The basic idea is that instead of having tens of small images (and of course, tens of small HTTP requests) you embed all those images as characters into a font. Having only one request of a bigger size it is highly recommended instead of having multiple smaller requests, as the overhead of a HTTP request is huge in bandwidth and time.

You can also use sprites, but this approach has several benefits. First of all, it is easier and your code will be cleaner. When using sprites, the images will have only one resolution and one color. With icon fonts, you can set different colors and sizes for your icons without having to download another set – you actually set the font color and size. Here’s a demo.

There are some downsides, but I would say none of them major. Editing an icon font could be a little bit harder than editing just a simple image. Also multicolor icons are not suitable to be embedded in icon fonts. But the trend now is to have cleaner pages and icons, so multicolor icons could not be on your wishlist anyway.

As with any new feature, the biggest question is browser support. Good news here: all major browsers are on board.

If this convinced you, everything comes down to two things: creation and integration.

Creation of icon fonts

Editing

Basic idea is simple: vectorize your image into SVG images and embed them all into one SVG font. For this you can use InkScape and, as a beginner, a comprehensive tutorial and a video tutorial can be of great help.

Tip: It is recommended to fill in the name for each glyph (glyph-name XML attribute) in the SVG font. This way anyone with a text editor can easily identify the glyphs in the SVG font and change the unicode mapping for example.

Conversion

The end result will be an SVG font, but as you saw browsers support different formats. Now it comes to converting the SVG font into other formats.
For TTF I used to use FontSquirrel, but there are other better choices. http://fontface.codeandmore.com/ was a good and very fast online converter, but unfortunately you have to pay for it, though it’s only $8 per year.

What I currently use is http://onlinefontconverter.com/ to convert from SVG to TTF and WOFF. I don’t know why but usually EOT conversion got stuck so I use http://www.font2web.com/ for this final step. You can also use http://www.freefontconverter.com/ but it doesn’t convert to EOT, so again you will need font2web.

Integration of icon fonts

Font definition

To define a font you should use @font-face in your CSS and that’s pretty much it.
A basic common code sample will look like this:

@font-face {
    font-family: "MyFont";
    src: url('myfont.eot');
    src: url('myfont.eot?#iefix') format('embedded-opentype'), /* IE6 fix */
        url('myfont.woff') format('woff'),
        url('myfont.ttf') format('truetype'),
        url('myfont.svgz#MyFont') format('svg'),
        url('myfont.svg#MyFont') format('svg');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: "MyFont";
    src: url('myfont_bi.eot');
    src: url('myfont_bi.eot?#iefix') format('embedded-opentype'), /* IE6 fix */
        url('myfont_bi.woff') format('woff'),
        url('myfont_bi.ttf') format('truetype'),
        url('myfont_bi.svgz#MyFontBoldItalic') format('svg'),
        url('myfont_bi.svg#MyFontBoldItalic') format('svg');
    font-weight: bold;
    font-style: italic;
}

Or if you’re using SCSS and Compass, which I highly recommend, then the above sample will become:

@import "compass/css3";
 
@include font-face('MyFont', font-files('myfont.eot', 'myfont.woff', 'myfont.ttf', 'myfont.svgz', 'myfont.svg'));
@include font-face('MyFont', font-files('myfont_bi.eot', 'myfont_bi.woff', 'myfont_bi.ttf', 'myfont_bi.svgz', 'myfont_bi.svg'), bold, italic);

Icon usage

Now that you declared your font you can use the icons. I will show below a few examples.

<span class='icon star' aria-hidden="true"></span>

<span data-icon='S' aria-hidden="true"></span>

… and the CSS …

.icon:after {
    font-family: "MyFont", sans-serif;	
    font-size: 12px;
    line-height: 12px;
    speak: none;
}
.icon.star:after {
    content: "S";
}
.icon.star-empty:after {
    content: "s";
}

[data-icon]:after {
    font-family: "MyFont", sans-serif;	
    font-size: 12px;
    line-height: 12px;
    content: attr(data-icon);
    speak: none;
}

For the first icon I split the declaration in two, so that you can easily add other icons as well. Of course, IE7 does not have support for :after, but, oh well, if you really need it, I think you can live without icons. Second form it’s more generic and it has the same browser support as the first one.

Notice the aria-hidden attribute and speak CSS property added here for accessibility purposes. The preferred way will be the speak property, but unfortunately there is almost no support for CSS2 Aural Style Sheets or CSS3 Speech.

In the end, a few free icon fonts:

Categories: Web

Responsive design. One web. Semantic CSS.

September 18, 2012 2 comments

A new buzzword hit the streets of web development lately: responsive design. But what is it? If I wouldn’t trust Wikipedia(not saying that I don’t) and I would have to give my own definition, I would say that it is the ability of a web site to adapt to the user’s browsing device and offer the optimal experience, look and feel.
As usual, from theory to practice, there is a long and hard way. When talking about implementation, responsive design is an umbrella for a series of web development techniques and patterns. I will try to describe some of them in the next lines.
First of all responsive design starts with user device browser detection. I already wrote an article on the matter and I will come to this subjects on future posts as well. Now I will just enumerate the main techniques without focusing on a specific framework.

  • Device information repository. It is usually done on server side using the HTTP User-Agent header and mapping it against a database of devices. This database contains information about the device hardware and software like: name, manufacturer, input device (trackball, keyboard, touch screen), OS, browser, support for video, audio and image formats and many more. The most well known device repositories are OpenDDR (free), WURFL(free for non-commercial use) and DeviceAtlas (commercial). Apache DeviceMap is a new one, but it’s not on a stable release yet.
  • Pattern recognition. If you need just basic device detection, like to distinct only between mobile and desktop, you can use the browser name and map it against a list of given patterns (e.g. contains iPhone or Android). Needless to say that this method has a high failure rate and it doesn’t give you detailed information about the device and its capabilities. This technique can be applied on the server side using HTTP User-Agent header or on the client side using the window.navigator JavaScript object and its properties (e.g. appName)
  • Features recognition. This technique is applied on client side in JavaScript. This is only a part of a broader technique, progressive enhancements, which I will detailed it later on.

As soon as you’ve identified the user device, your website has several options on how to react. You can create different websites for mobile and desktop (and even one for tablets), you can create a desktop website and transcode it for mobiles/tablets or you can create only one, smart enough to adapt to all devices (existing and upcoming). And this is revealing the concept of One web. But what this concept implies, a concept for each W3C is lobbying as one of the most important guideline in web development? It is practically the same thing as responsive design, or I would say the best method to implement it, to have one website that can offer the best user experience no matter on the browser that it is accessing it.

Is it easy to implement? I would say so, but you need to have a few important things in mind. Let’s start with the most important one: content-layout separation. As we said you want to have only one website, which actually means one content. But the layout, how it is rendered and how it interacts with the user, is different for each device. If you’re familiar with the MVC concept, this is similar, but applied to your markup. The advantages are obvious: you will be able to maintain one content, your website can react differently if needed and you can clearly delimit the tasks between content editors and web developers.

As soon as we made the separation we can leave the content in the content editors’ hands and we can focus on the web development part. But do we really need to develop one layout for desktops and one for mobiles? And another one for tablets? Or even one for each type of mobile – featured, smartphone etc? Not quite. Again if you’re structuring and modularizing your website, you can get away much easier.

To easily plug in different layouts you definitely must use CSS. CSS Zen Garden is a clear example that proves its power, by rendering the same content in hundreds of different ways. But CSS alone is only a tool, you will need a technique that will enable you to unleash this power. And now we’re coming to the broader discussion of semantic CSS. Using it will gave you this level of pluggability and the good news is that to apply it you need just a mindset switch. Even though you’re developing a layout using CSS, think only at its semantics. This way it will become easy to link a content with the layout. Let’s say that you want to define the CSS class for the page title, which is displayed in blue, bold and with a double font. You will call that class title and not blue_bold_double_text. Sometime, this will not be as obvious as in this example, but always think first of the semantics and ask yourself the question: Why and when I would use this CSS class? Forget about specifics.
There are a few other related tips that you might find useful:

  • Give your CSS classes short, but meaningful names. Even though shorter is desirable, do not trade meaning over size. Do not abbreviate, further down the road you or some other developer may forget the meaning.
  • Use the semantic of HTML tags instead of defining new CSS classes, where appropriate. It is preferable to use H1 instead of .title and H2/3 instead of .sectionTitle.
  • Use the new HTML tags instead of the deprecated ones. STRONG is preferable to B, as it is related to semantic instead of layout.
  • Use as few CSS classes as possible. It will be harder to remember which class is for what if you have hundreds of them and when to use one over the other. Prefer using contextual references in CSS selectors or combining existing classes rather than creating new classes.

You structured your content and layout and now you have to develop it. There is an old concept, liquid layout, but I think it still can suit most needs. The idea is to develop a layout that can easily fit in different screen resolutions. This will translate mostly into using relative positioning and relative sizes instead of absolute ones.

We covered how a website should look like, but what about how it should feel, how it should interact with the user? I mentioned earlier about progressive enhancements and I already describe it in a previous post, so I will just restate it. The term sounds very complicated and futuristic, but it is not rocket science. It is not a framework or a new technology to learn and use. It is only a change of mindset. Mainly this applies to JavaScript and you have to keep in mind that some features that you’re going to use in your scripts could not be implemented on some devices/browsers.

To better understand the concept let’s take an example. Let’s say that you’re going to use geolocation on your website.

		navigator.geolocation.getCurrentPosition(locationHandler);
	

The above could be one option. But what happens if the user browser does not support geolocation. Your website will break and offer a poor user experience.
By simply adding an if you’re out of the trouble.

		if (navigator.geolocation)
			navigator.geolocation.getCurrentPosition(locationHandler);
	

You can even have some fail-over mechanism implemented on else branch. As I said nothing complicated, only a mindset change. Develop for the highest end browsers/devices, but think of all.

The same can be applied to CSS. If you want to implement CSS gradients you will have to do something like

		background-color: #00ff00;
		background-image: url(bg.jpg);
		background-image: url(bg.jpg), -moz-linear-gradient(90deg, #00ff00, #0000ff);
		background-image: url(bg.jpg), -webkit-gradient(linear, 0% 0%, 0% 100%, from(#00ff00), to(#0000ff));
	

This way you will be able to have a green to blue CSS gradient on both Mozilla and WebKit and just a plain green background on older browsers. Also if you have an image that one will be there as well. The browsers without CSS gradient support will just ignore the last two lines.

Another example will be pagination. If you want to implement a More like functionality (like the one from Facebook news feed) you don’t have to forget about non-Ajax devices and have a next/previous fallback.

Some other examples are JavaScript frameworks that implement features not yet supported on some browsers (read IE here), like Explorer Canvas or CSSPie.

Using progressive enhancements you can offer a better experience for advanced user devices, but without losing the low end ones. Remember that the 80/20 rule applies here as well. 20% of the users generates 80% of the traffic. You don’t want to lose the big amount of traffic, but you also don’t want to lose a big amount of users.

W3C is coming with new techniques to help you in your quest, like media queries. Using an easy syntax you can easily customize your CSS for different device characteristics, like resolution. And the good part is that media queries are becoming widely adopted, even though not fully. Another W3C standard worth to keep in mind for the future, but still draft, is CSS variables.

All these techniques apply mostly to your HTML content, but you should not forget about images. Image optimization is to be done mostly on the server side, after detecting device capabilities.

To be continued …

A short slide presentation on the topic you can find here.

Categories: Web
Follow

Get every new post delivered to your Inbox.

Join 751 other followers