The slide show project currently only shows one slide. I know a number of people who can talk for 75 minutes using one slide, but fortunately they've all retired from university life and taken their overhead projectors with them.
Today's speakers need to show at least one Internet meme infested slide every 30 seconds to keep an audience alert and happy. We must find a way to allow a presenter to move through slides with a keystroke, or the swipe of the finger. We'll look at touch later, and work on just the keystrokes.
One way to process keys is to use a giant switch statement.
switch(event.keyCode) { case 39: // that's the right arrow case 40: // down arrow ... // etc... }
Let's try something different. We'll add a variable to our p5 object that maps key codes to objects with action function. The name property is just here for readability.
var keys = { 39: { name: "rightArrow", action: moveForward }, 40: { name: "downArrow", action: moveForward }, 34: { name: "pageDown", action: moveForward }, 32: { name: "space", action: moveForward }, 37: { name: "leftArrow", action: moveBackward }, 38: { name: "upArrow", action: moveBackward }, 33: { name: "pageUp", action: moveBackward }, 36: { name: "home", action: moveFirst }, 35: { name: "end", action: moveLast } };
Then, once we've wired up the keydown event in the start method..
var start = function () { setFirstVisibleSlide(); $(window).bind("keydown", keyDown); };
.. we can handle a key down event without an ugly switch.
var keyDown = function (event) { var handler = keys[event.keyCode]; if (handler) { event.preventDefault(); handler.action(); } };
Next we'll add a brute force implementation of the actions.
var moveForward = function () { var current = $("section.current"); var next = current.next("section"); if (next.length) { current.removeClass("current"); next.addClass("current"); } }; var moveBackward = function () { var current = $("section.current"); var prev = current.prev("section"); if (prev.length) { current.removeClass("current"); prev.addClass("current"); } }; var moveFirst = function () { $("section.current").removeClass("current"); $("section").first().addClass("current"); }; var moveLast = function () { $("section.current").removeClass("current"); $("section").last().addClass("current"); };
I already hate the code. The number of string literals drives me crazy. We'll need to schedule another post just for refactoring and cleanup. Everyone cleans up their JavaScript code, right?
At this point we have a semi-working slide show! Only ... it's ugly and scrolls downward because the section elements are in the normal flow of the document and have a height despite being invisible. We will fix the aesthetics in the next post.
For all the code, see github.
In this series of posts we'll iterate on an HTML slide show. When I say "HTML", I mean we'll use all the buzzwords technologies that I kept out of the title of this post to avoid attracting attention from shallow minded subscribers who would only read a post titled something like "Top 7 Ways To Use HTML 5, JavaScript, and CSS3 To Ditch PowerPoint and Build Your Own GeoLocated TwitterBook Slideshow Software".
If you've made it this far, you are a sophisticated reader who can appreciate an understated title, and I welcome you here.
Let's start with the following HTML excerpt, which identifies the contents of each "slide" in a presentation using an HTML5 <section> element.
<section> <h1>This is a slide title</h1> <ul> <li>This is a bullet point</li> <li>Bullet points are exciting</li> </ul> </section> ... <section> <div>Slide titles are optional</div> <img src="images/colorful.jpg" alt="So are bullets" /> </section> <footer> This is a footer </footer>
Only one slide should appear in the browser at a time. We'll use CSS to hide all slides by default, and assume JavaScript code can set one of the sections to "current" by adding a class. We'll also position the footer so it stays in the bottom right of the window.
section { opacity: 0; } section.current { opacity: 1; } footer { position: fixed; bottom: 0px; right: 25px; }
The opacity property in the style sheet is a widely supported part of CSS3. We'll use the opacity property instead of the display property because opacity opens up more possibilities for animation transitions later.
Next, we'll add some simple JavaScript code.
Except ...
Well, it turns out simple JavaScript code is not allowed anymore. We'll need to follow the sensually named revealing module pattern and wrap the code inside the complexity of a self-executing function.
var p5 = function () { "use strict"; var start = function () { setFirstVisibleSlide(); }; var setFirstVisibleSlide = function () { $("section").first().addClass("current"); }; return { start: start }; } ();
Self-executing functions help to hide the implementation details of a library and avoid global variables and functions. The "use strict" string will toggle compatible browsers into ECMAScript 5 Strict Mode, which is a good place to be. The only code needed to start the slide show is a call to the start method.
p5.start();
Next up: moving through slides with the keyboard.
In the meantime, view the code on github.
Microsoft unveiled Windows 8 at the //build/ conference in September. Since then I've spent time seeing how to put together Windows 8 metro applications with HTML and JavaScript.
The following is all you need for a native Windows 8 Metro application.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Hello App</title> </head> <body> <h1>Hello!</h1> </body> </html>
There are some other small administrative details, like a manifest file. And, the above application is plain looking without styles or colors, but it is a real, native Metro application. To the user, the product is indistinguishable from a Windows 8 application written in C++ or C#. In Windows 8, HTML (and its friends JavaScript and CSS) are first class citizens.
Contrast this model against other platforms whose creators tout the benefits of HTML 5, but provide second-rate support. Their users still demand native applications on those platforms because they can feel the difference between an application written in Objective-C or Java, and an application written in HTML, just like they can taste the difference between grandma's peach pie and a vacuum packed peach pie they bought from the bottom of a freezer bin in a convenience store.
The support for HTML 5 in Windows 8 is an impressive, bold move for Microsoft and also validates the capabilities of the new web specifications. When you build an HTML application in Windows 8 you can feel an amazing potential. Consider what web development would be like if we had flexible-box layout, grid layout, rounded borders, and box shadows 5 years ago. The gross domestic product of the planet would be measurably higher as developers and designers spent less time creating useless images, less time cursing three column layouts, and less time searching and hacking to vertically center text in a div.
CSS has a history of making easy things difficult (and that's without the troubles of IE6, 7, and 8), but all of the above scenarios are trivial with the new standards.
CSS animations and transitions are another pleasure to work with. Consider what's inside the following style rule:
.class { transition: all 1s ease-in-out; }
That's pretty much all the code you need to add subtle, realistic animations to an otherwise herky-jerky effect. Contrast this against the mind numbering amount of namespace infested XML required by XAML for simple animations.
It's not all about CSS, though. There is scriptable video, bitmapped graphics, and vector graphics. There's WebWokers, WebStorage, and a NOSQL database built in. Everything you need, including all the APIs of the Windows Runtime - the same API available to C# and C++ applications - is available to JavaScript, and that's where this post reaches a turning point.
Programming Windows 8 with HTML and CSS is a joy. Programming Windows 8 with JavaScript is . . . different. It's not that you can't use utility belt libraries like jQuery and Underscore – you can. You can even use a library like jQuery UI (but keep it mind that jQuery UI doesn't process touch events or produce touch-sized widgets, so it's not a good idea).
There was some other feeling that kept growing on me as I wrote code and browsed the samples. Code like the following (but don't read the code, just look at the shape):
The code is verbose. I don't mind verbosity, but noisy code is a pet peeve. The SDK samples for Windows 8 are noisy and often have consecutive lines of code stretching over 120+ columns. It looks like a wall of text.
Nobody wants to read a wall of text, much less comprehend it, debug it, and maintain it.
This is a difficult problem, because the Windows Runtime API is expansive and will grow. Namespaces are required, but there is no automatic and simple "imports" or "using" in JavaScript. What we'll need is an automated refactoring operation. "I see you are using the Windows.ApplicationModel.DataTransfer.SendTarget namespace, would you like me to alias that to a module-scoped variable named wads?" Yes!
I also don't feel comfortable with the built-in declarative data binding.
<span data-win-bind="innerHTML: productName"></span>
This approach easily avoids all 'flash of unbound content' problems, but it feels significantly different from every other JavaScript templating technology. Navigation is also cumbersome and complex. I was expecting some template loading and a pushState API based on the new history specifications, like every other one page HTML application, but there appears to be an entire API designed around the concepts of fragments, navigation, and state, and I find it difficult to wrap my head around the magic.
There are some good points in the JavaScript code. Modern practices are in play with the module pattern appearing in the default project template. There is a nod to ECMAScript 5 with "use strict" in the module scope. And, with the Windows Runtime offering only non-blocking asynchronous APIs, it's good to see the Windows JavaScript libraries implement the CommonJS specification for a Promise. Promises remove noise by getting rid of the "continuation tail of curly braces". I'll save details of that topic for a future post.
I'm impressed by Microsoft's implementation of the Windows Runtime, the bindings from the runtime to JavaScript, and the implementation of HTML, CSS, and JavaScript standards. Ironically, it makes me think more about the day when we are using all these new features to implement web applications (and finally retire support for obstinate, outdated browsers), and less about desktop development for Windows 8. Because …
I'm not 100% sold on Metro.
There are a couple challenges I see.
First, even though you are writing an application with HTML 5, CSS, and JavaScript, as soon as you take a dependency on Windows.Runtime you have at least some of your code tied to Windows. It's not a script you can send to anything but a Metro app on Windows 8. This in itself isn't a problem, because we can expect millions of machines to run Windows 8 in the future. But, right now the Metro sweet spot is tablets. All of the oversized, touch-optimized controls feel ridiculous when running on a desktop machine – it's a like drawing on high quality graph paper with crayons. Unless we get a way to put a Metro app in a Window, I think the success of Metro will depend entirely on Microsoft's success in the ultra-competitive tablet market. That's a wait and see game, and a game where many will hedge their bets.
Secondly, with regards to Metro and native HTML applications, I just don't see JavaScript programmers getting excited about the platform. I have flashbacks to the ASP.NET Control Toolkit when writing Metro code. It's heavy. It's noisy. It's a lot of ceremony surrounding little nuggets of essence. It's going to require some work to properly architect and design an application to hide the infrastructure details and promote maintainability.
Finally, on a personal note, the way the whole thing went down leaves me with a bit of a bad taste and a slight bias. For the last few years many people have been working hard at turning Microsoft into a "kindler, gentler" entity that listens to a wider community and addresses issues forthright. Then earlier this year came the "Silverlight is dead" whispers, followed an enforced silence, followed by more talk of dead platforms, followed by panicked customers followed by total silence. No, I haven't talked to anyone with a blue badge about this scenario, but I did have a mental imagine of Mafioso heavies roaming the halls of Redmond wielding clubs emblazoned with a Windows 8 team logo and holding people up against walls to demonstrate what might happen if they don't stay ... "on message".
And for what?
It's not that Metro is revolutionary. Metro primarily represents a shift in focus from the enterprise to the consumer. The languages, the development environment, the technologies – they've been with us for some time. You'll see many familiar controls and paradigms in Metro applications as it builds upon things we've been using for years (except in the case of the JavaScript libraries, where everything is written from scratch, and going through the Metro SDK samples you'd think the earth was devoid of any other JavaScript libraries that might possibly help build stuff for a web browser). It's the old Microsoft – the corporate giant that does everything right and doesn't need your help or feedback.
Hopefully that behavior was not a harbinger of things to come.
The HTML 5 DOM interface for a video element allows you to get the underlying video's width and height in pixels, but, be careful not to ask for the dimensions too early. If you ask as soon as the DOM is ready, like in the following code, you'll probably see width and height as 0.
$(function () { var video = $("#video").get(0); var width = video.videoWidth; var height = video.videoHeight; // ... });
You'll want to wait for the video element to raise the loadedmetadata event before asking for the dimensions. The event is documented as firing when "the user agent has just determined the duration and dimensions of the media resource and the text tracks are ready".
Example:
$(function () { $("#video").bind("loadedmetadata", function () { var width = this.videoWidth; var height = this.videoHeight; // ... }); });
The canonical example for fluent configuration with the Entity Framework is to take a few simple entity definitions:
public class Product { public int Id { get; set; } public string Name { get; set; } public byte[] Version { get; protected set; } }
... and configure them all inside of the DbContext's OnModelCreating method:
protected override void OnModelCreating( DbModelBuilder modelBuilder) { modelBuilder.Entity<Product>().ToTable("products"); // ... more configuration base.OnModelCreating(modelBuilder); }
This approach doesn't scale well as we add more entities, so let's try an alternate approach. We'll put the configuration for each entity into a distinct class.
public class ProductConfiguration : EntityTypeConfiguration<Product> { public ProductConfiguration() { ToTable("products"); Property(p => p.Name).HasMaxLength(255); Property(p => p.Version) .IsConcurrencyToken() .IsRowVersion(); } }
Now model building is as simple as adding all the configuration objects into the model builder's configuration registrar.
protected override void OnModelCreating( DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new ProductConfiguration()); // ... and so on, for each configuration class base.OnModelCreating(modelBuilder); }
The new drawback is someone needs to instantiate every configuration object during OnModelCreating, which is a boring, silly, maintenance concern to worry about when things start to change. The next improvement is to automate this chore.
We can use reflection, or any decent composition / IoC container to find all of the configuration classes in an application and hand them to us in a collection. It's easy to fall into a line of thinking that says we need this collection to be a collection of EntityTypeConfiguration<TEntity>, because it's easy to picture the model building code like this:
foreach (var configuration in allConfigurations) { modelBuilder.Configurations.Add(configuration); }
It turns out this approach is not only limiting, it can also be difficult to pull off. Since the TEntity parameter in EntityTypeConfiguration<TEntity> will vary across all the entities, you either end up working with things like open generic types (EntityTypeConfiguration<>) or a closed type of EntityTypeConfiguration<object>. It's ugly and I'll spare you the details. Let's take a different approach that starts with an interface.
public interface IEntityConfiguration { void AddConfiguration(ConfigurationRegistrar registrar); }
And then a class that will collect (via MEF) all the objects that want to participate in the configuration of a context.
public class ContextConfiguration { [ImportMany(typeof(IEntityConfiguration))] public IEnumerable<IEntityConfiguration> Configurations { get; set; } }
The individual configuration objects then get decorated with MEF export attributes and implement the IEntityConfiguration interface.
[Export(typeof(IEntityConfiguration))] public class ProductConfiguration : EntityTypeConfiguration<Product>, IEntityConfiguration { public ProductConfiguration() { ToTable("products"); // ... more configuration } public void AddConfiguration(ConfigurationRegistrar registrar) { registrar.Add(this); } }
Then a brute force approach to model building might look like this:
protected override void OnModelCreating( DbModelBuilder modelBuilder) { var contextConfiguration = new ContextConfiguration(); var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var container = new CompositionContainer(catalog); container.ComposeParts(contextConfiguration); foreach (var configuration in contextConfiguration.Configurations) { configuration.AddConfiguration( modelBuilder.Configurations); } base.OnModelCreating(modelBuilder); }
With this approach the code inside OnModelCreating never has to change, even when new entity configurations appear in the application. Also, there are no messy type issues with generic parameters, and the relationship between model building and configurations is a bit more flexible (in a double-dispatch / visitor pattern kind of way).
In the last post we looked at feature detection with Modernizr. Before moving forward, let me answer a few questions that came up.
First, you can build a custom Modernizr download containing only the tests you care about when you visit http://www.modernizr.com/download/. If you don't care about the geolocation APIs, then don't check the geolocation checkbox. The script file you download will be smaller, and more importantly there are fewer tests to run when the script hits the browser. Chances are good you will only care about a handful of the possible tests.
Secondly, Modernizr doesn't add any missing features to a browser. Modernizr only tests to see if specific features are available. The single exception is that Modernizr does create HTML 5 elements for older versions of IE. We looked at this capability in the first post of this series. Everything else is just a test. Modernizer can tell you if the geolocation API is available, or if it isn't. If the API is available you can use it. If the API is not available then you have a decision to make. Do you gracefully degrade the page and hide content that requires the user's location? Or, do you enter the world of polyfills and web shims?
Polyfills are spackling paste for web browsers. They fill the holes left behind when a browser doesn't implement a feature. There are dozen of polyfills available, and some are more elaborate than others. Ideally a polyfill API will mimic the real HTML 5 API so you can use a single codebase for all browsers, but this ideal scenario is not always possible.
Let's say, for example, that you want to use the geolocation API to display a user's current latitude and longitude. You might use something like the following:
navigator.geolocation.getCurrentPosition( onGeoSuccess, onGeoError); function onGeoSuccess(position) { var display = $("#position").tmpl(position.coords); $("body").append(display); } function onGeoError(e) { $("body").append(e.message); }
And use the following template to display the result:
<script id="position" type="text/x-tmpl"> <div> Latitude: ${latitude} Longitude: ${longitude} </div> </script>
Now imagine someone with a new Kindle Fire comes to your website. The Fire's browser (Silk) doesn't support the geolocation API. You could discover this if you just ask Modernizr.
if (!Modernizr.geolocation) { // }
To support geolocation on browsers like Silk, you could use the Webshims Lib by Alexander Farkas. The WebShims lib includes scripts to polyfill not just geolocation features, but also ECMAScript 5 features, new HTML 5 inputs, canvas, and more. You just need to load the polyfiller.js bootstrapping code (which requires jQuery and Modernizr's script loader).
<script src="jquery.js"></script> <script src="modernizr-geo.js"></script> <script src="polyfiller.js"></script> <script> $.webshims.polyfill(); </script>
The beauty of the geolocation polyfill is how the script lets you use the same API you would use when a browser natively implements geolocation – no code has to change! Of course, not all polyfills are as easy, but hopefully we won't have to live with them for more than a few more years. Or 5. Or 10 ...
From Wikipedia:
The tragedy of the commons is a dilemma arising from the situation in which multiple individuals, acting independently and rationally consulting their own self-interest, will ultimately deplete a shared limited resource, even when it is clear that it is not in anyone's long-term interest for this to happen.
It might seem odd to take a term related to environmental issues and apply the term to software, but please allow some poetic license around the meaning of "shared limited resource".
The architecture and design of an existing application is a resource providing a benefit to the developers and operational people who have to build features in an application and keep it running in production. It's a limited resource since misuse will reduce the benefit for everyone.
"Architectural tragedy of the commons" is a term that jumped into my mind a few years ago as something that can happen (not always, but sometimes) when:
- developers build new features into a product without talking to each other (individuals act in their own self interest.
- teams build new features for a product without coordinating (teams can act in their own self interest).
- companies go through developers like Netflix goes through business plans (in a body shop, nearly everyone acts in their own self interest).
You've probably worked on applications where shortcuts and hacks make a codebase fragile and inconsistent. Maybe you've even worked on products where the developers took shortcuts that made the application more difficult to deploy and operate (thus making the IT department's life miserable). This are examples of what I'd call an architectural tragedy of the commons.
Communication and leadership can commonly prevent an architectural tragedy of the commons, and often leads to sustainable design.