Diorama

Made for a big screen.

This site is one 3D scene, built for a computer: a wide window and a mouse. Open dioramajs.dev on a desktop or a laptop to see it.This site is one 3D scene, built for a wide window. Make this one wider, or open dioramajs.dev on a larger screen.

GitHub

DioramaDocs

Page transitions with routers

Pair elements across pages with data-dio-key and wire transition() into Astro, Next.js, Nuxt, Barba, Swup or your own history code.

View as Markdown
On this page

A page transition keeps the canvas alive while a router swaps the page in place, and flies every keyed element to its partner on the new page. This guide shows how pairs are found, what transition() adds over the default, and the recipe for each router.

Pair elements with a key

Give the element on the old page and the element on the new page the same data-dio-key. The source needs a drawn copy, so it carries at least one effect; the target may be any element.

work.html
<a href="/work/aurora">
<img
src="/img/aurora-thumb.avif"
data-dio="image"
data-dio-key="aurora"
/>
</a>
work/aurora.html
<img
src="/img/aurora-cover.avif"
data-dio="image ripple"
data-dio-key="aurora"
/>

Diorama looks for the target among elements that came in with the swap and takes the first one in document order. Two new elements with one key fly to the first, and development builds warn once with TRANSITION_KEY. Keys compare exactly: aurora and Aurora are different keys.

  • Dawn
  • Dusk
  • Lanterns

Live preview needs WebGPU or WebGL 2. Two small pages in a box, a grid of three thumbnails and a cover per work: a click swaps the page inside transition() and the thumbnail flies into its cover.

This example failed to draw.

<main class="box">
<ul class="grid">
<li>
<a href="#dawn">
<img
src="/media/prints/dawn.jpg"
width="150"
height="150"
data-dio="image"
data-dio-key="dawn"
/>
</a>
</li>
<li>
<a href="#dusk">
<img
src="/media/prints/dusk.jpg"
width="150"
height="150"
data-dio="image"
data-dio-key="dusk"
/>
</a>
</li>
<li>
<a href="#lanterns">
<img
src="/media/prints/lanterns.jpg"
width="150"
height="150"
data-dio="image"
data-dio-key="lanterns"
/>
</a>
</li>
</ul>
</main>
<template id="work">
<ul class="grid">
<li>
<a href="#dawn">
<img
src="/media/prints/dawn.jpg"
width="150"
height="150"
data-dio="image"
data-dio-key="dawn"
/>
</a>
</li>
<li>
<a href="#dusk">
<img
src="/media/prints/dusk.jpg"
width="150"
height="150"
data-dio="image"
data-dio-key="dusk"
/>
</a>
</li>
<li>
<a href="#lanterns">
<img
src="/media/prints/lanterns.jpg"
width="150"
height="150"
data-dio="image"
data-dio-key="lanterns"
/>
</a>
</li>
</ul>
</template>
<template id="dawn">
<figure>
<img
src="/media/prints/dawn.jpg"
width="640"
height="360"
data-dio="image ripple"
data-dio-key="dawn"
/>
</figure>
<a href="#work">All work</a>
</template>
<template id="dusk">
<figure>
<img
src="/media/prints/dusk.jpg"
width="640"
height="360"
data-dio="image ripple"
data-dio-key="dusk"
/>
</figure>
<a href="#work">All work</a>
</template>
<template id="lanterns">
<figure>
<img
src="/media/prints/lanterns.jpg"
width="640"
height="360"
data-dio="image ripple"
data-dio-key="lanterns"
/>
</figure>
<a href="#work">All work</a>
</template>
import { transition } from '@dioramajs/diorama'
import { app } from '../../docs/diorama.ts'
// The swap of the plain history recipe below, without fetch and history: pages are templates.
export default (example: HTMLElement) => {
const box = example.querySelector('.box')
if (!box) return
const onClick = (event: Event) => {
const link =
event.target instanceof Element ? event.target.closest('a') : null
const page = link && example.querySelector(`template${link.hash}`)
if (!(page instanceof HTMLTemplateElement)) return
event.preventDefault()
transition(app, () =>
box.replaceChildren(page.content.cloneNode(true)),
)
}
box.addEventListener('click', onClick)
return () => box.removeEventListener('click', onClick)
}

A target without effects, such as <img data-dio-key="aurora"> with no data-dio, still receives the flight: the flying copy lands on it and fades into its DOM. A source without effects has no copy to fly. To let every keyed image fly, attach image to them once.

import {
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
} from '@dioramajs/diorama'
const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
()
const app: App
app
.
Services.attach: Attach
<"image">(
target: Target,
name: "image",
params?: Partial<ParamsOf<Record<never, never>>> | undefined,
options?: AttachOptions
) => EffectHandle<Record<never, never>> (+1 overload)
attach
(
'img[data-dio-key]:not([data-dio]), video[data-dio-key]:not([data-dio])',
'image',
)

Keys from view-transition-name

Inside transition(), an element without data-dio-key is keyed by its computed view-transition-name. Astro writes it for transition:name, so those elements pair without new markup. The values none, auto and match-element are not keys. Without transition(), only data-dio-key pairs: the style of a removed element can no longer be read.

Fly without code

Transitions are on by default in start(). When a router removes a drawn keyed element and inserts its partner in the same task, the pair flies. Astro ClientRouter, Turbo Drive, the Next.js App Router, Vue without mode="out-in" and SvelteKit all work this way.

When the pathname changes but the partner is not there yet (loading.tsx, Suspense, streaming), the copy waits invisibly for up to grace seconds, 1 by default, and flies when the partner arrives. A change of ?query or #hash alone is not a navigation: cards removed by a filter leave with their DOM. A copy that was off screen in the last frame does not fly, so it never enters from beyond the viewport edge.

While a copy flies, the DOM of its target is hidden with data-dio-state="entering". Hold back a caption until the landing with the same attribute.

figure:has([data-dio-state="entering"]) figcaption {
opacity: 0;
}

