Navigation UX SPA+
View transitions, hash fragment navigation, scroll restoration, and history state management.
View Transitions
The View Transitions API provides smooth, animated transitions between pages. WildflowerJS integrates with the browser's native View Transitions API for seamless navigation animations.
Enabling View Transitions
// Enable via createRouter factory
const router = wildflower.createRouter({
mode: 'hash',
viewTransitions: true, // Enable view transitions
routes: [
{ path: '/', handler: () => showHome() },
{ path: '/about', handler: () => showAbout() }
]
});
// Or enable after creation
const router = wildflower.createRouter({ mode: 'hash' });
router.setViewTransitions(true);
Checking API Availability
// Check if browser supports View Transitions
if (router.viewTransitionsAvailable) {
console.log('View Transitions API is supported!');
}
// Check if transitions are both enabled AND supported
if (router.viewTransitionsEnabled) {
console.log('View transitions will be used for navigation');
}
Transition Events
Subscribe to transition lifecycle events:
// When a view transition starts
router.on('viewTransitionStart', ({ from, to, transition }) => {
console.log(`Transitioning from ${from} to ${to}`);
// 'transition' is the native ViewTransition object
});
// When a view transition completes
router.on('viewTransitionEnd', ({ from, to }) => {
console.log('Transition complete!');
});
// If a transition fails
router.on('viewTransitionError', ({ error, from, to }) => {
console.error('Transition failed:', error);
});
Skipping Transitions
Skip the animation for specific navigations:
// Skip transition for this navigation
router.navigate('/login', { skipTransition: true });
// Useful for:
// - Programmatic redirects (e.g., after form submission)
// - Navigation from guards
// - Initial page load
Per-Route Transition Config
Configure transitions per route:
const router = wildflower.createRouter({
viewTransitions: true,
routes: [
{
path: '/',
handler: showHome,
transition: 'fade' // Custom transition type (for CSS targeting)
},
{
path: '/modal',
handler: showModal,
transition: false // Disable transitions for this route
}
]
});
CSS Customization
Style your transitions with CSS:
/* Name your content for targeting */
.page-content {
view-transition-name: page-content;
}
/* Customize the transition animations */
::view-transition-old(page-content) {
animation: 200ms ease-out both slide-to-left;
}
::view-transition-new(page-content) {
animation: 200ms ease-out both slide-from-right;
}
/* Define the animations */
@keyframes slide-to-left {
from { transform: translateX(0); opacity: 1; }
to { transform: translateX(-30px); opacity: 0; }
}
@keyframes slide-from-right {
from { transform: translateX(30px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
Runtime Control
// Enable/disable at runtime
router.setViewTransitions(true);
router.setViewTransitions(false);
// Access current transition during animation
router.on('viewTransitionStart', () => {
const transition = router.currentTransition;
// Wait for animation to be ready
transition.ready.then(() => {
console.log('Animation started');
});
// Wait for animation to finish
transition.finished.then(() => {
console.log('Animation finished');
});
});
Hash Fragment Navigation
Navigate to specific sections within a page using hash fragments. The router parses fragments from the URL and can automatically scroll to the matching element.
Basic Usage
// Navigate with a hash fragment
router.navigate('/docs/api#methods');
// Or pass hash as an option
router.navigate('/docs/api', { hash: '#methods' });
// Access hash in route handlers
router.onRoute('/docs/:section', {
handler: ({ params, hash }) => {
showDocs(params.section);
// hash === '#methods' for /docs/api#methods
}
});
hash mode, the URL's # is already used for routing (e.g. page.html#/docs/api), so hash fragments cannot appear in href attributes like href="#/docs/api#methods"; the browser treats everything after the first # as a single fragment. Use programmatic navigation instead: router.navigate('/docs/api', { hash: '#methods' }). In history mode this limitation does not apply.
Auto-Scroll Behavior
When a hash fragment is present, the router automatically scrolls to the element with a matching id. It retries up to 10 times (100ms apart) to handle dynamically rendered content.
<!-- The router will scroll to this element for #features -->
<section id="features">
<h2>Features</h2>
<p>Content here...</p>
</section>
Hash in Named Routes
// Generate URL with hash
const url = router.getRouteUrl('docs', { section: 'api' });
// Returns: /docs/api, append hash manually:
router.navigate(url + '#methods');
Scroll Position Restoration
The router automatically saves scroll position before navigation. On browser back/forward, the saved position is restored.
Default Behavior
- New navigation scrolls to the top (or to a hash fragment if present)
- Back/forward restores the previous scroll position
Custom Scroll Behavior
const router = wildflower.createRouter({
scrollBehavior(to, from, savedPosition) {
// savedPosition is available on back/forward navigation
if (savedPosition) {
return savedPosition; // { x: number, y: number }
}
// Scroll to hash fragment
if (to.hash) {
return { selector: to.hash };
}
// Default: scroll to top
return { x: 0, y: 0 };
}
});
Scroll Return Values
| Return Value | Effect |
|---|---|
{ x, y } | Scroll to coordinates |
{ selector: '#id' } | Scroll to element (smooth) |
{ el: '#id' } | Alias for selector |
null / undefined | No scroll change |
History State
Attach custom state to navigation entries. State is stored in history.state and survives back/forward navigation.
// Navigate with custom state
router.navigate('/products/42', {
state: { fromList: true, scrollIndex: 15 }
});
// Access state in popstate (back/forward)
window.addEventListener('popstate', (e) => {
if (e.state && e.state.fromList) {
// User came back from product detail to list
restoreListPosition(e.state.scrollIndex);
}
});
scrollX, scrollY, and path.