domchristie / turn

📖 Animate page transitions in Turbo Drive apps
https://domchristie.github.io/turn/
MIT License
155 stars 7 forks source link

Dynamic view transitions #12

Closed domchristie closed 1 year ago

domchristie commented 1 year ago

This pull request makes it possible to dynamically apply unique view-transition-names, making it easier to customise transitions in CSS.

Why? View Transitions require unique view-transition-names so it can animate between the two states. For example, in a photo gallery, you might give each photo in the grid a unique name of image-:id (where :id is unique), which is also applied to the photo when viewing it in full. Customising view transitions in CSS requires referencing the view-transition-name. However, if each element has a unique view-transition-name then the CSS has to reference each of these names for customisation.

https://github.com/w3c/csswg-drafts/issues/8319 has some ideas to improve this, but in the meantime this pull request allows for simple view-transition-names to be applied on-the-fly.

How? This pull request adds events to the transition lifecycle. These include:

The detail of these events includes:

turn:before-exit and turn:before-transition also include newBody for customising the incoming markup.

With these events, it's possible to annotate links with references to the elements that should transition. For example:

window.addEventListener('turn:before-transition', function ({ detail }) {
  let { action, initiator, newBody, referrer } = detail

  // apply `view-transition-name`s to both element in the current body and `newBody`,
  // based on the `action`, `initiator`, and `referrer`
})

In this way, view-transition-names can be simple, and easily referenceable, e.g. image

adrienpoly commented 12 months ago

Oh this is cool. Thanks for that

domchristie commented 12 months ago

@adrienpoly no problem; it needed to be done! Hidden demo here: https://domchristie.github.io/turn/examples/dynamic-view-transitions/