Wrap the swap in transition()

transition(app, swap, options) gives you an exact snapshot, the right URL for the new page and control over timing. Call it with a function that changes the DOM.

const
const running: Transition
running
=
function transition(
app: { readonly transition?: TransitionApi | undefined; },
swap: Swap,
options?: TransitionOptions
): Transition

Calls app.transition if the plugin is running, otherwise runs swap once and returns a settled 'skipped' transition. Safe for routers that navigate before app.start() resolves.

transition
(
const app: App
app
, () => {
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
ParentNode.querySelector<"main">(selectors: "main"): HTMLElement
| null (+4 overloads)

Returns the first element that is a descendant of node that matches selectors.

MDN Reference

querySelector
('main')
?.
ChildNode.replaceWith(
...nodes: (Node | string)[]
): void

Replaces node with nodes, while replacing strings in nodes with equivalent Text nodes.

Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated.

MDN Reference

replaceWith
(
const next: Document
next
.
ParentNode.querySelector<"main">(selectors: "main"): HTMLElement
| null (+4 overloads)

Returns the first element that is a descendant of node that matches selectors.

MDN Reference

querySelector
('main') ?? '')
})
const
const result: TransitionResult
result
= await
const running: Transition
running
var console: Console
console
.
Console.log(...data: any[]): void

The console.log() static method outputs a message to the console.

MDN Reference

log
(
const result: TransitionResult
result
.
TransitionResult.status:
| "done"
| "superseded"
| "aborted"
| "failed"
| "skipped"

How it ended. superseded means a newer transition took over.

status
,
const result: TransitionResult
result
.
TransitionResult.flights: number

Number of flights that landed.

flights
)

It takes the drawn keyed copies in view, calls swap once and synchronously, then flies each copy to its partner. The rules that make it safe inside any router:

  • swap always runs, even when the app has not started yet, in server rendering or with an aborted signal. Without a running app the result is skipped.
  • A synchronous throw from swap is rethrown to the router. A swap may return a promise; the transition waits for it at most timeout seconds, 10 by default.
  • await running resolves with { status, flights } and never rejects. The status is done, superseded, aborted, failed or skipped.
  • running.swapped settles with the swap, so a router hook can wait for it.

Use the free function in router code rather than app.transition(). The service appears on the app only once it runs, and routers may navigate before that.

Tune the flight

Defaults apply to every transition; pass them to start(). The same fields work for one call in the options of transition().

import {
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
} from '@dioramajs/diorama'
export const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
({
StartOptions.transitions?:
| boolean
| (
Partial<TransitionsOptions>
& { readonly cover?: CoverName | CoverOptions; }
)
| undefined

Page transitions by data-dio-key. On by default, false turns them off. cover adds a GL cover the pages change behind: { cover: 'ink' } or { cover: { name: 'curtain', color } }.

transitions
: {
duration?: number | undefined

Seconds. Default 0.8.

duration
: 0.9, // seconds, default 0.8
stagger?: number | undefined

Seconds between flight starts, in document order of the targets. Default 0.

stagger
: 0.04, // between flights, in document order of the targets
crossfade?: number | undefined

Seconds a landed copy fades over the target's own copy or DOM. Default 0.25.

crossfade
: 0.25, // fade over the target after landing, when needed
wait?: number | undefined

Seconds a landed copy waits for the target's copy before giving way to the DOM. Default 2.

wait
: 2, // seconds a landed copy waits for its target's picture
grace?: number | undefined

Seconds an unpaired keyed copy waits, invisible, for a late partner. Default 1.

grace
: 1, // seconds a copy waits for a late partner
},
})

The default ease is cubic in-out. Any function from 0 to 1 works, GSAP eases included: ease: gsap.parseEase('expo.inOut'). sources: 'follow' makes taken copies track their elements while the router animates the old page out; the default 'hold' keeps them where the user saw them. auto: false turns off pairing without transition(), and transitions: false turns transitions off.

Leave and enter

Copies without a partner leave with their DOM, and new copies appear with theirs. Set leave or enter above 0 to give them time on the canvas: removed copies outlive their elements while u.presence goes from 1 to 0, and new copies in view go from 0 to 1.

function transition(
app: { readonly transition?: TransitionApi | undefined; },
swap: Swap,
options?: TransitionOptions
): Transition

Calls app.transition if the plugin is running, otherwise runs swap once and returns a settled 'skipped' transition. Safe for routers that navigate before app.start() resolves.

transition
(
const app: App
app
,
function swap(): void
swap
, {
leave?: number | undefined

Seconds unpaired copies outlive their removed elements, as u.presence goes from 1 to 0. Default 0, or 0.25 inside a browser view transition. Under reduced motion the option is ignored, the default applies and the copy's opacity fades instead.

leave
: 0.3,
enter?: number | undefined

Seconds new copies in view take to appear, as u.presence goes from 0 to 1. Their DOM waits at most 0.5 s. Default 0, or 0.25 inside a browser view transition. Under reduced motion the option is ignored, the default applies and the copy's opacity fades instead.

enter
: 0.5 })

By default an effect shows presence through opacity: the copy’s alpha is multiplied by u.presence. An effect that declares presence: 'custom' reads u.presence itself, for a dissolve or scattering particles.

For your own choreography pass animate. It receives the transition when the flights start; its result is awaited, so a GSAP timeline works. Writes to progress, opacity and presence request a frame.

transition(app, swap, {
// Non-zero leave and enter fill `leaving`
// and `entering`; the timeline times them.
leave: 0.4,
enter: 0.6,
animate: ({ flights, leaving, entering }) =>
gsap
.timeline()
.to(leaving, { presence: 0, duration: 0.4, stagger: 0.02 }, 0)
.to(
flights,
{
progress: 1,
duration: 1.1,
ease: 'expo.inOut',
stagger: 0.06,
},
0.1,
)
.to(entering, { presence: 1, duration: 0.6, stagger: 0.04 }, 0.7),
})

