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.

Browser Support: View Transitions are supported in Chrome 111+, Edge 111+, Firefox 129+, and Safari 18+. The router gracefully falls back to instant updates in unsupported browsers.

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; }
}
Router Example View Transitions Demo Open Full Example
Try it: Toggle view transitions on/off and navigate between pages. Watch the smooth slide animation when transitions are enabled.

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 Conflict: In 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');
Router Example Hash Fragment Navigation Open Full Example
Try it: Click the section links to navigate with hash fragments. The content scrolls to the target section and the route info updates.

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 / undefinedNo 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);
    }
});
Merged with Scroll: Custom state is merged with the router's automatic scroll position data. Your properties are preserved alongside scrollX, scrollY, and path.