Pinecone Router

repository·main·Indexed 43 days ago

https://github.com/rehhouari/pinecone-router

A lightweight, feature-packed router for Alpine.js applications. Version 7.6.0 provides route declaration via the x-route directive, parameter handling, and flexible template management including inline, external, and preloaded templates. It includes support for named routes, global handlers, navigation history management, and custom base path configuration.

Tokens
9.1K
Snippets
35
Records
47
Agent score
53%

What's inside Pinecone Router

  1. Manage navigation with NavigationHistory

    main

    Pinecone Router maintains an independent NavigationHistory object that tracks path visits. This allows for back() and forward() operations without relying solely on the browser API.

    History Logic:

    • Duplicates: Visiting the same path twice does not add a new entry.
    • Redirects: If a handler redirects, the original (redirected-from) path is not added to the history, preventing loops.
    • Branching: If you navigate back and then click a new link, all entries after your current index are removed before the new path is appended.

    API:

    • index: The current position in history.
    • entries: Array of visited paths.
    • canGoBack() / canGoForward(): Check if navigation is possible.
    • back() / forward(): Move through history.
    • to(index): Jump to a specific history position.
    // Access via $history in Alpine or PineconeRouter.history in JS
    if (history.canGoBack()) {
        history.back();
    }
  2. Customize the `notfound` route

    main

    By default, Pinecone Router creates a notfound route that logs a ReferenceError when a path is not matched. You can override this behavior in two ways:

    1. Declaratively: Use a <template> element with x-route="notfound" combined with x-template or x-handler.
    2. Programmatically: Use PineconeRouter.add('notfound', { ... }). Unlike other routes, adding to notfound will not throw an error if the route already exists.
    <template x-route="notfound" x-template="/404.html"></template>
  3. Access the PineconeRouter object

    main

    The PineconeRouter object is the central controller for the routing system. You can access it via several methods depending on your environment:

    • Alpine.js components: Use the $router magic helper.
    • JS Modules: Use window.PineconeRouter.
    • Global JS: Use PineconeRouter.
    • Alpine Global: Use Alpine.$router.
  4. Access route parameters

    main

    Once a route with named segments (e.g., /:name) is matched, you can access the parameter values in three ways:

    1. In Alpine.js components: Use the $params magic helper (e.g., $params.name).
    2. Inside route handlers: Use context.params.paramName.
    3. In plain JavaScript: Use PineconeRouter.context.params.
  5. Migrate from Pinecone Router 6.x to 7.x

    main

    When upgrading to version 7.x, several core abstractions and magic helpers have changed. Key changes include:

    $router Object

    • The $router object now provides the PineconeRouter object instead of the Context object. To access the context, use $router.context.
    • Replace $router.route with $router.context.route.
    • Replace $router.redirect() with $router.navigate().
    • Use the new $params magic helper instead of $router.params.
    • Context.query and Context.hash have been removed. Access these directly via window.location.search and window.location.hash.
    • Use the new $history magic helper for history navigation: $history.back(), $history.canGoBack(), $history.forward(), and $history.canGoForward().
    • Access history from JavaScript using PineconeRouter.history.

    Event Renames

    Update your event listeners to use the new colon-separated naming convention:

    • pinecone-start $\rightarrow$ pinecone:start
    • pinecone-end $\rightarrow$ pinecone:end
    • fetch-error $\rightarrow$ pinecone:fetch-error
  6. Update Handlers for Pinecone Router 7.x

    main

    Handlers in version 7.x have undergone several changes regarding context access and arguments:

    • Context Access: Do not use context.navigate or context.redirect as these have been removed from the Context object. Instead, use this.$router.navigate() inside handlers to perform redirects.
    • Argument Changes: Handlers now receive a second argument of type AbortController.
    • Context Scope: Handlers must use the provided local context parameter. The global context ($router.context) is not updated until handlers finish executing.
  7. Install Pinecone Router via CDN, NPM, or Browser Module

    main

    You can integrate Pinecone Router into your project using three different methods depending on your build setup.

    CDN

    Include the script tag in your <head> before Alpine.js:

    <script src="https://cdn.jsdelivr.net/npm/pinecone-router@7.6.0/dist/router.min.js"></script>

    NPM

    Install the package via npm:

    npm install pinecone-router

    Then, register it as an Alpine.js plugin:

    import PineconeRouter from 'pinecone-router'
    import Alpine from 'alpinejs'
    Alpine.plugin(PineconeRouter)
    Alpine.start()

    Browser Module

    Use ES modules directly in the browser:

    import PineconeRouter from 'https://cdn.jsdelivr.net/npm/pinecone-router@7.6.0/dist/router.esm.js'
    import Alpine from 'https://cdn.jsdelivr.net/npm/alpinejs@3.14.9/dist/module.esm.js'
    Alpine.plugin(PineconeRouter)
    Alpine.start()
    npm install pinecone-router
  8. Monitor router loading state and events

    main

    The router provides a loading property and dispatches DOM events to track navigation lifecycle:

    • loading: A boolean indicating if a navigation is currently in progress.
    • pinecone:start: Dispatched when loading becomes true.
    • pinecone:end: Dispatched when loading becomes false.
    • pinecone:handler-error: Dispatched as a CustomEvent when a route handler fails. The error details are contained in the detail property.
    // Listen for loading start
    document.addEventListener('pinecone:start', () => {
      console.log('Navigation started...');
    });
    
    // Listen for errors
    document.addEventListener('pinecone:handler-error', (event) => {
      console.error('Handler failed:', event.detail);
    });
  9. Bypass or disable link click handling

    main

    Pinecone Router intercepts clicks on anchor elements by default. You can control this behavior:

    Bypass a single link: Add the native or data-native attribute to an anchor tag to let the browser handle the click normally.

    <a href="/foo" native>This will be handled by the browser</a>

    Disable globally: Set Settings.handleClicks to false. When disabled, the router only handles links that explicitly have the x-link attribute.

    <a href="/path">This will reload the page</a>
    <a href="/path" x-link>This won't reload the page</a>
  10. Configure Pinecone Router settings

    main

    Use PineconeRouter.settings() to configure the router. Calling it without arguments returns the current settings; calling it with a partial settings object updates them.

    Common Settings:

    • hash: (boolean) Enable hash routing. Default: false.
    • basePath: (string) The base path of the site (e.g., /blog). Default: /.
    • targetID: (string) The ID of the element where templates render. Default: undefined.
    • handleClicks: (boolean) Whether to intercept link clicks. Default: true.
    • globalHandlers: (Array) Handlers to run on every route.
    • preload: (boolean) Preload all templates. Default: false.
    • pushState: (boolean) Whether to call history.pushState(). Default: true.
    <!-- In Alpine -->
    <div x-data="router" x-init="$router.settings({targetID: 'app'})"></div>
    // In JS
    window.PineconeRouter.settings({
        basePath: '/app',
        targetID: 'app',
    });