With animate, leave and enter only set how long the fades take when the transition is cut short.

Interrupted and back navigation

One transition runs per app. A new one, from a second click or Back in the middle of a flight, takes each key’s visible copy from where it is now and flies it to the new target. A copy moving at speed keeps its velocity into the new flight, and a short way back takes a shorter time, so nothing jumps.

  • Back during a flight from the list to a project turns the flying thumbnail around towards its tile.
  • A copy in the air with no partner on the new page fades out where the click caught it.
  • A hidden tab finishes the transition at once: the copies land.
  • running.finish() lands everything now. running.abort() does the same and ends with aborted, as does an aborted signal.

The source box is fixed in viewport pixels, so a router that scrolls to the top inside the swap does not move the flying copy. The target is tracked live, so when the router restores the scroll position on Back, the flight follows its target.

Under reduced motion nothing flies: the old copy fades in place over 0.2 seconds and the new page shows its DOM until its own copies are ready.

Run code per page

app.transition.page is the scope of the current page. Its cleanups run right after the next swap, before effects reconcile the new page, so rules of the old page never mount on elements of the new one. Handles from attach() work as cleanups.

function
function enter(url: string): void
enter
(
url: string
url
: string): void {
if (!new
var URL: new (url: string | URL, base?: string | URL) => URL

The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.

MDN Reference

URL
(
url: string
url
).
URL.pathname: string

The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.

MDN Reference

pathname
.
String.startsWith(
searchString: string,
position?: number
): boolean

Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at position. Otherwise returns false.

startsWith
('/work')) return
const app: App
app
.
Services.transition: TransitionApi

Page transitions, see TransitionApi.

transition
.
TransitionApi.page: PageScope

The current page. Closed right after the next swap.

page
.
PageScope.onDispose(cleanup: Cleanup): Off

Runs when the next page replaces this one. Accepts app.attach handles as is.

onDispose
(
const app: App
app
.
Services.attach: Attach
<"ripple">(
target: Target,
name: "ripple",
params?:
| Partial<
ParamsOf<
{ strength: number; frequency: number; speed: number; }
>
>
| undefined,
options?: AttachOptions
) => EffectHandle<
{ strength: number; frequency: number; speed: number; }
> (+1 overload)
attach
('.gallery img', 'ripple'))
}
const app: App
app
.
AppCore<Services & Empty, string>.on<"page:enter">(
event: "page:enter",
listener: Listener<"page:enter">
): Off

Listens to an event. Returns Off.

on
('page:enter', ({
url: string
url
}) =>
function enter(url: string): void
enter
(
url: string
url
))
// The first page gets no page:enter.
void
function ready(app?: App): Promise<App>

Resolves with the app once it runs: the page's app of start() by default, waiting for the call if it has not happened yet. Rejects if the app fails or is destroyed first.

const app = await ready()
app.effects.get(el, 'ripple')

ready
(
const app: App
app
).
Promise<App>.then<void, never>(
onfulfilled?:
| ((value: App) => void | PromiseLike<void>)
| null
| undefined,
onrejected?:
| ((reason: any) => PromiseLike<never>)
| null
| undefined
): Promise<void>

Attaches callbacks for the resolution and/or rejection of the Promise.

@param ― onfulfilled The callback to execute when the Promise is resolved.

@param ― onrejected The callback to execute when the Promise is rejected.

@returns ― A Promise for the completion of which ever callback is executed.

then
(() =>
function enter(url: string): void
enter
(
var location: Location

The read-only location property of the Window interface returns a Location object with information about the current location of the document.

MDN Reference

location
.
Location.href: string

The href property of the Location interface is a stringifier that returns a string containing the whole URL, and allows the href to be updated.

MDN Reference

href
))

page:leave comes before the old scope closes, page:enter after the new page is reconciled, and transition:end with the result. Without a recipe the scope turns when DOM is removed under a new pathname, not on popstate, because routers change the URL before the DOM.

Recipes

Each recipe calls transition() at the moment the router replaces the page. The app comes from the module that calls start(); a second start() returns the same app.

Astro ClientRouter

Without code the flights already work. The recipe takes the snapshot before Astro swaps, gives the page scope the new URL (Astro changes history only after the swap returns) and passes the browser view transition along.

src/diorama.ts
import {
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
,
function transition(
app: { readonly transition?: TransitionApi | undefined; },
swap: Swap,
options?: TransitionOptions
): Transition

Calls app.transition if the plugin is running, otherwise runs swap once and returns a settled 'skipped' transition. Safe for routers that navigate before app.start() resolves.

transition
} from '@dioramajs/diorama'
export const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
()
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
Document.addEventListener<"astro:before-swap">(
type: "astro:before-swap",
listener: (this: Document, ev: BeforeSwap) => any,
options?: boolean | AddEventListenerOptions
): void (+1 overload)

The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.

MDN Reference

addEventListener
('astro:before-swap', (
event: BeforeSwap
event
) => {
const
const swap: () => void
swap
=
event: BeforeSwap
event
.
BeforeSwap.swap: () => void
swap
event: BeforeSwap
event
.
BeforeSwap.swap: () => void
swap
= () =>
void
function transition(
app: { readonly transition?: TransitionApi | undefined; },
swap: Swap,
options?: TransitionOptions
): Transition

Calls app.transition if the plugin is running, otherwise runs swap once and returns a settled 'skipped' transition. Safe for routers that navigate before app.start() resolves.

transition
(
const app: App
app
,
const swap: () => void
swap
, {
TransitionOptions.url?: string | URL | undefined

URL of the new page for the page scope and events. Default location.href after the swap.

url
:
event: BeforeSwap
event
.
BeforeSwap.to: URL
to
,
TransitionOptions.viewTransition?:
| ViewTransition
| null
| undefined

The browser view transition the swap runs in, or null for none. When omitted, or when it is a router's look-alike object, it is detected with :active-view-transition.

viewTransition
:
event: BeforeSwap
event
.
BeforeSwap.viewTransition: ViewTransition
viewTransition
,
})
})
// Decode the keyed covers of the next
// page while the swap and the flight run.
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
Document.addEventListener<"astro:before-preparation">(
type: "astro:before-preparation",
listener: (this: Document, ev: BeforePreparation) => any,
options?: boolean | AddEventListenerOptions
): void (+1 overload)

