Skip to content

springtype-org/st-route

Repository files navigation

SpringType: st-route

Nano library for client-side DOM routing

Gitter

Purpose

This is an exremely tiny, yet powerful library for HTML5 history API based DOM routing. st-route makes client-side page navigation dead simple.

Features

  • ✅ Abstracts the HTML5 history API
  • ✅ Tiny: 374 bytes (best, brotli) - 535 bytes (worst, umd, gz)
  • ✅ Zero dependencies
  • ✅ First class TypeScript support
  • ✅ 100% Unit Test coverage
  • ✅ TestCafé smoke tests

How to

This is how using st-route looks like:

import { tsx, render, Ref } from 'springtype';
import { $ } from 'st-query';
import { route, RouteRequest } from 'st-route';

const nav = route();

const HomePage = () => (
  <div>
    HomePage
    <br />
    <a href="/blog">Go to BlogPage</a>
  </div>
);
const BlogPage = () => <div>BlogPage</div>;

const BlogArticlePage = ({ request }: { request: RouteRequest }) => (
  <div>
    Blog / show article:
    {request.params.slug}
  </div>
);

const RouteList = () => {
  const containerRef: Ref = {};

  nav.get('/', () => {
    $(containerRef.current).html(<HomePage />);
  });

  nav.get('/blog', () => {
    $(containerRef.current).html(<BlogPage />);
  });

  nav.get('/blog/article/:slug', (request: RouteRequest) => {
    $(containerRef.current).html(<BlogArticlePage request={request} />);
  });

  return <div ref={containerRef}>Loading...</div>;
};
render(<RouteList />);

// initial match after initial render
nav.match();

API

The following contract is made between the webapp and st-router:

export interface API {
  get(path: string, handler: RouteHandler): API;
  match(path?: string): RouteRequest | false;
  getRouteRegistrations(): Array<RouteRegistration>;
  tokenizePath(path: string): TokenizedPath;
}

// calling route() returns the API object like:
// const nav = route();
// nav.get('/foo')
export route = () => API;

Troubleshooting

⚠️ Please make sure that you have a http server in place that can handle pushState well (re-routes all HTTP GET requests back to the index.html file serving the JavaScript). Please read about "SPA / Single Page Application routing" if you have any further questions about this.

Backers

Thank you so much for supporting us financially! 🙏🏻😎🥳👍


Tom

Maintainers

st-route is brought to you by:


Aron Homberg

Paul Kinlan

Original implementation of the routing logic is based on ideas of LeviRoutes developed by Paul Kinlan about 10 years ago -- however, this is a TypeScript-based clean room re-implementation which improves the original code in a few aspects.

Contributing

Please help out to make this project even better and see your name added to the list of our CONTRIBUTORS.md 🎉

About

~400 byte nano library for client-side DOM routing

Resources

License

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published