Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document swapFunctions of astro:transitions/client #9084

Merged
merged 9 commits into from
Aug 28, 2024
30 changes: 30 additions & 0 deletions src/content/docs/en/guides/view-transitions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,36 @@ At this point of the lifecycle, you could choose to define your own swap impleme
</script>
```

#### Building a custom swap function

<p><Since v="4.15.0" /></p>

The `swapFunction` object of the `astro:transitions/client` module provides five utility functions that handle specific swap-related tasks, including handling document attributes, page elements, and script execution. These functions can be used directly to define a custom swap implementation.

The following example demonstrates how to use these functions to recreate Astro's built-in swap implementation:

```astro
<script>
import { swapFunctions } from 'astro:transitions/client';

// substitutes window.document with doc
function mySwap(doc: Document) {
swapFunctions.deselectScripts(doc);
swapFunctions.swapRootAttributes(doc);
swapFunctions.swapHeadElements(doc);
const restoreFocusFunction = swapFunctions.saveFocus();
swapFunctions.swapBodyElement(doc.body, document.body);
restoreFocusFunction();
};

...
ev.swap = () => mySwap(ev.newDocument);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
ev.swap = () => mySwap(ev.newDocument);
event.swap = () => mySwap(event.newDocument);

Last tiny tiny thing: assuming that ev stands for event, we generally prefer to write these words out in full as they can help people who aren't used to standard abbreviations. This would be my preference, if correct!

Copy link
Member Author

@martrapp martrapp Aug 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good one! I had used ev for consistency with the rest of the page. Now everything is consistent again ;-)

...
<script>
```
Custom swap implementations can start with this template and add or replace individual steps with custom logic as needed.


### `astro:after-swap`

An event that fires immediately after the new page replaces the old page. You can listen to this event on the `document` and trigger actions that will occur before the new page's DOM elements render and scripts run.
Expand Down
Loading