The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.

MDN Reference

addEventListener
('astro:before-preparation', (
event: BeforePreparation
event
) => {
const
const load: () => Promise<void>
load
=
event: BeforePreparation
event
.
BeforePreparation.loader: () => Promise<void>
loader
event: BeforePreparation
event
.
BeforePreparation.loader: () => Promise<void>
loader
= async () => {
await
const load: () => Promise<void>
load
()
// A failed load keeps the current document: nothing to preload.
if (
event: BeforePreparation
event
.
Event.defaultPrevented: boolean

The defaultPrevented read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event.

MDN Reference

defaultPrevented
||
event: BeforePreparation
event
.
BeforePreparation.newDocument: Document
newDocument
===
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
) return
void
const app: App
app
.
Services.assets: AssetsApi

Asset cache and preloading, see AssetsApi.

assets
?.
AssetsApi.preload(
source: PreloadSource,
options?: PreloadOptions
): Preload

Next page's media and models: URLs, a parsed Document (Astro, Swup) or a container (Barba).

preload
(
event: BeforePreparation
event
.
BeforePreparation.newDocument: Document
newDocument
, {
PreloadOptions.base?: string | URL | undefined

Base for relative URLs and srcset, i.e. the next page's URL. Defaults to , then document.baseURI.

base
:
event: BeforePreparation
event
.
BeforePreparation.to: URL
to
})
}
})

Import the module from a <script> in the layout. Astro bundles it and runs it once, so the listeners live across pages.

src/layouts/Layout.astro
<script>
import '../diorama'
</script>

An element with transition:persist is the same node on both pages: its instance survives, and if it moved, its copy flies to the new place. Where Astro swaps without a browser view transition (no API, or the browser’s own back-swipe animation), event.viewTransition holds a stand-in object, and unpaired copies leave with the DOM.

Scroll position on the way back

Back and Forward restore the scroll position. A link opens its page at the top, as in any browser, even a link back to the page the reader has left a moment ago, such as the logo back to the home page. The restoreScroll option of the integration changes that:

astro.config.mjs
import diorama from '@dioramajs/diorama/astro'
export default { integrations: [diorama({ restoreScroll: 'parents' })] }
  • 'parents': a link up the address lands where the reader left that page, like Back: / from any page, /work from /work/aurora. A project opened from the list still starts at the top, where its cover flies in.
  • 'visited': a link to any page seen earlier in the tab lands where the reader left it.
  • 'history', the default: only Back and Forward, as browsers do.

A link with a #hash still goes to its anchor, and a link to the page on screen or a form’s answer opens at the top. Positions live in sessionStorage. The page moves before other astro:after-swap listeners run, so flights land on targets where the page ends up and Lenis goes on from there. Without the integration, call restoreScroll('parents') from @dioramajs/diorama/astro/client in a layout script.

src/diorama.ts
import {
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
} from '@dioramajs/diorama'
import
class Lenis
Lenis
from 'lenis'
const
const lenis: Lenis
lenis
= new
new Lenis(
{
wrapper, content, eventsTarget, smoothWheel, syncTouch,
syncTouchLerp, touchInertiaExponent, duration, easing, lerp,
infinite, orientation, gestureOrientation, touchMultiplier,
wheelMultiplier, autoResize, prevent, virtualScroll,
overscroll, autoRaf, anchors, autoToggle, allowNestedScroll,
__experimental__naiveDimensions, naiveDimensions,
stopInertiaOnNavigate, respectReducedMotion
}?: LenisOptions
): Lenis
Lenis
()
export const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
({
StartOptions.lenis?: LenisLike | undefined

The site's Lenis instance, so smooth scroll lands in the same frame as the canvas.

lenis
})
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
Document.addEventListener<"astro:before-swap">(
type: "astro:before-swap",
listener: (this: Document, ev: BeforeSwap) => any,
options?: boolean | AddEventListenerOptions
): void (+1 overload)

The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.

MDN Reference

addEventListener
('astro:before-swap', () =>
const lenis: Lenis
lenis
.
Lenis.stop(): void

Stop lenis scroll

stop
())
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
Document.addEventListener<"astro:after-swap">(
type: "astro:after-swap",
listener: (this: Document, ev: Event) => any,
options?: boolean | AddEventListenerOptions
): void (+1 overload)

The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.

MDN Reference

addEventListener
('astro:after-swap', () => {
// ClientRouter replaces the <html> attributes, including Lenis classes.
const lenis: Lenis
lenis
.
Lenis.rootElement: HTMLElement

The root element on which lenis is instanced

rootElement
.
Element.classList: DOMTokenList

The read-only classList property of the Element interface contains a live DOMTokenList collection representing the class attribute of the element. This can then be used to manipulate the class list.

MDN Reference

classList
.
DOMTokenList.add(...tokens: string[]): void

The add() method of the DOMTokenList interface adds the given tokens to the list, omitting any that are already present.

MDN Reference

add
(...
const lenis: Lenis
lenis
.
Lenis.className: string

The class name applied to the wrapper element

className
.
String.split(
separator: string | RegExp,
limit?: number
): string[] (+1 overload)

Split a string into substrings using the specified separator and return them as an array.

@param ― separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.

@param ― limit A value used to limit the number of elements returned in the array.

split
(' '))
const lenis: Lenis
lenis
.
Lenis.resize(): void

Force lenis to recalculate the dimensions

resize
()
const lenis: Lenis
lenis
.
Lenis.start(): void

Start lenis scroll after it has been stopped

start
()
})

Next.js

