Async Talk on Chrome Extensions and Chrome Web Store

I gave a talk last night at Async, a fortnightly meetup for Brighton’s ever-thriving JavaScript community, organised by the talented Prem Rose. The talk was on Chrome Extensions and the Chrome Web Store, and was a mashup of our separate GDD talks on those topics (GitHub), some live coding, and some new stuff now that the Web Store is live…though the main focus was Chrome extensions.

Slide Deck: Chrome Extensions and the Chrome Web Store

A fun part of the talk was live coding. I haven’t done it before, but I felt it went well and was definitely worthwhile. The project was an extension to show the latest blog posts on the Async website, in a toolbar button (aka browser action). Chrome extensions are a lot easier to write than most people imagine, so it was an effective demo to start with a new directory and make it happen. For the record, here’s the extension we hacked up in 15 minutes or so: async.crx. (Styling was not the main focus of this exercise :) ).

I also did something I’ve been meaning to do for a while: A Venn diagram to illustrate the relationship between extensions, packaged apps, and hosted apps:

Finally, I had a good question about detecting if you’re website is running as an installed app. I couldn’t remember the details, but they are here:

javascript
< view plain text >
  1. if (window.chrome && chrome.app && chrome.app.isInstalled)

(Updated the snippet following Johan’s suggestion in the comments.)

WebWait Upgrade: Deletion, Quick Entry of Multiple Sites

I made a couple of upgrades to WebWait this week.

First, you can now delete entries. This is useful for curating a set of results, since you can save a result set for others to try out, or for later analysis and comparison. If I get requests, I may also allow users to re-order the results for that reason too. You can only delete a trial when it is complete, i.e. when all calls to it have been made. This is not ideal, but would require significant rework. Again, I’ll respond to feedback on this one.

Second, you can now enter multiple URLs in the input field, separating them by space. I received a request from a Dzmitry Markovich, who wanted to time hundreds of websites at once, and figured I should support it. It’s an undocumented feature intended for advanced users, as I don’t have time to think about how to integrate it into the UI without compromising the simplicity of the design (e.g. with a text area; I should at least mention the feature in the FAQ, which is now ancient.) In the case of someone wanting to enter dozens or hundreds of websites, they need to cut-and-paste into the input field.

Funnily enough, both of these features had previously existed, but were removed when I overhauled the architecture to make way for the benchmark saving feature. The new architecture, being based on semantic events, made the deletion feature rather easy. The multiple-URL feature was also quite straightforward, as it would be with any architecture.

This is the latest of four updates in WebWait’s lifetime of as many years. Slowly but surely :).

Is this what the App of 2015 looks like? HTML5 + CoffeeScript + Less + WebStore + PhoneGap + Apparatio

My weekend project was a Hacker News Reader (source code). It works on Chrome, Safari, and Opera. Sorry, Firefox doesn’t work at present, reasons why speculated below. Mostly started this project because I want one with Twitter integration, but also to play with a few technologies, which I did. Among things explored and demonstrated:

  • Server-Less App The app is entirely browser-side. The server serves only as a repository of static files. Content comes from the iHackerNews unofficial API, by way of JSONP, the protocol we’ll still use for cross-domain calls until CORS becomes eminent in the hopefully not-too-distant future.
  • CoffeeScript. The app logic is written in CoffeeScript, and compiled to JavaScript in the browser with coffee-script.js.
  • Less. The UI styling is written in Less and compiled to CSS with less.js.
  • Chrome Web App. The app is also a hosted web app on the Chrome Web Store, which is to say (a) it can be discovered by users of the store; (b) it can be installed into the New Tab page of Chrome, for convenience sake; (c) if I wanted to, and added some extra server smarts, I could charge for it. I wrapped it up as an app with Paul’s super-handy Appmator utility.
  • Mobile HTML5. Although I didn’t (yet) optimise the site for HTML5, I did make it available on mobile, with the right icons for being added to the Home Page, and used Build.PhoneGap.com and Apparatio to roll it up as a native mobile app.

