How to use View Transitions in Hotwire Turbo
Tags: hotwire, css, animations, rails
Published: 2023-02-16 09:55:37

Have you heard the news? **Google Chrome 111** will be released on March 1st 2023 and – among other things – [will ship](https://chromestatus.com/feature/5193009714954240) a feature I was eager to try since I first heard about it: **View Transitions**. This is a new API proposed by Google at W3C, currently as a [1st Working Draft](https://drafts.csswg.org/css-view-transitions-1/). An informal summary for it can be found in [this Explainer](https://github.com/WICG/view-transitions/blob/main/explainer.md) which seems to be a more up-to-date version of the original [introductory article](https://developer.chrome.com/docs/web-platform/view-transitions/#changing-on-navigation-type) published at the Chrome Developers site last year. I highly recommend reading either of the documents. **Update:** there is now some [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) available, too!

So what are View Transitions good for? In short, they allow adding **animated page transitions**. Although we already have several standard options to animate stuff on web pages ([CSS Transitions](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions), [CSS Animations](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations) or the [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API)) and countless more options in particular JavaScript frameworks and libraries ([Framer Motion](https://www.framer.com/motion/) for React, [Vue Transitions](https://vuejs.org/guide/built-ins/transition.html), [Svelte Transitions](https://svelte.dev/docs#template-syntax-element-directives-transition-fn), [Swup](https://swup.js.org), [Barba.js](https://barba.js.org/) or [Animate.css](https://animate.style/) to name just a few), the web still lacks a generic, standards-based and easy-to-use solution to **animate transitions between pages or during DOM updates**. At least that’s what Google engineers say and I tend to agree with them.

In the **[Hotwire Turbo](https://turbo.hotwired.dev/)** world specifically, several [discussions](https://discuss.hotwired.dev/t/are-transitions-and-animations-on-hotwire-roadmap/1547) about integrating transition animations also took place and a few promising approaches emerged, namely the [Turn project](https://github.com/domchristie/turn) or the [transitions in Bridgetown](https://github.com/bridgetownrb/bridgetown/blob/13a9c4faf4df8efa1b1a00bd08929e32f66e5f8b/bridgetown-core/lib/bridgetown-core/configurations/turbo/turbo_transitions.js). There is also a chapter in the [Noel Rappin’s Modern Front-End book](https://pragprog.com/titles/nrclient2/modern-front-end-development-for-rails-second-edition/) and an interesting [article](https://edforshaw.co.uk/hotwire-turbo-stream-animations) but overall, frankly, this topic still fells somewhat early-stage and exploratory.

And here comes the View Transitions proposal. Could it change the situation for Hotwire and others? It of course depends on many things, most importantly on the adoption rate by [other browser](https://github.com/mozilla/standards-positions/issues/677) [vendors](https://github.com/WebKit/standards-positions/issues/48) and the community in general and whether the W3C Draft Recommendation track succeeds. But I have a gut feeling that yes, it might change things!

## A ”Hello world“ example

Let’s take a look at a simple example. Coincidentally, a bunch of examples for an animated counter have recently been created by [Jake Archibald](https://twitter.com/jaffathecake) in [React](https://codesandbox.io/s/nervous-mclaren-j8v8y0?file=/src/App.tsx:0-57), [Svelte](https://svelte.dev/repl/84cffc3241514c1581bf951bdf818def?version=3.55.1) and [Lit](https://lit.dev/playground/#project=W3sibmFtZSI6ImFwcC50cyIsImNvbnRlbnQiOiJpbXBvcnQge2h0bWwsIGNzcywgTGl0RWxlbWVudH0gZnJvbSAnbGl0JztcbmltcG9ydCB7Y3VzdG9tRWxlbWVudCwgcHJvcGVydHl9IGZyb20gJ2xpdC9kZWNvcmF0b3JzLmpzJztcbmltcG9ydCB7IHRyYW5zaXRpb25IZWxwZXIgfSBmcm9tICcuL3V0aWxzLmpzJztcblxuQGN1c3RvbUVsZW1lbnQoJ2RlbW8tYXBwJylcbmV4cG9ydCBjbGFzcyBEZW1vQXBwIGV4dGVuZHMgTGl0RWxlbWVudCB7XG4gIHN0YXRpYyBzdHlsZXMgPSBjc3NgXG4gICAgLmNvdW50IHtcbiAgICAgIGZvbnQtZmFtaWx5OiBzYW5zLXNlcmlmO1xuICAgICAgdGV4dC1hbGlnbjogY2VudGVyO1xuICAgICAgcG9zaXRpb246IGFic29sdXRlO1xuICAgICAgaW5zZXQ6IDUwJSAwIGF1dG87XG4gICAgICB0cmFuc2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ICBjbGFzc05hbWVzID0gW10sXG4gIHVwZGF0ZURPTSxcbn0pIHtcbiAgaWYgKHNraXBUcmFuc2l0aW9uIHx8ICFkb2N1bWVudC5zdGFydFZpZXdUcmFuc2l0aW9uKSB7XG4gICAgY29uc3QgdXBkYXRlQ2FsbGJhY2tEb25lID0gUHJvbWlzZS5yZXNvbHZlKHVwZGF0ZURPTSgpKS50aGVuKCgpID0-IHt9KTtcbiAgICBjb25zdCByZWFkeSA9IFByb21pc2UucmVqZWN0KEVycm9yKCdWaWV3IHRyYW5zaXRpb25zIHVuc3VwcG9ydGVkJykpO1xuXG4gICAgLy8gQXZvaWQgc3BhbW1pbmcgdGhlIGNvbnNvbGUgd2l0aCB0aGlzIGVycm9yIHVubGVzcyB0aGUgcHJvbWlzZSBpcyB1c2VkLlxuICAgIHJlYWR5LmNhdGNoKCgpID0-IHt9KTtcblxuICAgIHJldHVybiB7XG4gICAgICByZWFkeSxcbiAgICAgIHVwZGF0ZUNhbGxiYWNrRG9uZSxcbiAgICAgIGZpbmlzaGVkOiB1cGRhdGVDYWxsYmFja0RvbmUsXG4gICAgICBza2lwVHJhbnNpdGlvbjogKCkgPT4ge30sXG4gICAgfTtcbiAgfVxuXG4gIGRvY3VtZW50LmRvY3VtZW50RWxlbWVudC5jbGFzc0xpc3QuYWRkKC4uLmNsYXNzTmFtZXMpO1xuXG4gIGNvbnN0IHRyYW5zaXRpb24gPSBkb2N1bWVudC5zdGFydFZpZXdUcmFuc2l0aW9uKHVwZGF0ZURPTSk7XG5cbiAgdHJhbnNpdGlvbi5maW5pc2hlZC5maW5hbGx5KCgpID0-XG4gICAgZG9jdW1lbnQuZG9jdW1lbnRFbGVtZW50LmNsYXNzTGlzdC5yZW1vdmUoLi4uY2xhc3NOYW1lcylcbiAgKTtcblxuICByZXR1cm4gdHJhbnNpdGlvbjtcbn0ifV0), so let’s try building the same in Turbo! I will demonstrate it in a Ruby on Rails app as this is what I’m most accustomed to but it should work the same in any other Turbo-enabled framework.

So, we will create a simple page with a big bold number and a link that will increment this number using a [Turbo Frame](https://turbo.hotwired.dev/handbook/frames). First, we’ll build a bare-bones page and then we’ll add a View Transition animation.

Turbo Frame needs to route it’s requests somewhere so let’s add a route first:

```ruby
# config/routes.rb
Rails.application.routes.draw do
  resources :counter, only: :index
end
```

The corresponding controller (by the way, a [”singular“ one](https://guides.rubyonrails.org/routing.html#singular-resources)) can stay basically empty:

```ruby
# app/controllers/counter_controller.rb
class CounterController < ApplicationController
  def index; end
end
```

The template renders the `<turbo-frame>` tag and inside it the link and the counter itself (the [Slim](https://github.com/slim-template/slim) template language and [Tailwind](https://tailwindcss.com/) styling are used here, hopefully the notation is sufficiently self-explaining):

```slim
/ app/views/counter/index.html.slim
= turbo_frame_tag(:incrementing_counter)
  - counter = params[:counter].to_i
  = link_to "Increment", counter_index_path(counter: counter + 1),
            class: "block p-2 bg-gray-100 active:bg-gray-200"

  #counter.absolute.w-full.text-8xl.font-bold.text-center
    = counter
```

And this is how it looks so far: Turbo makes requests and replaces the Frame upon clicking the link and no animations are triggered (as can be seen in the lower-right panel):

{% youtube 99dPzcOQ_SA %}

Now, **let’s add View Transitions to the Turbo Frame**. To do this, we need to [override the default rendering function](https://turbo.hotwired.dev/handbook/frames#custom-rendering) for Turbo Frames in the [`turbo:before-frame-render` event](https://turbo.hotwired.dev/reference/events) handler with a custom one that utilizes View Transitions:

```js
// app/javascript/application.js
addEventListener("turbo:before-frame-render", (event) => {
  if (document.startViewTransition) {
    const originalRender = event.detail.render
    event.detail.render = (currentElement, newElement) => {
      document.startViewTransition(()=> originalRender(currentElement, newElement))
    }
  }
})

```

The handler code first checks whether View Transitions are supported by the browser and if so, it wraps the original rendering function with the [`document.startViewTransition`](https://github.com/WICG/view-transitions/blob/main/explainer.md#how-the-cross-fade-worked) function. **And that’s it!** These couple of lines trigger a [default cross-fade animation](https://github.com/WICG/view-transitions/blob/main/explainer.md#revisiting-the-cross-fade-example) of the whole page whenever any Turbo Frame renders. Yes, the **whole page** is indeed animated by default but since most elements on the page are either identical (those outside the Turbo Frame) or replaced by identically looking elements (e.g. the link inside the Frame), in practice only the counter itself feels animated. It looks like this:

{% youtube WMaSNm6n918 %}

Finally, we can customize the transition a bit. To match the examples mentioned above, let’s rotate the counter during transitions. For this we will need to utilize **”named“ View Transitions**, explained [here](https://github.com/WICG/view-transitions/blob/main/explainer.md#transitioning-multiple-elements) in the documentation. Whenever we select a part of the screen with a CSS selector and name it using the `view-transition-name` attribute, the browser starts to animate the corresponding screen region **independently of all other parts**. This way, we can animate one or more elements on the page without affecting the rest of the page.

So let’s add the following CSS to the `index` template (Slim recognizes a `css:` block that just renders a normal `<style>` tag):

```slim
/ app/views/counter/index.html.slim
/ (anywhere outside the Turbo Frame tag)
css:
  /* (1) */
  #counter {
    view-transition-name: counter;
    contain: layout;
  }

  /* (2) */
  @keyframes rotate-out {
    to {
      transform: rotate(90deg);
    }
  }

  @keyframes rotate-in {
    from {
      transform: rotate(-90deg);
    }
  }

  /* (3) */
  ::view-transition-old(counter) {
    animation-duration: 200ms;
    animation-name: -ua-view-transition-fade-out, rotate-out;
  }
  ::view-transition-new(counter) {
    animation-duration: 200ms;
    animation-name: -ua-view-transition-fade-in, rotate-in;
  }
```

Let’s break this code down a bit:

1. The CSS selector `#counter` matches the counter div and the **`view-transition-name` property** names this area of the screen, for the purpose of View Transitions, as `counter`. This name will be used in the animation declarations below.

    The `clone` property currently must be added here for some reasons internal to the current View Transitions implementation in Chrome and must be set to `paint` or `layout`. This restriction is planned to be removed from the specification, though, and in fact I’ve heard that it is not needed in Chrome Canary any more.

2. The rotation animation [keyframes](https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes) are defined here. Note that while the transition also uses fade-in and fade-out animations, they don’t have to be defined here because the spec [requires](https://www.w3.org/TR/css-view-transitions-1/#ua-keyframes) browsers to implement them natively under the name `-ua-view-transition-fade-in/out`.

3. The [CSS animations](https://devdocs.io/css/css_animations/using_css_animations) for the counter (the View Transition area named `counter`) are configured here. The CSS selectors here are some of the [pseudo-elements](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements) [automatically created](https://github.com/WICG/view-transitions/blob/main/explainer.md#how-the-cross-fade-worked) during the transition. The `-old` pseudo-element represents a screenshot of the old DOM state that should somehow disappear or ”go away“ from the viewport and the `-new` pseudo-element represents a live version of the final DOM state that should be brought into sight.

So, overall, this code selects a portion of the page and **animates it independently from the rest of the page during Turbo Frames DOM updates**. Behind the scenes, the default cross-fade for the rest of the page still also takes place, it just is not visible because all its elements are visually identical. The result looks like this:

{% youtube Op0Fyrg0MJo %}

## A few initial tips & tricks

### Does this work for [Turbo Drive](https://turbo.hotwired.dev/handbook/drive) visits, too?

Sure it does and it’s actually pretty easy! All we have to do is define the same event handler as we did above but [attach](https://turbo.hotwired.dev/handbook/drive#custom-rendering) it to the [`turbo:before-render` event](https://turbo.hotwired.dev/reference/events) instead. By default we’ll get a cross-fade animation of the whole page during Turbo Drive page visits.

### Do not try to ”name“ the Turbo Frame itself

When playing with Turbo Frame View Transitions I first tried to use a custom animation for the whole Turbo Frame element by naming it via the `view-transition-name` property. For some reason, this does not work and you end up with a very cryptic and misleading error message in the console (yes I _did_ have the `contain` property in the CSS declaration):

> Aborting transition. Element must contain paint or layout for view-transition-name : counter

So, when using custom animations, an element from _inside_ the Frame must be selected and named.

### Debugging View Transitions

Since View Transitions are technically just normal CSS animations, they can be [inspected](https://github.com/WICG/view-transitions/blob/main/explainer.md#compatibility-with-existing-developer-tooling) with the Animations panel in the Dev Tools. Also, the automatically created pseudo-elements are visible in the Elements tab during the transitions:

{% youtube GeLTAEv7ENU %}

## Conclusions

I confess I am quite excited about the new View Transitions API. Among the things I particularly like about it are the following:

-  It is **surprisingly easy** to plug this inside Hotwire Turbo and you get the default cross-fade transition animation immediately for free (in latest Chrome-like browsers, that is).
- Since this is implemented natively in the browser, the animations are **highly optimized and performant**.
- View Transitions should allow (today or in the future) building highly interactive transitions similar to [those in Material Design](https://m3.material.io/styles/motion/transitions/transition-patterns).
- There is some initial **[support for Multi-Page Applications](https://github.com/WICG/view-transitions/blob/main/explainer.md#cross-document-same-origin-transitions)**, too, which is great news because we can bring transition animations declared in CSS to our old but gold apps.
- It [should be possible](https://github.com/WICG/view-transitions/blob/main/explainer.md#customizing-the-transition-based-on-the-type-of-navigation) to use a different animation based on the ”direction“ of the visit (Back/Forward) using the Navigation API (also still experimental and not very well supported, though).

Things I am still concerned about:

- **Browser support**: the Firefox team [evaluates it](https://github.com/mozilla/standards-positions/issues/677), the Safari team is [silent](https://github.com/WebKit/standards-positions/issues/48). This will be a log run and making a polyfill is probably [too difficult](https://developer.chrome.com/docs/web-platform/view-transitions/#not-a-polyfill). For web sites where transition animations are critical, this is still a no go.
- If you’re not careful enough, the transition feels **more fluid but also a little bit slower**. The reason for it is that View Transitions start the animations at the moment when both the old and new DOM states are already rendered. This means that the exit animation is delayed until new content is available and until that time, nothing happens. Also, the entry animations for the new state usually delay its appearance a little bit more.

    This is not a problem of View Transitions themselves but rather a more generic one. If the exit animation (e.g. a fade out) started immediately after user interaction (e.g. a link click), sometimes the user would have to stare at a blank page until the new page content is grabbed, rendered and run through an entry animation. Still, some kind of support for this scenario (possibly with custom loaders or skeletons) would be nice.

- Tailwind support: I think the current Tailwind syntax does not allow targeting the HTML document-connected pseudo-elements so we have to resort to custom CSS (which is not a big problem, actually).
- All transitions target the whole page, there is currently no option to make, say, two components (Frames) animate totally independently. An initial proposal for ”scoped transitions“ can be found [here](https://github.com/WICG/view-transitions/blob/main/scoped-transitions.md).


Overall, I like this feature and wish it matures enough and gets wider support soon!