kevinresol / coconut.router

Router for Coconut
10 stars 0 forks source link

Add support for non-root applications (base HREF?) #3

Open cedx opened 4 years ago

cedx commented 4 years ago

This library assumes that the application will be mounted at the web root. But in real life, this is not always the case. When the application is mounted under a non-root path, we must do some hacks like that to fix the route/location (in this snippet, the mount path of the application is provided by the <base href="..."> tag):

import js.Browser.document;
import tink.Url;

using haxe.io.Path;

new BrowserRouter<Route>({
    routeToLocation: route -> {
        final baseHref = document.head.querySelector("base").getAttribute("href").removeTrailingSlashes();

        // => Need to add the mount path to every URLs!
        switch route {
            case Homepage: '$baseHref/';
            case Foo: '$baseHref/foo';
            case Bar(baz): '$baseHref/bar/$baz';
            default: '$baseHref/error/404';
        }
    },
    locationToRoute: url -> {
        final pathParts = url.path.parts().toStringArray();

        // => Need to strip the mount path from every URLs!
        switch pathParts.slice(Url.parse(document.baseURI).path.parts().length) {
            case []: Homepage;
            case ["foo"]: Foo;
            case ["bar", baz]: Bar(baz);
            default: ErrorHandler(404);
        }
    }
});

It would be cool if this library could handle the mount path by itself, by reading the <base href> tag or via a dedicated property (let's name it baseHref for now):

new BrowserRouter<Route>({
    baseHref: "/apps/my_app",
    routeToLocation: (...),
    locationToRoute: (...)
});