Without code the flights already work: a React commit removes the old page and inserts the new one in one task. With loading.tsx the fallback commits first, the thumbnail waits in the pool and flies when the cover arrives.

For an exact snapshot, or to wait for the commit before your own choreography, wrap navigation in transition(). Commit lives in the root layout, which persists across navigations, and settles a promise when a route with another pathname has committed. The root template.tsx does not work for this: Next.js does not remount it between /work and /work/aurora.

src/app/commit.tsx
'use client'
import { usePathname } from 'next/navigation'
import { useLayoutEffect } from 'react'
let done: (() => void) | undefined
/** Settles when a route with another pathname has committed, or after 3 s. */
export const committed = (): Promise<void> =>
new Promise((resolve) => {
done = resolve
setTimeout(resolve, 3000)
})
/** Rendered once in the root layout. */
export function Commit(): null {
const pathname = usePathname()
useLayoutEffect(() => {
done?.()
done = undefined
}, [pathname])
return null
}
src/app/fly-link.tsx
'use client'
import { start, transition } from '@dioramajs/diorama'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { type ComponentProps, useRef } from 'react'
import { committed } from './commit'
export function FlyLink(props: ComponentProps<typeof Link>) {
const router = useRouter()
const anchor = useRef<HTMLAnchorElement>(null)
return (
<Link
{...props}
ref={anchor}
onNavigate={(event) => {
// The rendered href: a UrlObject keeps
// its query, a relative one is resolved.
const href = anchor.current?.href
if (!href) return
event.preventDefault()
// start() returns the app the root layout already started.
void transition(start(), () => {
const go = props.replace ? router.replace : router.push
go(href, { scroll: props.scroll ?? true })
return committed()
})
}}
/>
)
}

Render <Commit /> in src/app/layout.tsx next to {children} and use <FlyLink> where a flight should start. onNavigate needs Next.js 15.3 or later; on older versions use onClick and skip modified clicks.

Nuxt

Without code <NuxtPage> swaps pages in one render and the flights work. With mode: 'out-in' the old page leaves before the new one enters, so the recipe snapshots in the page transition hooks.

app/plugins/diorama.client.ts
import {
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
,
function transition(
app: { readonly transition?: TransitionApi | undefined; },
swap: Swap,
options?: TransitionOptions
): Transition

Calls app.transition if the plugin is running, otherwise runs swap once and returns a settled 'skipped' transition. Safe for routers that navigate before app.start() resolves.

transition
} from '@dioramajs/diorama'
export default
function defineNuxtPlugin<T>(
setup: (
nuxtApp: { hook(name: "app:error", run: () => void): void; }
) => T
): T
type T = {
provide: {
dioPage: { onBeforeLeave: () => void; onEnter: () => void; };
};
}
defineNuxtPlugin
((
nuxtApp: {
hook(name: "app:error", run: () => void): void;
}
nuxtApp
) => {
const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
()
let
let done: (() => void) | undefined
done
: (() => void) | undefined
const
const finish: () => void
finish
= (): void => {
let done: (() => void) | undefined
done
?.()
let done: (() => void) | undefined
done
=
var undefined
undefined
}
nuxtApp: {
hook(name: "app:error", run: () => void): void;
}
nuxtApp
.
function hook(name: "app:error", run: () => void): void
hook
('app:error',
const finish: () => void
finish
)
return {
provide: {
dioPage: { onBeforeLeave: () => void; onEnter: () => void; };
}
provide
: {
// One-argument hooks: Vue keeps its own
// CSS timing and calls `done` itself.
dioPage: {
onBeforeLeave: () => void;
onEnter: () => void;
}
dioPage
: {
// The old page is still drawn: snapshot
// now, settle once the new one is in.
onBeforeLeave: () => void
onBeforeLeave
: () => {
const finish: () => void
finish
()
void
function transition(
app: { readonly transition?: TransitionApi | undefined; },
swap: Swap,
options?: TransitionOptions
): Transition

Calls app.transition if the plugin is running, otherwise runs swap once and returns a settled 'skipped' transition. Safe for routers that navigate before app.start() resolves.

transition
(
const app: App
app
,
() => new
var Promise: PromiseConstructor
new <void>(
executor: (
resolve: (value: void | PromiseLike<void>) => void,
reject: (reason?: any) => void
) => void
) => Promise<void>

Creates a new Promise.

@param ― executor A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.

Promise
<void>((
resolve: (value: void | PromiseLike<void>) => void
resolve
) => (
let done: (() => void) | undefined
done
=
resolve: (value: void | PromiseLike<void>) => void
resolve
)),
)
},
onEnter: () => void
onEnter
: () =>
const finish: () => void
finish
(),
},
},
}
})
app/app.vue
<template>
<NuxtPage :transition="{ name: 'page', mode: 'out-in', ...$dioPage }" />
</template>

While the old page fades out, the thumbnails hold where they were; once removed they fly into the new page. The first navigation renders without a page transition, so the hooks do not run. A failed navigation settles the swap through app:error.

Barba

Barba keeps a wrapper and swaps a container inside it. The recipe snapshots in before and settles the swap in after, when the old container is gone.