CoffeeScript

I wanted to try out CoffeeScript. While I’ve been skeptical about languages which are said to “compile down” to JavaScript, as if JavaScript was a complicated tangle of 1s and 0s rather than the high-level language it is…CoffeeScript is different. It’s more like JavaScript++ as the name implies. While I do find JavaScript to be pretty good, its syntax can get too verbose. Especially for closures, where you have too many curly braces and “function” keywords getting in the way of the actual logic we care about. You can also be more expressive with keywords like “unless”.

As ~98% of code people write never sees high-scale production use, I like to opt for quick and dynamic over tedious and “it just feels like the right way to do it”. So I employed coffee-script.js to compile dynamically, in the browser when the web app loads, instead of pre-compiling it on the command-line. Doing it dynamically means I can just type some code and reload the browser page, about the smallest possible debug-test cycle that is possible.

I found it slow-going at first, because I ran into some coffee-script.js gotchas and learned a few things about the language on the way:

  • Keep CoffeeScript in a separate server. Although CoffeeScript supports inline CoffeeScripts in your HTML (<script type=”text/coffeescript”>…here is my script….</script>) – perfect for quick hacking), I recommend you stick them in a separate file (<script type=”text/coffeescript” src=”myscript.coffee”></script>. I can’t explain exactly why, but when it was inline, things were note very deterministic and I found my CoffeeScript script was getting executed three times!
  • Use a server, not file:/// URIs. As with less.js, CoffeeScript mocks the browser’s script-downloading behaviour, using XMLHttpRequest to pull down any scripts specified in “text/coffeescript” script tags. Unforuntately, Chrome doesn’t let you XHR one file from another file, so you need to set up a server, if only to serve these static files over HTTP.
  • Don’t bother with window.onload (or jQuery intializer). I *think* coffee-script.js guarantees any CoffeeScripts you provide will be executed after the window has already loaded. I haven’t confirmed this, but seems to be that way on Chrome, Safari, and Opera. OTOH, the app doesn’t work on Firefox – CoffeeScript isn’t executed at all – and this may be related.
  • Declare before you use. A consequence of the previous rule is that your initialisation sequence will run in the order you specify it. This is different to the usual JS situation where you make a window.onload handler, which might call things that you’ve declared further down in the file. So in the code further down, note that I declare “show” before I call it. Pretty obvious, but JS habits and lack of descriptive error messages meant it caught me out.
  • Whitespace matters. There are no semi-colons and no braces here; similar to Python, whitespace dictates structure. However, you can also use parantheses to keep things on the same line, so I didn’t find this threatening to concise code.
  • Use “window” for global. Declarations like “x=5″ out in the open will *not* make global variables; and nor is there a “var” keyword. The only way to hook into global space is to explicitly reference the “window” object; e.g. “window.x = 5″.

How’s the code look? See for yourself, CoffeeScript keeps it pretty tight. I couldn’t find many examples of jQuery-CoffeeScript combos, so this will hopefully be useful in that regard:

javascript
< view plain text >
  1. storiesTemplate = _.template($("#storiesTemplate").html())
  2. show = () ->
  3.   $.getJSON "http://api.ihackernews.com/page?format=jsonp&callback=?",
  4.     (storyInfo) -> $("#stories").fadeOut () ->
  5.       $(this).html(storiesTemplate(storyInfo))
  6.       $(this).fadeIn()
  7.  
  8. show()
  9. setInterval show, 10*60*1000
  10.  
  11. $(".story").live "click", (ev) ->
  12.   return if $(ev.target).closest("a").length
  13.   window.open($(".url", this).attr("href"), "hackernews"+Math.random());

  • Less fails silently. Unfotunately, you don’t get error messages, so develop things gradually and be prepared to undo.

Less

If I was going to take a sip of CoffeeScript, it would only be fair to munch on a slice of Less too. If CoffeeScript is JavaScript++, then Less is CSS+. It’s really augmented CSS, because you can present a regular CSS stylesheet and it will be valid Less too. That’s not true at all about CoffeeScript; a typical JavaScript script has Buckley’s of passing the CoffeeScript compiler.

The other thing they have in common is JavaScript compilers. Which is not the case with SASS for instance.

Less talk:

  • Same XHR issues. As with CoffeeScript, the Chrome cross-domain restriction means you have to use a server even though the files are static. Also, it doesn’t seem to be possible to include Less stylesheets inline, or to get hold of the less compiler, which I think is a shame if true.
  • Silent fail. If any Less doesn’t parse, the entire stylesheet won’t be applied, and there’s no error message.

So some downsides, but the upside was a cleaner stylesheet with less redundancy. Gradient macro makes the ridiculously verbose gradient declarations completely DRY:

  1. /*****************************************************************************
  2.    MACROS
  3. *****************************************************************************/
  4. .linearGradient(@color1:#ccc, @color2:#ddd) {
  5.   background-image:-webkit-gradient(linear, left bottom, left top, color-stop(0, @color1), color-stop(100%, @color2));
  6.   background-image:-moz-linear-gradient(center bottom, @color1 0, @color2 100%);
  7.   background-image:-o-linear-gradient(center bottom, @color1 0, @color2 100%);
  8.   background-image:linear-gradient(center bottom, @color1 0, @color2 100%);
  9.   background-color: @color1;
  10. }
  11. .postedBy:hover, .commentsLink:hover span { .linearGradient(#fa0, #f80); }

Elements can be nested in their parent selectors:

  1. .commentsLink,.commentsLink:visited {
  2.   position: absolute; top: 50%; right: 1em; height: 1em;
  3.   ...
  4.  
  5.   span {
  6.     ...
  7.     border-radius: 0.3em;
  8.   }
  9.  
  10. }

… and so can pseudo-selectors:

  1. .story {
  2.   padding: 0.5em 9em 0.5em @leftIndent;
  3.   border: 1px solid black;  border-bottom-width: 0;
  4.   background: #fff6f6;  cursor: pointer;
  5.   position: relative;
  6.  
  7.   &:hover { .linearGradient(#fc0, #fa0); }
  8.  
  9.   &:last-child { border-bottom-width: 1px; }
  10.    
  11. }

And you can do cross-browser CSS calculations today:

  1. .commentsLink,.commentsLink:visited {
  2.    ...
  3.   margin-top: -0.5em-@commentsLinkPadding;
  4.  
  5.   span {
  6.     ...
  7.     padding: 0em + @commentsLinkPadding;
  8.   }
  9.  
  10. }

Chrome Web Store

This is a full-screen, focused, app which therefore meets the criteria for Web Apps I outlined in Thinking In Web Apps. (It would be more so if it showed the actual stories and comments in the app too, but that’s something for later.)

So it made sense to submit to the Chrome Web Store. Fortunately, my colleague Paul Kinlan had the gall to attempt building a web app that packages up Chrome apps … and then he actually pulled it off! Appmator asks you for the address of your web app, asks a few other basic questions, and then makes a Zip file you can drag to your desktop and upload to the store. All in all, a 30 minute submission to the Chrome Web Store and a nice way for people to discover your web app. I would only recommend this for true “Apps” as opposed to general websites, and ideally those apps should be tailored to a full-screen experience.

Anyway, it’s on the store now – Hacker News landing page.

PhoneGap, PhoneGap Build, Apparatio

The app is NOT optimised for mobile at this time, but the cool thing about HTML5 is, for the most part, it “just worked” when I pointed iPad and Android phones to it. Some things need improvement, but this is good to see.

For exploration purposes, I decided to build it as a native mobile app anyway. I was lucky enough to receive beta invites for PhoneGap Build and Apparatio, two web services which let you do PhoneGap without actually installing anything on your PC. I built this app with both products.

Apparatio, which I used previously, worked nicely and I was able to get a native Android app.

PhoneGap Build supports GitHub like Apparatio, but also allows uploading a zip file. I actually had a problem pointing it at my GitHub repo (as with Apparatio, it needs to provide clearer instructions on exactly what form of URL is required). After I uploaded the zip file, it showed me a dashboard of 4 packages being built, and just went ahead and built each of them. Nice and simple!

Android, WebOS, Symbian, Nokia. Conspicuous by its absence is iOS, which Apparatio does support.

DropBox on my Macbook and Galaxy made it easy to copy the APK downloads to my Galaxy and install it. The Apparatio one took some time to download initially, but worked fine. The

Other Notes

Block-level “a” element, NOT. HTML5 makes it possible for “a” elements to be block-level, i.e. to include other tags including other “a” elements. This would be ideal for the Hacker News Reader UI, where the entire story block is a link to the story itself, but the block also contains links to comments and authors. It turned out to be legal in modern browsers, but with blatantly wrong layout, as someone else found earlier. Shame as I had to introduce considerably more JavaScriptCoffeeScript and CSSLess.

InnerHTML, Templating, and Live(). Seems like every project I do these days, I’m building dynamic content with innerHTML, as opposed to DOM manipulation. The first reason is I’ve become accustomed and satisfied with templating, and see it as a growing trend thanks to language-agnostic formats like Mustache as well as server-side JavaScript. (Though in this case, it’s a pure browser-side app.) So make a template and stick it on the page with innerHTML (or jQuery’s .html() ). The second reason is jQuery’s live() command makes it easy to handle events against the newly formed elements, which was previously a pain with innerHTML().

Setting text size. As you can see, text size varies with the number of points a story has. The relevant line appears in the template:

font-size:<%= Math.log(Math.log(Math.max(s.points,10))) %>em;

Using a log scale ensures a story with 2000 points isn’t 2000 times bigger than a story with 2 points. To dampen the effect further, which I think is important in mobile displays, I used a double-log and applied a minimum threshold of 10 points.

Future Things

There was actually an itch to be scratched here, beyond trying out various tech. Specifically, I’ve been wanting a mobile HN reader that would: (a) tweet; (b) quickly mark for instapaper reading, and ideally when I’m offline. (It would show the latest stories it saw when online, and cue them up for later…in general, I wish more offline apps would support cueing things like Tweets and Read Laters for when you’re back online.)

Fin.

So is this the Web App of 2015 or not?

There are definitely elements here that are not in wide use now, but will be in wide use by 2015. The whole “write once, run many” aspect of HTML5 is just getting wheels. It’s now clear that Apple won’t dominate the landscape by 2015, so regardless of their ever-fluctuating stance, HTML5 will be able to power the apps of the majority of smartphones and tablets…not to mention the possibility of apps on TV, cars, watches, washing machines, etc etc etc. (Can you tell it’s been CES week?)

And with HTML5 being able to power these apps, we’ll need ways to fit them into the App ecosystem, and that’s where PhoneGap and friends fit in. As I’ve said in various places, I always found it painful to have to set up Eclipse, PhoneGap SDK, and so on just to make a native app from HTML5. These are the things HTML5 developers don’t want to do, and the PhoneGap team is well aware of it, hence their PhoneGap Build effort. Apparatio provides relief in the same way and we can expect the same from others, especially so in light of Heroku’s high-valuation acquisition bringing attention to the whole idea of cloud programming. GitHub is also a vital component of this vision becoming reality. The next step will be to automate deployment into the stores, hopefully something that app-hungry stores will be happy to facilitate.

The Chrome Web Store is a related concept aiming to “app-ize” we apps. Mozilla is investigating a similar idea, and we’ll see a lot more of it in the next few years too. Some people say “but it’s just a bookmark”, an understandable reaction, but I think people are starting to get it now. It should only be an app if it really is an app, ie. if the underlying URL is really a media-rich, focused, app rather than a big collection of information and hyperlinks. And the Web Store is not just a place where you can buy and install apps; it’s also a directory where you can find all the cool apps on the web, with screenshots and reviews and comments to help you decide if they’re worth trying out.

Offline is important in the app story too (although this app doesn’t (yet) do any offline). You don’t type in URLs when you’re on a plane, but you do click on app icons to launch them. So offline web apps need an app-like presence to meet user expectations.

How about those languages, CoffeeScript and Less? CoffeeScript seems promising and I’ll definitely be using it more. At the same time, I’m weary because I feel like JavaScript may be “good enough” and CoffeeScript becomes a maintenance problem if others need to see your code. But the leap is not a big one.

As for Less, I’m more convinced it’s the way to go. We nowadays have an absurd proliferation of “-webkit-” “-moz-” “-o-” “-msie-” prefixes and the various syntaxes to go with them. It’s for good reason, but it’s also as much an affront to the DRY principle as any agilist could ever fear, and it’s unfortunate the standards don’t provide better support for dealing with this sort of thing. Likewise, the need for variables/constants and calculations. Less allows for all of that, and in a way that will work on legacy browsers even when some of these features do come about. So, yes, I’ll be committing to Less in the future.

What’s very cool about both Less and CoffeeScript is the JavaScript frameworks. It’s ideal for starting off a project, and when performance gets to be an issue, you can easily switch to the compiled version after that.

Finally, I’ll mention that templating is a design pattern that’s also going to be big in 2015. There’s much more framework support these days and it’s easy to use the same templates on the browser and the server.

HTML5 Fonts: Let’s Make them DRY

The Problem

Much fun can be had designing with the ever-increasing universe of fonts offered by directory’s like Google’s. Photoshop Tamagotchi is a thing of the past as you can rapidly iterate with a few keystrokes. But it’s still a few keystrokes too many …

A niggle with CSS3 fonts is they involve some redundancy. Here’s a real-world example:

  1. @font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); }
  2. @font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf'); }
  3. h3 { font-family: Delicious, sans-serif; }

What happened to Don’t Repeat Yourself? We have “Delicious” mentioned five times here! If we switch from the “Delicious” font to the “Pinboard” font, we’ll need to make five changes. And not everyone uses vim, yo. Moreover, we’ll need to locate a suitable font, e.g. Pinboard, and download it.

I get it, this level of indirection serves a purpose. We can give a handle to the font once and then use that everywhere else. Heck, we could even continue to call the font “Delicious”, but surreptiously switch the “src” to “Pinboard-Roman.otf”. But that wouldn’t be very nice, would it?

Now, a font directory like Google solves part of the problem by explicitly allowing you to link cross-domain to Google. In fact, if you want, it will even generate the stylesheet for you. But you’ll still have the same DRY issue in your CSS – for each new font, you’ll need to include the stylesheet and use it in your CSS.

The Solution

Bottom line, I decided to make this crazy snippet, by manually walking through the font directory and picking out every single possible font:

  1. <link href="http://fonts.googleapis.com/css?family=Droid+Sans|Lobster|Droid+Serif:regular,italic,bold,bolditalic|Nobile|Yanone+Kaffeesatz|PT+Sans:regular,italic,bold,bolditalic|PT+Sans+Caption:regular,bold|PT+Sans+Narrow|Reenie+Beanie|Tangerine:regular,bold|Molengo|OFL+Sorts+Mill+Goudy+TT:regular,italic|Vollkorn:regular,italic,bold,bolditalic|Cantarell|Inconsolata|Crimson+Text|Arvo:regular,italic,bold,bolditalic|Cardo|Neucha|Neuton|Droid+Sans+Mono|Cuprum|Old+Standard+TT:regular,italic,bold|Philosopher|Tinos:regular,italic,bold,bolditalic|Josefin+Sans:100,100italic,light,lightitalic,regular,regularitalic,600,600italic,bold,bolditalic|Arimo:regular,italic,bold,bolditalic|Josefin+Slab:100,100italic,light,lightitalic,regular,regularitalic,600,600italic,bold,bolditalic|Allerta|Geo|Allerta+Stencil|Puritan|Puritan:regular,italic,bold,bolditalic|Cousine:regular,italic,bold,bolditalic|UnifrakturMaguntia|Bentham|IM+Fell+DW+Pica:regular,italic|IM+Fell+English:regular,italic|IM+Fell+English+SC|IM+Fell+DW+Pica+SC|IM+Fell+Double+Pica+SC|IM+Fell+Double+Pica|IM+Fell+Great+Primer+SC|IM+Fell+Great+Primer|IM+Fell+French+Canon|IM+Fell+French+Canon+SC|Coda:800|Raleway:100|UnifrakturCook:bold|Covered+By+Your+Grace|Just+Me+Again+Down+Here" rel="stylesheet" type="text/css" />

I’ll repeat that below for ease of cut-and-paste:

<link href=”http://fonts.googleapis.com/css?family=Droid+Sans|Lobster| Droid+Serif:regular,italic,bold,bolditalic|Nobile|Yanone+Kaffeesatz| PT+Sans:regular,italic,bold,bolditalic|PT+Sans+Caption:regular,bold| PT+Sans+Narrow|Reenie+Beanie|Tangerine:regular,bold|Molengo| OFL+Sorts+Mill+Goudy+TT:regular,italic| Vollkorn:regular,italic,bold,bolditalic|Cantarell|Inconsolata|Crimson+Text| Arvo:regular,italic,bold,bolditalic|Cardo|Neucha|Neuton|Droid+Sans+Mono| Cuprum|Old+Standard+TT:regular,italic,bold|Philosopher| Tinos:regular,italic,bold,bolditalic| Josefin+Sans:100,100italic,light,lightitalic, regular,regularitalic,600,600italic,bold,bolditalic| Arimo:regular,italic,bold,bolditalic| Josefin+Slab:100,100italic,light,lightitalic,regular, regularitalic,600,600italic,bold,bolditalic| Allerta|Geo|Allerta+Stencil|Puritan|Puritan:regular,italic,bold,bolditalic| Cousine:regular,italic,bold,bolditalic|UnifrakturMaguntia|Bentham| IM+Fell+DW+Pica:regular,italic|IM+Fell+English:regular,italic| IM+Fell+English+SC|IM+Fell+DW+Pica+SC|IM+Fell+Double+Pica+SC| IM+Fell+Double+Pica|IM+Fell+Great+Primer+SC|IM+Fell+Great+Primer| IM+Fell+French+Canon|IM+Fell+French+Canon+SC|Coda:800|Raleway:100| UnifrakturCook:bold|Covered+By+Your+Grace| Just+Me+Again+Down+Here” rel=”stylesheet” type=”text/css” />

Now include that in your CSS and you can freely use whatever font you want, whenever you want:

  1. h3 { font-family: Neucha, sans-serif; }
  2. div { font-family: "Reenie Beenie"; }

Production Use

I haven’t tested it, but I’m informed modern browsers will thankfully download only the fonts they need, so this is actually a viable solution for sites which will be frequented only by modern browsers, though obviously the snippet itself is too big for sites where performance is critical.

Unfortunately, IE6-IE8 will actually download every single font specified! So really, you should only be using this for development, and ensure production sites only declare the fonts they need. However, don’t lose site of DRY! In the spirit of Agile, DRY, and Continuous Integration, it would still be worth looking at ways to automate that process, e.g. with a server-side solution that generates the minimalist “link” tag.

Of course, the snippet is limited only to the Google fonts, good enough for my aesthetically-challenged purposes, but the principle could be generalised to encompass other font directories. Or someone in a company which has licensed and/or issued a standard set of fonts via their style guide, could also generate a company-specific snippet fot this purpose, containing all fonts. They could then make this a standard stylesheet which could be linked to from any HTML document.