CSS Classes State Machine Puzzle

It is quite nature to code CSS classes as “states” in a web applications. Say if you have three <div class="view">s within the <body> tag, you can easily toggle the class of the body to show/hide the views, with one-off CSS animations as view-to-view transitions, right? Wrong.

It turns out, it works with two states even with transition/animation, but not so much if there are three states. For two states like A & B, there is only one possible route to get into each state, A→B for B, and B→A for A. However, if there are three states, A would have routes B→A and C→A, and so on. It’s basically n*(n-1) for n states.

How do you specify two different CSS animations for the two routes? This doesn’t sounds like a common question, but I have personally encountered twice in different projects, and I bet sooner or later this would happen to everyone as we moved from DOM animation to CSS and rely more and more on browser to run the animation smoothly.

One way to look at it would be that this is a design flaw of the CSS language. There should be some pseudo-class like :was() to specify what exact route to match against. However, inventing a pseudo-class just for the animation property doesn’t sound like a great idea.

The other way, and a more practical approach is to look for solution with what we have right now. Inevitably, to distinguish route B→A and route C→A, one should introduce immediate states, making the routes B→A’→A and C→A”→A. Yet, this further complicate things if one would like the scripting part stay as a clean finite-state machine: First, the transition of A’→A will depend on animationend event, which couples the CSS code with Javascript code. Second, and the bummer that makes the solution incomplete, is that the animationend event will never fire if the state changes again during the A’ or A” state, which make it necessary to handling the changing in Javascript code again ourselves. Good luck on codify all the A’→B, A”→C, A’→C, … transitions.

Now you know how hard it is to write a mobile OS window manager with Javascript + CSS. There might be some obvious answers I overlooked, if you would like to give your solutions, feel free to comment here or post it on your own blog.

One thought on “CSS Classes State Machine Puzzle

  1. I think the first step is to stop using classes here.
    element.className is not unique and its semantic looks strange.
    We won’t know what happens if class=”A B”. You need to clear the className by yourself if necessary. Use dataset to ensure the value is one and only one.

Leave a Reply

Your email address will not be published. Required fields are marked *