const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
()
let
let swapped: (() => void) | undefined
swapped
: (() => void) | undefined
const
const settle: () => void
settle
= (): void => {
let swapped: (() => void) | undefined
swapped
?.()
let swapped: (() => void) | undefined
swapped
=
var undefined
undefined
}
const barba: {
hooks: {
before(run: () => void): void;
after(run: () => void): void;
};
init(
options: {
transitions: {
name: string;
leave(data: Data): unknown;
enter(): void;
}[];
}
): void;
}
barba
.
hooks: {
before(run: () => void): void;
after(run: () => void): void;
}
hooks
.
function before(run: () => void): void
before
(() => {
const settle: () => void
settle
()
void
function transition(
app: { readonly transition?: TransitionApi | undefined; },
swap: Swap,
options?: TransitionOptions
): Transition

Calls app.transition if the plugin is running, otherwise runs swap once and returns a settled 'skipped' transition. Safe for routers that navigate before app.start() resolves.

transition
(
const app: App
app
,
() => new
var Promise: PromiseConstructor
new <void>(
executor: (
resolve: (value: void | PromiseLike<void>) => void,
reject: (reason?: any) => void
) => void
) => Promise<void>

Creates a new Promise.

@param ― executor A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.

Promise
<void>((
resolve: (value: void | PromiseLike<void>) => void
resolve
) => (
let swapped: (() => void) | undefined
swapped
=
resolve: (value: void | PromiseLike<void>) => void
resolve
)),
)
})
// The flights start after Barba's own transition, so a click during
// them starts a new navigation instead of Barba's forced reload.
const barba: {
hooks: {
before(run: () => void): void;
after(run: () => void): void;
};
init(
options: {
transitions: {
name: string;
leave(data: Data): unknown;
enter(): void;
}[];
}
): void;
}
barba
.
hooks: {
before(run: () => void): void;
after(run: () => void): void;
}
hooks
.
function after(run: () => void): void
after
(
const settle: () => void
settle
)
const barba: {
hooks: {
before(run: () => void): void;
after(run: () => void): void;
};
init(
options: {
transitions: {
name: string;
leave(data: Data): unknown;
enter(): void;
}[];
}
): void;
}
barba
.
function init(
options: {
transitions: {
name: string;
leave(data: Data): unknown;
enter(): void;
}[];
}
): void
init
({
transitions: {
name: string;
leave(data: Data): unknown;
enter(): void;
}[]
transitions
: [
{
name: string
name
: 'dio',
function leave(data: Data): unknown
leave
: ({
current: {
readonly container: HTMLElement;
}
current
}) =>
current: {
readonly container: HTMLElement;
}
current
.
container: HTMLElement
container
.
Animatable.animate(
keyframes: Keyframe[] | PropertyIndexedKeyframes | null,
options?: number | KeyframeAnimationOptions
): Animation
animate
({
opacity: number[]
opacity
: [1, 0] }, 300).
Animation.finished: Promise<Animation>

The Animation.finished read-only property of the Web Animations API returns a Promise which resolves once the animation has finished playing.

MDN Reference

finished
,
function enter(): void
enter
() {},
},
],
})

With sync: true both containers sit in the document at once. Put them in one grid cell so the new one does not push the old one down.

[data-barba="wrapper"] {
display: grid;
}
[data-barba="container"] {
grid-area: 1 / 1;
}

Swup

Without code Swup replaces the container in place and the flights work, but the snapshot is taken after the out animation, when the old page has already faded. The recipe snapshots before it.

const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
()
let
let done: (() => void) | undefined
done
: (() => void) | undefined
const
const settle: () => void
settle
= (): void => {
let done: (() => void) | undefined
done
?.()
let done: (() => void) | undefined
done
=
var undefined
undefined
}
const swup: {
hooks: {
before(hook: "animation:out:start", run: () => void): void;
on(
hook: "content:replace" | "visit:end",
run: () => void
): void;
on(
hook: "page:load",
run: (
visit: unknown,
args: { page?: { url: string; html: string; }; }
) => void
): void;
};
}
swup
.
hooks: {
before(hook: "animation:out:start", run: () => void): void;
on(
hook: "content:replace" | "visit:end",
run: () => void
): void;
on(
hook: "page:load",
run: (
visit: unknown,
args: { page?: { url: string; html: string; }; }
) => void
): void;
}
hooks
.
function before(
hook: "animation:out:start",
run: () => void
): void
before
('animation:out:start', () => {
const settle: () => void
settle
()
void
function transition(
app: { readonly transition?: TransitionApi | undefined; },
swap: Swap,
options?: TransitionOptions
): Transition

Calls app.transition if the plugin is running, otherwise runs swap once and returns a settled 'skipped' transition. Safe for routers that navigate before app.start() resolves.

transition
(
const app: App
app
,
() => new
var Promise: PromiseConstructor
new <void>(
executor: (
resolve: (value: void | PromiseLike<void>) => void,
reject: (reason?: any) => void
) => void
) => Promise<void>

Creates a new Promise.

@param ― executor A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.

Promise
<void>((
resolve: (value: void | PromiseLike<void>) => void
resolve
) => (
let done: (() => void) | undefined
done
=
resolve: (value: void | PromiseLike<void>) => void
resolve
)),
)
})
const swup: {
hooks: {
before(hook: "animation:out:start", run: () => void): void;
on(
hook: "content:replace" | "visit:end",
run: () => void
): void;
on(
hook: "page:load",
run: (
visit: unknown,
args: { page?: { url: string; html: string; }; }
) => void
): void;
};
}
swup
.
hooks: {
before(hook: "animation:out:start", run: () => void): void;
on(
hook: "content:replace" | "visit:end",
run: () => void
): void;
on(
hook: "page:load",
run: (
visit: unknown,
args: { page?: { url: string; html: string; }; }
) => void
): void;
}
hooks
.
function on(
hook: "content:replace" | "visit:end",
run: () => void
): void (+1 overload)
on
('content:replace',
const settle: () => void
settle
)
const swup: {
hooks: {
before(hook: "animation:out:start", run: () => void): void;
on(
hook: "content:replace" | "visit:end",
run: () => void
): void;
on(
hook: "page:load",
run: (
visit: unknown,
args: { page?: { url: string; html: string; }; }
) => void
): void;
};
}
swup
.
hooks: {
before(hook: "animation:out:start", run: () => void): void;
on(
hook: "content:replace" | "visit:end",
run: () => void
): void;
on(
hook: "page:load",
run: (
visit: unknown,
args: { page?: { url: string; html: string; }; }
) => void
): void;
}
hooks
.
function on(
hook: "content:replace" | "visit:end",
run: () => void
): void (+1 overload)
on
('visit:end',
const settle: () => void
settle
)
// Decode the covers of the fetched page while the swap and the flight run.
const swup: {
hooks: {
before(hook: "animation:out:start", run: () => void): void;
on(
hook: "content:replace" | "visit:end",
run: () => void
): void;
on(
hook: "page:load",
run: (
visit: unknown,
args: { page?: { url: string; html: string; }; }
) => void
): void;
};
}
swup
.
hooks: {
before(hook: "animation:out:start", run: () => void): void;
on(
hook: "content:replace" | "visit:end",
run: () => void
): void;
on(
hook: "page:load",
run: (
visit: unknown,
args: { page?: { url: string; html: string; }; }
) => void
): void;
}
hooks
.
function on(
hook: "page:load",
run: (
visit: unknown,
args: { page?: { url: string; html: string; }; }
) => void
): void (+1 overload)
on
('page:load', (
_visit: unknown
_visit
, {
page: {
url: string;
html: string;
} | undefined
page
}) => {
if (!
page: {
url: string;
html: string;
} | undefined
page
) return
const
const next: Document
next
= new
var DOMParser: new () => DOMParser

The DOMParser interface provides the ability to parse XML or HTML source code from a string into a DOM Document.

MDN Reference

DOMParser
().
DOMParser.parseFromString(
string: string,
type: DOMParserSupportedType
): Document

The parseFromString() method of the DOMParser interface parses an input containing either HTML or XML, returning a Document with the type given in the contentType property.

MDN Reference

parseFromString
(
page: {
url: string;
html: string;
}
page
.
html: string
html
, 'text/html')
void
const app: App
app
.
Services.assets: AssetsApi

Asset cache and preloading, see AssetsApi.

assets
?.
AssetsApi.preload(
source: PreloadSource,
options?: PreloadOptions
): Preload

Next page's media and models: URLs, a parsed Document (Astro, Swup) or a container (Barba).

preload
(
const next: Document
next
, {
PreloadOptions.base?: string | URL | undefined

Base for relative URLs and srcset, i.e. the next page's URL. Defaults to , then document.baseURI.

base
:
page: {
url: string;
html: string;
}
page
.
url: string
url
})
})

