View Transitions Router API Reference
Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.
Hinzugefügt in:
astro@3.0.0
These modules provide functions to control and interact with the View Transitions API and client-side router.
This API is compatible with the <ClientRouter /> included in astro:transitions, but can’t be used with native browser MPA routing.
For features and usage examples, see our View Transitions guide.
Imports from astro:transitions
Section titled “Imports from astro:transitions”import { ClientRouter, createAnimationScope, fade, slide,} from 'astro:transitions';<ClientRouter />
Section titled “<ClientRouter />”
Hinzugefügt in:
astro@5.0.0
Opt in to using view transitions on individual pages by importing and adding the <ClientRouter /> routing component to <head> on every desired page.
---import { ClientRouter } from 'astro:transitions';---<html lang="en"> <head> <title>My Homepage</title> <ClientRouter /> </head> <body> <h1>Welcome to my website!</h1> </body></html>See more about how to control the router and add transition directives to page elements and components.
The <ClientRouter /> component accepts the following props:
fallback
Type: Fallback
Default: animate
Defines the fallback strategy to use for browsers that do not support the View Transitions API.
Type: (opts: { duration?: string | number }) => TransitionDirectionalAnimations
astro@3.0.0
Utility function to support customizing the duration of the built-in fade animation.
---import { fade } from 'astro:transitions';---
<!-- Fade transition with the default duration --><div transition:animate="fade" />
<!-- Fade transition with a duration of 400 milliseconds --><div transition:animate={fade({ duration: '0.4s' })} />Type: (opts: { duration?: string | number }) => TransitionDirectionalAnimations
astro@3.0.0
Utility function to support customizing the duration of the built-in slide animation.
---import { slide } from 'astro:transitions';---
<!-- Slide transition with the default duration --><div transition:animate="slide" />
<!-- Slide transition with a duration of 400 milliseconds --><div transition:animate={slide({ duration: '0.4s' })} />createAnimationScope()
Section titled “createAnimationScope()”Type: (transitionName: string, animations: Record<string,TransitionAnimationPair>) => { scope: string; styles: string; }
astro@3.6.0
Defines custom animations with fine-grained control over navigation directions. This takes a transition name and an object to configure animation pairs (e.g., left/right). This low-level API only generates the scope and styles. You are still responsible for defining CSS keyframes and associating the appropriate direction with an event listener tied to the astro:before-preparation event.
This can be useful when you need custom directional animations like an interface allowing the user to navigate between north, south, east, and west.
The following example creates a custom animation for a top-to-bottom navigable gallery, associates the direction in an event listener, and defines the CSS animations:
---import { createAnimationScope } from "astro:transitions";
const { scope, styles } = createAnimationScope("gallery", { north: { new: { name: "slideFromTop" }, old: { name: "slideFromBottom" }, }, south: { new: { name: "slideFromBottom" }, old: { name: "slideFromTop" }, },});---
<main data-astro-transition-scope={scope}> <Fragment set:html={styles} /> <a href="/next" data-direction="north">Go North</a> <a href="/prev" data-direction="south">Go South</a></main>
<script> document.addEventListener("astro:before-preparation", (event) => { if (event.sourceElement instanceof HTMLAnchorElement) { event.direction = event.sourceElement.dataset.direction ?? "south"; } });</script>
<style> @keyframes slideFromTop { from { transform: translateY(-100%); } to { transform: translateY(0); } }
@keyframes slideFromBottom { from { transform: translateY(100%); } to { transform: translateY(0); } }</style>Imports from astro:transitions/client
Section titled “Imports from astro:transitions/client”import { getFallback, isTransitionBeforePreparationEvent, isTransitionBeforeSwapEvent, navigate, supportsViewTransitions, swapFunctions, transitionEnabledOnThisPage, TRANSITION_AFTER_PREPARATION, TRANSITION_AFTER_SWAP, TRANSITION_BEFORE_PREPARATION, TRANSITION_BEFORE_SWAP, TRANSITION_PAGE_LOAD,} from 'astro:transitions/client';navigate()
Section titled “navigate()”Type: (href: string, options?: Options) => void
astro@3.2.0
Executes a navigation to the given href using the View Transitions API.
This function signature is based on the navigate function from the browser Navigation API. Although based on the Navigation API, this function is implemented on top of the History API to allow for navigation without reloading the page.
history option
Section titled “history option”Type: 'auto' | 'push' | 'replace'
Default: 'auto'
astro@3.2.0
Defines how this navigation should be added to the browser history.
'push': the router will usehistory.pushStateto create a new entry in the browser history.'replace': the router will usehistory.replaceStateto update the URL without adding a new entry into navigation.'auto'(default): the router will attempthistory.pushState, but if the URL cannot be transitioned to, the current URL will remain with no changes to the browser history.
This option follows the history option from the browser Navigation API but simplified for the cases that can happen on an Astro project.
formData option
Section titled “formData option”Type: FormData
astro@3.5.0
When provided, the requests to the navigation target page will be sent as a POST request with the FormData object as the content.
Submitting an HTML form with view transitions enabled will use this method instead of the default navigation with page reload. Calling this method allows triggering the same behavior programmatically.
info option
Section titled “info option”Type: any
astro@3.6.0
Arbitrary data to be included in the astro:before-preparation and astro:before-swap events caused by this navigation.
This option mimics the info option from the browser Navigation API.
state option
Section titled “state option”Type: any
astro@3.6.0
Arbitrary data to be associated with the NavigationHistoryEntry object created by this navigation. This data can then be retrieved using the history.getState function from the History API.
This option mimics the state option from the browser Navigation API.
sourceElement option
Section titled “sourceElement option”Type: Element
astro@3.6.0
The element that triggered this navigation, if any. This element will be available in the following events:
supportsViewTransitions
Section titled “supportsViewTransitions”Type: boolean
astro@3.2.0
Whether or not view transitions are supported and enabled in the current browser.
transitionEnabledOnThisPage()
Section titled “transitionEnabledOnThisPage()”Type: () => boolean
astro@3.2.0
Whether or not the current page has view transitions enabled for client-side navigation. This can be used to make components that behave differently when they are used on pages with view transitions.
getFallback()
Section titled “getFallback()”Type: () => Fallback
astro@3.6.0
Returns the fallback strategy to use in browsers that do not support view transitions. This returns animate by default when the strategy has not been overridden.
swapFunctions
Section titled “swapFunctions”Type: object
astro@4.15.0
An object containing the utility functions used to build Astro’s default swap function. These can be useful when building a custom swap function.
swapFunctions provides the following methods:
deselectScripts()
Section titled “deselectScripts()”Type: (newDocument: Document) => void
Marks scripts in the new document that should not be executed. Those scripts are already in the current document and are not flagged for re-execution using data-astro-rerun.
swapRootAttributes()
Section titled “swapRootAttributes()”Type: (newDocument: Document) => void
Swaps the attributes between the document roots, like the lang attribute. This also includes Astro-injected internal attributes like data-astro-transition, which makes the transition direction available to Astro-generated CSS rules.
When making a custom swap function, it is important to call this function so as not to break the view transition’s animations.
swapHeadElements()
Section titled “swapHeadElements()”Type: (newDocument: Document) => void
Removes every element from the current document’s <head> that is not persisted to the new document. Then appends all new elements from the new document’s <head> to the current document’s <head>.
saveFocus()
Section titled “saveFocus()”Type: () => () => void
Stores the element in focus on the current page and returns a function that when called, if the focused element was persisted, returns the focus to it.
swapBodyElement()
Section titled “swapBodyElement()”Type: (newBody: Element, oldBody: Element) => void
Replaces the old body with the new body. Then, goes through every element in the old body that should be persisted and have a matching element in the new body and swaps the old element back in place.
isTransitionBeforePreparationEvent
Section titled “isTransitionBeforePreparationEvent”Type: (value: any) => boolean
astro@3.6.0
Determines whether the given value matches a TransitionBeforePreparationEvent. This can be useful when you need to narrow the type of an event in an event listener.
------
<script> import { isTransitionBeforePreparationEvent, TRANSITION_BEFORE_PREPARATION, } from "astro:transitions/client";
function listener(event: Event) { const setting = isTransitionBeforePreparationEvent(event) ? 1 : 2; /* do something with setting */ }
document.addEventListener(TRANSITION_BEFORE_PREPARATION, listener);</script>isTransitionBeforeSwapEvent
Section titled “isTransitionBeforeSwapEvent”Type: (value: any) => boolean
astro@3.6.0
Determines whether the given value matches a TransitionBeforeSwapEvent. This can be useful when you need to narrow the type of an event in an event listener.
------
<script> import { isTransitionBeforeSwapEvent, TRANSITION_BEFORE_SWAP, } from "astro:transitions/client";
function listener(event: Event) { const setting = isTransitionBeforeSwapEvent(event) ? 1 : 2; /* do something with setting */ }
document.addEventListener(TRANSITION_BEFORE_SWAP, listener);</script>TRANSITION_BEFORE_PREPARATION
Section titled “TRANSITION_BEFORE_PREPARATION”Type: 'astro:before-preparation'
astro@3.6.0
A constant to avoid writing the astro:before-preparation event name in plain text when you define an event.
------
<script> import { TRANSITION_BEFORE_PREPARATION } from "astro:transitions/client";
document.addEventListener(TRANSITION_BEFORE_PREPARATION, () => { /* the listener logic */ });</script>TRANSITION_AFTER_PREPARATION
Section titled “TRANSITION_AFTER_PREPARATION”Type: 'astro:after-preparation'
astro@3.6.0
A constant to avoid writing the astro:after-preparation event name in plain text when you define an event.
------
<script> import { TRANSITION_AFTER_PREPARATION } from "astro:transitions/client";
document.addEventListener(TRANSITION_AFTER_PREPARATION, () => { /* the listener logic */ });</script>TRANSITION_BEFORE_SWAP
Section titled “TRANSITION_BEFORE_SWAP”Type: 'astro:before-swap'
astro@3.6.0
A constant to avoid writing the astro:before-swap event name in plain text when you define an event.
------
<script> import { TRANSITION_BEFORE_SWAP } from "astro:transitions/client";
document.addEventListener(TRANSITION_BEFORE_SWAP, () => { /* the listener logic */ });</script>TRANSITION_AFTER_SWAP
Section titled “TRANSITION_AFTER_SWAP”Type: 'astro:after-swap'
astro@3.6.0
A constant to avoid writing the astro:after-swap event name in plain text when you define an event.
------
<script> import { TRANSITION_AFTER_SWAP } from "astro:transitions/client";
document.addEventListener(TRANSITION_AFTER_SWAP, () => { /* the listener logic */ });</script>TRANSITION_PAGE_LOAD
Section titled “TRANSITION_PAGE_LOAD”Type: 'astro:page-load'
astro@3.6.0
A constant to avoid writing the astro:page-load event name in plain text when you define an event.
------
<script> import { TRANSITION_PAGE_LOAD } from "astro:transitions/client";
document.addEventListener(TRANSITION_PAGE_LOAD, () => { /* the listener logic */ });</script>astro:transitions/client types
Section titled “astro:transitions/client types”import type { Direction, Fallback, NavigationTypeString, Options, TransitionBeforePreparationEvent, TransitionBeforeSwapEvent,} from 'astro:transitions/client';Direction
Section titled “Direction”Type: 'forward' | 'back'
astro@3.2.0
A union of animation directions:
forward: navigating to the next page in the history or to a new page.back: navigating to the previous page in the history.
Fallback
Section titled “Fallback”Type: 'none' | 'animate' | 'swap'
astro@3.2.0
A union of fallback strategies to use in browsers that do not support view transitions:
animate: Astro will simulate view transitions using custom attributes before updating page content.swap: Astro will not attempt to animate the page. Instead, the old page will be immediately replaced by the new one.none: Astro will not do any animated page transitions at all. Instead, you will get full page navigation in non-supporting browsers.
ClientRouter.
NavigationTypeString
Section titled “NavigationTypeString”Type: 'push' | 'replace' | 'traverse'
astro@3.6.0
A union of supported history navigation events.
TransitionBeforePreparationEvent
Section titled “TransitionBeforePreparationEvent”Type: Event
astro@3.6.0
Represents an astro:before-preparation event. This can be useful to type the event received by a listener:
------
<script> import { TRANSITION_BEFORE_PREPARATION, type TransitionBeforePreparationEvent } from "astro:transitions/client";
function listener(event: TransitionBeforePreparationEvent) { /* do something */ }
document.addEventListener(TRANSITION_BEFORE_PREPARATION, listener);</script>TransitionBeforeSwapEvent
Section titled “TransitionBeforeSwapEvent”Type: Event
astro@3.6.0
Represents an astro:before-swap event. This can be useful to type the event received by a listener:
------
<script> import { TRANSITION_BEFORE_SWAP, type TransitionBeforeSwapEvent } from "astro:transitions/client";
function listener(event: TransitionBeforeSwapEvent) { /* do something */ }
document.addEventListener(TRANSITION_BEFORE_SWAP, listener);</script>Lifecycle events
Section titled “Lifecycle events”astro:before-preparation event
Section titled “astro:before-preparation event”Type: TransitionBeforePreparationEvent
astro@3.6.0
An event dispatched at the beginning of a navigation using the View Transitions router. This event happens before any request is made and any browser state is changed.
This event has the attributes:
astro:after-preparation event
Section titled “astro:after-preparation event”Type: Event
astro@3.6.0
An event dispatched after the next page in a navigation using View Transitions router is loaded.
This event has no attributes.
astro:before-swap event
Section titled “astro:before-swap event”Type: TransitionBeforeSwapEvent
astro@3.6.0
An event dispatched after the next page is parsed, prepared, and linked into a document in preparation for the transition but before any content is swapped between the documents.
This event can’t be canceled. Calling preventDefault() is a no-op.
This event has the attributes:
astro:after-swap event
Section titled “astro:after-swap event”Type: Event
An event dispatched after the contents of the page have been swapped but before the view transition ends.
The history entry and scroll position have already been updated when this event is triggered.
astro:page-load event
Section titled “astro:page-load event”Type: Event
An event dispatched after a page completes loading, whether from a navigation using view transitions or native to the browser.
When view transitions is enabled on the page, code that would normally execute on DOMContentLoaded should be changed to execute on this event.
Lifecycle events attributes
Section titled “Lifecycle events attributes”
Hinzugefügt in:
astro@3.6.0
The following attributes are common to both the astro:before-preparation and astro:before-swap events, except for some that are only available with one or the other.
Type: any
Arbitrary data defined during navigation.
This is the literal value passed on the info option of the navigate() function.
sourceElement
Section titled “sourceElement”Type: Element | undefined
The element that triggered the navigation. This can be, for example, an <a> element that was clicked.
When using the navigate() function, this will be the element specified in the call.
newDocument
Section titled “newDocument”Type: Document
The document for the next page in the navigation. The contents of this document will be swapped in place of the contents of the current document.
navigationType
Section titled “navigationType”Type: NavigationTypeString
Which kind of history navigation is happening.
push: a newNavigationHistoryEntryis being created for the new page.replace: the currentNavigationHistoryEntryis being replaced with an entry for the new page.traverse: noNavigationHistoryEntryis created. The position in the history is changing. The direction of the traversal is given on thedirectionattribute.
direction
Section titled “direction”Type: string
The direction of the transition. This can be a predefined Direction or anything else some other listener might have set.
In the astro:before-preparation event, the value is writable and accepts any string. In the astro:before-swap event, the value is readonly.
Type: URL
The URL of the page initiating the navigation.
Type: URL
The URL of the page being navigated to. This property can be modified, the value at the end of the lifecycle will be used in the NavigationHistoryEntry for the next page.
formData
Section titled “formData”Type: FormData | undefined
Available in: astro:before-preparation event
When set, a POST request will be sent to the to URL with the given FormData object as the content instead of the normal GET request.
When submitting an HTML form with view transitions enabled, this field is automatically set to the data in the form. When using the navigate() function, this value is the same as given in the options.
loader()
Section titled “loader()”Type: () => Promise<void>
Available in: astro:before-preparation event
Implementation of the following phase in the navigation (loading the next page). This implementation can be overridden to add extra behavior.
viewTransition
Section titled “viewTransition”Type: ViewTransition
Available in: astro:before-swap event
The view transition object used in this navigation. On browsers that do not support the View Transitions API, this is an object implementing the same API for convenience but without the DOM integration.
swap()
Section titled “swap()”Type: () => void
Available in: astro:before-swap event
Calls the default document swap logic. By default, this implementation will call the following functions in order: