15 Feb 2024 · Software Engineering

    Seamless SPA Transitions Using the New View Transitions API (Part 2)

    7 min read
    Contents

    In the first part of our exploration, we delved into the significance of seamless transitions in web applications, particularly in Single-Page Applications (SPAs), and introduced the View Transitions API as a groundbreaking solution. Now, let’s take it a step further by implementing various transitions using Astro JS.

    This versatile JavaScript framework empowers developers to create performant and dynamic web experiences using the View Transitions API.

    Understanding View Transitions in Astro JS

    The View Transitions API in Astro JS provides developers with a comprehensive toolset for managing transitions between various views within an application. It allows for a more holistic and dynamic approach to animating content changes.

    Key Features of View Transitions in Astro JS

    • Default View Transitions: Astro JS comes with an inherent fade-in effect as the default transition when moving between views. This built-in feature enhances user interaction without the need for explicit setup.
    • Named Transition Effects: These offer a methodical way to animate transitions between various routes in a web application. This functionality empowers developers to allocate specific animations to assigned elements, resulting in a more personalized and visually captivating user journey.
    • Custom Animations: In addition to the default fade-in, developers have the freedom to specify custom animations for particular views or elements. This adaptability enables a personalized approach to visual storytelling within the application.

    Getting Started with Astro

    To kickstart your Astro application, run npm create astro@latest on your computer’s terminal. This initiates the installation process, offering a range of customization props that you can fine-tune according to your project requirements. As of the time of this article, Astro v3 has been released, eliminating the need for any extra configuration to support the API.

    You can find the demo app’s source code here on GitHub, as well as Astro’s View Transitions API reference docs.

    To run the demo app linked on Github above, just run the first couple Commands!

    Default View Transitions

    One of the standout features of Astro JS is its provision of default view transitions, making it easy for developers to enhance their SPAs without additional configuration.

    By importing the <ViewTransitions /> component from Astro Transitions into a parent element of your routes, all children elements inherit a default fade-in animation.

    ---
    import { ViewTransitions } from "astro:transitions";
    
    ---
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="description" content="Astro description" />
        <meta name="viewport" content="width=device-width" />
        <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
        <meta name="generator" content={Astro.generator} />
        <title>{title}</title>
        <ViewTransitions />
      </head>
      <body>
        <slot />
      </body><style is:global></style>
    </html>

    Here’s the output using the default ViewTransitions animation. 

    Understanding Named Transitions

    Named transitions provide a structured approach to animating transitions between different routes in a web application. While traditional methods often rely on generic animations, named transitions in Astro JS allow developers to assign specific animations to designated elements, creating a more tailored and visually engaging user experience.

    To use named transitions, we start by importing view transitions in the common parent of the elements you wish to transition like in the default transition.

    Then in your first route, use the transition:name property with a unique name to identify the element you want to transition from.

    ---
    import Layout from "../layouts/Layout.astro";
    ---
    <Layout title="home">
      <div>
        <h1>Home Page</h1>
        <div class="container">
          <img src="./image.png" alt="" transition:name="img" />
        </div>
    
        <div class="button">
          <a href="/about">Go to About Page</a>
        </div>
      </div>
    </Layout>

    Then use the same name for the second page you wish to transition to:

    ---
    import Layout from "../layouts/Layout.astro";
    ---
    
    <Layout title="About">
      <div>
        <h1>About Page</h1>
        <div class="container">
          <div>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda,
            voluptatibus? Voluptatibus saepe magnam repudiandae, ullam placeat
            voluptates. Eius totam odio, excepturi nostrum facere natus ipsum dolor
            voluptas commodi velit delectus modi repudiandae non similique hic
            pariatur enim inventore, sunt impedit incidunt aperiam libero laboriosam
            reprehenderit dolorum? Dolores deserunt officiis eos sit porro nihil
            error, quaerat minus fuga rem ab autem? Consequatur quasi provident
            labore omnis deleniti eligendi at harum, sint ducimus blanditiis ipsum
            doloremque modi voluptatibus eaque nam itaque veritatis! A ea error iure
            nobis distinctio veniam odit voluptatum harum alias placeat aperiam,
            obcaecati sequi exercitationem excepturi. Vero, ut excepturi.
          </div>
          <img src="./image.png" alt="" transition:name="img" />
        </div>
    
        <div class="button">
          <a href="/">Go to Home Page</a>
        </div>
      </div>
    </Layout>

    And the result becomes: 

    Custom Animations

    Astro provides a set of built-in animations that allow you to customize the transitions between views. By using thetransition:animatedirective on individual elements, you can override the default fade transition and tailor the behavior of specific transitions to suit your application’s needs.

    • fade (default): An opinionated crossfade animation where the old content fades out, and the new content fades in.
    • initial: Opt out of Astro’s opinionated crossfade animation and use the browser’s default styling.
    • slide: An animation where the old content slides out to the left, and the new content slides in from the right. On backward navigation, the animations are the opposite.
    • none: Disable the browser’s default animations. Use on a page’s <html> element to disable the default fade for every element on the page.

    Let’s take an example where we customize the duration of the built-in slide animation:

    ---
    import { slide } from "astro:transitions";
    import Layout from "../layouts/Layout.astro";
    ---
    
    <Layout title="home">
      <div>
        <h1>Home Page</h1>
        <div class="container">
          <img
            src="./image.png"
            alt=""
            transition:animate={slide({ duration: "1s" })}
          />
        </div>
    
        <div class="button">
          <a href="/about">Go to About Page</a>
        </div>
      </div>
    </Layout>
    

    Creating custom animations

    For more extensive customization, you can define your own animations for use with transition:animate. Astro allows you to specify both the forward and backward behavior, as well as animations for new and old pages. Utilize the TransitionAnimationand TransitionAnimation interfaces for this purpose.

    Advantages of Named Transitions in Astro JS

    Granular Control

    Unlike generic transitions, named transitions enable developers to exercise granular control over the animation of individual elements on different routes. This level of specificity allows for a more nuanced and context-aware approach to visual storytelling within the application.

    Enhanced Aesthetics and Branding

    Named transitions contribute to the overall aesthetics of the application, creating a cohesive and branded feel. By aligning transitions with the visual identity of the application, developers can enhance the user’s connection with the brand.

    Improved User Guidance

    Assigning meaningful names to transitions helps users navigate the application intuitively. The transitions serve as visual cues, providing a guided journey through different sections of the application, thereby reducing cognitive load.

    Conclusion

    Astro JS’s View Transitions API, incorporating both default and named transitions, opens up new possibilities for developers seeking to create dynamic and visually captivating SPAs. Whether leveraging the default fade-in, implementing custom animations, or applying named transitions, Astro JS offers a flexible and efficient solution for achieving seamless transitions. By combining functionality and aesthetics, developers can create a compelling user experience that sets their applications apart in the realm of web development.

    Leave a Reply

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

    David Herbert
    Writen by:
    David is a front-end developer by day and a technical writer by night, who enjoys breaking down complex topics into comprehensible bits digestible to even 5-year-olds.
    Avatar
    Reviewed by:
    I picked up most of my soft/hardware troubleshooting skills in the US Army. A decade of Java development drove me to operations, scaling infrastructure to cope with the thundering herd. Engineering coach and CTO of Teleclinic.