Read the HTML from the page argument: Swup fills visit.to.document only after the page:load handlers have run.

Turbo Drive

Turbo replaces <body> in one task, so the flights work without code. Elements with data-turbo-permanent move to the new body as the same node and keep their instances.

Plain history

With your own router, fetch the next page, then swap inside transition(). Handle Back with popstate and restore the scroll position inside the swap.

src/main.ts
import {
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
,
function transition(
app: { readonly transition?: TransitionApi | undefined; },
swap: Swap,
options?: TransitionOptions
): Transition

Calls app.transition if the plugin is running, otherwise runs swap once and returns a settled 'skipped' transition. Safe for routers that navigate before app.start() resolves.

transition
} from '@dioramajs/diorama'
export const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
()
var history: History

The Window.history read-only property returns a reference to the History object, which provides an interface for manipulating the browser session history (pages visited in the tab or frame that the current page is loaded in).

MDN Reference

history
.
History.scrollRestoration: ScrollRestoration

The scrollRestoration property of the History interface allows web applications to explicitly set default scroll restoration behavior on history navigation.

MDN Reference

scrollRestoration
= 'manual'
async function
function go(url: string, back?: boolean): Promise<void>
go
(
url: string
url
: string,
back: boolean
back
= false):
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<void> {
const
const html: string
html
= await (await
function fetch(
input: RequestInfo | URL,
init?: RequestInit
): Promise<Response>
fetch
(
url: string
url
)).
Body.text(): Promise<string>
text
()
const
const next: Document
next
= new
var DOMParser: new () => DOMParser

The DOMParser interface provides the ability to parse XML or HTML source code from a string into a DOM Document.

MDN Reference

DOMParser
().
DOMParser.parseFromString(
string: string,
type: DOMParserSupportedType
): Document

The parseFromString() method of the DOMParser interface parses an input containing either HTML or XML, returning a Document with the type given in the contentType property.

MDN Reference

parseFromString
(
const html: string
html
, 'text/html')
void
const app: App
app
.
Services.assets: AssetsApi

Asset cache and preloading, see AssetsApi.

assets
?.
AssetsApi.preload(
source: PreloadSource,
options?: PreloadOptions
): Preload

Next page's media and models: URLs, a parsed Document (Astro, Swup) or a container (Barba).

preload
(
const next: Document
next
, {
PreloadOptions.base?: string | URL | undefined

Base for relative URLs and srcset, i.e. the next page's URL. Defaults to , then document.baseURI.

base
:
url: string
url
})
await
function transition(
app: { readonly transition?: TransitionApi | undefined; },
swap: Swap,
options?: TransitionOptions
): Transition

Calls app.transition if the plugin is running, otherwise runs swap once and returns a settled 'skipped' transition. Safe for routers that navigate before app.start() resolves.

transition
(
const app: App
app
,
() => {
if (!
back: boolean
back
)
var history: History

The Window.history read-only property returns a reference to the History object, which provides an interface for manipulating the browser session history (pages visited in the tab or frame that the current page is loaded in).

MDN Reference

history
.
History.replaceState(
data: any,
unused: string,
url?: string | URL | null
): void

The replaceState() method of the History interface modifies the current history entry, replacing it with the state object and URL passed in the method parameters. This method is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.

MDN Reference

replaceState
({
y: number
y
:
var scrollY: number

The read-only scrollY property of the Window interface returns the number of pixels by which the document is currently scrolled vertically. This value is subpixel precise in modern browsers, meaning that it isn't necessarily a whole number. You can get the number of pixels the document is scrolled horizontally from the scrollX property.

MDN Reference

scrollY
}, '')
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
ParentNode.querySelector<"main">(selectors: "main"): HTMLElement
| null (+4 overloads)

Returns the first element that is a descendant of node that matches selectors.

MDN Reference

querySelector
('main')
?.
ChildNode.replaceWith(
...nodes: (Node | string)[]
): void

Replaces node with nodes, while replacing strings in nodes with equivalent Text nodes.

Throws a "HierarchyRequestError" DOMException if the constraints of the node tree are violated.

MDN Reference

replaceWith
(
const next: Document
next
.
ParentNode.querySelector<"main">(selectors: "main"): HTMLElement
| null (+4 overloads)

Returns the first element that is a descendant of node that matches selectors.

MDN Reference

querySelector
('main') ?? '')
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
Document.title: string

The document.title property gets or sets the current title of the document. When present, it defaults to the value of the .

MDN Reference

title
=
const next: Document
next
.
Document.title: string

The document.title property gets or sets the current title of the document. When present, it defaults to the value of the .

MDN Reference

title
if (!
back: boolean
back
)
var history: History

The Window.history read-only property returns a reference to the History object, which provides an interface for manipulating the browser session history (pages visited in the tab or frame that the current page is loaded in).

MDN Reference

history
.
History.pushState(
data: any,
unused: string,
url?: string | URL | null
): void

The pushState() method of the History interface adds an entry to the browser's session history stack.

MDN Reference

pushState
({
y: number
y
: 0 }, '',
url: string
url
)
const
const state: {
y?: number;
} | null
state
=
var history: History

The Window.history read-only property returns a reference to the History object, which provides an interface for manipulating the browser session history (pages visited in the tab or frame that the current page is loaded in).

MDN Reference

history
.
History.state: any

The state read-only property of the History interface returns a value representing the state at the top of the history stack. This is a way to look at the state without having to wait for a popstate event.

MDN Reference

state
as {
y?: number | undefined
y
?: number } | null
function scrollTo(x: number, y: number): void (+1 overload)

Window.scrollTo() scrolls to a particular set of coordinates in the document.

MDN Reference

scrollTo
(0,
const state: {
y?: number;
} | null
state
?.
y?: number | undefined
y
?? 0)
},
{
TransitionOptions.url?: string | URL | undefined

URL of the new page for the page scope and events. Default location.href after the swap.

url
},
)
}
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
Document.addEventListener<"click">(
type: "click",
listener: (this: Document, ev: PointerEvent) => any,
options?: boolean | AddEventListenerOptions
): void (+1 overload)

