Projects

Crumbs

Simple framework-agnostic SPA routing

View / Source
Type

library

Active

2024 - 2026

Status

Done

Tags

SPA Routing, TypeScript, HTML Pages

Projects
Crumbslibrary2024 - 2026View / Source

Ever since cavemen (and cave-women) left the caves, they’ve been wondering how to move on from using SSR and move all the state and functionality to the browser. Worry not, this completely original implementation of client-side routing is what will shake the web dev scene to its foundations.

I introduce to you: the CRUMBS. Sheesh, who spilled all these routes all over the floor?

Usage

Simple. Just create it lol. Full documentation

This library assumes you’re using it in an environment which can import HTML files as strings. If you wish to define pages using the *.page.html syntax, you need to add a type reference to your global .d.ts file and use the Crumbs Vite plugin.

// env.d.ts
/// <reference types="@dolanske/crumbs/client" />

// vite.config.ts
import crumbs from '@dolanske/crumbs/vite'

export default defineConfig({
  plugins: [crumbs()]
})

Define the router in your main.ts file.

import { defineRouter } from '@dolanske/crumbs'
import errorFallback from './routes/errorFallback.html?raw'

// Without the setup above, you can still import pages like this
import main from './routes/main.html?raw'

// With the setup, you can import them like this
import user from './routes/user.page.html'

const routes = {
  '/': main,
  '/users': '<div><h1>People!</h1></div>',
  '/user/:id': {
    html: user,
    // In case loader throws, you can provide a fallback route to render instead
    fallback: errorFallback,
    async loader({ id }: { id: string }) {
      return fetch(`https://swapi.dev/api/people/${id}`).then(r => r.json())
    },
  },
}

const router = defineRouter(routes, {
  base: '/portfolio',
})

router.run('#app')

Each route can contain these fields during definition

interface Route {
  // Sets the title of the page
  title?: string

  // Content of the route, which gets rendered on navigation. Strings are
  // parsed on every navigation, elements are reused as they are.
  html: string | Element

  // Fallback should be used together with loader, to display error state
  fallback?: string | Element

  // If loader returns a promise, the route is not loaded until the loader
  // function resolves. The returned dataset is then available through
  // `onRouteResolve()` callback or when calling `getRoute()` after the route
  // has loaded. Parameters extracted from the path are always strings.
  loader?: (params: Record<string, string>) => Promise<any>

  // When page is first loaded, the router will look for a matching path,
  // if one is not found, it will then check if any route is set
  // as `default` and if it finds one, it loads that route
  default?: boolean

  // You can define any data which will be available on the route object
  meta?: Record<string, any>
}

Define a page

The recommended way of defining routes is using an HTML file. Crumbs specifically checks for a top-level <script> and allows you to run JavaScript whenever the route loads. One big caveat is that the script cannot import packages or local files, because it runs in its own context.

<div id="page">
  <h1>Hello world</h1>
</div>

<style>
  h1 {
    color: yellow;
  }
</style>

<script type="module">
  export function mount(root, ctx) {
    // You can only write code inside the `mount` function
    // root = the top level element, in this case <div id="page" />
    // ctx  = object containing path, query, props, hash, global provides
    return {
      // Runs before page is destroyed
      unmount() {},
      // Runs before navigating out, returning false cancels navigation
      beforeLeave() {},
    }
  }
</script>

One way we can work around this is to provide methods to the router object via options

interface RouterOptions {
  // Any data available to the pages. For instance methods we can't import
  // inside `.page.html` or globally available datasets
  provide?: Record<string, any>
  // Base path the app is served from, eg. `/my-repo/`
  base?: string
}

defineRouter(routes, {
  provide: {
    // Add any imported/package methods here
    test: () => console.log('Hello from page!'),
    // Globally available dataset
    users: ['a', 'b']
  }
})

Now, if you want to navigate to a route, you can do so in two ways

interface NavigateOptions {
  // Append a hash parameter to the URL such as #henlo.
  // Pass `false` to remove the hash from the path.
  hash?: string | boolean | number

  // Query object which gets serialized into search parameters
  // Such as ?hello=world&second=hello
  query?: Record<string, string | number | boolean>

  props?: Record<string, any>

  // Whether to replace the current History entry. Navigating to the exact URL
  // which is already open always replaces the entry.
  replace?: boolean
}

And that’s basically it. Interested in how it works? Here you go. Feedback, issues and PRs welcome as always!