The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.

MDN Reference

addEventListener
('click', (
event: PointerEvent
event
) => {
const
const link: HTMLAnchorElement | null
link
= (
event: PointerEvent
event
.
Event.target: EventTarget | null

The read-only target property of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.

MDN Reference

target
as
interface Element

Element is the most general base class from which all element objects (i.e., objects that represent elements) in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element.

MDN Reference

Element
).
Element.closest<"a">(selector: "a"): HTMLAnchorElement
| null (+3 overloads)

The closest() method of the Element interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.

MDN Reference

closest
('a')
if (
!
const link: HTMLAnchorElement | null
link
||
const link: HTMLAnchorElement
link
.
HTMLHyperlinkElementUtils.origin: string

Returns the hyperlink's URL's origin.

MDN Reference

origin
!==
var location: Location

The read-only location property of the Window interface returns a Location object with information about the current location of the document.

MDN Reference

location
.
Location.origin: string

The origin read-only property of the Location interface returns a string containing the Unicode serialization of the origin of the location's URL.

MDN Reference

origin
||
event: PointerEvent
event
.
MouseEvent.metaKey: boolean

The MouseEvent.metaKey read-only property is a boolean value that indicates whether the meta key was pressed or not when a given mouse event occurs.

MDN Reference

metaKey
||
event: PointerEvent
event
.
MouseEvent.ctrlKey: boolean

The MouseEvent.ctrlKey read-only property is a boolean value that indicates whether the ctrl key was pressed or not when a given mouse event occurs.

MDN Reference

ctrlKey
)
return
event: PointerEvent
event
.
Event.preventDefault(): void

The preventDefault() method of the Event interface tells the user agent that the event is being explicitly handled, so its default action, such as page scrolling, link navigation, or pasting text, should not be taken.

MDN Reference

preventDefault
()
void
function go(url: string, back?: boolean): Promise<void>
go
(
const link: HTMLAnchorElement
link
.
HTMLHyperlinkElementUtils.href: string

Returns the hyperlink's URL.

Can be set, to change the URL.

MDN Reference

href
)
})
function addEventListener<"popstate">(
type: "popstate",
listener: (this: Window, ev: PopStateEvent) => any,
options?: boolean | AddEventListenerOptions
): void (+1 overload)
addEventListener
('popstate', () => void
function go(url: string, back?: boolean): Promise<void>
go
(
var location: Location

The read-only location property of the Window interface returns a Location object with information about the current location of the document.

MDN Reference

location
.
Location.href: string

The href property of the Location interface is a stringifier that returns a string containing the whole URL, and allows the href to be updated.

MDN Reference

href
, true))

Browser view transitions

Astro, Swup’s native mode and experimental.viewTransition in Next.js and Nuxt wrap the swap in document.startViewTransition(). Diorama names the canvas dio-stage-1 so the browser keeps it live instead of fading a still of the old frame over the flight. Inside a view transition unpaired copies leave and new ones appear over 0.25 seconds, together with the browser’s root crossfade.

  • A fixed header over the canvas needs its own view-transition-name. Otherwise the live canvas group draws above it during the transition.
  • With the canvas behind the page (canvas: 'behind') the canvas is not named. Turn off the root crossfade instead, so the DOM changes at once and the flight stays clean.
::view-transition-old(root),
::view-transition-new(root) {
animation: none;
}
  • For a view transition of your own, such as a theme switch with a circular reveal, remove the name for its duration: html.theme-switch canvas[data-dio-vt] { view-transition-name: none }.

Cross-document view transitions (@view-transition { navigation: auto }) are not supported. A full page load starts a new canvas, so there is nothing to fly.